Application.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "AnimatedModel.h"
  25. #include "Animation.h"
  26. #include "AnimationState.h"
  27. #include "Audio.h"
  28. #include "Application.h"
  29. #include "BillboardSet.h"
  30. #include "CollisionShape.h"
  31. #include "Cursor.h"
  32. #include "CustomObject.h"
  33. #include "DebugHud.h"
  34. #include "DebugRenderer.h"
  35. #include "Engine.h"
  36. #include "EngineEvents.h"
  37. #include "Exception.h"
  38. #include "File.h"
  39. #include "Font.h"
  40. #include "Geometry.h"
  41. #include "IndexBuffer.h"
  42. #include "Input.h"
  43. #include "InstancedModel.h"
  44. #include "Joint.h"
  45. #include "Light.h"
  46. #include "Log.h"
  47. #include "Material.h"
  48. #include "Mod.h"
  49. #include "OcclusionBuffer.h"
  50. #include "Octree.h"
  51. #include "OctreeQuery.h"
  52. #include "PhysicsEvents.h"
  53. #include "PhysicsWorld.h"
  54. #include "Pipeline.h"
  55. #include "ParticleEmitter.h"
  56. #include "Profiler.h"
  57. #include "Renderer.h"
  58. #include "RendererImpl.h"
  59. #include "ResourceCache.h"
  60. #include "RigidBody.h"
  61. #include "Scene.h"
  62. #include "Skybox.h"
  63. #include "StaticModel.h"
  64. #include "Text.h"
  65. #include "StringUtils.h"
  66. #include "Texture2D.h"
  67. #include "UI.h"
  68. #include "UIEvents.h"
  69. #include "VertexBuffer.h"
  70. #include "Window.h"
  71. #include "XM.h"
  72. #include "XMLFile.h"
  73. #include "Zone.h"
  74. #include "DebugNew.h"
  75. void calculateTangents(float* vertexData, unsigned vertexCount, const unsigned short* indexData, unsigned indexCount);
  76. float vertexData[] =
  77. {
  78. // Side 1
  79. -1, 1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0,
  80. 1, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0,
  81. 1, -1, -1, 0, 0, -1, 1, 1, 0, 0, 0, 0,
  82. -1, -1, -1, 0, 0, -1, 0, 1, 0, 0, 0, 0,
  83. // Side 2
  84. 1, 1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  85. 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0,
  86. 1, -1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0,
  87. 1, -1, -1, 1, 0, 0, 0, 1, 0, 0, 0, 0,
  88. // Side 3
  89. 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,
  90. -1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0,
  91. -1, -1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0,
  92. 1, -1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0,
  93. // Side 4
  94. -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0,
  95. -1, 1, -1, -1, 0, 0, 1, 0, 0, 0, 0, 0,
  96. -1, -1, -1, -1, 0, 0, 1, 1, 0, 0, 0, 0,
  97. -1, -1, 1, -1, 0, 0, 0, 1, 0, 0, 0, 0,
  98. // Side 5
  99. -1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
  100. 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
  101. 1, 1, -1, 0, 1, 0, 1, 1, 0, 0, 0, 0,
  102. -1, 1, -1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
  103. // Side 6
  104. -1, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0,
  105. 1, -1, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0,
  106. 1, -1, 1, 0, -1, 0, 1, 1, 0, 0, 0, 0,
  107. -1, -1, 1, 0, -1, 0, 0, 1, 0, 0, 0, 0
  108. };
  109. const unsigned short indexData[] =
  110. {
  111. 0, 1, 2,
  112. 2, 3, 0,
  113. 4, 5, 6,
  114. 6, 7, 4,
  115. 8, 9, 10,
  116. 10, 11, 8,
  117. 12, 13, 14,
  118. 14, 15, 12,
  119. 16, 17, 18,
  120. 18, 19, 16,
  121. 20, 21, 22,
  122. 22, 23, 20
  123. };
  124. float objectangle = 0;
  125. float yaw = 0;
  126. float pitch = 0;
  127. bool paused = true;
  128. int texturequality = 2;
  129. int materialquality = 2;
  130. int fallbacklevel = 0;
  131. int shadowmapsize = 1024;
  132. bool hiresshadowmap = false;
  133. int texturefilter = 2;
  134. bool usespecular = true;
  135. int drawdebug = 0;
  136. bool drawshadows = true;
  137. bool attach = true;
  138. bool useocclusion = true;
  139. bool shadowfocus = true;
  140. static const int NUM_OBJECTS = 250;
  141. static const int NUM_LIGHTS = 20;
  142. static const int NUM_INSTANCENODES = 20;
  143. static const int NUM_INSTANCES = 50;
  144. static const int NUM_BILLBOARDNODES = 20;
  145. static const int NUM_BILLBOARDS = 15;
  146. Application::Application(const std::vector<std::string>& arguments) :
  147. mArguments(arguments)
  148. {
  149. subscribeToEvent(EVENT_UPDATE, EVENT_HANDLER(Application, handleUpdate));
  150. subscribeToEvent(EVENT_POSTRENDERUPDATE, EVENT_HANDLER(Application, handlePostRenderUpdate));
  151. subscribeToEvent(EVENT_MOUSEMOVE, EVENT_HANDLER(Application, handleMouseMove));
  152. subscribeToEvent(EVENT_MOUSEBUTTONDOWN, EVENT_HANDLER(Application, handleMouseButtonDown));
  153. subscribeToEvent(EVENT_MOUSEBUTTONUP, EVENT_HANDLER(Application, handleMouseButtonUp));
  154. }
  155. Application::~Application()
  156. {
  157. if (mEngine)
  158. {
  159. mEngine->dumpResources();
  160. mEngine->dumpProfilingData();
  161. }
  162. }
  163. void Application::run()
  164. {
  165. init();
  166. while (!mEngine->isExiting())
  167. mEngine->runFrame(mScene, mCameraEntity->getComponent<Camera>());
  168. }
  169. void Application::init()
  170. {
  171. mEngine = new Engine("Test.log");
  172. mEngine->init("Urho3D Test", mArguments);
  173. PROFILE(App_Init);
  174. mCache = mEngine->getResourceCache();
  175. mCache->addResourcePath(getSystemFontDirectory());
  176. Renderer* renderer = mEngine->getRenderer();
  177. UI* ui = mEngine->getUI();
  178. UIElement* uiRoot = ui->getRootElement();
  179. XMLFile* uiStyle = mCache->getResource<XMLFile>("UI/DefaultStyle.xml");
  180. Cursor* cursor = new Cursor("Cursor");
  181. cursor->setStyleAuto(uiStyle, mCache);
  182. cursor->setPosition(renderer->getWidth() / 2, renderer->getHeight() / 2);
  183. ui->setCursor(cursor);
  184. //XMLFile* uiLayout = mCache->getResource<XMLFile>("UI/TestLayout.xml");
  185. //SharedPtr<UIElement> layoutElement = ui->loadLayout(uiLayout, uiStyle);
  186. //uiRoot->addChild(layoutElement);
  187. mScene = mEngine->createScene();
  188. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  189. world->setGravity(Vector3(0.0f, -9.81f, 0.0f));
  190. world->setFps(100);
  191. world->setLinearRestThreshold(0.1f);
  192. world->setAngularRestThreshold(0.1f);
  193. world->setContactSurfaceLayer(0.001f);
  194. DebugHud* debugHud = mEngine->createDebugHud();
  195. debugHud->setFont(mCache->getResource<Font>("cour.ttf"), 12);
  196. debugHud->setMode(DEBUGHUD_SHOW_STATS | DEBUGHUD_SHOW_MODE);
  197. mCameraEntity = mScene->createEntity();
  198. Camera* camera = mCameraEntity->createComponent<Camera>();
  199. camera->setPosition(Vector3(-50.0f, 2.0f, -50.0f));
  200. camera->setAspectRatio((float)renderer->getWidth() / (float)renderer->getHeight());
  201. calculateTangents(vertexData, 24, indexData, 36);
  202. SharedPtr<VertexBuffer> vb(new VertexBuffer(renderer, false));
  203. vb->setSize(24, MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1 | MASK_TANGENT);
  204. vb->setData(vertexData);
  205. SharedPtr<IndexBuffer> ib(new IndexBuffer(renderer, false));
  206. ib->setSize(36, false);
  207. ib->setData(indexData);
  208. SharedPtr<Geometry> g(new Geometry());
  209. g->setVertexBuffer(0, vb);
  210. g->setIndexBuffer(ib);
  211. g->setDrawRange(TRIANGLE_LIST, 0, ib->getIndexCount());
  212. SharedPtr<Model> box(new Model(renderer, "Models/Box.mdl"));
  213. box->setNumGeometries(1);
  214. box->setNumGeometryLodLevels(0, 1);
  215. box->setGeometry(0, 0, g);
  216. box->setBoundingBox(BoundingBox(-1.0f, 1.0f));
  217. mCache->addManualResource(box);
  218. createScene();
  219. Entity* sun = mScene->createEntity();
  220. Light* sunLight = sun->createComponent<Light>();
  221. sunLight->setLightType(LIGHT_DIRECTIONAL);
  222. sunLight->setDirection(Vector3(0.5f, -1.0f, 0.5f));
  223. sunLight->setColor(Color(0.2f, 0.2f, 0.2f));
  224. sunLight->setSpecularIntensity(1.0);
  225. //sunLight->setCastShadows(true);
  226. //sunLight->setShadowCascade(CascadeParameters(3, 0.95f, 0.2f, 500.0f));
  227. Light* cameraLight = mCameraEntity->createComponent<Light>();
  228. cameraLight->setLightType(LIGHT_SPOT);
  229. cameraLight->setDirection(Vector3(0.0f, 0.0f, 1.0f));
  230. cameraLight->setRange(50.0f);
  231. cameraLight->setColor(Color(2.0f, 2.0f, 2.0f));
  232. cameraLight->setSpecularIntensity(2.0f);
  233. cameraLight->setCastShadows(true);
  234. cameraLight->setShadowResolution(0.5f);
  235. cameraLight->setShadowFocus(FocusParameters(false, false, false, 0.5f, 3.0f));
  236. cameraLight->setRampTexture(mCache->getResource<Texture2D>("Textures/RampWide.png"));
  237. cameraLight->setSpotTexture(mCache->getResource<Texture2D>("Textures/SpotWide.png"));
  238. camera->addChild(cameraLight);
  239. }
  240. void Application::createScene()
  241. {
  242. PROFILE(App_CreateScene);
  243. Octree* octree = mScene->getExtension<Octree>();
  244. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  245. // Create a zone to control the ambient lighting
  246. Zone* zone = new Zone(octree);
  247. zone->setBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  248. zone->setAmbientColor(Color(0.1f, 0.1f, 0.1f));
  249. Entity* newEntity = mScene->createEntity();
  250. newEntity->addComponent(zone);
  251. // Create the "floor"
  252. for (int y = -5; y <= 5; y++)
  253. {
  254. for (int x = -5; x <= 5; x++)
  255. {
  256. RigidBody* body = new RigidBody(world);
  257. body->setPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
  258. body->setScale(Vector3(10.0f, 0.5f, 10.0f));
  259. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  260. body->setCollisionGroup(2);
  261. body->setCollisionMask(1);
  262. StaticModel* object = new StaticModel(octree);
  263. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  264. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  265. body->addChild(object);
  266. Entity* newEntity = mScene->createEntity();
  267. newEntity->addComponent(body);
  268. newEntity->addComponent(object);
  269. }
  270. }
  271. // Create 2 occluder walls
  272. for (int x = 0; x < 2; x++)
  273. {
  274. RigidBody* body = new RigidBody(world);
  275. body->setPosition(Vector3(0.0f, 5.0f, 0.0f));
  276. body->setRotation(Quaternion(x * 90.0f, Vector3::sUp));
  277. body->setScale(Vector3(112.0f, 5.0f, 0.5f));
  278. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  279. body->setCollisionGroup(2);
  280. body->setCollisionMask(1);
  281. StaticModel* object = new StaticModel(octree);
  282. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  283. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  284. object->setCastShadows(true);
  285. object->setOccluder(true);
  286. body->addChild(object);
  287. Entity* newEntity = mScene->createEntity();
  288. newEntity->addComponent(body);
  289. newEntity->addComponent(object);
  290. }
  291. // Create static mushroom with physics
  292. {
  293. RigidBody* body = new RigidBody(world);
  294. body->setPosition(Vector3(50.0f, 0.0f, 50.0f));
  295. body->setScale(10.0f);
  296. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Mushroom.xml"));
  297. body->setCollisionGroup(2);
  298. body->setCollisionMask(1);
  299. StaticModel* object = new StaticModel(octree);
  300. object->setModel(mCache->getResource<Model>("Models/Mushroom.mdl"));
  301. object->setMaterial(mCache->getResource<Material>("Materials/Mushroom.xml"));
  302. object->setCastShadows(true);
  303. object->setOccluder(true);
  304. body->addChild(object);
  305. Entity* newEntity = mScene->createEntity();
  306. newEntity->addComponent(body);
  307. newEntity->addComponent(object);
  308. }
  309. // Create instanced mushrooms
  310. for (unsigned j = 0; j < NUM_INSTANCENODES; ++j)
  311. {
  312. InstancedModel* instanced = new InstancedModel(octree);
  313. instanced->setModel(mCache->getResource<Model>("Models/Mushroom.mdl"));
  314. instanced->setMaterial(mCache->getResource<Material>("Materials/Mushroom.xml"));
  315. instanced->setPosition(Vector3(random() * 160.0f - 80.0f, 0.0f, random() * 160.0f - 80.0f));
  316. instanced->setCastShadows(true);
  317. instanced->setNumInstances(50);
  318. std::vector<Instance>& instances = instanced->getInstances();
  319. for (unsigned i = 0; i < NUM_INSTANCES; ++i)
  320. {
  321. Vector3 position(random() * 20.0f - 10.0f, 0.0f, random() * 20.0f - 10.0f);
  322. float angle = random() * 360.0f;
  323. float size = 1.0f + random() * 2.0f;
  324. instances[i].mPosition = position;
  325. instances[i].mRotation = Quaternion(angle, Vector3::sUp);
  326. instances[i].mScale = Vector3(size, size, size);
  327. }
  328. instanced->updated();
  329. Entity* newEntity = mScene->createEntity();
  330. newEntity->addComponent(instanced);
  331. }
  332. // Create animated models
  333. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  334. {
  335. AnimatedModel* object = new AnimatedModel(octree);
  336. Vector3 position(random() * 180.0f - 90.0f, 0.0f, random() * 180.0f - 90.0f);
  337. float angle = random() * 360.0f;
  338. object->setPosition(position);
  339. object->setRotation(Quaternion(angle, Vector3::sUp));
  340. object->setCastShadows(true);
  341. object->setScale(1.0f + random() * 0.25f);
  342. object->setModel(mCache->getResource<Model>("Models/Jack.mdl"));
  343. object->setMaterial(mCache->getResource<Material>("Materials/Jack.xml"));
  344. object->setShadowDistance(200.0f);
  345. object->setDrawDistance(300.0f);
  346. AnimationState* anim = object->addAnimationState(mCache->getResource<Animation>("Models/Jack_Walk.ani"));
  347. if (anim)
  348. {
  349. anim->setUseNlerp(true);
  350. anim->setLooped(true);
  351. anim->setWeight(1.0f);
  352. }
  353. Entity* newEntity = mScene->createEntity();
  354. newEntity->addComponent(object);
  355. mAnimatingObjects.push_back(newEntity);
  356. }
  357. // Create floating smoke clouds
  358. for (unsigned b = 0; b < NUM_BILLBOARDNODES; ++b)
  359. {
  360. BillboardSet* billboard = new BillboardSet(octree);
  361. billboard->setNumBillboards(NUM_BILLBOARDS);
  362. billboard->setPosition(Vector3(random() * 200.0f - 100.0f, random() * 15.0f + 5.0f, random() * 200.0f - 100.0f));
  363. billboard->setMaterial(mCache->getResource<Material>("Materials/LitSmoke.xml"));
  364. billboard->setBillboardsSorted(true);
  365. std::vector<Billboard>& bb = billboard->getBillboards();
  366. for (unsigned i = 0; i < NUM_BILLBOARDS; ++i)
  367. {
  368. bb[i].mPosition = Vector3(random() * 15.0f - 7.5f, random() * 8.0f - 4.0f, random() * 15.0f - 7.5f);
  369. bb[i].mSize = Vector2(random() * 2.0f + 3.0f, random() * 2.0f + 3.0f);
  370. bb[i].mRotation = random() * 360.0f;
  371. bb[i].mEnabled = true;
  372. }
  373. billboard->updated();
  374. Entity* newEntity = mScene->createEntity();
  375. newEntity->addComponent(billboard);
  376. mBillboards.push_back(newEntity);
  377. }
  378. // Create lights
  379. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  380. {
  381. Light* light = new Light(octree);
  382. Vector3 position(
  383. random() * 150.0f - 75.0f,
  384. random() * 30.0f + 30.0f,
  385. random() * 150.0f - 75.0f
  386. );
  387. Color color(
  388. (rand() & 1) * 0.5f + 0.5f,
  389. (rand() & 1) * 0.5f + 0.5f,
  390. (rand() & 1) * 0.5f + 0.5f
  391. );
  392. if ((color.mR == 0.5f) && (color.mG == 0.5f) && (color.mB == 0.5f))
  393. color = Color(1.0f, 1.0f, 1.0f);
  394. float angle = random() * 360.0f;
  395. light->setPosition(position);
  396. light->setDirection(Vector3(sinf(angle * M_DEGTORAD), -1.0f, cosf(angle * M_DEGTORAD)));
  397. light->setLightType(LIGHT_SPOT);
  398. light->setRange(75.0f);
  399. light->setRampTexture(mCache->getResource<Texture2D>("Textures/RampExtreme.png"));
  400. light->setFov(15.0f);
  401. light->setColor(color);
  402. light->setSpecularIntensity(1.0f);
  403. light->setCastShadows(true);
  404. light->setShadowBias(BiasParameters(0.00002f, 0.0f));
  405. light->setShadowResolution(0.5f);
  406. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  407. // for better shadow depth resolution
  408. light->setShadowNearFarRatio(0.01f);
  409. Entity* newEntity = mScene->createEntity();
  410. newEntity->addComponent(light);
  411. mLights.push_back(newEntity);
  412. }
  413. }
  414. void Application::handleUpdate(StringHash eventType, VariantMap& eventData)
  415. {
  416. using namespace Update;
  417. float timeStep = eventData[P_TIMESTEP].getFloat();
  418. if (!paused)
  419. {
  420. objectangle += 10.0f * timeStep;
  421. for (unsigned i = 0; i < mLights.size(); ++i)
  422. {
  423. Light* light = mLights[i]->getComponent<Light>();
  424. light->setRotation(Quaternion(0, objectangle * 2, 0));
  425. }
  426. for (unsigned i = 0; i < mAnimatingObjects.size(); ++i)
  427. {
  428. AnimatedModel* model = mAnimatingObjects[i]->getComponent<AnimatedModel>();
  429. const std::vector<AnimationState*>& anims = model->getAnimationStates();
  430. for (unsigned j = 0; j < anims.size(); ++j)
  431. anims[j]->addTime(timeStep);
  432. }
  433. for (unsigned i = 0; i < mBillboards.size(); ++i)
  434. {
  435. BillboardSet* billboard = mBillboards[i]->getComponent<BillboardSet>();
  436. std::vector<Billboard>& bb = billboard->getBillboards();
  437. for (unsigned j = 0; j < bb.size(); ++j)
  438. bb[j].mRotation += 50.0f * timeStep;
  439. billboard->updated();
  440. }
  441. }
  442. UI* ui = mEngine->getUI();
  443. if (!ui->getFocusElement())
  444. {
  445. Input* input = mEngine->getInput();
  446. float speedMultiplier = 1.0f;
  447. if (input->getKeyDown(KEY_SHIFT))
  448. speedMultiplier = 5.0f;
  449. if (input->getKeyDown(KEY_CONTROL))
  450. speedMultiplier = 0.1f;
  451. if (input->getKeyDown('W'))
  452. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,10.0f) * timeStep * speedMultiplier);
  453. if (input->getKeyDown('S'))
  454. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,-10.0f) * timeStep * speedMultiplier);
  455. if (input->getKeyDown('A'))
  456. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(-10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  457. if (input->getKeyDown('D'))
  458. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  459. if (input->getKeyPress('1'))
  460. {
  461. Renderer* renderer = mEngine->getRenderer();
  462. int nextRenderMode = renderer->getRenderMode();
  463. if (input->getKeyDown(KEY_SHIFT))
  464. {
  465. --nextRenderMode;
  466. if (nextRenderMode < 0)
  467. nextRenderMode = 2;
  468. }
  469. else
  470. {
  471. ++nextRenderMode;
  472. if (nextRenderMode > 2)
  473. nextRenderMode = 0;
  474. }
  475. renderer->setMode((RenderMode)nextRenderMode, renderer->getWidth(), renderer->getHeight(), renderer->getFullscreen(),
  476. renderer->getVsync(), renderer->getMultiSample());
  477. }
  478. if (input->getKeyPress('2'))
  479. {
  480. texturequality++;
  481. if (texturequality > 2)
  482. texturequality = 0;
  483. mEngine->getPipeline()->setTextureQuality(texturequality);
  484. }
  485. if (input->getKeyPress('3'))
  486. {
  487. materialquality++;
  488. if (materialquality > 2)
  489. materialquality = 0;
  490. mEngine->getPipeline()->setMaterialQuality(materialquality);
  491. }
  492. if (input->getKeyPress('4'))
  493. {
  494. usespecular = !usespecular;
  495. mEngine->getPipeline()->setSpecularLighting(usespecular);
  496. }
  497. if (input->getKeyPress('5'))
  498. {
  499. drawshadows = !drawshadows;
  500. mEngine->getPipeline()->setDrawShadows(drawshadows);
  501. }
  502. if (input->getKeyPress('6'))
  503. {
  504. shadowmapsize *= 2;
  505. if (shadowmapsize > 2048)
  506. shadowmapsize = 512;
  507. mEngine->getPipeline()->setShadowMapSize(shadowmapsize);
  508. }
  509. if (input->getKeyPress('7'))
  510. {
  511. hiresshadowmap = !hiresshadowmap;
  512. mEngine->getPipeline()->setShadowMapHiresDepth(hiresshadowmap);
  513. }
  514. if (input->getKeyPress('8'))
  515. {
  516. useocclusion = !useocclusion;
  517. mEngine->getPipeline()->setMaxOccluderTriangles(useocclusion ? 5000 : 0);
  518. }
  519. if (input->getKeyPress('L'))
  520. {
  521. Light* cameraLight = mCameraEntity->getComponent<Light>();
  522. attach = !attach;
  523. if (attach)
  524. {
  525. cameraLight->setPosition(Vector3::sZero);
  526. cameraLight->setRotation(Quaternion::sIdentity);
  527. mCameraEntity->getComponent<Camera>()->addChild(cameraLight);
  528. }
  529. else
  530. {
  531. // Detach child and set world transform to match what it was before detach
  532. mCameraEntity->getComponent<Camera>()->removeChild(cameraLight, true);
  533. }
  534. }
  535. if (input->getKeyPress(' '))
  536. {
  537. drawdebug++;
  538. if (drawdebug > 2) drawdebug = 0;
  539. mEngine->setDebugDrawMode(drawdebug);
  540. }
  541. if (input->getKeyPress('P'))
  542. {
  543. paused = !paused;
  544. }
  545. if (input->getKeyPress('C'))
  546. {
  547. Camera* camera = mCameraEntity->getComponent<Camera>();
  548. camera->setOrthographic(!camera->isOrthographic());
  549. }
  550. if (input->getKeyPress('O'))
  551. {
  552. if (!mOcclusionDebugImage)
  553. {
  554. try
  555. {
  556. Renderer* renderer = mEngine->getRenderer();
  557. UIElement* uiRoot = mEngine->getUIRoot();
  558. mOcclusionDebugTexture = new Texture2D(renderer, TEXTURE_DYNAMIC);
  559. mOcclusionDebugTexture->setNumLevels(1);
  560. mOcclusionDebugTexture->setSize(256, 256, D3DFMT_R32F);
  561. mOcclusionDebugImage = new BorderImage();
  562. mOcclusionDebugImage->setSize(256, 256);
  563. mOcclusionDebugImage->setTexture(mOcclusionDebugTexture);
  564. mOcclusionDebugImage->setAlignment(HA_RIGHT, VA_BOTTOM);
  565. uiRoot->addChild(mOcclusionDebugImage);
  566. }
  567. catch (...)
  568. {
  569. }
  570. }
  571. else
  572. {
  573. mOcclusionDebugImage->setVisible(!mOcclusionDebugImage->isVisible());
  574. }
  575. }
  576. if (input->getKeyPress('T'))
  577. mEngine->getDebugHud()->toggle(DEBUGHUD_SHOW_PROFILER);
  578. if (input->getKeyPress('F'))
  579. {
  580. Pipeline* pipeline = mEngine->getPipeline();
  581. EdgeFilterParameters params = pipeline->getEdgeFilter();
  582. if (params.mMaxFilter > 0.0f)
  583. params.mMaxFilter = 0.0f;
  584. else
  585. params.mMaxFilter = 1.0f;
  586. pipeline->setEdgeFilter(params);
  587. }
  588. if (input->getKeyPress(KEY_ESCAPE))
  589. mEngine->exit();
  590. }
  591. }
  592. void Application::handlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  593. {
  594. using namespace PostRenderUpdate;
  595. float timeStep = eventData[P_TIMESTEP].getFloat();
  596. // Test world raycast
  597. Camera* camera = mCameraEntity->getComponent<Camera>();
  598. UI* ui = mEngine->getUI();
  599. Renderer* renderer = mEngine->getRenderer();
  600. DebugRenderer* debug = mEngine->getDebugRenderer();
  601. if (camera)
  602. {
  603. IntVector2 pos = ui->getCursorPosition();
  604. if (!ui->getElementAt(pos))
  605. {
  606. Ray cameraRay = camera->getScreenRay(((float)pos.mX) / renderer->getWidth(), ((float)pos.mY) / renderer->getHeight());
  607. std::vector<RayQueryResult> result;
  608. RayOctreeQuery query(cameraRay, result, NODE_GEOMETRY, NODE_BILLBOARDSET, false, false, 250.0f, RAY_TRIANGLE);
  609. mScene->getExtension<Octree>()->getNodes(query);
  610. if (result.size())
  611. {
  612. VolumeNode* node = result[0].mNode;
  613. Vector3 rayHitPos = cameraRay.mOrigin + query.mResult[0].mDistance * cameraRay.mDirection;
  614. debug->addBoundingBox(BoundingBox(-0.01f, 0.01f), Matrix4x3(rayHitPos, Quaternion::sIdentity, Vector3::sUnity), Color(1.0f, 1.0f, 1.0f));
  615. // Check for sub-object results (node-specific)
  616. if (result[0].mSubObject < M_MAX_UNSIGNED)
  617. {
  618. // Bone
  619. if (node->getNodeFlags() & NODE_ANIMATEDMODEL)
  620. {
  621. AnimatedModel* anim = static_cast<AnimatedModel*>(node);
  622. Bone* bone = anim->getSkeleton().getBone(result[0].mSubObject);
  623. debug->addBoundingBox(bone->getBoundingBox(), bone->getWorldTransform(), Color(1.0f, 1.0f, 1.0f));
  624. }
  625. // Instance
  626. else if (node->getNodeFlags() & NODE_INSTANCEDMODEL)
  627. {
  628. InstancedModel* instanced = static_cast<InstancedModel*>(node);
  629. Instance* instance = instanced->getInstance(result[0].mSubObject);
  630. Matrix4x3 transform(instance->mPosition, instance->mRotation, instance->mScale);
  631. if (instanced->getInstancesRelative())
  632. transform = instanced->getWorldTransform() * transform;
  633. debug->addBoundingBox(instanced->getBoundingBox().getTransformed(transform), Color(1.0f, 1.0f, 1.0f));
  634. }
  635. // Custom object subgeometry
  636. else if (node->getNodeFlags() & NODE_CUSTOMOBJECT)
  637. {
  638. CustomObject* custom = static_cast<CustomObject*>(node);
  639. const CustomGeometry* geom = custom->getGeometry(result[0].mSubObject);
  640. debug->addBoundingBox(geom->mBoundingBox.getTransformed(custom->getWorldTransform()), Color(1.0f, 1.0f, 1.0f));
  641. }
  642. }
  643. else
  644. debug->addBoundingBox(node->getWorldBoundingBox(), Color(1.0f, 1.0f, 1.0f));
  645. }
  646. }
  647. }
  648. // Update occlusion debug texture if visible
  649. if ((mOcclusionDebugImage) && (mOcclusionDebugImage->isVisible()))
  650. {
  651. PROFILE(App_UpdateOcclusionDebugTextures);
  652. static const float INV_Z_SCALE = 1.0f / (OCCLUSION_Z_SCALE);
  653. // Dump occlusion depth buffer to debug texture
  654. // Get an occlusion buffer matching the aspect ratio, it should be the main view occlusion buffer
  655. const OcclusionBuffer* buffer = mEngine->getPipeline()->getOcclusionBuffer(camera->getAspectRatio());
  656. if (buffer)
  657. {
  658. int width = buffer->getWidth();
  659. int height = buffer->getHeight();
  660. if (buffer->getBuffer())
  661. {
  662. mOcclusionDebugTexture->setSize(width, height, D3DFMT_R32F);
  663. mOcclusionDebugImage->setSize(width, height);
  664. mOcclusionDebugImage->setFullImageRect();
  665. D3DLOCKED_RECT hwRect;
  666. mOcclusionDebugTexture->lock(0, 0, &hwRect);
  667. for (int y = 0; y < height; ++y)
  668. {
  669. float* dest = (float*)(((unsigned char*)hwRect.pBits) + y * hwRect.Pitch);
  670. int* src = buffer->getBuffer() + y * width;
  671. for (int x = 0; x < width; ++x)
  672. {
  673. float depth = src[x] * INV_Z_SCALE;
  674. dest[x] = depth * 0.5f;
  675. }
  676. }
  677. mOcclusionDebugTexture->unlock();
  678. }
  679. }
  680. }
  681. }
  682. void Application::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  683. {
  684. using namespace MouseButtonDown;
  685. int button = eventData[P_BUTTON].getInt();
  686. if (button == MOUSEB_RIGHT)
  687. {
  688. UIElement* cursor = mEngine->getUICursor();
  689. if (cursor)
  690. cursor->setVisible(false);
  691. }
  692. UI* ui = mEngine->getUI();
  693. if ((button == MOUSEB_LEFT) && (!ui->getElementAt(ui->getCursorPosition())) && (!ui->getFocusElement()))
  694. {
  695. // Test creating a new physics object
  696. if (mCameraEntity)
  697. {
  698. Camera* camera = mCameraEntity->getComponent<Camera>();
  699. Octree* octree = mScene->getExtension<Octree>();
  700. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  701. Entity* newEntity = mScene->createEntity();
  702. RigidBody* body = new RigidBody(world);
  703. body->setMode(PHYS_DYNAMIC);
  704. body->setPosition(camera->getPosition());
  705. body->setRotation(camera->getRotation());
  706. body->setScale(0.1f);
  707. body->setFriction(1.0f);
  708. body->setAngularMaxVelocity(500.0f);
  709. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  710. body->setCollisionGroup(1);
  711. body->setCollisionMask(3);
  712. body->setLinearVelocity(camera->getUpVector() + camera->getForwardVector() * 10.0f);
  713. StaticModel* object = new StaticModel(octree);
  714. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  715. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  716. object->setCastShadows(true);
  717. object->setShadowDistance(75.0f);
  718. object->setDrawDistance(100.0f);
  719. body->addChild(object);
  720. newEntity->addComponent(body);
  721. newEntity->addComponent(object);
  722. }
  723. }
  724. }
  725. void Application::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  726. {
  727. using namespace MouseButtonDown;
  728. if (eventData[P_BUTTON].getInt() == MOUSEB_RIGHT)
  729. {
  730. UIElement* cursor = mEngine->getUICursor();
  731. if (cursor)
  732. cursor->setVisible(true);
  733. }
  734. }
  735. void Application::handleMouseMove(StringHash eventType, VariantMap& eventData)
  736. {
  737. using namespace MouseMove;
  738. if (eventData[P_BUTTONS].getInt() & MOUSEB_RIGHT)
  739. {
  740. int mousedx = eventData[P_X].getInt();
  741. int mousedy = eventData[P_Y].getInt();
  742. yaw += mousedx / 10.0f;
  743. pitch += mousedy / 10.0f;
  744. if (pitch < -90.0f)
  745. pitch = -90.0f;
  746. if (pitch > 90.0f)
  747. pitch = 90.0f;
  748. if (mCameraEntity)
  749. mCameraEntity->getComponent<Camera>()->setRotation(Quaternion(yaw, Vector3::sUp) * Quaternion(pitch, Vector3::sRight));
  750. }
  751. }
  752. void calculateTangents(float* vertexData, unsigned vertexCount, const unsigned short* indexData, unsigned indexCount)
  753. {
  754. // Tangent generation from
  755. // http://www.terathon.com/code/tangent.html
  756. static const int V_OFS = 0;
  757. static const int N_OFS = 3;
  758. static const int UV_OFS = 6;
  759. static const int T_OFS = 8;
  760. static const int V_SIZE = 12;
  761. Vector3 *tan1 = new Vector3[vertexCount * 2];
  762. Vector3 *tan2 = tan1 + vertexCount;
  763. memset(tan1, 0, sizeof(Vector3) * vertexCount * 2);
  764. for (unsigned a = 0; a < indexCount; a += 3)
  765. {
  766. unsigned short i1 = indexData[a+0];
  767. unsigned short i2 = indexData[a+1];
  768. unsigned short i3 = indexData[a+2];
  769. const Vector3 v1 = Vector3(&vertexData[i1 * V_SIZE + V_OFS]);
  770. const Vector3 v2 = Vector3(&vertexData[i2 * V_SIZE + V_OFS]);
  771. const Vector3 v3 = Vector3 (&vertexData[i3 * V_SIZE + V_OFS]);
  772. const Vector2 w1 = Vector2(&vertexData[i1 * V_SIZE + UV_OFS]);
  773. const Vector2 w2 = Vector2(&vertexData[i2 * V_SIZE + UV_OFS]);
  774. const Vector2 w3 = Vector2(&vertexData[i3 * V_SIZE + UV_OFS]);
  775. float x1 = v2.mX - v1.mX;
  776. float x2 = v3.mX - v1.mX;
  777. float y1 = v2.mY - v1.mY;
  778. float y2 = v3.mY - v1.mY;
  779. float z1 = v2.mZ - v1.mZ;
  780. float z2 = v3.mZ - v1.mZ;
  781. float s1 = w2.mX - w1.mX;
  782. float s2 = w3.mX - w1.mX;
  783. float t1 = w2.mY - w1.mY;
  784. float t2 = w3.mY - w1.mY;
  785. float r = 1.0f / (s1 * t2 - s2 * t1);
  786. Vector3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
  787. (t2 * z1 - t1 * z2) * r);
  788. Vector3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
  789. (s1 * z2 - s2 * z1) * r);
  790. tan1[i1] += sdir;
  791. tan1[i2] += sdir;
  792. tan1[i3] += sdir;
  793. tan2[i1] += tdir;
  794. tan2[i2] += tdir;
  795. tan2[i3] += tdir;
  796. }
  797. for (unsigned a = 0; a < vertexCount; a++)
  798. {
  799. const Vector3 n = Vector3(&vertexData[a * V_SIZE + N_OFS]);
  800. const Vector3 t = Vector3(tan1[a]);
  801. Vector3 xyz;
  802. float w;
  803. // Gram-Schmidt orthogonalize
  804. xyz = (t - n * n.dotProduct(t)).getNormalized();
  805. // Calculate handedness
  806. w = n.crossProduct(t).dotProduct(tan2[a]) < 0.0f ? -1.0f : 1.0f;
  807. vertexData[a * V_SIZE + T_OFS] = xyz.mX;
  808. vertexData[a * V_SIZE + T_OFS + 1] = xyz.mY;
  809. vertexData[a * V_SIZE + T_OFS + 2] = xyz.mZ;
  810. vertexData[a * V_SIZE + T_OFS + 3] = w;
  811. }
  812. delete[] tan1;
  813. }