balloon.bmx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. ' balloon.bmx
  2. ' create a spherical body, apply a force, and track its motion over time
  3. SuperStrict
  4. Framework Openb3d.B3dglgraphics
  5. Import Openb3dLibs.NewtonDynamics
  6. Import Brl.Standardio
  7. ' global variables
  8. Global ng:TNewtonGlobal = New TNewtonGlobal
  9. Main()
  10. Function Main()
  11. ' init scene
  12. Graphics3D DesktopWidth(),DesktopHeight(),0,2
  13. Local cam:TCamera = CreateCamera()
  14. PositionEntity cam,0,5,-20
  15. Local light:TLight = CreateLight()
  16. Local balloon:TMesh = CreateSphere()
  17. EntityColor balloon,200,200,0
  18. Local plane:TMesh = CreatePlane()
  19. EntityColor plane,0,100,200
  20. ' Create the Newton world.
  21. Local world:TNWorld = TNWorld.Create()
  22. ' Add the sphere.
  23. ng.matrix = New TNMatrix ' new global
  24. Local body:TNBody = addSphereToSimulation(world)
  25. ' Step the (empty) world 60 times in increments of 1/60 second.
  26. Local timestep:Float = 1.0 / 60
  27. While Not KeyHit(KEY_ESCAPE)
  28. world.Update(timestep)
  29. ' update the position of the balloon
  30. PositionEntity balloon,ng.matrix.positX,ng.matrix.positY,ng.matrix.positZ
  31. RenderWorld
  32. Text 0,20,"timestep="+timestep+" x="+ng.matrix.positX+" y="+ng.matrix.positY+" z="+ng.matrix.positZ
  33. Text 0,40,"Memory: "+GCMemAlloced()
  34. Flip
  35. GCCollect
  36. Wend
  37. ' Clean up.
  38. world.DestroyAllBodies()
  39. world.Destroy()
  40. End
  41. End Function
  42. Function addSphereToSimulation:TNBody(world:TNWorld)
  43. Local foo:TNMatrix = TNMatrix.GetIdentityMatrix()
  44. ' Create the sphere, size is radius
  45. Local collision:TNCollision = world.CreateSphere(1.0, 0, Null)
  46. ' Create the rigid body
  47. Local body:TNBody = world.CreateDynamicBody(collision,foo,Null)
  48. body.SetMassMatrix(1.0, 1, 1, 1)
  49. ' Install callback. Newton will call it whenever the object moves.
  50. body.SetForceAndTorqueCallback(cb_applyForce)
  51. collision.Destroy()
  52. Return body
  53. End Function
  54. ' callbacks are for sending newton data, each callback has a specific set of parameters
  55. Function cb_applyForce(body:TNBody, timestep:Float, threadIndex:Int)
  56. ' Apply a force to the object.
  57. Local force:Float[] = [0, 1.0, 0, 0]
  58. body.SetForce(force[0],force[1],force[2],force[3])
  59. ' Query the state (4x4 matrix) and extract the body's position.
  60. body.GetMatrix(ng.matrix)
  61. End Function
  62. Type TNewtonGlobal
  63. ' should be global if used in callback
  64. Field matrix:TNMatrix
  65. End Type