SceneView3D.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. Input* input = GetSubsystem<Input>();
  178. IntVector2 pos = input->GetMousePosition();
  179. IntRect rect = GetRect();
  180. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  181. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  182. return rect.IsInside(pos);
  183. }
  184. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  185. {
  186. // Visualize the currently selected nodes
  187. if (selectedNode_.NotNull())
  188. {
  189. //DrawNodeDebug(selectedNode_, debugRenderer_);
  190. }
  191. if (!MouseInView())
  192. return;
  193. Input* input = GetSubsystem<Input>();
  194. mouseLeftDown_ = false;
  195. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  196. {
  197. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  198. {
  199. Ray camRay = GetCameraRay();
  200. PODVector<RayQueryResult> result;
  201. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  202. octree_->RaycastSingle(query);
  203. if (query.result_.Size())
  204. {
  205. const RayQueryResult& r = result[0];
  206. if (r.drawable_)
  207. {
  208. VariantMap neventData;
  209. neventData[EditorActiveNodeChange::P_NODE] = r.drawable_->GetNode();
  210. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  211. }
  212. }
  213. }
  214. mouseMoved_ = false;
  215. }
  216. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  217. {
  218. Ray camRay = GetCameraRay();
  219. PODVector<RayQueryResult> result;
  220. mouseMoved_ = false;
  221. /*
  222. Array<int> pickModeDrawableFlags = {
  223. DRAWABLE_GEOMETRY,
  224. DRAWABLE_LIGHT,
  225. DRAWABLE_ZONE
  226. };
  227. */
  228. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  229. octree_->RaycastSingle(query);
  230. if (query.result_.Size())
  231. {
  232. const RayQueryResult& r = result[0];
  233. if (r.drawable_)
  234. {
  235. //debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  236. //r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  237. }
  238. }
  239. }
  240. else
  241. {
  242. mouseLeftDown_ = true;
  243. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  244. {
  245. mouseMoved_ = true;
  246. }
  247. }
  248. }
  249. void SceneView3D::SelectNode(Node* node)
  250. {
  251. selectedNode_ = node;
  252. }
  253. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  254. {
  255. return sceneEditor_->OnEvent(ev);
  256. }
  257. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  258. {
  259. // Timestep parameter is same no matter what event is being listened to
  260. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  261. if (MouseInView())
  262. MoveCamera(timeStep);
  263. QueueUpdate();
  264. if (preloadResourceScene_.NotNull())
  265. {
  266. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  267. {
  268. ResourceCache* cache = GetSubsystem<ResourceCache>();
  269. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  270. if (dragNode_.NotNull())
  271. {
  272. dragNode_->LoadXML(xml->GetRoot());
  273. UpdateDragNode(0, 0);
  274. AnimationController* controller = dragNode_->GetComponent<AnimationController>();
  275. if (controller)
  276. {
  277. controller->PlayExclusive("Idle", 0, true);
  278. dragNode_->GetScene()->SetUpdateEnabled(true);
  279. }
  280. }
  281. preloadResourceScene_ = 0;
  282. dragAssetGUID_ = "";
  283. }
  284. }
  285. }
  286. void SceneView3D::HandleEditorActiveNodeChange(StringHash eventType, VariantMap& eventData)
  287. {
  288. Node* node = (Node*) (eventData[EditorActiveNodeChange::P_NODE].GetPtr());
  289. SelectNode(node);
  290. }
  291. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  292. {
  293. if (dragNode_.Null())
  294. return;
  295. Ray ray = GetCameraRay();
  296. Vector3 pos = ray.origin_;
  297. pos += ray.direction_ * 10;
  298. dragNode_->SetWorldPosition(pos);
  299. }
  300. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  301. {
  302. if (dragNode_.Null())
  303. return;
  304. Input* input = GetSubsystem<Input>();
  305. if (!input->IsMouseVisible())
  306. return;
  307. using namespace MouseMove;
  308. int x = eventData[P_X].GetInt();
  309. int y = eventData[P_Y].GetInt();
  310. UpdateDragNode(x, y);
  311. }
  312. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  313. {
  314. using namespace DragEnterWidget;
  315. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  316. if (widget != this)
  317. return;
  318. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  319. Object* object = dragObject->GetObject();
  320. if (!object)
  321. return;
  322. if (object->GetType() == Asset::GetTypeStatic())
  323. {
  324. Asset* asset = (Asset*) object;
  325. AssetDatabase* db = GetSubsystem<AssetDatabase>();
  326. AssetImporter* importer = asset->GetImporter();
  327. if (!importer)
  328. return;
  329. StringHash importerType = importer->GetType();
  330. if (importerType == PrefabImporter::GetTypeStatic())
  331. {
  332. dragNode_ = scene_->CreateChild(asset->GetName());
  333. SharedPtr<File> file(new File(context_, asset->GetPath()));
  334. SharedPtr<XMLFile> xml(new XMLFile(context_));
  335. if (!xml->Load(*file))
  336. return;
  337. dragNode_->LoadXML(xml->GetRoot());
  338. dragNode_->SetName(asset->GetName());
  339. }
  340. else if (importerType == ModelImporter::GetTypeNameStatic())
  341. {
  342. dragNode_ = scene_->CreateChild(asset->GetName());
  343. SharedPtr<File> file(new File(context_, asset->GetCachePath()));
  344. SharedPtr<XMLFile> xml(new XMLFile(context_));
  345. if (!xml->Load(*file))
  346. return;
  347. dragNode_->LoadXML(xml->GetRoot());
  348. dragNode_->SetName(asset->GetName());
  349. /*
  350. dragNode_ = scene_->CreateChild(asset->GetName());
  351. preloadResourceScene_ = new Scene(context_);
  352. SharedPtr<File> file(new File(context_, asset->GetCachePath()));
  353. preloadResourceScene_->LoadAsyncXML(file, LOAD_RESOURCES_ONLY);
  354. dragAssetGUID_ = asset->GetGUID();
  355. */
  356. }
  357. if (dragNode_.NotNull())
  358. {
  359. Input* input = GetSubsystem<Input>();
  360. IntVector2 pos = input->GetMousePosition();
  361. UpdateDragNode(pos.x_, pos.y_);
  362. SendEvent("EditorUpdateHierarchy");
  363. }
  364. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  365. }
  366. }
  367. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  368. {
  369. if (preloadResourceScene_.NotNull())
  370. {
  371. preloadResourceScene_->StopAsyncLoading();
  372. preloadResourceScene_ = 0;
  373. }
  374. if (dragNode_.NotNull())
  375. {
  376. // BUG! https://github.com/urho3d/Urho3D/issues/748
  377. dragNode_->RemoveAllComponents();
  378. scene_->RemoveChild(dragNode_);
  379. VariantMap neventData;
  380. neventData[EditorActiveNodeChange::P_NODE] = (RefCounted*) 0;
  381. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  382. }
  383. dragAssetGUID_ = "";
  384. dragNode_ = 0;
  385. }
  386. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  387. {
  388. if (dragNode_.NotNull())
  389. {
  390. VariantMap neventData;
  391. neventData[EditorActiveNodeChange::P_NODE] = dragNode_;
  392. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  393. }
  394. dragAssetGUID_ = "";
  395. dragNode_ = 0;
  396. }
  397. }