Application.cpp 34 KB

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