08_Decals.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. -- Decals example.
  2. -- This sample demonstrates:
  3. -- - Performing a raycast to the octree and adding a decal to the hit location
  4. -- - Defining a Cursor UI element which stays inside the window and can be shown/hidden
  5. -- - Marking suitable (large) objects as occluders for occlusion culling
  6. -- - Displaying renderer debug geometry to see the effect of occlusion
  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 input = GetInput()
  15. local graphics = GetGraphics()
  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. CreateUI()
  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. -- Also create a DebugRenderer component so that we can draw debug geometry
  34. scene_:CreateComponent("Octree")
  35. scene_:CreateComponent("DebugRenderer")
  36. -- Create scene node & StaticModel component for showing a static plane
  37. local planeNode = scene_:CreateChild("Plane")
  38. planeNode.scale = Vector3(100.0, 1.0, 100.0)
  39. local planeObject = planeNode:CreateComponent("StaticModel")
  40. planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
  41. planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  42. -- Create a Zone component for ambient lighting & fog control
  43. local zoneNode = scene_:CreateChild("Zone")
  44. local zone = zoneNode:CreateComponent("Zone")
  45. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  46. zone.ambientColor = Color(0.15, 0.15, 0.15)
  47. zone.fogColor = Color(0.5, 0.5, 0.7)
  48. zone.fogStart = 100.0
  49. zone.fogEnd = 300.0
  50. -- Create a directional light to the world. Enable cascaded shadows on it
  51. local lightNode = scene_:CreateChild("DirectionalLight")
  52. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  53. local light = lightNode:CreateComponent("Light")
  54. light.lightType = LIGHT_DIRECTIONAL
  55. light.castShadows = true
  56. light.shadowBias = BiasParameters(0.00025, 0.5)
  57. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  58. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  59. -- Create some mushrooms
  60. local NUM_MUSHROOMS = 240
  61. for i = 1, NUM_MUSHROOMS do
  62. local mushroomNode = scene_:CreateChild("Mushroom")
  63. mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
  64. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  65. mushroomNode:SetScale(0.5 + Random(2.0))
  66. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  67. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  68. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  69. mushroomObject.castShadows = true
  70. end
  71. -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  72. -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  73. local NUM_BOXES = 20
  74. for i = 1, NUM_BOXES do
  75. local boxNode = scene_:CreateChild("Box")
  76. local size = 1.0 + Random(10.0)
  77. boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
  78. boxNode:SetScale(size)
  79. local boxObject = boxNode:CreateComponent("StaticModel")
  80. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  81. boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
  82. boxObject.castShadows = true
  83. if size >= 3.0 then
  84. boxObject.occluder = true
  85. end
  86. end
  87. -- Create the camera. Limit far clip distance to match the fog
  88. cameraNode = scene_:CreateChild("Camera")
  89. local camera = cameraNode:CreateComponent("Camera")
  90. camera.farClip = 300.0
  91. -- Set an initial position for the camera scene node above the plane
  92. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  93. end
  94. function CreateUI()
  95. -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  96. -- control the camera, and when visible, it will point the raycast target
  97. local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
  98. local cursor = ui.root:CreateChild("Cursor")
  99. cursor:SetStyleAuto(style)
  100. ui.cursor = cursor
  101. -- Set starting position of the cursor at the rendering window center
  102. cursor:SetPosition(graphics.width / 2, graphics.height / 2)
  103. -- Construct new Text object, set string to display and font to use
  104. local instructionText = ui.root:CreateChild("Text")
  105. instructionText.text =
  106. "Use WASD keys to move\n"..
  107. "LMB to paint decals, RMB to rotate view\n"..
  108. "Space to toggle debug geometry\n"..
  109. "7 to toggle occlusion culling"
  110. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  111. -- The text has multiple rows. Center them in relation to each other
  112. instructionText.textAlignment = HA_CENTER
  113. -- Position the text relative to the screen center
  114. instructionText.horizontalAlignment = HA_CENTER
  115. instructionText.verticalAlignment = VA_CENTER
  116. instructionText:SetPosition(0, ui.root.height / 4)
  117. end
  118. function SetupViewport()
  119. -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  120. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  121. renderer:SetViewport(0, viewport)
  122. end
  123. function SubscribeToEvents()
  124. -- Subscribe HandleUpdate() function for processing update events
  125. SubscribeToEvent("Update", "HandleUpdate")
  126. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  127. -- debug geometry
  128. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  129. end
  130. function MoveCamera(timeStep)
  131. -- Right mouse button controls mouse cursor visibility: hide when pressed
  132. ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT)
  133. -- Do not move if the UI has a focused element (the console)
  134. if ui.focusElement ~= nil then
  135. return
  136. end
  137. -- Movement speed as world units per second
  138. local MOVE_SPEED = 20.0
  139. -- Mouse sensitivity as degrees per pixel
  140. local MOUSE_SENSITIVITY = 0.1
  141. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  142. -- Only move the camera when the cursor is hidden
  143. if not ui.cursor.visible then
  144. local mouseMove = input.mouseMove
  145. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  146. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  147. pitch = Clamp(pitch, -90.0, 90.0)
  148. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  149. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  150. end
  151. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  152. if input:GetKeyDown(KEY_W) then
  153. cameraNode:TranslateRelative(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  154. end
  155. if input:GetKeyDown(KEY_S) then
  156. cameraNode:TranslateRelative(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  157. end
  158. if input:GetKeyDown(KEY_A) then
  159. cameraNode:TranslateRelative(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  160. end
  161. if input:GetKeyDown(KEY_D) then
  162. cameraNode:TranslateRelative(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  163. end
  164. -- Toggle debug geometry with space
  165. if input:GetKeyPress(KEY_SPACE) then
  166. drawDebug = not drawDebug
  167. end
  168. -- Paint decal with the left mousebutton cursor must be visible
  169. if ui.cursor.visible and input:GetMouseButtonPress(MOUSEB_LEFT) then
  170. PaintDecal()
  171. end
  172. end
  173. function PaintDecal()
  174. local result, hitPos, hitDrawable = Raycast(250.0)
  175. if result then
  176. -- Check if target scene node already has a DecalSet component. If not, create now
  177. local targetNode = hitDrawable:GetNode()
  178. local decal = targetNode:GetComponent("DecalSet")
  179. if decal == nil then
  180. decal = targetNode:CreateComponent("DecalSet")
  181. decal.material = cache:GetResource("Material", "Materials/UrhoDecal.xml")
  182. end
  183. -- Add a square decal to the decal set using the geometry of the drawable that was hit, orient it to face the camera,
  184. -- use full texture UV's (0,0) to (1,1). Note that if we create several decals to a large object (such as the ground
  185. -- plane) over a large area using just one DecalSet component, the decals will all be culled as one unit. If that is
  186. -- undesirable, it may be necessary to create more than one DecalSet based on the distance
  187. decal:AddDecal(hitDrawable, hitPos, cameraNode.rotation, 0.5, 1.0, 1.0, Vector2(0.0, 0.0), Vector2(1.0, 1.0))
  188. end
  189. end
  190. function Raycast(maxDistance)
  191. local hitPos = nil
  192. local hitDrawable = nil
  193. local pos = ui.cursorPosition
  194. -- Check the cursor is visible and there is no UI element in front of the cursor
  195. if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then
  196. return false, nil, nil
  197. end
  198. local camera = cameraNode:GetComponent("Camera")
  199. local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height)
  200. -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
  201. local octree = scene_:GetComponent("Octree")
  202. local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY)
  203. if result.drawable ~= nil then
  204. -- Calculate hit position in world space
  205. hitPos = cameraRay.origin + cameraRay.direction * result.distance
  206. hitDrawable = result.drawable
  207. return true, hitPos, hitDrawable
  208. end
  209. return false, nil, nil
  210. end
  211. function HandleUpdate(eventType, eventData)
  212. -- Take the frame time step, which is stored as a float
  213. local timeStep = eventData:GetFloat("TimeStep")
  214. -- Move the camera, scale movement with time step
  215. MoveCamera(timeStep)
  216. end
  217. function HandlePostRenderUpdate(eventType, eventData)
  218. -- If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  219. if drawDebug then
  220. renderer:DrawDebugGeometry(false)
  221. end
  222. end