SceneView3D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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/Model.h>
  20. #include <Atomic/Atomic3D/StaticModel.h>
  21. #include <Atomic/Atomic3D/AnimatedModel.h>
  22. #include <Atomic/Atomic3D/AnimationController.h>
  23. #include <Atomic/Input/Input.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/Resource/ResourceCache.h>
  26. #include <Atomic/Resource/XMLFile.h>
  27. #include <Atomic/Physics/PhysicsWorld.h>
  28. #include <Atomic/UI/UI.h>
  29. #include <Atomic/UI/UIEvents.h>
  30. #include <Atomic/Resource/ResourceEvents.h>
  31. #include <ToolCore/Assets/Asset.h>
  32. #include <ToolCore/Assets/AssetDatabase.h>
  33. #include "../../EditorMode/AEEditorEvents.h"
  34. #include "SceneView3D.h"
  35. #include "SceneEditor3D.h"
  36. #include "SceneEditor3DEvents.h"
  37. #include "SceneSelection.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. cameraMove_(false)
  49. {
  50. sceneEditor_ = sceneEditor;
  51. ResourceCache* cache = GetSubsystem<ResourceCache>();
  52. scene_ = sceneEditor->GetScene();
  53. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  54. if (debugRenderer_.Null())
  55. {
  56. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  57. debugRenderer_->SetTemporary(true);
  58. }
  59. octree_ = scene_->GetComponent<Octree>();
  60. if (octree_.Null())
  61. {
  62. LOGWARNING("Scene without an octree loaded");
  63. octree_ = scene_->CreateComponent<Octree>();
  64. }
  65. cameraNode_ = scene_->CreateChild("__atomic_sceneview3d_camera");
  66. cameraNode_->SetTemporary(true);
  67. camera_ = cameraNode_->CreateComponent<Camera>();
  68. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  69. assert(debugRenderer_.NotNull());
  70. octree_ = scene_->GetComponent<Octree>();
  71. assert(octree_.NotNull());
  72. cameraNode_->SetPosition(Vector3(0, 0, -10));
  73. SetView(scene_, camera_);
  74. SetAutoUpdate(false);
  75. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  76. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  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. bool SceneView3D::GetOrbitting()
  103. {
  104. Input* input = GetSubsystem<Input>();
  105. return framedBBox_.defined_ && MouseInView() && input->GetKeyDown(KEY_ALT) && input->GetMouseButtonDown(MOUSEB_LEFT);
  106. }
  107. bool SceneView3D::GetZooming()
  108. {
  109. Input* input = GetSubsystem<Input>();
  110. return MouseInView() && input->GetKeyDown(KEY_ALT) && input->GetMouseMoveWheel();
  111. }
  112. void SceneView3D::MoveCamera(float timeStep)
  113. {
  114. if (!enabled_ && !GetFocus())
  115. return;
  116. Input* input = GetSubsystem<Input>();
  117. bool shiftDown = false;
  118. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  119. shiftDown = true;
  120. bool mouseInView = MouseInView();
  121. bool orbitting = GetOrbitting();
  122. bool zooming = GetZooming();
  123. // Movement speed as world units per second
  124. float MOVE_SPEED = 20.0f;
  125. // Mouse sensitivity as degrees per pixel
  126. const float MOUSE_SENSITIVITY = 0.2f;
  127. if (shiftDown)
  128. MOVE_SPEED *= 3.0f;
  129. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  130. if ((mouseInView && input->GetMouseButtonDown(MOUSEB_RIGHT)) || orbitting)
  131. {
  132. SetFocus();
  133. IntVector2 mouseMove = input->GetMouseMove();
  134. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  135. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  136. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  137. }
  138. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  139. Quaternion q(pitch_, yaw_, 0.0f);
  140. if (!zooming)
  141. cameraNode_->SetRotation(q);
  142. if (orbitting)
  143. {
  144. BoundingBox bbox;
  145. sceneEditor_->GetSelection()->GetBounds(bbox);
  146. if (bbox.defined_)
  147. {
  148. Vector3 centerPoint = bbox.Center();
  149. Vector3 d = cameraNode_->GetWorldPosition() - centerPoint;
  150. cameraNode_->SetWorldPosition(centerPoint - q * Vector3(0.0, 0.0, d.Length()));
  151. }
  152. }
  153. if (zooming)
  154. {
  155. Ray ray = GetCameraRay();
  156. Vector3 wpos = cameraNode_->GetWorldPosition();
  157. wpos += ray.direction_ * (float (input->GetMouseMoveWheel()) * (shiftDown ? 0.6f : 0.2f));
  158. cameraNode_->SetWorldPosition(wpos);
  159. }
  160. #ifdef ATOMIC_PLATFORM_WINDOWS
  161. bool superdown = input->GetKeyDown(KEY_LCTRL) || input->GetKeyDown(KEY_RCTRL);
  162. #else
  163. bool superdown = input->GetKeyDown(KEY_LGUI) || input->GetKeyDown(KEY_RGUI);
  164. #endif
  165. if (!orbitting && mouseInView && !superdown && input->GetMouseButtonDown(MOUSEB_RIGHT)) {
  166. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  167. // Use the Translate() function (default local space) to move relative to the node's orientation.
  168. if (input->GetKeyDown(KEY_W))
  169. {
  170. SetFocus();
  171. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  172. }
  173. if (input->GetKeyDown(KEY_S))
  174. {
  175. SetFocus();
  176. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  177. }
  178. if (input->GetKeyDown(KEY_A))
  179. { SetFocus();
  180. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  181. }
  182. if (input->GetKeyDown(KEY_D))
  183. {
  184. SetFocus();
  185. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  186. }
  187. if (input->GetKeyDown(KEY_Q))
  188. {
  189. SetFocus();
  190. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  191. }
  192. if (input->GetKeyDown(KEY_E))
  193. {
  194. SetFocus();
  195. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  196. }
  197. }
  198. else if (!superdown)
  199. {
  200. if (input->GetKeyPress(KEY_F))
  201. {
  202. FrameSelection();
  203. }
  204. }
  205. if (cameraMove_)
  206. {
  207. cameraMoveTime_ += timeStep * 3.0f;
  208. if (cameraMoveTime_ > 1.0f)
  209. {
  210. cameraMove_ = false;
  211. cameraMoveTime_ = 1.0f;
  212. }
  213. Vector3 pos = cameraMoveStart_.Lerp(cameraMoveTarget_, cameraMoveTime_);
  214. cameraNode_->SetWorldPosition(pos);
  215. }
  216. }
  217. Ray SceneView3D::GetCameraRay()
  218. {
  219. Ray camRay;
  220. Input* input = GetSubsystem<Input>();
  221. IntVector2 cpos = input->GetMousePosition();
  222. IntRect rect = GetRect();
  223. if (!rect.Width() || !rect.Height())
  224. return camRay;
  225. int x = rect.left_;
  226. int y = rect.top_;
  227. GetInternalWidget()->ConvertToRoot(x, y);
  228. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  229. float(cpos.y_ - y) / rect.Height());
  230. }
  231. bool SceneView3D::MouseInView()
  232. {
  233. if (!GetInternalWidget())
  234. return false;
  235. if (!TBWidget::hovered_widget || TBWidget::hovered_widget->GetDelegate() != this)
  236. return false;
  237. Input* input = GetSubsystem<Input>();
  238. IntVector2 pos = input->GetMousePosition();
  239. IntRect rect = GetRect();
  240. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  241. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  242. return rect.IsInside(pos);
  243. }
  244. void SceneView3D::HandleUIUnhandledShortcut(StringHash eventType, VariantMap& eventData)
  245. {
  246. if (!enabled_)
  247. return;
  248. unsigned id = eventData[UIUnhandledShortcut::P_REFID].GetUInt();
  249. if (id == TBIDC("undo"))
  250. sceneEditor_->Undo();
  251. else if (id == TBIDC("redo"))
  252. sceneEditor_->Redo();
  253. else if (id == TBIDC("copy"))
  254. sceneEditor_->Copy();
  255. else if (id == TBIDC("paste"))
  256. sceneEditor_->Paste();
  257. return;
  258. }
  259. void SceneView3D::HandleUIWidgetFocusEscaped(StringHash eventType, VariantMap& eventData)
  260. {
  261. if (!enabled_)
  262. return;
  263. SetFocus();
  264. }
  265. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  266. {
  267. if (!MouseInView() || GetOrbitting())
  268. return;
  269. Input* input = GetSubsystem<Input>();
  270. mouseLeftDown_ = false;
  271. bool shiftDown = input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT);
  272. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  273. {
  274. SetFocus();
  275. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  276. {
  277. Ray camRay = GetCameraRay();
  278. PODVector<RayQueryResult> result;
  279. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  280. octree_->RaycastSingle(query);
  281. if (query.result_.Size())
  282. {
  283. const RayQueryResult& r = result[0];
  284. if (r.drawable_)
  285. {
  286. VariantMap neventData;
  287. Node* node = r.drawable_->GetNode();
  288. // if temporary, this is a prefab
  289. // TODO: if we use temporary for other stuff
  290. // fix this to look for prefab
  291. if (node->IsTemporary())
  292. node = node->GetParent();
  293. if (sceneEditor_->GetSelection()->Contains(node) && shiftDown)
  294. {
  295. sceneEditor_->GetSelection()->RemoveNode(node);
  296. }
  297. else
  298. {
  299. sceneEditor_->GetSelection()->AddNode(node, !shiftDown);
  300. }
  301. }
  302. }
  303. }
  304. mouseMoved_ = false;
  305. }
  306. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  307. {
  308. Ray camRay = GetCameraRay();
  309. PODVector<RayQueryResult> result;
  310. mouseMoved_ = false;
  311. /*
  312. Array<int> pickModeDrawableFlags = {
  313. DRAWABLE_GEOMETRY,
  314. DRAWABLE_LIGHT,
  315. DRAWABLE_ZONE
  316. };
  317. */
  318. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  319. octree_->RaycastSingle(query);
  320. if (query.result_.Size())
  321. {
  322. const RayQueryResult& r = result[0];
  323. if (r.drawable_)
  324. {
  325. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  326. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  327. }
  328. }
  329. }
  330. else
  331. {
  332. mouseLeftDown_ = true;
  333. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  334. {
  335. mouseMoved_ = true;
  336. }
  337. }
  338. }
  339. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  340. {
  341. if (ev.type == EVENT_TYPE_SHORTCUT)
  342. {
  343. if (ev.ref_id == TBIDC("close"))
  344. return false;
  345. }
  346. return sceneEditor_->OnEvent(ev);
  347. }
  348. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  349. {
  350. // Timestep parameter is same no matter what event is being listened to
  351. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  352. MoveCamera(timeStep);
  353. QueueUpdate();
  354. if (preloadResourceScene_.NotNull())
  355. {
  356. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  357. {
  358. ResourceCache* cache = GetSubsystem<ResourceCache>();
  359. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  360. if (dragNode_.NotNull())
  361. {
  362. dragNode_->LoadXML(xml->GetRoot());
  363. UpdateDragNode(0, 0);
  364. AnimationController* controller = dragNode_->GetComponent<AnimationController>();
  365. if (controller)
  366. {
  367. controller->PlayExclusive("Idle", 0, true);
  368. dragNode_->GetScene()->SetUpdateEnabled(true);
  369. }
  370. }
  371. preloadResourceScene_ = 0;
  372. dragAssetGUID_ = "";
  373. }
  374. }
  375. }
  376. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  377. {
  378. if (dragNode_.Null())
  379. return;
  380. Ray ray = GetCameraRay();
  381. Vector3 pos = ray.origin_;
  382. pos += ray.direction_ * 10;
  383. dragNode_->SetWorldPosition(pos);
  384. }
  385. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  386. {
  387. if (dragNode_.Null())
  388. return;
  389. Input* input = GetSubsystem<Input>();
  390. if (!input->IsMouseVisible())
  391. return;
  392. using namespace MouseMove;
  393. int x = eventData[P_X].GetInt();
  394. int y = eventData[P_Y].GetInt();
  395. UpdateDragNode(x, y);
  396. }
  397. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  398. {
  399. using namespace DragEnterWidget;
  400. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  401. if (widget != this)
  402. return;
  403. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  404. Object* object = dragObject->GetObject();
  405. if (!object)
  406. return;
  407. if (object->GetType() == Asset::GetTypeStatic())
  408. {
  409. Asset* asset = (Asset*) object;
  410. dragNode_ = asset->InstantiateNode(scene_, asset->GetName());
  411. if (dragNode_.NotNull())
  412. {
  413. Input* input = GetSubsystem<Input>();
  414. IntVector2 pos = input->GetMousePosition();
  415. UpdateDragNode(pos.x_, pos.y_);
  416. }
  417. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  418. }
  419. }
  420. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  421. {
  422. if (preloadResourceScene_.NotNull())
  423. {
  424. preloadResourceScene_->StopAsyncLoading();
  425. preloadResourceScene_ = 0;
  426. }
  427. if (dragNode_.NotNull())
  428. {
  429. scene_->RemoveChild(dragNode_);
  430. }
  431. dragAssetGUID_ = "";
  432. dragNode_ = 0;
  433. }
  434. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  435. {
  436. using namespace DragEnded;
  437. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  438. if (dragNode_.NotNull())
  439. {
  440. PODVector<Node*> nodes;
  441. nodes.Push(dragNode_);
  442. sceneEditor_->RegisterNodes(nodes);
  443. sceneEditor_->GetSelection()->AddNode(dragNode_, true);
  444. }
  445. if (dragObject && dragObject->GetObject()->GetType() == ToolCore::Asset::GetTypeStatic())
  446. {
  447. Asset* asset = (ToolCore::Asset*) dragObject->GetObject();
  448. if (asset->GetImporterTypeName() == "MaterialImporter") {
  449. Material* material = GetSubsystem<ResourceCache>()->GetResource<Material>(asset->GetPath());
  450. if (material) {
  451. material = material;
  452. Ray camRay = GetCameraRay();
  453. PODVector<RayQueryResult> result;
  454. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  455. octree_->RaycastSingle(query);
  456. if (query.result_.Size())
  457. {
  458. const RayQueryResult& r = result[0];
  459. if (r.drawable_ && (r.drawable_->GetType() == StaticModel::GetTypeStatic() || r.drawable_->GetType() == AnimatedModel::GetTypeStatic()))
  460. {
  461. ((StaticModel*)r.drawable_)->SetMaterial(material);
  462. }
  463. }
  464. }
  465. }
  466. }
  467. dragAssetGUID_ = "";
  468. dragNode_ = 0;
  469. }
  470. void SceneView3D::FrameSelection()
  471. {
  472. BoundingBox bbox;
  473. sceneEditor_->GetSelection()->GetBounds(bbox);
  474. if (!bbox.defined_)
  475. return;
  476. Sphere sphere(bbox);
  477. if (sphere.radius_ < .01f || sphere.radius_ > 512)
  478. return;
  479. framedBBox_ = bbox;
  480. cameraMoveStart_ = cameraNode_->GetWorldPosition();
  481. cameraMoveTarget_ = bbox.Center() - (cameraNode_->GetWorldDirection() * sphere.radius_ * 3);
  482. cameraMoveTime_ = 0.0f;
  483. cameraMove_ = true;
  484. }
  485. }