SceneView3D.cpp 15 KB

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