#include once "InitGL.bi"
#define USEDEBUG
#include once "TrueAxis.bi"

sub _AppInit_ constructor
  InitGL()
  PhysicsCreateInstance
end sub

sub _AppExit_ destructor
  PhysicsDestroyInstance
end sub

' Regardless of whether you want to simulate (a boat, train, plane or a construction machine or whatever)
' it are always the same 5 steps that are needed.
sub ThingUpdate TA_CB(byval self as DynamicObjectTemplate ptr,fDt as single)
  dim as single px,py,pz

  ' stap 1. be sure all forces was cleared in last update callback
  DynamicObjectAssertForceAndTorqueCleared self

  ' step 2. let earth G do it's job
  DynamicObjectAccumulateGravity self

  ' step 3. calculate and accumulate all forces you need 
  ' (Lateral Force, Longitudinal Force, Normal Force ...)
  
  DynamicObjectGetPosition self,px,py,pz
  if py<8 then
    dim as single mass = DynamicObjectGetMass(self)
    dim as single NormalForce=8-py:NormalForce*=mass*4
    DynamicObjectAccumulateForceAndTorque self,0,9.81*NormalForce,0,px,py,pz
  end if

  ' step 4.
  DynamicObjectApplyForceAndTorqueToVelocities self,fDt

  ' step 5. clear all forces for next update
  DynamicObjectClearForceAndTorque self
end sub

' create a static ground
PhysicsAddStaticGround 50

var combo = CollisionObjectComboCreateNew()
CollisionObjectComboInitialiseAsACube(combo,0,0,0,1)

' create a user defined dynamic object 
var thing = DynamicObjectTemplateCreateNew()
DynamicObjectTemplateInitialise(thing,combo,@ThingUpdate)
DynamicObjectSetPosition(thing,0,5,0)
' add the thing object to the simulation
PhysicsAddDynamicObject thing

' render and simulation loop
dim as integer key,frames
while key<>K_ESCAPE andalso key<>K_WINDOW_CLOSE
  key=GetKeyCode()
  if DynamicObjectIsInMovingList(thing)=0 then
    PhysicsSetDynamicObjectIsMoving thing
  end if
  
  ' one step in simulation
  PhysicsUpdate(1.0/75.0)

  if frames mod 2=0 then
    glClear GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT
    glLoadIdentity
    glTranslatef 0,-15,-40
    ' draw all objects (only in debug mode) 
    PhysicsRender()
    flip
  end if
  Sleep(10)
  frames+=1
wend

