SceneView3D.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // Portions Copyright (c) 2008-2015 the Urho3D project.
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. // Please see LICENSE.md in repository root for license information
  4. // https://github.com/AtomicGameEngine/AtomicGameEngine
  5. #include "AtomicEditor.h"
  6. #include <Atomic/IO/Log.h>
  7. #include <Atomic/Core/CoreEvents.h>
  8. #include <Atomic/Scene/Scene.h>
  9. #include <Atomic/Graphics/Camera.h>
  10. #include <Atomic/Graphics/Graphics.h>
  11. #include <Atomic/Graphics/DebugRenderer.h>
  12. #include <Atomic/Graphics/Viewport.h>
  13. #include <Atomic/Graphics/Octree.h>
  14. #include <Atomic/Graphics/Material.h>
  15. #include <Atomic/Atomic3D/Terrain.h>
  16. #include <Atomic/Atomic3D/Model.h>
  17. #include <Atomic/Input/Input.h>
  18. #include <Atomic/IO/FileSystem.h>
  19. #include <Atomic/Resource/ResourceCache.h>
  20. #include <Atomic/Physics/PhysicsWorld.h>
  21. #include <Atomic/UI/UI.h>
  22. #include <Atomic/UI/UIEvents.h>
  23. #include <ToolCore/Assets/Asset.h>
  24. #include <ToolCore/Assets/AssetDatabase.h>
  25. #include "AEEditor.h"
  26. #include "AEEvents.h"
  27. #include "SceneView3D.h"
  28. #include "SceneEditor3D.h"
  29. using namespace ToolCore;
  30. namespace AtomicEditor
  31. {
  32. SceneView3D ::SceneView3D(Context* context, SceneEditor3D *sceneEditor) :
  33. UISceneView(context),
  34. yaw_(0.0f),
  35. pitch_(0.0f),
  36. mouseLeftDown_(false),
  37. mouseMoved_(false),
  38. enabled_(true)
  39. {
  40. sceneEditor_ = sceneEditor;
  41. ResourceCache* cache = GetSubsystem<ResourceCache>();
  42. scene_ = sceneEditor->GetScene();
  43. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  44. if (debugRenderer_.Null())
  45. {
  46. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  47. }
  48. octree_ = scene_->GetComponent<Octree>();
  49. if (octree_.Null())
  50. {
  51. LOGWARNING("Scene without an octree loaded");
  52. octree_ = scene_->CreateComponent<Octree>();
  53. }
  54. cameraNode_ = scene_->CreateChild("Camera");
  55. cameraNode_->SetTemporary(true);
  56. camera_ = cameraNode_->CreateComponent<Camera>();
  57. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  58. assert(debugRenderer_.NotNull());
  59. octree_ = scene_->GetComponent<Octree>();
  60. assert(octree_.NotNull());
  61. cameraNode_->SetPosition(Vector3(0, 0, -10));
  62. SetView(scene_, camera_);
  63. SetAutoUpdate(false);
  64. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  65. SubscribeToEvent(E_EDITORACTIVENODECHANGE, HANDLER(SceneView3D, HandleEditorActiveNodeChange));
  66. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  67. SubscribeToEvent(E_DRAGENDED, HANDLER(SceneView3D, HandleDragEnded));
  68. // TODO: generate this event properly
  69. VariantMap eventData;
  70. eventData[EditorActiveSceneChange::P_SCENE] = scene_;
  71. SendEvent(E_EDITORACTIVESCENECHANGE, eventData);
  72. SetIsFocusable(true);
  73. }
  74. SceneView3D::~SceneView3D()
  75. {
  76. }
  77. void SceneView3D::Enable()
  78. {
  79. if (enabled_)
  80. return;
  81. enabled_ = true;
  82. SetVisibility(UI_WIDGET_VISIBILITY_VISIBLE);
  83. }
  84. void SceneView3D::Disable()
  85. {
  86. if (!enabled_)
  87. return;
  88. enabled_ = false;
  89. SetVisibility(UI_WIDGET_VISIBILITY_INVISIBLE);
  90. }
  91. void SceneView3D::MoveCamera(float timeStep)
  92. {
  93. if (!enabled_)
  94. return;
  95. Input* input = GetSubsystem<Input>();
  96. // Movement speed as world units per second
  97. float MOVE_SPEED = 20.0f;
  98. // Mouse sensitivity as degrees per pixel
  99. const float MOUSE_SENSITIVITY = 0.2f;
  100. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  101. MOVE_SPEED *= 3.0f;
  102. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  103. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  104. {
  105. IntVector2 mouseMove = input->GetMouseMove();
  106. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  107. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  108. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  109. // Not working on OSX
  110. //input->SetMouseMode(MM_RELATIVE);
  111. }
  112. else
  113. {
  114. // Not working on OSX
  115. /*
  116. if (input->GetMouseMode() != MM_ABSOLUTE)
  117. input->SetMouseMode(MM_ABSOLUTE);
  118. */
  119. }
  120. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  121. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  122. //Vector3 pos = cameraNode_->GetWorldPosition();
  123. //Quaternion q = cameraNode_->GetWorldRotation();
  124. //LOGINFOF("%f %f %f : %f %f %f %f", pos.x_, pos.y_, pos.z_, q.x_, q.y_, q.z_, q.w_ );
  125. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  126. // Use the Translate() function (default local space) to move relative to the node's orientation.
  127. if (input->GetKeyDown('W'))
  128. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  129. if (input->GetKeyDown('S'))
  130. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  131. if (input->GetKeyDown('A'))
  132. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  133. if (input->GetKeyDown('D'))
  134. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  135. }
  136. Ray SceneView3D::GetCameraRay()
  137. {
  138. Ray camRay;
  139. Input* input = GetSubsystem<Input>();
  140. IntVector2 cpos = input->GetMousePosition();
  141. IntRect rect = GetRect();
  142. if (!rect.Width() || !rect.Height())
  143. return camRay;
  144. int x = rect.left_;
  145. int y = rect.top_;
  146. GetInternalWidget()->ConvertToRoot(x, y);
  147. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  148. float(cpos.y_ - y) / rect.Height());
  149. }
  150. void SceneView3D::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode)
  151. {
  152. if (drawNode)
  153. debug->AddNode(node, 1.0, false);
  154. // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem-
  155. // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount
  156. // (TerrainPatch component itself draws nothing as debug geometry)
  157. if (node != scene_ && !node->GetComponent<Terrain>())
  158. {
  159. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  160. for (unsigned j = 0; j < components.Size(); ++j)
  161. components[j]->DrawDebugGeometry(debug, false);
  162. // To avoid cluttering the view, do not draw the node axes for child nodes
  163. for (unsigned k = 0; k < node->GetNumChildren(); ++k)
  164. DrawNodeDebug(node->GetChild(k), debug, false);
  165. }
  166. }
  167. bool SceneView3D::MouseInView()
  168. {
  169. Input* input = GetSubsystem<Input>();
  170. IntVector2 pos = input->GetMousePosition();
  171. IntRect rect = GetRect();
  172. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  173. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  174. return rect.IsInside(pos);
  175. }
  176. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  177. {
  178. // Visualize the currently selected nodes
  179. if (selectedNode_.NotNull())
  180. {
  181. DrawNodeDebug(selectedNode_, debugRenderer_);
  182. }
  183. if (!MouseInView())
  184. return;
  185. Input* input = GetSubsystem<Input>();
  186. mouseLeftDown_ = false;
  187. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  188. {
  189. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  190. {
  191. Ray camRay = GetCameraRay();
  192. PODVector<RayQueryResult> result;
  193. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  194. octree_->RaycastSingle(query);
  195. if (query.result_.Size())
  196. {
  197. const RayQueryResult& r = result[0];
  198. if (r.drawable_)
  199. {
  200. VariantMap neventData;
  201. neventData[EditorActiveNodeChange::P_NODE] = r.drawable_->GetNode();
  202. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  203. }
  204. }
  205. }
  206. mouseMoved_ = false;
  207. }
  208. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  209. {
  210. Ray camRay = GetCameraRay();
  211. PODVector<RayQueryResult> result;
  212. mouseMoved_ = false;
  213. /*
  214. Array<int> pickModeDrawableFlags = {
  215. DRAWABLE_GEOMETRY,
  216. DRAWABLE_LIGHT,
  217. DRAWABLE_ZONE
  218. };
  219. */
  220. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  221. octree_->RaycastSingle(query);
  222. if (query.result_.Size())
  223. {
  224. const RayQueryResult& r = result[0];
  225. if (r.drawable_)
  226. {
  227. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  228. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  229. }
  230. }
  231. }
  232. else
  233. {
  234. mouseLeftDown_ = true;
  235. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  236. {
  237. mouseMoved_ = true;
  238. }
  239. }
  240. }
  241. void SceneView3D::SelectNode(Node* node)
  242. {
  243. selectedNode_ = node;
  244. }
  245. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  246. {
  247. return sceneEditor_->OnEvent(ev);
  248. }
  249. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  250. {
  251. // Timestep parameter is same no matter what event is being listened to
  252. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  253. if (MouseInView())
  254. MoveCamera(timeStep);
  255. QueueUpdate();
  256. }
  257. void SceneView3D::HandleEditorActiveNodeChange(StringHash eventType, VariantMap& eventData)
  258. {
  259. Node* node = (Node*) (eventData[EditorActiveNodeChange::P_NODE].GetPtr());
  260. SelectNode(node);
  261. }
  262. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  263. {
  264. using namespace DragEnded;
  265. UIWidget* widget = static_cast<UIWidget*>(eventData[P_TARGET].GetPtr());
  266. if (widget != this)
  267. return;
  268. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  269. Object* object = dragObject->GetObject();
  270. if (object->GetType() == Asset::GetTypeStatic())
  271. {
  272. Asset* asset = (Asset*) object;
  273. ResourceCache* cache = GetSubsystem<ResourceCache>();
  274. Model* model = cache->GetResource<Model>(asset->GetGUID());
  275. Node* node = scene_->CreateChild(asset->GetName());
  276. StaticModel* mc = node->CreateComponent<StaticModel>();
  277. mc->SetModel(model);
  278. Material* material1 = cache->GetResource<Material>("Materials/AlphaMaterial.xml");
  279. Material* material2 = cache->GetResource<Material>("Materials/BedMaterial.xml");
  280. if (mc->GetNumGeometries() > 1)
  281. {
  282. mc->SetMaterial(0, material1);
  283. mc->SetMaterial(1, material2);
  284. }
  285. else
  286. {
  287. mc->SetMaterial(0, material2);
  288. }
  289. LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  290. }
  291. }
  292. }