SceneView3D.cpp 15 KB

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