SceneView3D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // Portions Copyright (c) 2008-2015 the Urho3D project.
  2. //
  3. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  4. // LICENSE: Atomic Game Engine Editor and Tools EULA
  5. // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
  6. // license information: https://github.com/AtomicGameEngine/AtomicGameEngine
  7. //
  8. #include <Atomic/IO/Log.h>
  9. #include <Atomic/Core/CoreEvents.h>
  10. #include <Atomic/Scene/SceneEvents.h>
  11. #include <Atomic/Scene/Scene.h>
  12. #include <Atomic/Scene/PrefabComponent.h>
  13. #include <Atomic/Graphics/Camera.h>
  14. #include <Atomic/Graphics/Graphics.h>
  15. #include <Atomic/Graphics/DebugRenderer.h>
  16. #include <Atomic/Graphics/Viewport.h>
  17. #include <Atomic/Graphics/Octree.h>
  18. #include <Atomic/Graphics/Material.h>
  19. #include <Atomic/Atomic3D/Terrain.h>
  20. #include <Atomic/Atomic3D/Model.h>
  21. #include <Atomic/Atomic3D/StaticModel.h>
  22. #include <Atomic/Atomic3D/AnimatedModel.h>
  23. #include <Atomic/Atomic3D/AnimationController.h>
  24. #include <Atomic/Input/Input.h>
  25. #include <Atomic/IO/FileSystem.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #include <Atomic/Resource/XMLFile.h>
  28. #include <Atomic/Physics/PhysicsWorld.h>
  29. #include <Atomic/UI/UI.h>
  30. #include <Atomic/UI/UIEvents.h>
  31. #include <Atomic/Resource/ResourceEvents.h>
  32. #include <ToolCore/Assets/Asset.h>
  33. #include <ToolCore/Assets/AssetDatabase.h>
  34. #include "../../EditorMode/AEEditorEvents.h"
  35. #include "SceneView3D.h"
  36. #include "SceneEditor3D.h"
  37. #include "SceneEditor3DEvents.h"
  38. using namespace ToolCore;
  39. namespace AtomicEditor
  40. {
  41. SceneView3D ::SceneView3D(Context* context, SceneEditor3D *sceneEditor) :
  42. UISceneView(context),
  43. yaw_(0.0f),
  44. pitch_(0.0f),
  45. mouseLeftDown_(false),
  46. mouseMoved_(false),
  47. enabled_(true)
  48. {
  49. sceneEditor_ = sceneEditor;
  50. ResourceCache* cache = GetSubsystem<ResourceCache>();
  51. scene_ = sceneEditor->GetScene();
  52. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  53. if (debugRenderer_.Null())
  54. {
  55. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  56. }
  57. octree_ = scene_->GetComponent<Octree>();
  58. if (octree_.Null())
  59. {
  60. LOGWARNING("Scene without an octree loaded");
  61. octree_ = scene_->CreateComponent<Octree>();
  62. }
  63. cameraNode_ = scene_->CreateChild("__atomic_sceneview3d_camera");
  64. cameraNode_->SetTemporary(true);
  65. camera_ = cameraNode_->CreateComponent<Camera>();
  66. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  67. assert(debugRenderer_.NotNull());
  68. octree_ = scene_->GetComponent<Octree>();
  69. assert(octree_.NotNull());
  70. cameraNode_->SetPosition(Vector3(0, 0, -10));
  71. SetView(scene_, camera_);
  72. SetAutoUpdate(false);
  73. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  74. SubscribeToEvent(E_EDITORACTIVENODECHANGE, HANDLER(SceneView3D, HandleEditorActiveNodeChange));
  75. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  76. SubscribeToEvent(scene_, E_NODEREMOVED, HANDLER(SceneView3D, HandleNodeRemoved));
  77. SubscribeToEvent(E_MOUSEMOVE, HANDLER(SceneView3D,HandleMouseMove));
  78. SubscribeToEvent(this, E_DRAGENTERWIDGET, HANDLER(SceneView3D, HandleDragEnterWidget));
  79. SubscribeToEvent(this, E_DRAGEXITWIDGET, HANDLER(SceneView3D, HandleDragExitWidget));
  80. SubscribeToEvent(this, E_DRAGENDED, HANDLER(SceneView3D, HandleDragEnded));
  81. SubscribeToEvent(E_UIUNHANDLEDSHORTCUT, HANDLER(SceneView3D, HandleUIUnhandledShortcut));
  82. SubscribeToEvent(E_UIWIDGETFOCUSESCAPED, HANDLER(SceneView3D, HandleUIWidgetFocusEscaped));
  83. SetIsFocusable(true);
  84. }
  85. SceneView3D::~SceneView3D()
  86. {
  87. }
  88. void SceneView3D::Enable()
  89. {
  90. if (enabled_)
  91. return;
  92. enabled_ = true;
  93. SetVisibility(UI_WIDGET_VISIBILITY_VISIBLE);
  94. }
  95. void SceneView3D::Disable()
  96. {
  97. if (!enabled_)
  98. return;
  99. enabled_ = false;
  100. SetVisibility(UI_WIDGET_VISIBILITY_INVISIBLE);
  101. }
  102. void SceneView3D::MoveCamera(float timeStep)
  103. {
  104. if (!enabled_ && !GetFocus())
  105. return;
  106. Input* input = GetSubsystem<Input>();
  107. // Movement speed as world units per second
  108. float MOVE_SPEED = 20.0f;
  109. // Mouse sensitivity as degrees per pixel
  110. const float MOUSE_SENSITIVITY = 0.2f;
  111. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  112. MOVE_SPEED *= 3.0f;
  113. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  114. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  115. {
  116. SetFocus();
  117. IntVector2 mouseMove = input->GetMouseMove();
  118. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  119. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  120. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  121. }
  122. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  123. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  124. #ifdef ATOMIC_PLATFORM_WINDOWS
  125. bool superdown = input->GetKeyDown(KEY_LCTRL) || input->GetKeyDown(KEY_RCTRL);
  126. #else
  127. bool superdown = input->GetKeyDown(KEY_LGUI) || input->GetKeyDown(KEY_RGUI);
  128. #endif
  129. if (!superdown && input->GetMouseButtonDown(MOUSEB_RIGHT)) {
  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. {
  134. SetFocus();
  135. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  136. }
  137. if (input->GetKeyDown('S'))
  138. {
  139. SetFocus();
  140. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  141. }
  142. if (input->GetKeyDown('A'))
  143. { SetFocus();
  144. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  145. }
  146. if (input->GetKeyDown('D'))
  147. {
  148. SetFocus();
  149. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  150. }
  151. }
  152. }
  153. Ray SceneView3D::GetCameraRay()
  154. {
  155. Ray camRay;
  156. Input* input = GetSubsystem<Input>();
  157. IntVector2 cpos = input->GetMousePosition();
  158. IntRect rect = GetRect();
  159. if (!rect.Width() || !rect.Height())
  160. return camRay;
  161. int x = rect.left_;
  162. int y = rect.top_;
  163. GetInternalWidget()->ConvertToRoot(x, y);
  164. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  165. float(cpos.y_ - y) / rect.Height());
  166. }
  167. void SceneView3D::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode)
  168. {
  169. if (drawNode)
  170. debug->AddNode(node, 1.0, false);
  171. // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem-
  172. // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount
  173. // (TerrainPatch component itself draws nothing as debug geometry)
  174. if (node != scene_ && !node->GetComponent<Terrain>())
  175. {
  176. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  177. for (unsigned j = 0; j < components.Size(); ++j)
  178. components[j]->DrawDebugGeometry(debug, false);
  179. // To avoid cluttering the view, do not draw the node axes for child nodes
  180. for (unsigned k = 0; k < node->GetNumChildren(); ++k)
  181. DrawNodeDebug(node->GetChild(k), debug, false);
  182. }
  183. }
  184. bool SceneView3D::MouseInView()
  185. {
  186. if (!GetInternalWidget())
  187. return false;
  188. if (!TBWidget::hovered_widget || TBWidget::hovered_widget->GetDelegate() != this)
  189. return false;
  190. Input* input = GetSubsystem<Input>();
  191. IntVector2 pos = input->GetMousePosition();
  192. IntRect rect = GetRect();
  193. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  194. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  195. return rect.IsInside(pos);
  196. }
  197. void SceneView3D::HandleUIUnhandledShortcut(StringHash eventType, VariantMap& eventData)
  198. {
  199. if (!enabled_)
  200. return;
  201. unsigned id = eventData[UIUnhandledShortcut::P_REFID].GetUInt();
  202. if (id == TBIDC("undo"))
  203. sceneEditor_->Undo();
  204. else if (id == TBIDC("redo"))
  205. sceneEditor_->Redo();
  206. return;
  207. }
  208. void SceneView3D::HandleUIWidgetFocusEscaped(StringHash eventType, VariantMap& eventData)
  209. {
  210. if (!enabled_)
  211. return;
  212. SetFocus();
  213. }
  214. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  215. {
  216. // Visualize the currently selected nodes
  217. if (selectedNode_.NotNull())
  218. {
  219. DrawNodeDebug(selectedNode_, debugRenderer_);
  220. }
  221. if (!MouseInView())
  222. return;
  223. Input* input = GetSubsystem<Input>();
  224. mouseLeftDown_ = false;
  225. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  226. {
  227. SetFocus();
  228. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  229. {
  230. Ray camRay = GetCameraRay();
  231. PODVector<RayQueryResult> result;
  232. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  233. octree_->RaycastSingle(query);
  234. if (query.result_.Size())
  235. {
  236. const RayQueryResult& r = result[0];
  237. if (r.drawable_)
  238. {
  239. VariantMap neventData;
  240. Node* node = r.drawable_->GetNode();
  241. // if temporary, this is a prefab
  242. // TODO: if we use temporary for other stuff
  243. // fix this to look for prefab
  244. if (node->IsTemporary())
  245. node = node->GetParent();
  246. neventData[EditorActiveNodeChange::P_NODE] = node;
  247. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  248. }
  249. }
  250. }
  251. mouseMoved_ = false;
  252. }
  253. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  254. {
  255. Ray camRay = GetCameraRay();
  256. PODVector<RayQueryResult> result;
  257. mouseMoved_ = false;
  258. /*
  259. Array<int> pickModeDrawableFlags = {
  260. DRAWABLE_GEOMETRY,
  261. DRAWABLE_LIGHT,
  262. DRAWABLE_ZONE
  263. };
  264. */
  265. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  266. octree_->RaycastSingle(query);
  267. if (query.result_.Size())
  268. {
  269. const RayQueryResult& r = result[0];
  270. if (r.drawable_)
  271. {
  272. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  273. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  274. }
  275. }
  276. }
  277. else
  278. {
  279. mouseLeftDown_ = true;
  280. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  281. {
  282. mouseMoved_ = true;
  283. }
  284. }
  285. }
  286. void SceneView3D::SelectNode(Node* node)
  287. {
  288. selectedNode_ = node;
  289. }
  290. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  291. {
  292. if (ev.type == EVENT_TYPE_SHORTCUT)
  293. {
  294. if (ev.ref_id == TBIDC("close"))
  295. return false;
  296. }
  297. return sceneEditor_->OnEvent(ev);
  298. }
  299. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  300. {
  301. // Timestep parameter is same no matter what event is being listened to
  302. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  303. if (MouseInView())
  304. MoveCamera(timeStep);
  305. QueueUpdate();
  306. if (preloadResourceScene_.NotNull())
  307. {
  308. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  309. {
  310. ResourceCache* cache = GetSubsystem<ResourceCache>();
  311. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  312. if (dragNode_.NotNull())
  313. {
  314. dragNode_->LoadXML(xml->GetRoot());
  315. UpdateDragNode(0, 0);
  316. AnimationController* controller = dragNode_->GetComponent<AnimationController>();
  317. if (controller)
  318. {
  319. controller->PlayExclusive("Idle", 0, true);
  320. dragNode_->GetScene()->SetUpdateEnabled(true);
  321. }
  322. }
  323. preloadResourceScene_ = 0;
  324. dragAssetGUID_ = "";
  325. }
  326. }
  327. }
  328. void SceneView3D::HandleEditorActiveNodeChange(StringHash eventType, VariantMap& eventData)
  329. {
  330. Node* node = (Node*) (eventData[EditorActiveNodeChange::P_NODE].GetPtr());
  331. SelectNode(node);
  332. }
  333. void SceneView3D::HandleNodeRemoved(StringHash eventType, VariantMap& eventData)
  334. {
  335. Node* node = (Node*) (eventData[NodeRemoved::P_NODE].GetPtr());
  336. if (node == selectedNode_)
  337. SelectNode(0);
  338. }
  339. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  340. {
  341. if (dragNode_.Null())
  342. return;
  343. Ray ray = GetCameraRay();
  344. Vector3 pos = ray.origin_;
  345. pos += ray.direction_ * 10;
  346. dragNode_->SetWorldPosition(pos);
  347. }
  348. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  349. {
  350. if (dragNode_.Null())
  351. return;
  352. Input* input = GetSubsystem<Input>();
  353. if (!input->IsMouseVisible())
  354. return;
  355. using namespace MouseMove;
  356. int x = eventData[P_X].GetInt();
  357. int y = eventData[P_Y].GetInt();
  358. UpdateDragNode(x, y);
  359. }
  360. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  361. {
  362. using namespace DragEnterWidget;
  363. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  364. if (widget != this)
  365. return;
  366. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  367. Object* object = dragObject->GetObject();
  368. if (!object)
  369. return;
  370. if (object->GetType() == Asset::GetTypeStatic())
  371. {
  372. Asset* asset = (Asset*) object;
  373. dragNode_ = asset->InstantiateNode(scene_, asset->GetName());
  374. if (dragNode_.NotNull())
  375. {
  376. Input* input = GetSubsystem<Input>();
  377. IntVector2 pos = input->GetMousePosition();
  378. UpdateDragNode(pos.x_, pos.y_);
  379. }
  380. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  381. }
  382. }
  383. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  384. {
  385. if (preloadResourceScene_.NotNull())
  386. {
  387. preloadResourceScene_->StopAsyncLoading();
  388. preloadResourceScene_ = 0;
  389. }
  390. if (dragNode_.NotNull())
  391. {
  392. scene_->RemoveChild(dragNode_);
  393. }
  394. dragAssetGUID_ = "";
  395. dragNode_ = 0;
  396. }
  397. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  398. {
  399. using namespace DragEnded;
  400. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  401. if (dragNode_.NotNull())
  402. {
  403. VariantMap neventData;
  404. neventData[EditorActiveNodeChange::P_NODE] = dragNode_;
  405. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  406. VariantMap editData;
  407. editData[SceneEditNodeAddedRemoved::P_SCENE] = scene_;
  408. editData[SceneEditNodeAddedRemoved::P_NODE] = dragNode_;
  409. editData[SceneEditNodeAddedRemoved::P_ADDED] = true;
  410. scene_->SendEvent(E_SCENEEDITNODEADDEDREMOVED, editData);
  411. }
  412. if (dragObject && dragObject->GetObject()->GetType() == ToolCore::Asset::GetTypeStatic())
  413. {
  414. Asset* asset = (ToolCore::Asset*) dragObject->GetObject();
  415. if (asset->GetImporterTypeName() == "MaterialImporter") {
  416. Material* material = GetSubsystem<ResourceCache>()->GetResource<Material>(asset->GetPath());
  417. if (material) {
  418. material = material;
  419. Ray camRay = GetCameraRay();
  420. PODVector<RayQueryResult> result;
  421. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  422. octree_->RaycastSingle(query);
  423. if (query.result_.Size())
  424. {
  425. const RayQueryResult& r = result[0];
  426. if (r.drawable_ && (r.drawable_->GetType() == StaticModel::GetTypeStatic() || r.drawable_->GetType() == AnimatedModel::GetTypeStatic()))
  427. {
  428. ((StaticModel*)r.drawable_)->SetMaterial(material);
  429. }
  430. }
  431. }
  432. }
  433. }
  434. dragAssetGUID_ = "";
  435. dragNode_ = 0;
  436. }
  437. }