11_Physics.lua 12 KB

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