user_data.bmx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. ' user_data.bmx
  2. ' set and retrieve custom user data
  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. Local inc:Int=0
  28. While (inc<40)
  29. inc:+1
  30. world.Update(timestep)
  31. RenderWorld
  32. Flip
  33. GCCollect
  34. Wend
  35. ' Clean up.
  36. world.DestroyAllBodies()
  37. world.Destroy()
  38. End
  39. End Function
  40. Function addSphereToSimulation:TNBody(world:TNWorld)
  41. Local foo:TNMatrix = TNMatrix.GetIdentityMatrix()
  42. ' Create the sphere, size is radius
  43. Local collision:TNCollision = world.CreateSphere(1.0, 0, Null)
  44. ' Create the rigid body
  45. Local body:TNBody = world.CreateDynamicBody(collision,foo,Null)
  46. body.SetMassMatrix(1.0, 1, 1, 1)
  47. ' Install callback. Newton will call it whenever the object moves.
  48. body.SetForceAndTorqueCallback(cb_applyForce)
  49. ' Attach our custom data structure to the body.
  50. ng.mydata = New TUserData ' new global
  51. ng.mydata.bodyID = 5
  52. body.SetUserData(Object(ng.mydata))
  53. collision.Destroy()
  54. Return body
  55. End Function
  56. ' callbacks are for sending newton data, each callback has a specific set of parameters
  57. Function cb_applyForce(body:TNBody, timestep:Float, threadIndex:Int)
  58. ' Request the custom data, print the ID, and increment it.
  59. Local mydata:TUserData = TUserData(body.GetUserData())
  60. Print "BodyID: "+mydata.bodyID
  61. mydata.bodyID:+1
  62. End Function
  63. ' Define a custom data structure to store a body ID.
  64. Type TUserData
  65. Field bodyID:Int=0
  66. End Type
  67. Type TNewtonGlobal
  68. ' should be global if used in callback
  69. Field matrix:TNMatrix
  70. Field mydata:TUserData
  71. End Type