09_MultipleViewports.as 9.9 KB

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