11_Physics.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. -- Physics example.
  2. -- This sample demonstrates:
  3. -- - Creating both static and moving physics objects to a scene
  4. -- - Displaying physics debug geometry
  5. -- - Using the Skybox component for setting up an unmoving sky
  6. -- - Saving a scene to a file and loading it to restore a previous state
  7. require "LuaScripts/Utilities/Sample"
  8. local scene_ = nil
  9. local cameraNode = nil
  10. local yaw = 0.0
  11. local pitch = 0.0
  12. local drawDebug = false
  13. local cache = GetCache()
  14. local fileSystem = GetFileSystem()
  15. local input = GetInput()
  16. local renderer = GetRenderer()
  17. local ui = GetUI()
  18. function Start()
  19. -- Execute the common startup for samples
  20. SampleStart()
  21. -- Create the scene content
  22. CreateScene()
  23. -- Create the UI content
  24. CreateInstructions()
  25. -- Setup the viewport for displaying the scene
  26. SetupViewport()
  27. -- Hook up to the frame update and render post-update events
  28. SubscribeToEvents()
  29. end
  30. function CreateScene()
  31. scene_ = Scene()
  32. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  33. -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
  34. -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
  35. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry
  36. scene_:CreateComponent("Octree")
  37. scene_:CreateComponent("PhysicsWorld")
  38. scene_:CreateComponent("DebugRenderer")
  39. -- Create a Zone component for ambient lighting & fog control
  40. local zoneNode = scene_:CreateChild("Zone")
  41. local zone = zoneNode:CreateComponent("Zone")
  42. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  43. zone.ambientColor = Color(0.15, 0.15, 0.15)
  44. zone.fogColor = Color(1.0, 1.0, 1.0)
  45. zone.fogStart = 300.0
  46. zone.fogEnd = 500.0
  47. -- Create a directional light to the world. Enable cascaded shadows on it
  48. local lightNode = scene_:CreateChild("DirectionalLight")
  49. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  50. local light = lightNode:CreateComponent("Light")
  51. light.lightType = LIGHT_DIRECTIONAL
  52. light.castShadows = true
  53. light.shadowBias = BiasParameters(0.00025, 0.5)
  54. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  55. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  56. -- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  57. -- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  58. -- generate the necessary 3D texture coordinates for cube mapping
  59. local skyNode = scene_:CreateChild("Sky")
  60. skyNode:SetScale(500.0) -- The scale actually does not matter
  61. local skybox = skyNode:CreateComponent("Skybox")
  62. skybox.model = cache:GetResource("Model", "Models/Box.mdl")
  63. skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
  64. -- Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
  65. local floorNode = scene_:CreateChild("Floor")
  66. floorNode.position = Vector3(0.0, -0.5, 0.0)
  67. floorNode.scale = Vector3(1000.0, 1.0, 1000.0)
  68. local floorObject = floorNode:CreateComponent("StaticModel")
  69. floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
  70. floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  71. -- Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
  72. -- parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
  73. -- in the physics simulation
  74. local body = floorNode:CreateComponent("RigidBody")
  75. local shape = floorNode:CreateComponent("CollisionShape")
  76. -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
  77. -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
  78. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  79. -- Create a pyramid of movable physics objects
  80. for y = 0, 7 do
  81. for x = -y, y do
  82. local boxNode = scene_:CreateChild("Box")
  83. boxNode.position = Vector3(x, -y + 8.0, 0.0)
  84. local boxObject = boxNode:CreateComponent("StaticModel")
  85. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  86. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  87. boxObject.castShadows = true
  88. -- Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
  89. -- and also adjust friction. The actual mass is not important only the mass ratios between colliding
  90. -- objects are significant
  91. local body = boxNode:CreateComponent("RigidBody")
  92. body.mass = 1.0
  93. body.friction = 0.75
  94. local shape = boxNode:CreateComponent("CollisionShape")
  95. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  96. end
  97. end
  98. -- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  99. -- the scene, because we want it to be unaffected by scene load / save
  100. cameraNode = Node()
  101. local camera = cameraNode:CreateComponent("Camera")
  102. camera.farClip = 500.0
  103. -- Set an initial position for the camera scene node above the floor
  104. cameraNode.position = Vector3(0.0, 5.0, -20.0)
  105. end
  106. function CreateInstructions()
  107. -- Construct new Text object, set string to display and font to use
  108. local instructionText = ui.root:CreateChild("Text")
  109. instructionText:SetText("Use WASD keys and mouse to move\n"..
  110. "LMB to spawn physics objects\n"..
  111. "F5 to save scene, F7 to load\n"..
  112. "Space to toggle physics debug geometry")
  113. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  114. -- The text has multiple rows. Center them in relation to each other
  115. instructionText.textAlignment = HA_CENTER
  116. -- Position the text relative to the screen center
  117. instructionText.horizontalAlignment = HA_CENTER
  118. instructionText.verticalAlignment = VA_CENTER
  119. instructionText:SetPosition(0, ui.root.height / 4)
  120. end
  121. function SetupViewport()
  122. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  123. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  124. renderer:SetViewport(0, viewport)
  125. end
  126. function SubscribeToEvents()
  127. -- Subscribe HandleUpdate() function for processing update events
  128. SubscribeToEvent("Update", "HandleUpdate")
  129. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  130. -- debug geometry
  131. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  132. end
  133. function MoveCamera(timeStep)
  134. -- Do not move if the UI has a focused element (the console)
  135. if ui.focusElement ~= nil then
  136. return
  137. end
  138. -- Movement speed as world units per second
  139. local MOVE_SPEED = 20.0
  140. -- Mouse sensitivity as degrees per pixel
  141. local MOUSE_SENSITIVITY = 0.1
  142. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  143. local mouseMove = input.mouseMove
  144. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  145. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  146. pitch = Clamp(pitch, -90.0, 90.0)
  147. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  148. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  149. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  150. if input:GetKeyDown(KEY_W) then
  151. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  152. end
  153. if input:GetKeyDown(KEY_S) then
  154. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  155. end
  156. if input:GetKeyDown(KEY_A) then
  157. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  158. end
  159. if input:GetKeyDown(KEY_D) then
  160. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  161. end
  162. -- "Shoot" a physics object with left mousebutton
  163. if input:GetMouseButtonPress(MOUSEB_LEFT) then
  164. SpawnObject()
  165. end
  166. -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
  167. -- directory
  168. if input:GetKeyPress(KEY_F5) then
  169. scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  170. end
  171. if input:GetKeyPress(KEY_F7) then
  172. scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
  173. end
  174. -- Toggle debug geometry with space
  175. if input:GetKeyPress(KEY_SPACE) then
  176. drawDebug = not drawDebug
  177. end
  178. end
  179. function SpawnObject()
  180. -- Create a smaller box at camera position
  181. local boxNode = scene_:CreateChild("SmallBox")
  182. boxNode.position = cameraNode.position
  183. boxNode.rotation = cameraNode.rotation
  184. boxNode:SetScale(0.25)
  185. local boxObject = boxNode:CreateComponent("StaticModel")
  186. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  187. boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
  188. boxObject.castShadows = true
  189. -- Create physics components, use a smaller mass also
  190. local body = boxNode:CreateComponent("RigidBody")
  191. body.mass = 0.25
  192. body.friction = 0.75
  193. local shape = boxNode:CreateComponent("CollisionShape")
  194. shape:SetBox(Vector3(1.0, 1.0, 1.0))
  195. local OBJECT_VELOCITY = 10.0
  196. -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
  197. -- to overcome gravity better
  198. body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
  199. end
  200. function HandleUpdate(eventType, eventData)
  201. -- Take the frame time step, which is stored as a float
  202. local timeStep = eventData:GetFloat("TimeStep")
  203. -- Move the camera, scale movement with time step
  204. MoveCamera(timeStep)
  205. end
  206. function HandlePostRenderUpdate(eventType, eventData)
  207. -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
  208. -- Note the convenience accessor to the physics world component
  209. if drawDebug then
  210. scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
  211. end
  212. end