RenderToTexture.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // Copyright (c) 2008-2021 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Material.h>
  27. #include <Urho3D/Graphics/Model.h>
  28. #include <Urho3D/Graphics/Octree.h>
  29. #include <Urho3D/Graphics/Renderer.h>
  30. #include <Urho3D/Graphics/RenderSurface.h>
  31. #include <Urho3D/Graphics/StaticModel.h>
  32. #include <Urho3D/Graphics/Technique.h>
  33. #include <Urho3D/Graphics/Texture2D.h>
  34. #include <Urho3D/Graphics/Zone.h>
  35. #include <Urho3D/Input/Input.h>
  36. #include <Urho3D/Resource/ResourceCache.h>
  37. #include <Urho3D/Scene/Scene.h>
  38. #include <Urho3D/UI/Font.h>
  39. #include <Urho3D/UI/Text.h>
  40. #include <Urho3D/UI/UI.h>
  41. #include "RenderToTexture.h"
  42. #include "Rotator.h"
  43. #include <Urho3D/DebugNew.h>
  44. URHO3D_DEFINE_APPLICATION_MAIN(RenderToTexture)
  45. RenderToTexture::RenderToTexture(Context* context) :
  46. Sample(context)
  47. {
  48. // Register an object factory for our custom Rotator component so that we can create them to scene nodes
  49. context->RegisterFactory<Rotator>();
  50. }
  51. void RenderToTexture::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update events
  62. SubscribeToEvents();
  63. // Set the mouse mode to use in the sample
  64. Sample::InitMouseMode(MM_RELATIVE);
  65. }
  66. void RenderToTexture::CreateScene()
  67. {
  68. auto* cache = GetSubsystem<ResourceCache>();
  69. {
  70. // Create the scene which will be rendered to a texture
  71. rttScene_ = new Scene(context_);
  72. // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  73. rttScene_->CreateComponent<Octree>();
  74. // Create a Zone for ambient light & fog control
  75. Node* zoneNode = rttScene_->CreateChild("Zone");
  76. auto* zone = zoneNode->CreateComponent<Zone>();
  77. // Set same volume as the Octree, set a close bluish fog and some ambient light
  78. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  79. zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
  80. zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
  81. zone->SetFogStart(10.0f);
  82. zone->SetFogEnd(100.0f);
  83. // Create randomly positioned and oriented box StaticModels in the scene
  84. const unsigned NUM_OBJECTS = 2000;
  85. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  86. {
  87. Node* boxNode = rttScene_->CreateChild("Box");
  88. boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
  89. // Orient using random pitch, yaw and roll Euler angles
  90. boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  91. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  92. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  93. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  94. // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event.
  95. // Simply set same rotation speed for all objects
  96. auto* rotator = boxNode->CreateComponent<Rotator>();
  97. rotator->SetRotationSpeed(Vector3(10.0f, 20.0f, 30.0f));
  98. }
  99. // Create a camera for the render-to-texture scene. Simply leave it at the world origin and let it observe the scene
  100. rttCameraNode_ = rttScene_->CreateChild("Camera");
  101. auto* camera = rttCameraNode_->CreateComponent<Camera>();
  102. camera->SetFarClip(100.0f);
  103. // Create a point light to the camera scene node
  104. auto* light = rttCameraNode_->CreateComponent<Light>();
  105. light->SetLightType(LIGHT_POINT);
  106. light->SetRange(30.0f);
  107. }
  108. {
  109. // Create the scene in which we move around
  110. scene_ = new Scene(context_);
  111. // Create octree, use also default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
  112. scene_->CreateComponent<Octree>();
  113. // Create a Zone component for ambient lighting & fog control
  114. Node* zoneNode = scene_->CreateChild("Zone");
  115. auto* zone = zoneNode->CreateComponent<Zone>();
  116. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  117. zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
  118. zone->SetFogStart(100.0f);
  119. zone->SetFogEnd(300.0f);
  120. // Create a directional light without shadows
  121. Node* lightNode = scene_->CreateChild("DirectionalLight");
  122. lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
  123. auto* light = lightNode->CreateComponent<Light>();
  124. light->SetLightType(LIGHT_DIRECTIONAL);
  125. light->SetColor(Color(0.2f, 0.2f, 0.2f));
  126. light->SetSpecularIntensity(1.0f);
  127. // Create a "floor" consisting of several tiles
  128. for (int y = -5; y <= 5; ++y)
  129. {
  130. for (int x = -5; x <= 5; ++x)
  131. {
  132. Node* floorNode = scene_->CreateChild("FloorTile");
  133. floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  134. floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
  135. auto* floorObject = floorNode->CreateComponent<StaticModel>();
  136. floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  137. floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  138. }
  139. }
  140. // Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the frame
  141. // and a plane for the actual view
  142. {
  143. Node* boxNode = scene_->CreateChild("ScreenBox");
  144. boxNode->SetPosition(Vector3(0.0f, 10.0f, 0.0f));
  145. boxNode->SetScale(Vector3(21.0f, 16.0f, 0.5f));
  146. auto* boxObject = boxNode->CreateComponent<StaticModel>();
  147. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  148. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  149. Node* screenNode = scene_->CreateChild("Screen");
  150. screenNode->SetPosition(Vector3(0.0f, 10.0f, -0.27f));
  151. screenNode->SetRotation(Quaternion(-90.0f, 0.0f, 0.0f));
  152. screenNode->SetScale(Vector3(20.0f, 0.0f, 15.0f));
  153. auto* screenObject = screenNode->CreateComponent<StaticModel>();
  154. screenObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
  155. // Create a renderable texture (1024x768, RGB format), enable bilinear filtering on it
  156. SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
  157. renderTexture->SetSize(1024, 768, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
  158. renderTexture->SetFilterMode(FILTER_BILINEAR);
  159. // Create a new material from scratch, use the diffuse unlit technique, assign the render texture
  160. // as its diffuse texture, then assign the material to the screen plane object
  161. SharedPtr<Material> renderMaterial(new Material(context_));
  162. renderMaterial->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffUnlit.xml"));
  163. renderMaterial->SetTexture(TU_DIFFUSE, renderTexture);
  164. // Since the screen material is on top of the box model and may Z-fight, use negative depth bias
  165. // to push it forward (particularly necessary on mobiles with possibly less Z resolution)
  166. renderMaterial->SetDepthBias(BiasParameters(-0.001f, 0.0f));
  167. screenObject->SetMaterial(renderMaterial);
  168. // Get the texture's RenderSurface object (exists when the texture has been created in rendertarget mode)
  169. // and define the viewport for rendering the second scene, similarly as how backbuffer viewports are defined
  170. // to the Renderer subsystem. By default the texture viewport will be updated when the texture is visible
  171. // in the main view
  172. RenderSurface* surface = renderTexture->GetRenderSurface();
  173. SharedPtr<Viewport> rttViewport(new Viewport(context_, rttScene_, rttCameraNode_->GetComponent<Camera>()));
  174. surface->SetViewport(0, rttViewport);
  175. }
  176. // Create the camera which we will move around. Limit far clip distance to match the fog
  177. cameraNode_ = scene_->CreateChild("Camera");
  178. auto* camera = cameraNode_->CreateComponent<Camera>();
  179. camera->SetFarClip(300.0f);
  180. // Set an initial position for the camera scene node above the plane
  181. cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -30.0f));
  182. }
  183. }
  184. void RenderToTexture::CreateInstructions()
  185. {
  186. auto* cache = GetSubsystem<ResourceCache>();
  187. auto* ui = GetSubsystem<UI>();
  188. // Construct new Text object, set string to display and font to use
  189. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  190. instructionText->SetText("Use WASD keys and mouse/touch to move");
  191. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  192. // Position the text relative to the screen center
  193. instructionText->SetHorizontalAlignment(HA_CENTER);
  194. instructionText->SetVerticalAlignment(VA_CENTER);
  195. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  196. }
  197. void RenderToTexture::SetupViewport()
  198. {
  199. auto* renderer = GetSubsystem<Renderer>();
  200. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  201. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  202. renderer->SetViewport(0, viewport);
  203. }
  204. void RenderToTexture::MoveCamera(float timeStep)
  205. {
  206. // Do not move if the UI has a focused element (the console)
  207. if (GetSubsystem<UI>()->GetFocusElement())
  208. return;
  209. auto* input = GetSubsystem<Input>();
  210. // Movement speed as world units per second
  211. const float MOVE_SPEED = 20.0f;
  212. // Mouse sensitivity as degrees per pixel
  213. const float MOUSE_SENSITIVITY = 0.1f;
  214. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  215. IntVector2 mouseMove = input->GetMouseMove();
  216. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  217. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  218. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  219. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  220. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  221. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  222. if (input->GetKeyDown(KEY_W))
  223. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  224. if (input->GetKeyDown(KEY_S))
  225. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  226. if (input->GetKeyDown(KEY_A))
  227. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  228. if (input->GetKeyDown(KEY_D))
  229. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  230. }
  231. void RenderToTexture::SubscribeToEvents()
  232. {
  233. // Subscribe HandleUpdate() function for processing update events
  234. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(RenderToTexture, HandleUpdate));
  235. }
  236. void RenderToTexture::HandleUpdate(StringHash eventType, VariantMap& eventData)
  237. {
  238. using namespace Update;
  239. // Take the frame time step, which is stored as a float
  240. float timeStep = eventData[P_TIMESTEP].GetFloat();
  241. // Move the camera, scale movement with time step
  242. MoveCamera(timeStep);
  243. }