09_MultipleViewports.lua 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. -- Multiple viewports example.
  2. -- This sample demonstrates:
  3. -- - Setting up two viewports with two separate cameras
  4. -- - Adding post processing effects to a viewport's render path and toggling them
  5. require "LuaScripts/Utilities/Sample"
  6. local rearCameraNode = nil
  7. function Start()
  8. -- Execute the common startup for samples
  9. SampleStart()
  10. -- Create the scene content
  11. CreateScene()
  12. -- Create the UI content
  13. CreateInstructions()
  14. -- Setup the viewports for displaying the scene
  15. SetupViewports()
  16. -- Set the mouse mode to use in the sample
  17. SampleInitMouseMode(MM_RELATIVE)
  18. -- Hook up to the frame update and render post-update events
  19. SubscribeToEvents()
  20. end
  21. function CreateScene()
  22. scene_ = Scene()
  23. -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  24. -- Also create a DebugRenderer component so that we can draw debug geometry
  25. scene_:CreateComponent("Octree")
  26. scene_:CreateComponent("DebugRenderer")
  27. -- Create scene node & StaticModel component for showing a static plane
  28. local planeNode = scene_:CreateChild("Plane")
  29. planeNode.scale = Vector3(100.0, 1.0, 100.0)
  30. local planeObject = planeNode:CreateComponent("StaticModel")
  31. planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
  32. planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
  33. -- Create a Zone component for ambient lighting & fog control
  34. local zoneNode = scene_:CreateChild("Zone")
  35. local zone = zoneNode:CreateComponent("Zone")
  36. zone.boundingBox = BoundingBox(-1000.0, 1000.0)
  37. zone.ambientColor = Color(0.15, 0.15, 0.15)
  38. zone.fogColor = Color(0.5, 0.5, 0.7)
  39. zone.fogStart = 100.0
  40. zone.fogEnd = 300.0
  41. -- Create a directional light to the world. Enable cascaded shadows on it
  42. local lightNode = scene_:CreateChild("DirectionalLight")
  43. lightNode.direction = Vector3(0.6, -1.0, 0.8)
  44. local light = lightNode:CreateComponent("Light")
  45. light.lightType = LIGHT_DIRECTIONAL
  46. light.castShadows = true
  47. light.shadowBias = BiasParameters(0.00025, 0.5)
  48. -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
  49. light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
  50. -- Create some mushrooms
  51. local NUM_MUSHROOMS = 240
  52. for i = 1, NUM_MUSHROOMS do
  53. local mushroomNode = scene_:CreateChild("Mushroom")
  54. mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
  55. mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
  56. mushroomNode:SetScale(0.5 + Random(2.0))
  57. local mushroomObject = mushroomNode:CreateComponent("StaticModel")
  58. mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
  59. mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
  60. mushroomObject.castShadows = true
  61. end
  62. -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
  63. -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
  64. local NUM_BOXES = 20
  65. for i = 1, NUM_BOXES do
  66. local boxNode = scene_:CreateChild("Box")
  67. local size = 1.0 + Random(10.0)
  68. boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
  69. boxNode:SetScale(size)
  70. local boxObject = boxNode:CreateComponent("StaticModel")
  71. boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
  72. boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
  73. boxObject.castShadows = true
  74. if size >= 3.0 then
  75. boxObject.occluder = true
  76. end
  77. end
  78. -- Create the camera. Limit far clip distance to match the fog
  79. cameraNode = scene_:CreateChild("Camera")
  80. local camera = cameraNode:CreateComponent("Camera")
  81. camera.farClip = 300.0
  82. -- Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
  83. -- Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
  84. rearCameraNode = cameraNode:CreateChild("RearCamera")
  85. rearCameraNode:Rotate(Quaternion(180.0, Vector3(0.0, 1.0, 0.0)))
  86. local rearCamera = rearCameraNode:CreateComponent("Camera")
  87. rearCamera.farClip = 300.0
  88. -- Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
  89. -- "view override flags" for this. We could also disable eg. shadows or force low material quality
  90. -- if we wanted
  91. rearCamera.viewOverrideFlags = VO_DISABLE_OCCLUSION
  92. -- Set an initial position for the front camera scene node above the plane
  93. cameraNode.position = Vector3(0.0, 5.0, 0.0)
  94. end
  95. function CreateInstructions()
  96. -- Construct new Text object, set string to display and font to use
  97. local instructionText = ui.root:CreateChild("Text")
  98. instructionText.text =
  99. "Use WASD keys and mouse to move\n"..
  100. "B to toggle bloom, F to toggle FXAA\n"..
  101. "Space to toggle debug geometry\n"
  102. instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
  103. -- The text has multiple rows. Center them in relation to each other
  104. instructionText.textAlignment = HA_CENTER
  105. -- Position the text relative to the screen center
  106. instructionText.horizontalAlignment = HA_CENTER
  107. instructionText.verticalAlignment = VA_CENTER
  108. instructionText:SetPosition(0, ui.root.height / 4)
  109. end
  110. function SetupViewports()
  111. renderer.numViewports = 2
  112. -- Set up the front camera viewport
  113. local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
  114. renderer:SetViewport(0, viewport)
  115. -- Clone the default render path so that we do not interfere with the other viewport, then add
  116. -- bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
  117. -- for example with the effect name to allow easy toggling on and off. We start with the effects
  118. -- disabled.
  119. local effectRenderPath = viewport:GetRenderPath():Clone()
  120. effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/Bloom.xml"))
  121. effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/FXAA2.xml"))
  122. -- Make the bloom mixing parameter more pronounced
  123. effectRenderPath:SetShaderParameter("BloomMix", Variant(Vector2(0.9, 0.6)))
  124. effectRenderPath:SetEnabled("Bloom", false)
  125. effectRenderPath:SetEnabled("FXAA2", false)
  126. viewport:SetRenderPath(effectRenderPath)
  127. -- Set up the rear camera viewport on top of the front view ("rear view mirror")
  128. -- The viewport index must be greater in that case, otherwise the view would be left behind
  129. local rearViewport = Viewport:new(scene_, rearCameraNode:GetComponent("Camera"),
  130. IntRect(graphics.width * 2 / 3, 32, graphics.width - 32, graphics.height / 3))
  131. renderer:SetViewport(1, rearViewport)
  132. end
  133. function SubscribeToEvents()
  134. -- Subscribe HandleUpdate() function for processing update events
  135. SubscribeToEvent("Update", "HandleUpdate")
  136. -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
  137. -- debug geometry
  138. SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
  139. end
  140. function MoveCamera(timeStep)
  141. -- Do not move if the UI has a focused element (the console)
  142. if ui.focusElement ~= nil then
  143. return
  144. end
  145. -- Movement speed as world units per second
  146. local MOVE_SPEED = 20.0
  147. -- Mouse sensitivity as degrees per pixel
  148. local MOUSE_SENSITIVITY = 0.1
  149. -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  150. local mouseMove = input.mouseMove
  151. yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
  152. pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
  153. pitch = Clamp(pitch, -90.0, 90.0)
  154. -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  155. cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
  156. -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  157. if input:GetKeyDown(KEY_W) then
  158. cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
  159. end
  160. if input:GetKeyDown(KEY_S) then
  161. cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
  162. end
  163. if input:GetKeyDown(KEY_A) then
  164. cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  165. end
  166. if input:GetKeyDown(KEY_D) then
  167. cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
  168. end
  169. -- Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
  170. local effectRenderPath = renderer:GetViewport(0).renderPath
  171. if input:GetKeyPress(KEY_B) then
  172. effectRenderPath:ToggleEnabled("Bloom")
  173. end
  174. if input:GetKeyPress(KEY_F) then
  175. effectRenderPath:ToggleEnabled("FXAA2")
  176. end
  177. -- Toggle debug geometry with space
  178. if input:GetKeyPress(KEY_SPACE) then
  179. drawDebug = not drawDebug
  180. end
  181. end
  182. function HandleUpdate(eventType, eventData)
  183. -- Take the frame time step, which is stored as a float
  184. local timeStep = eventData["TimeStep"]:GetFloat()
  185. -- Move the camera, scale movement with time step
  186. MoveCamera(timeStep)
  187. end
  188. function HandlePostRenderUpdate(eventType, eventData)
  189. -- If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
  190. if drawDebug then
  191. renderer:DrawDebugGeometry(false)
  192. end
  193. end
  194. -- Create XML patch instructions for screen joystick layout specific to this sample app
  195. function GetScreenJoystickPatchString()
  196. return
  197. "<patch>" ..
  198. " <add sel=\"/element\">" ..
  199. " <element type=\"Button\">" ..
  200. " <attribute name=\"Name\" value=\"Button3\" />" ..
  201. " <attribute name=\"Position\" value=\"-120 -120\" />" ..
  202. " <attribute name=\"Size\" value=\"96 96\" />" ..
  203. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
  204. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
  205. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
  206. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
  207. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
  208. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
  209. " <element type=\"Text\">" ..
  210. " <attribute name=\"Name\" value=\"Label\" />" ..
  211. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
  212. " <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
  213. " <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
  214. " <attribute name=\"Text\" value=\"FXAA\" />" ..
  215. " </element>" ..
  216. " <element type=\"Text\">" ..
  217. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  218. " <attribute name=\"Text\" value=\"F\" />" ..
  219. " </element>" ..
  220. " </element>" ..
  221. " </add>" ..
  222. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
  223. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Bloom</replace>" ..
  224. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
  225. " <element type=\"Text\">" ..
  226. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  227. " <attribute name=\"Text\" value=\"B\" />" ..
  228. " </element>" ..
  229. " </add>" ..
  230. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
  231. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
  232. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
  233. " <element type=\"Text\">" ..
  234. " <attribute name=\"Name\" value=\"KeyBinding\" />" ..
  235. " <attribute name=\"Text\" value=\"SPACE\" />" ..
  236. " </element>" ..
  237. " </add>" ..
  238. "</patch>"
  239. end