23_Water.as 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Water example.
  2. // This sample demonstrates:
  3. // - Creating a large plane to represent a water body for rendering
  4. // - Setting up a second camera to render reflections on the water surface
  5. #include "Scripts/Utilities/Sample.as"
  6. Node@ reflectionCameraNode;
  7. Node@ waterNode;
  8. Plane waterPlane;
  9. Plane waterClipPlane;
  10. void Start()
  11. {
  12. // Execute the common startup for samples
  13. SampleStart();
  14. // Create the scene content
  15. CreateScene();
  16. // Create the UI content
  17. CreateInstructions();
  18. // Setup the viewports for displaying the scene and rendering the water reflection
  19. SetupViewports();
  20. // Set the mouse mode to use in the sample
  21. SampleInitMouseMode(MM_RELATIVE);
  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. scene_.CreateComponent("Octree");
  30. scene_.CreateComponent("DebugRenderer");
  31. // Create a Zone component for ambient lighting & fog control
  32. Node@ zoneNode = scene_.CreateChild("Zone");
  33. Zone@ zone = zoneNode.CreateComponent("Zone");
  34. zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
  35. zone.ambientColor = Color(0.15f, 0.15f, 0.15f);
  36. zone.fogColor = Color(1.0f, 1.0f, 1.0f);
  37. zone.fogStart = 500.0f;
  38. zone.fogEnd = 750.0f;
  39. // Create a directional light to the world. Enable cascaded shadows on it
  40. Node@ lightNode = scene_.CreateChild("DirectionalLight");
  41. lightNode.direction = Vector3(0.3f, -0.5f, 0.425f);
  42. Light@ light = lightNode.CreateComponent("Light");
  43. light.lightType = LIGHT_DIRECTIONAL;
  44. light.castShadows = true;
  45. light.shadowBias = BiasParameters(0.00025f, 0.5f);
  46. light.shadowCascade = CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f);
  47. light.specularIntensity = 0.5f;
  48. // Apply slightly overbright lighting to match the skybox
  49. light.color = Color(1.2f, 1.2f, 1.2f);
  50. // Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
  51. // illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
  52. // generate the necessary 3D texture coordinates for cube mapping
  53. Node@ skyNode = scene_.CreateChild("Sky");
  54. skyNode.SetScale(500.0); // The scale actually does not matter
  55. Skybox@ skybox = skyNode.CreateComponent("Skybox");
  56. skybox.model = cache.GetResource("Model", "Models/Box.mdl");
  57. skybox.material = cache.GetResource("Material", "Materials/Skybox.xml");
  58. // Create heightmap terrain
  59. Node@ terrainNode = scene_.CreateChild("Terrain");
  60. terrainNode.position = Vector3(0.0f, 0.0f, 0.0f);
  61. Terrain@ terrain = terrainNode.CreateComponent("Terrain");
  62. terrain.patchSize = 64;
  63. terrain.spacing = Vector3(2.0f, 0.5f, 2.0f); // Spacing between vertices and vertical resolution of the height map
  64. terrain.smoothing = true;
  65. terrain.heightMap = cache.GetResource("Image", "Textures/HeightMap.png");
  66. terrain.material = cache.GetResource("Material", "Materials/Terrain.xml");
  67. // The terrain consists of large triangles, which fits well for occlusion rendering, as a hill can occlude all
  68. // terrain patches and other objects behind it
  69. terrain.occluder = true;
  70. // Create 1000 boxes in the terrain. Always face outward along the terrain normal
  71. const uint NUM_OBJECTS = 1000;
  72. for (uint i = 0; i < NUM_OBJECTS; ++i)
  73. {
  74. Node@ objectNode = scene_.CreateChild("Box");
  75. Vector3 position(Random(2000.0f) - 1000.0f, 0.0f, Random(2000.0f) - 1000.0f);
  76. position.y = terrain.GetHeight(position) + 2.25f;
  77. objectNode.position = position;
  78. // Create a rotation quaternion from up vector to terrain normal
  79. objectNode.rotation = Quaternion(Vector3(0.0f, 1.0f, 0.0f), terrain.GetNormal(position));
  80. objectNode.SetScale(5.0f);
  81. StaticModel@ object = objectNode.CreateComponent("StaticModel");
  82. object.model = cache.GetResource("Model", "Models/Box.mdl");
  83. object.material = cache.GetResource("Material", "Materials/Stone.xml");
  84. object.castShadows = true;
  85. }
  86. // Create a water plane object that is as large as the terrain
  87. waterNode = scene_.CreateChild("Water");
  88. waterNode.scale = Vector3(2048.0f, 1.0f, 2048.0f);
  89. waterNode.position = Vector3(0.0f, 5.0f, 0.0f);
  90. StaticModel@ water = waterNode.CreateComponent("StaticModel");
  91. water.model = cache.GetResource("Model", "Models/Plane.mdl");
  92. water.material = cache.GetResource("Material", "Materials/Water.xml");
  93. // Set a different viewmask on the water plane to be able to hide it from the reflection camera
  94. water.viewMask = 0x80000000;
  95. // Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
  96. // the scene, because we want it to be unaffected by scene load / save
  97. cameraNode = Node();
  98. Camera@ camera = cameraNode.CreateComponent("Camera");
  99. camera.farClip = 750.0f;
  100. // Set an initial position for the camera scene node above the ground
  101. cameraNode.position = Vector3(0.0f, 7.0f, -20.0f);
  102. }
  103. void CreateInstructions()
  104. {
  105. // Construct new Text object, set string to display and font to use
  106. Text@ instructionText = ui.root.CreateChild("Text");
  107. instructionText.text = "Use WASD keys and mouse to move";
  108. instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
  109. instructionText.textAlignment = HA_CENTER;
  110. // Position the text relative to the screen center
  111. instructionText.horizontalAlignment = HA_CENTER;
  112. instructionText.verticalAlignment = VA_CENTER;
  113. instructionText.SetPosition(0, ui.root.height / 4);
  114. }
  115. void SetupViewports()
  116. {
  117. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  118. Viewport@ viewport = Viewport(scene_, cameraNode.GetComponent("Camera"));
  119. renderer.viewports[0] = viewport;
  120. // Create a mathematical plane to represent the water in calculations
  121. waterPlane = Plane(waterNode.worldRotation * Vector3(0.0f, 1.0f, 0.0f), waterNode.worldPosition);
  122. // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
  123. waterClipPlane = Plane(waterNode.worldRotation * Vector3(0.0f, 1.0f, 0.0f), waterNode.worldPosition -
  124. Vector3(0.0f, 0.1f, 0.0f));
  125. // Create camera for water reflection
  126. // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
  127. // its position when rendering
  128. reflectionCameraNode = cameraNode.CreateChild();
  129. Camera@ reflectionCamera = reflectionCameraNode.CreateComponent("Camera");
  130. reflectionCamera.farClip = 750.0;
  131. reflectionCamera.viewMask = 0x7fffffff; // Hide objects with only bit 31 in the viewmask (the water plane)
  132. reflectionCamera.autoAspectRatio = false;
  133. reflectionCamera.useReflection = true;
  134. reflectionCamera.reflectionPlane = waterPlane;
  135. reflectionCamera.useClipping = true; // Enable clipping of geometry behind water plane
  136. reflectionCamera.clipPlane = waterClipPlane;
  137. // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
  138. reflectionCamera.aspectRatio = float(graphics.width) / float(graphics.height);
  139. // View override flags could be used to optimize reflection rendering. For example disable shadows
  140. //reflectionCamera.viewOverrideFlags = VO_DISABLE_SHADOWS;
  141. // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
  142. // texture unit of the water material
  143. int texSize = 1024;
  144. Texture2D@ renderTexture = Texture2D();
  145. renderTexture.SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  146. renderTexture.filterMode = FILTER_BILINEAR;
  147. RenderSurface@ surface = renderTexture.renderSurface;
  148. Viewport@ rttViewport = Viewport(scene_, reflectionCamera);
  149. surface.viewports[0] = rttViewport;
  150. Material@ waterMat = cache.GetResource("Material", "Materials/Water.xml");
  151. waterMat.textures[TU_DIFFUSE] = renderTexture;
  152. }
  153. void SubscribeToEvents()
  154. {
  155. // Subscribe HandleUpdate() function for processing update events
  156. SubscribeToEvent("Update", "HandleUpdate");
  157. }
  158. void MoveCamera(float timeStep)
  159. {
  160. // Do not move if the UI has a focused element (the console)
  161. if (ui.focusElement !is null)
  162. return;
  163. // Movement speed as world units per second
  164. const float MOVE_SPEED = 30.0;
  165. // Mouse sensitivity as degrees per pixel
  166. const float MOUSE_SENSITIVITY = 0.1;
  167. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  168. IntVector2 mouseMove = input.mouseMove;
  169. yaw += MOUSE_SENSITIVITY * mouseMove.x;
  170. pitch += MOUSE_SENSITIVITY * mouseMove.y;
  171. pitch = Clamp(pitch, -90.0, 90.0);
  172. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  173. cameraNode.rotation = Quaternion(pitch, yaw, 0.0);
  174. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  175. if (input.keyDown[KEY_W])
  176. cameraNode.Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  177. if (input.keyDown[KEY_S])
  178. cameraNode.Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  179. if (input.keyDown[KEY_A])
  180. cameraNode.Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  181. if (input.keyDown[KEY_D])
  182. cameraNode.Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  183. // In case resolution has changed, adjust the reflection camera aspect ratio
  184. Camera@ reflectionCamera = reflectionCameraNode.GetComponent("Camera");
  185. reflectionCamera.aspectRatio = float(graphics.width) / float(graphics.height);
  186. }
  187. void HandleUpdate(StringHash eventType, VariantMap& eventData)
  188. {
  189. // Take the frame time step, which is stored as a float
  190. float timeStep = eventData["TimeStep"].GetFloat();
  191. // Move the camera, scale movement with time step
  192. MoveCamera(timeStep);
  193. }
  194. // Create XML patch instructions for screen joystick layout specific to this sample app
  195. String patchInstructions = "";