SceneView3D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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/Resource/XMLFile.h>
  21. #include <Atomic/Physics/PhysicsWorld.h>
  22. #include <Atomic/UI/UI.h>
  23. #include <Atomic/UI/UIEvents.h>
  24. #include <Atomic/Resource/ResourceEvents.h>
  25. #include <ToolCore/Assets/Asset.h>
  26. #include <ToolCore/Assets/AssetDatabase.h>
  27. #include "AEEditor.h"
  28. #include "AEEvents.h"
  29. #include "SceneView3D.h"
  30. #include "SceneEditor3D.h"
  31. using namespace ToolCore;
  32. namespace AtomicEditor
  33. {
  34. SceneView3D ::SceneView3D(Context* context, SceneEditor3D *sceneEditor) :
  35. UISceneView(context),
  36. yaw_(0.0f),
  37. pitch_(0.0f),
  38. mouseLeftDown_(false),
  39. mouseMoved_(false),
  40. enabled_(true)
  41. {
  42. sceneEditor_ = sceneEditor;
  43. ResourceCache* cache = GetSubsystem<ResourceCache>();
  44. scene_ = sceneEditor->GetScene();
  45. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  46. if (debugRenderer_.Null())
  47. {
  48. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  49. }
  50. octree_ = scene_->GetComponent<Octree>();
  51. if (octree_.Null())
  52. {
  53. LOGWARNING("Scene without an octree loaded");
  54. octree_ = scene_->CreateComponent<Octree>();
  55. }
  56. cameraNode_ = scene_->CreateChild("Camera");
  57. cameraNode_->SetTemporary(true);
  58. camera_ = cameraNode_->CreateComponent<Camera>();
  59. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  60. assert(debugRenderer_.NotNull());
  61. octree_ = scene_->GetComponent<Octree>();
  62. assert(octree_.NotNull());
  63. cameraNode_->SetPosition(Vector3(0, 0, -10));
  64. SetView(scene_, camera_);
  65. SetAutoUpdate(false);
  66. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  67. SubscribeToEvent(E_EDITORACTIVENODECHANGE, HANDLER(SceneView3D, HandleEditorActiveNodeChange));
  68. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  69. SubscribeToEvent(E_MOUSEMOVE, HANDLER(SceneView3D,HandleMouseMove));
  70. SubscribeToEvent(E_DRAGENTERWIDGET, HANDLER(SceneView3D, HandleDragEnterWidget));
  71. SubscribeToEvent(E_DRAGEXITWIDGET, HANDLER(SceneView3D, HandleDragExitWidget));
  72. SubscribeToEvent(E_DRAGENDED, HANDLER(SceneView3D, HandleDragEnded));
  73. // TODO: generate this event properly
  74. VariantMap eventData;
  75. eventData[EditorActiveSceneChange::P_SCENE] = scene_;
  76. SendEvent(E_EDITORACTIVESCENECHANGE, eventData);
  77. SetIsFocusable(true);
  78. }
  79. SceneView3D::~SceneView3D()
  80. {
  81. }
  82. void SceneView3D::Enable()
  83. {
  84. if (enabled_)
  85. return;
  86. enabled_ = true;
  87. SetVisibility(UI_WIDGET_VISIBILITY_VISIBLE);
  88. }
  89. void SceneView3D::Disable()
  90. {
  91. if (!enabled_)
  92. return;
  93. enabled_ = false;
  94. SetVisibility(UI_WIDGET_VISIBILITY_INVISIBLE);
  95. }
  96. void SceneView3D::MoveCamera(float timeStep)
  97. {
  98. if (!enabled_)
  99. return;
  100. Input* input = GetSubsystem<Input>();
  101. // Movement speed as world units per second
  102. float MOVE_SPEED = 20.0f;
  103. // Mouse sensitivity as degrees per pixel
  104. const float MOUSE_SENSITIVITY = 0.2f;
  105. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  106. MOVE_SPEED *= 3.0f;
  107. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  108. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  109. {
  110. IntVector2 mouseMove = input->GetMouseMove();
  111. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  112. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  113. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  114. // Not working on OSX
  115. //input->SetMouseMode(MM_RELATIVE);
  116. }
  117. else
  118. {
  119. // Not working on OSX
  120. /*
  121. if (input->GetMouseMode() != MM_ABSOLUTE)
  122. input->SetMouseMode(MM_ABSOLUTE);
  123. */
  124. }
  125. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  126. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  127. //Vector3 pos = cameraNode_->GetWorldPosition();
  128. //Quaternion q = cameraNode_->GetWorldRotation();
  129. //LOGINFOF("%f %f %f : %f %f %f %f", pos.x_, pos.y_, pos.z_, q.x_, q.y_, q.z_, q.w_ );
  130. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  131. // Use the Translate() function (default local space) to move relative to the node's orientation.
  132. if (input->GetKeyDown('W'))
  133. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  134. if (input->GetKeyDown('S'))
  135. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  136. if (input->GetKeyDown('A'))
  137. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  138. if (input->GetKeyDown('D'))
  139. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  140. }
  141. Ray SceneView3D::GetCameraRay()
  142. {
  143. Ray camRay;
  144. Input* input = GetSubsystem<Input>();
  145. IntVector2 cpos = input->GetMousePosition();
  146. IntRect rect = GetRect();
  147. if (!rect.Width() || !rect.Height())
  148. return camRay;
  149. int x = rect.left_;
  150. int y = rect.top_;
  151. GetInternalWidget()->ConvertToRoot(x, y);
  152. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  153. float(cpos.y_ - y) / rect.Height());
  154. }
  155. void SceneView3D::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode)
  156. {
  157. if (drawNode)
  158. debug->AddNode(node, 1.0, false);
  159. // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem-
  160. // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount
  161. // (TerrainPatch component itself draws nothing as debug geometry)
  162. if (node != scene_ && !node->GetComponent<Terrain>())
  163. {
  164. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  165. for (unsigned j = 0; j < components.Size(); ++j)
  166. components[j]->DrawDebugGeometry(debug, false);
  167. // To avoid cluttering the view, do not draw the node axes for child nodes
  168. for (unsigned k = 0; k < node->GetNumChildren(); ++k)
  169. DrawNodeDebug(node->GetChild(k), debug, false);
  170. }
  171. }
  172. bool SceneView3D::MouseInView()
  173. {
  174. Input* input = GetSubsystem<Input>();
  175. IntVector2 pos = input->GetMousePosition();
  176. IntRect rect = GetRect();
  177. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  178. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  179. return rect.IsInside(pos);
  180. }
  181. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  182. {
  183. // Visualize the currently selected nodes
  184. if (selectedNode_.NotNull())
  185. {
  186. DrawNodeDebug(selectedNode_, debugRenderer_);
  187. }
  188. if (!MouseInView())
  189. return;
  190. Input* input = GetSubsystem<Input>();
  191. mouseLeftDown_ = false;
  192. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  193. {
  194. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  195. {
  196. Ray camRay = GetCameraRay();
  197. PODVector<RayQueryResult> result;
  198. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  199. octree_->RaycastSingle(query);
  200. if (query.result_.Size())
  201. {
  202. const RayQueryResult& r = result[0];
  203. if (r.drawable_)
  204. {
  205. VariantMap neventData;
  206. neventData[EditorActiveNodeChange::P_NODE] = r.drawable_->GetNode();
  207. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  208. }
  209. }
  210. }
  211. mouseMoved_ = false;
  212. }
  213. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  214. {
  215. Ray camRay = GetCameraRay();
  216. PODVector<RayQueryResult> result;
  217. mouseMoved_ = false;
  218. /*
  219. Array<int> pickModeDrawableFlags = {
  220. DRAWABLE_GEOMETRY,
  221. DRAWABLE_LIGHT,
  222. DRAWABLE_ZONE
  223. };
  224. */
  225. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  226. octree_->RaycastSingle(query);
  227. if (query.result_.Size())
  228. {
  229. const RayQueryResult& r = result[0];
  230. if (r.drawable_)
  231. {
  232. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  233. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  234. }
  235. }
  236. }
  237. else
  238. {
  239. mouseLeftDown_ = true;
  240. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  241. {
  242. mouseMoved_ = true;
  243. }
  244. }
  245. }
  246. void SceneView3D::SelectNode(Node* node)
  247. {
  248. selectedNode_ = node;
  249. }
  250. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  251. {
  252. return sceneEditor_->OnEvent(ev);
  253. }
  254. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  255. {
  256. // Timestep parameter is same no matter what event is being listened to
  257. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  258. if (MouseInView())
  259. MoveCamera(timeStep);
  260. QueueUpdate();
  261. if (preloadResourceScene_.NotNull())
  262. {
  263. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  264. {
  265. ResourceCache* cache = GetSubsystem<ResourceCache>();
  266. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  267. if (dragNode_.NotNull())
  268. {
  269. dragNode_->LoadXML(xml->GetRoot());
  270. UpdateDragNode(0, 0);
  271. }
  272. preloadResourceScene_ = 0;
  273. dragAssetGUID_ = "";
  274. }
  275. }
  276. }
  277. void SceneView3D::HandleEditorActiveNodeChange(StringHash eventType, VariantMap& eventData)
  278. {
  279. Node* node = (Node*) (eventData[EditorActiveNodeChange::P_NODE].GetPtr());
  280. SelectNode(node);
  281. }
  282. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  283. {
  284. if (dragNode_.Null())
  285. return;
  286. Ray ray = GetCameraRay();
  287. Vector3 pos = ray.origin_;
  288. pos += ray.direction_ * 10;
  289. dragNode_->SetWorldPosition(pos);
  290. }
  291. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  292. {
  293. if (dragNode_.Null())
  294. return;
  295. Input* input = GetSubsystem<Input>();
  296. if (!input->IsMouseVisible())
  297. return;
  298. using namespace MouseMove;
  299. int x = eventData[P_X].GetInt();
  300. int y = eventData[P_Y].GetInt();
  301. UpdateDragNode(x, y);
  302. }
  303. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  304. {
  305. using namespace DragEnterWidget;
  306. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  307. if (widget != this)
  308. return;
  309. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  310. Object* object = dragObject->GetObject();
  311. if (!object)
  312. return;
  313. if (object->GetType() == Asset::GetTypeStatic())
  314. {
  315. Asset* asset = (Asset*) object;
  316. AssetDatabase* db = GetSubsystem<AssetDatabase>();
  317. const String& importer = asset->GetImporterTypeName();
  318. if (importer == "ModelImporter")
  319. {
  320. dragNode_ = scene_->CreateChild(asset->GetName());
  321. preloadResourceScene_ = new Scene(context_);
  322. SharedPtr<File> file(new File(context_, db->GetCachePath() + asset->GetGUID()));
  323. preloadResourceScene_->LoadAsyncXML(file, LOAD_RESOURCES_ONLY);
  324. dragAssetGUID_ = asset->GetGUID();
  325. Input* input = GetSubsystem<Input>();
  326. IntVector2 pos = input->GetMousePosition();
  327. UpdateDragNode(pos.x_, pos.y_);
  328. }
  329. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  330. }
  331. }
  332. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  333. {
  334. if (preloadResourceScene_.NotNull())
  335. {
  336. preloadResourceScene_->StopAsyncLoading();
  337. preloadResourceScene_ = 0;
  338. }
  339. if (dragNode_.NotNull())
  340. {
  341. // BUG! https://github.com/urho3d/Urho3D/issues/748
  342. dragNode_->RemoveAllComponents();
  343. scene_->RemoveChild(dragNode_);
  344. VariantMap neventData;
  345. neventData[EditorActiveNodeChange::P_NODE] = (RefCounted*) 0;
  346. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  347. }
  348. dragAssetGUID_ = "";
  349. dragNode_ = 0;
  350. }
  351. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  352. {
  353. if (dragNode_.NotNull())
  354. {
  355. VariantMap neventData;
  356. neventData[EditorActiveNodeChange::P_NODE] = dragNode_;
  357. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  358. }
  359. dragAssetGUID_ = "";
  360. dragNode_ = 0;
  361. }
  362. }