scriptName defaultDisableHavokOnLoad extends ObjectReference

bool property havokOnHit = TRUE auto
{Start Havok Sim when hit? DEFAULT: TRUE}
bool property havokOnActivate auto
{Start Havok Sim when activated? DEFAULT: FALSE}
bool property havokOnZKey auto
{Start Havok Sim when grabbed by player? DEFAULT: FALSE}
keyword property linkHavokPartner auto
{Link with this keyword and that ref will also sim with myself}
bool property beenSimmed auto hidden
{prevent an object that has been havok'd in-game from going static}
Bool Property beenPutInContainer auto hidden

Event OnCellAttach()
	If Is3DLoaded() && beenSimmed == False && beenPutInContainer == False
		SetMotionType(Motion_Keyframed, True)
 		; debug.trace("havok disabled on: " + self)
	EndIf
EndEvent

Event OnLoad()
	If beenSimmed == False && beenPutInContainer == False
		SetMotionType(Motion_Keyframed, True)
 		; debug.trace("havok disabled on: " + self)
	EndIf
EndEvent

Event OnActivate(ObjectReference triggerRef)
	If havokonActivate && beenSimmed == False
		ReleaseToHavok()
	EndIf
EndEvent

Event OnHit(ObjectReference var1, Form var2, Projectile var3, bool var4, bool var5, bool var6, bool var7)
	If havokOnHit && beenSimmed == False 
		ReleaseToHavok()
	EndIf
EndEvent

Event OnGrab()
	If havokOnZkey && beenSimmed == False
		ReleaseToHavok()
	EndIf
EndEvent

;USKP 2.0.1 - Added event to deal with Papyrus spam caused by the player picking these things up since the game cannot process that properly.
Event OnContainerChanged(ObjectReference akNewContainer, ObjectReference akOldContainer)
	If beenSimmed == False
		If akNewContainer != None
			;Stops the OnLoad event from generating errors.
			beenPutInContainer = True
		Else
			;No container, means it's being dropped in the open. Let it loose now.
			ReleaseToHavok()
		EndIf
	EndIf
EndEvent

Function ReleaseToHavok()
	beenSimmed = True
	beenPutInContainer = False
	defaultDisableHavokOnLoad myLink = GetLinkedRef(linkHavokPartner) as defaultDisableHavokOnLoad
	If myLink  && (myLink.beenSimmed == False)
		myLink.ReleaseToHavok()
	EndIf
	if Is3DLoaded() ; prevent Papyrus errors on a taken object
		SetMotionType(Motion_Dynamic, True)
		Self.ApplyHavokImpulse(0, 0, 1, 5)
	endif
	; Debug.Trace("Released Havok.")
EndFunction