SceneView3D.cpp 16 KB

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