PBRMaterials.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #include <Urho3D/Core/CoreEvents.h>
  4. #include <Urho3D/Engine/Engine.h>
  5. #include <Urho3D/Graphics/Camera.h>
  6. #include <Urho3D/Graphics/Graphics.h>
  7. #include <Urho3D/Graphics/RenderPath.h>
  8. #include <Urho3D/Graphics/StaticModel.h>
  9. #include <Urho3D/Graphics/Zone.h>
  10. #include <Urho3D/Input/Input.h>
  11. #include <Urho3D/Resource/ResourceCache.h>
  12. #include <Urho3D/Scene/Scene.h>
  13. #include <Urho3D/UI/Button.h>
  14. #include <Urho3D/UI/Font.h>
  15. #include <Urho3D/UI/Slider.h>
  16. #include <Urho3D/UI/UI.h>
  17. #include <Urho3D/UI/UIEvents.h>
  18. #include <Urho3D/UI/Text.h>
  19. #ifdef URHO3D_ANGELSCRIPT
  20. #include <Urho3D/AngelScript/Script.h>
  21. #endif
  22. #include "PBRMaterials.h"
  23. #include <Urho3D/DebugNew.h>
  24. URHO3D_DEFINE_APPLICATION_MAIN(PBRMaterials)
  25. PBRMaterials::PBRMaterials(Context* context) :
  26. Sample(context),
  27. dynamicMaterial_(nullptr),
  28. roughnessLabel_(nullptr),
  29. metallicLabel_(nullptr),
  30. ambientLabel_(nullptr)
  31. {
  32. }
  33. void PBRMaterials::Start()
  34. {
  35. // Execute base class startup
  36. Sample::Start();
  37. // Create the scene content
  38. CreateScene();
  39. // Create the UI content
  40. CreateUI();
  41. CreateInstructions();
  42. // Setup the viewport for displaying the scene
  43. SetupViewport();
  44. // Subscribe to global events for camera movement
  45. SubscribeToEvents();
  46. }
  47. void PBRMaterials::CreateInstructions()
  48. {
  49. auto* cache = GetSubsystem<ResourceCache>();
  50. auto* ui = GetSubsystem<UI>();
  51. // Construct new Text object, set string to display and font to use
  52. auto* instructionText = ui->GetRoot()->CreateChild<Text>();
  53. instructionText->SetText("Use sliders to change Roughness and Metallic\n"
  54. "Hold RMB and use WASD keys and mouse to move");
  55. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  56. instructionText->SetTextAlignment(HA_CENTER);
  57. // Position the text relative to the screen center
  58. instructionText->SetHorizontalAlignment(HA_CENTER);
  59. instructionText->SetVerticalAlignment(VA_CENTER);
  60. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  61. }
  62. void PBRMaterials::CreateScene()
  63. {
  64. auto* cache = GetSubsystem<ResourceCache>();
  65. #ifdef URHO3D_ANGELSCRIPT
  66. // The scene uses an AngelScript component for animation. Instantiate the subsystem if possible
  67. context_->RegisterSubsystem(new Script(context_));
  68. #endif
  69. scene_ = new Scene(context_);
  70. // Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system
  71. // which scene.LoadXML() will read
  72. SharedPtr<File> file = cache->GetFile("Scenes/PBRExample.xml");
  73. scene_->LoadXML(*file);
  74. Node* sphereWithDynamicMatNode = scene_->GetChild("SphereWithDynamicMat");
  75. auto* staticModel = sphereWithDynamicMatNode->GetComponent<StaticModel>();
  76. dynamicMaterial_ = staticModel->GetMaterial(0);
  77. Node* zoneNode = scene_->GetChild("Zone");
  78. zone_ = zoneNode->GetComponent<Zone>();
  79. // Create the camera (not included in the scene file)
  80. cameraNode_ = scene_->CreateChild("Camera");
  81. cameraNode_->CreateComponent<Camera>();
  82. cameraNode_->SetPosition(sphereWithDynamicMatNode->GetPosition() + Vector3(2.0f, 2.0f, 2.0f));
  83. cameraNode_->LookAt(sphereWithDynamicMatNode->GetPosition());
  84. yaw_ = cameraNode_->GetRotation().YawAngle();
  85. pitch_ = cameraNode_->GetRotation().PitchAngle();
  86. }
  87. void PBRMaterials::CreateUI()
  88. {
  89. auto* cache = GetSubsystem<ResourceCache>();
  90. auto* ui = GetSubsystem<UI>();
  91. // Set up global UI style into the root UI element
  92. auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml");
  93. ui->GetRoot()->SetDefaultStyle(style);
  94. // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
  95. // control the camera, and when visible, it will interact with the UI
  96. SharedPtr<Cursor> cursor(new Cursor(context_));
  97. cursor->SetStyleAuto();
  98. ui->SetCursor(cursor);
  99. // Set starting position of the cursor at the rendering window center
  100. auto* graphics = GetSubsystem<Graphics>();
  101. cursor->SetPosition(graphics->GetWidth() / 2, graphics->GetHeight() / 2);
  102. roughnessLabel_ = ui->GetRoot()->CreateChild<Text>();
  103. roughnessLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  104. roughnessLabel_->SetPosition(370, 50);
  105. roughnessLabel_->SetTextEffect(TE_SHADOW);
  106. metallicLabel_ = ui->GetRoot()->CreateChild<Text>();
  107. metallicLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  108. metallicLabel_->SetPosition(370, 100);
  109. metallicLabel_->SetTextEffect(TE_SHADOW);
  110. ambientLabel_ = ui->GetRoot()->CreateChild<Text>();
  111. ambientLabel_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  112. ambientLabel_->SetPosition(370, 150);
  113. ambientLabel_->SetTextEffect(TE_SHADOW);
  114. auto* roughnessSlider = ui->GetRoot()->CreateChild<Slider>();
  115. roughnessSlider->SetStyleAuto();
  116. roughnessSlider->SetPosition(50, 50);
  117. roughnessSlider->SetSize(300, 20);
  118. roughnessSlider->SetRange(1.0f); // 0 - 1 range
  119. SubscribeToEvent(roughnessSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleRoughnessSliderChanged));
  120. roughnessSlider->SetValue(0.5f);
  121. auto* metallicSlider = ui->GetRoot()->CreateChild<Slider>();
  122. metallicSlider->SetStyleAuto();
  123. metallicSlider->SetPosition(50, 100);
  124. metallicSlider->SetSize(300, 20);
  125. metallicSlider->SetRange(1.0f); // 0 - 1 range
  126. SubscribeToEvent(metallicSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleMetallicSliderChanged));
  127. metallicSlider->SetValue(0.5f);
  128. auto* ambientSlider = ui->GetRoot()->CreateChild<Slider>();
  129. ambientSlider->SetStyleAuto();
  130. ambientSlider->SetPosition(50, 150);
  131. ambientSlider->SetSize(300, 20);
  132. ambientSlider->SetRange(10.0f); // 0 - 10 range
  133. SubscribeToEvent(ambientSlider, E_SLIDERCHANGED, URHO3D_HANDLER(PBRMaterials, HandleAmbientSliderChanged));
  134. ambientSlider->SetValue(zone_->GetAmbientColor().a_);
  135. }
  136. void PBRMaterials::HandleRoughnessSliderChanged(StringHash eventType, VariantMap& eventData)
  137. {
  138. float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
  139. dynamicMaterial_->SetShaderParameter("Roughness", newValue);
  140. roughnessLabel_->SetText("Roughness: " + String(newValue));
  141. }
  142. void PBRMaterials::HandleMetallicSliderChanged(StringHash eventType, VariantMap& eventData)
  143. {
  144. float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
  145. dynamicMaterial_->SetShaderParameter("Metallic", newValue);
  146. metallicLabel_->SetText("Metallic: " + String(newValue));
  147. }
  148. void PBRMaterials::HandleAmbientSliderChanged(StringHash eventType, VariantMap& eventData)
  149. {
  150. float newValue = eventData[SliderChanged::P_VALUE].GetFloat();
  151. Color col = Color(0.0, 0.0, 0.0, newValue);
  152. zone_->SetAmbientColor(col);
  153. ambientLabel_->SetText("Ambient HDR Scale: " + String(zone_->GetAmbientColor().a_));
  154. }
  155. void PBRMaterials::SetupViewport()
  156. {
  157. auto* cache = GetSubsystem<ResourceCache>();
  158. auto* renderer = GetSubsystem<Renderer>();
  159. renderer->SetHDRRendering(true);
  160. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  161. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  162. renderer->SetViewport(0, viewport);
  163. // Add post-processing effects appropriate with the example scene
  164. SharedPtr<RenderPath> effectRenderPath = viewport->GetRenderPath()->Clone();
  165. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));
  166. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/GammaCorrection.xml"));
  167. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/Tonemap.xml"));
  168. effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml"));
  169. viewport->SetRenderPath(effectRenderPath);
  170. }
  171. void PBRMaterials::SubscribeToEvents()
  172. {
  173. // Subscribe HandleUpdate() function for camera motion
  174. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(PBRMaterials, HandleUpdate));
  175. }
  176. void PBRMaterials::MoveCamera(float timeStep)
  177. {
  178. // Right mouse button controls mouse cursor visibility: hide when pressed
  179. auto* ui = GetSubsystem<UI>();
  180. auto* input = GetSubsystem<Input>();
  181. ui->GetCursor()->SetVisible(!input->GetMouseButtonDown(MOUSEB_RIGHT));
  182. // Do not move if the UI has a focused element
  183. if (ui->GetFocusElement())
  184. return;
  185. // Movement speed as world units per second
  186. const float MOVE_SPEED = 10.0f;
  187. // Mouse sensitivity as degrees per pixel
  188. const float MOUSE_SENSITIVITY = 0.1f;
  189. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  190. // Only move the camera when the cursor is hidden
  191. if (!ui->GetCursor()->IsVisible())
  192. {
  193. IntVector2 mouseMove = input->GetMouseMove();
  194. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  195. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  196. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  197. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  198. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  199. }
  200. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  201. if (input->GetKeyDown(KEY_W))
  202. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  203. if (input->GetKeyDown(KEY_S))
  204. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  205. if (input->GetKeyDown(KEY_A))
  206. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  207. if (input->GetKeyDown(KEY_D))
  208. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  209. }
  210. void PBRMaterials::HandleUpdate(StringHash eventType, VariantMap& eventData)
  211. {
  212. using namespace Update;
  213. // Take the frame time step, which is stored as a float
  214. float timeStep = eventData[P_TIMESTEP].GetFloat();
  215. // Move the camera, scale movement with time step
  216. MoveCamera(timeStep);
  217. }