Application.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. 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/Mushroom.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/Mushroom.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->setUseNlerp(true);
  348. anim->setLooped(true);
  349. anim->setWeight(1.0f);
  350. }
  351. Entity* newEntity = mScene->createEntity();
  352. newEntity->addComponent(object);
  353. mAnimatingObjects.push_back(newEntity);
  354. }
  355. // Create floating smoke clouds
  356. for (unsigned b = 0; b < NUM_BILLBOARDNODES; ++b)
  357. {
  358. BillboardSet* billboard = new BillboardSet(octree);
  359. billboard->setNumBillboards(NUM_BILLBOARDS);
  360. billboard->setPosition(Vector3(random() * 200.0f - 100.0f, random() * 15.0f + 5.0f, random() * 200.0f - 100.0f));
  361. billboard->setMaterial(mCache->getResource<Material>("Materials/LitSmoke.xml"));
  362. billboard->setBillboardsSorted(true);
  363. std::vector<Billboard>& bb = billboard->getBillboards();
  364. for (unsigned i = 0; i < NUM_BILLBOARDS; ++i)
  365. {
  366. bb[i].mPosition = Vector3(random() * 15.0f - 7.5f, random() * 8.0f - 4.0f, random() * 15.0f - 7.5f);
  367. bb[i].mSize = Vector2(random() * 2.0f + 3.0f, random() * 2.0f + 3.0f);
  368. bb[i].mRotation = random() * 360.0f;
  369. bb[i].mEnabled = true;
  370. }
  371. billboard->updated();
  372. Entity* newEntity = mScene->createEntity();
  373. newEntity->addComponent(billboard);
  374. mBillboards.push_back(newEntity);
  375. }
  376. // Create lights
  377. for (unsigned i = 0; i < NUM_LIGHTS; ++i)
  378. {
  379. Light* light = new Light(octree);
  380. Vector3 position(
  381. random() * 150.0f - 75.0f,
  382. random() * 30.0f + 30.0f,
  383. random() * 150.0f - 75.0f
  384. );
  385. Color color(
  386. (rand() & 1) * 0.5f + 0.5f,
  387. (rand() & 1) * 0.5f + 0.5f,
  388. (rand() & 1) * 0.5f + 0.5f
  389. );
  390. if ((color.mR == 0.5f) && (color.mG == 0.5f) && (color.mB == 0.5f))
  391. color = Color(1.0f, 1.0f, 1.0f);
  392. float angle = random() * 360.0f;
  393. light->setPosition(position);
  394. light->setDirection(Vector3(sinf(angle * M_DEGTORAD), -1.0f, cosf(angle * M_DEGTORAD)));
  395. light->setLightType(LIGHT_SPOT);
  396. light->setRange(75.0f);
  397. light->setRampTexture(mCache->getResource<Texture2D>("Textures/RampExtreme.png"));
  398. light->setFov(15.0f);
  399. light->setColor(color);
  400. light->setSpecularIntensity(1.0f);
  401. light->setCastShadows(true);
  402. light->setShadowBias(BiasParameters(0.00002f, 0.0f));
  403. light->setShadowResolution(0.5f);
  404. // The spot lights will not have anything near them, so move the near plane of the shadow camera farther
  405. // for better shadow depth resolution
  406. light->setShadowNearFarRatio(0.01f);
  407. Entity* newEntity = mScene->createEntity();
  408. newEntity->addComponent(light);
  409. mLights.push_back(newEntity);
  410. }
  411. }
  412. void Application::handleUpdate(StringHash eventType, VariantMap& eventData)
  413. {
  414. using namespace Update;
  415. float timeStep = eventData[P_TIMESTEP].getFloat();
  416. if (!paused)
  417. {
  418. objectangle += 10.0f * timeStep;
  419. for (unsigned i = 0; i < mLights.size(); ++i)
  420. {
  421. Light* light = mLights[i]->getComponent<Light>();
  422. light->setRotation(Quaternion(0, objectangle * 2, 0));
  423. }
  424. for (unsigned i = 0; i < mAnimatingObjects.size(); ++i)
  425. {
  426. AnimatedModel* model = mAnimatingObjects[i]->getComponent<AnimatedModel>();
  427. const std::vector<AnimationState*>& anims = model->getAnimationStates();
  428. for (unsigned j = 0; j < anims.size(); ++j)
  429. anims[j]->addTime(timeStep);
  430. }
  431. for (unsigned i = 0; i < mBillboards.size(); ++i)
  432. {
  433. BillboardSet* billboard = mBillboards[i]->getComponent<BillboardSet>();
  434. std::vector<Billboard>& bb = billboard->getBillboards();
  435. for (unsigned j = 0; j < bb.size(); ++j)
  436. bb[j].mRotation += 50.0f * timeStep;
  437. billboard->updated();
  438. }
  439. }
  440. Input* input = mEngine->getInput();
  441. float speedMultiplier = 1.0f;
  442. if (input->getKeyDown(KEY_SHIFT))
  443. speedMultiplier = 5.0f;
  444. if (input->getKeyDown(KEY_CONTROL))
  445. speedMultiplier = 0.1f;
  446. if (input->getKeyDown('W'))
  447. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,10.0f) * timeStep * speedMultiplier);
  448. if (input->getKeyDown('S'))
  449. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(0.0f,0.0f,-10.0f) * timeStep * speedMultiplier);
  450. if (input->getKeyDown('A'))
  451. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(-10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  452. if (input->getKeyDown('D'))
  453. mCameraEntity->getComponent<Camera>()->translateRelative(Vector3(10.0f,0.0f,0.0f) * timeStep * speedMultiplier);
  454. if (input->getKeyPress('1'))
  455. {
  456. Renderer* renderer = mEngine->getRenderer();
  457. int nextRenderMode = renderer->getRenderMode();
  458. if (input->getKeyDown(KEY_SHIFT))
  459. {
  460. --nextRenderMode;
  461. if (nextRenderMode < 0)
  462. nextRenderMode = 2;
  463. }
  464. else
  465. {
  466. ++nextRenderMode;
  467. if (nextRenderMode > 2)
  468. nextRenderMode = 0;
  469. }
  470. renderer->setMode((RenderMode)nextRenderMode, renderer->getWidth(), renderer->getHeight(), renderer->getFullscreen(),
  471. renderer->getVsync(), renderer->getMultiSample());
  472. }
  473. if (input->getKeyPress('2'))
  474. {
  475. texturequality++;
  476. if (texturequality > 2)
  477. texturequality = 0;
  478. mEngine->getPipeline()->setTextureQuality(texturequality);
  479. }
  480. if (input->getKeyPress('3'))
  481. {
  482. materialquality++;
  483. if (materialquality > 2)
  484. materialquality = 0;
  485. mEngine->getPipeline()->setMaterialQuality(materialquality);
  486. }
  487. if (input->getKeyPress('4'))
  488. {
  489. usespecular = !usespecular;
  490. mEngine->getPipeline()->setSpecularLighting(usespecular);
  491. }
  492. if (input->getKeyPress('5'))
  493. {
  494. drawshadows = !drawshadows;
  495. mEngine->getPipeline()->setDrawShadows(drawshadows);
  496. }
  497. if (input->getKeyPress('6'))
  498. {
  499. shadowmapsize *= 2;
  500. if (shadowmapsize > 2048)
  501. shadowmapsize = 512;
  502. mEngine->getPipeline()->setShadowMapSize(shadowmapsize);
  503. }
  504. if (input->getKeyPress('7'))
  505. {
  506. hiresshadowmap = !hiresshadowmap;
  507. mEngine->getPipeline()->setShadowMapHiresDepth(hiresshadowmap);
  508. }
  509. if (input->getKeyPress('8'))
  510. {
  511. useocclusion = !useocclusion;
  512. mEngine->getPipeline()->setMaxOccluderTriangles(useocclusion ? 5000 : 0);
  513. }
  514. if (input->getKeyPress('L'))
  515. {
  516. Light* cameraLight = mCameraEntity->getComponent<Light>();
  517. attach = !attach;
  518. if (attach)
  519. {
  520. cameraLight->setPosition(Vector3::sZero);
  521. cameraLight->setRotation(Quaternion::sIdentity);
  522. mCameraEntity->getComponent<Camera>()->addChild(cameraLight);
  523. }
  524. else
  525. {
  526. // Detach child and set world transform to match what it was before detach
  527. mCameraEntity->getComponent<Camera>()->removeChild(cameraLight, true);
  528. }
  529. }
  530. if (input->getKeyPress(' '))
  531. {
  532. drawdebug++;
  533. if (drawdebug > 2) drawdebug = 0;
  534. mEngine->setDebugDrawMode(drawdebug);
  535. }
  536. if (input->getKeyPress('P'))
  537. {
  538. paused = !paused;
  539. }
  540. if (input->getKeyPress('C'))
  541. {
  542. Camera* camera = mCameraEntity->getComponent<Camera>();
  543. camera->setOrthographic(!camera->isOrthographic());
  544. }
  545. if (input->getKeyPress('O'))
  546. {
  547. if (!mOcclusionDebugImage)
  548. {
  549. try
  550. {
  551. Renderer* renderer = mEngine->getRenderer();
  552. UIElement* uiRoot = mEngine->getUIRoot();
  553. mOcclusionDebugTexture = new Texture2D(renderer, TEXTURE_DYNAMIC);
  554. mOcclusionDebugTexture->setNumLevels(1);
  555. mOcclusionDebugTexture->setSize(256, 256, D3DFMT_R32F);
  556. mOcclusionDebugImage = new BorderImage();
  557. mOcclusionDebugImage->setSize(256, 256);
  558. mOcclusionDebugImage->setTexture(mOcclusionDebugTexture);
  559. mOcclusionDebugImage->setAlignment(HA_RIGHT, VA_BOTTOM);
  560. uiRoot->addChild(mOcclusionDebugImage);
  561. }
  562. catch (...)
  563. {
  564. }
  565. }
  566. else
  567. {
  568. mOcclusionDebugImage->setVisible(!mOcclusionDebugImage->isVisible());
  569. }
  570. }
  571. if (input->getKeyPress('T'))
  572. mEngine->getDebugHud()->toggle(DEBUGHUD_SHOW_PROFILER);
  573. if (input->getKeyPress('F'))
  574. {
  575. Pipeline* pipeline = mEngine->getPipeline();
  576. EdgeFilterParameters params = pipeline->getEdgeFilter();
  577. if (params.mMaxFilter > 0.0f)
  578. params.mMaxFilter = 0.0f;
  579. else
  580. params.mMaxFilter = 1.0f;
  581. pipeline->setEdgeFilter(params);
  582. }
  583. if (input->getKeyPress(KEY_ESCAPE))
  584. mEngine->exit();
  585. }
  586. void Application::handlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  587. {
  588. using namespace PostRenderUpdate;
  589. float timeStep = eventData[P_TIMESTEP].getFloat();
  590. // Test world raycast
  591. Camera* camera = mCameraEntity->getComponent<Camera>();
  592. UI* ui = mEngine->getUI();
  593. Renderer* renderer = mEngine->getRenderer();
  594. DebugRenderer* debug = mEngine->getDebugRenderer();
  595. if (camera)
  596. {
  597. IntVector2 pos = ui->getCursorPosition();
  598. if (!ui->getElementAt(pos))
  599. {
  600. Ray cameraRay = camera->getScreenRay(((float)pos.mX) / renderer->getWidth(), ((float)pos.mY) / renderer->getHeight());
  601. std::vector<RayQueryResult> result;
  602. RayOctreeQuery query(cameraRay, result, NODE_GEOMETRY, NODE_BILLBOARDSET, false, false, 250.0f, RAY_TRIANGLE);
  603. mScene->getExtension<Octree>()->getNodes(query);
  604. if (result.size())
  605. {
  606. VolumeNode* node = result[0].mNode;
  607. Vector3 rayHitPos = cameraRay.mOrigin + query.mResult[0].mDistance * cameraRay.mDirection;
  608. debug->addBoundingBox(BoundingBox(-0.01f, 0.01f), Matrix4x3(rayHitPos, Quaternion::sIdentity, Vector3::sUnity), Color(1.0f, 1.0f, 1.0f));
  609. // Check for sub-object results (node-specific)
  610. if (result[0].mSubObject < M_MAX_UNSIGNED)
  611. {
  612. // Bone
  613. if (node->getNodeFlags() & NODE_ANIMATEDMODEL)
  614. {
  615. AnimatedModel* anim = static_cast<AnimatedModel*>(node);
  616. Bone* bone = anim->getSkeleton().getBone(result[0].mSubObject);
  617. debug->addBoundingBox(bone->getBoundingBox(), bone->getWorldTransform(), Color(1.0f, 1.0f, 1.0f));
  618. }
  619. // Instance
  620. else if (node->getNodeFlags() & NODE_INSTANCEDMODEL)
  621. {
  622. InstancedModel* instanced = static_cast<InstancedModel*>(node);
  623. Instance* instance = instanced->getInstance(result[0].mSubObject);
  624. Matrix4x3 transform(instance->mPosition, instance->mRotation, instance->mScale);
  625. if (instanced->getInstancesRelative())
  626. transform = instanced->getWorldTransform() * transform;
  627. debug->addBoundingBox(instanced->getBoundingBox().getTransformed(transform), Color(1.0f, 1.0f, 1.0f));
  628. }
  629. // Custom object subgeometry
  630. else if (node->getNodeFlags() & NODE_CUSTOMOBJECT)
  631. {
  632. CustomObject* custom = static_cast<CustomObject*>(node);
  633. const CustomGeometry* geom = custom->getGeometry(result[0].mSubObject);
  634. debug->addBoundingBox(geom->mBoundingBox.getTransformed(custom->getWorldTransform()), Color(1.0f, 1.0f, 1.0f));
  635. }
  636. }
  637. else
  638. debug->addBoundingBox(node->getWorldBoundingBox(), Color(1.0f, 1.0f, 1.0f));
  639. }
  640. }
  641. }
  642. // Update occlusion debug texture if visible
  643. if ((mOcclusionDebugImage) && (mOcclusionDebugImage->isVisible()))
  644. {
  645. PROFILE(App_UpdateOcclusionDebugTextures);
  646. static const float INV_Z_SCALE = 1.0f / (OCCLUSION_Z_SCALE);
  647. // Dump occlusion depth buffer to debug texture
  648. // Get an occlusion buffer matching the aspect ratio, it should be the main view occlusion buffer
  649. const OcclusionBuffer* buffer = mEngine->getPipeline()->getOcclusionBuffer(camera->getAspectRatio());
  650. if (buffer)
  651. {
  652. int width = buffer->getWidth();
  653. int height = buffer->getHeight();
  654. if (buffer->getBuffer())
  655. {
  656. mOcclusionDebugTexture->setSize(width, height, D3DFMT_R32F);
  657. mOcclusionDebugImage->setSize(width, height);
  658. mOcclusionDebugImage->setFullImageRect();
  659. D3DLOCKED_RECT hwRect;
  660. mOcclusionDebugTexture->lock(0, 0, &hwRect);
  661. for (int y = 0; y < height; ++y)
  662. {
  663. float* dest = (float*)(((unsigned char*)hwRect.pBits) + y * hwRect.Pitch);
  664. int* src = buffer->getBuffer() + y * width;
  665. for (int x = 0; x < width; ++x)
  666. {
  667. float depth = src[x] * INV_Z_SCALE;
  668. dest[x] = depth * 0.5f;
  669. }
  670. }
  671. mOcclusionDebugTexture->unlock();
  672. }
  673. }
  674. }
  675. }
  676. void Application::handleMouseButtonDown(StringHash eventType, VariantMap& eventData)
  677. {
  678. using namespace MouseButtonDown;
  679. int button = eventData[P_BUTTON].getInt();
  680. if (button == MOUSEB_RIGHT)
  681. {
  682. UIElement* cursor = mEngine->getUICursor();
  683. if (cursor)
  684. cursor->setVisible(false);
  685. }
  686. if (button == MOUSEB_LEFT)
  687. {
  688. // Test creating a new physics object
  689. if (mCameraEntity)
  690. {
  691. Camera* camera = mCameraEntity->getComponent<Camera>();
  692. Octree* octree = mScene->getExtension<Octree>();
  693. PhysicsWorld* world = mScene->getExtension<PhysicsWorld>();
  694. Entity* newEntity = mScene->createEntity();
  695. RigidBody* body = new RigidBody(world);
  696. body->setMode(PHYS_DYNAMIC);
  697. body->setPosition(camera->getPosition());
  698. body->setRotation(camera->getRotation());
  699. body->setScale(0.1f);
  700. body->setFriction(1.0f);
  701. body->setAngularMaxVelocity(500.0f);
  702. body->setCollisionShape(mCache->getResource<CollisionShape>("Physics/Box.xml"));
  703. body->setCollisionGroup(1);
  704. body->setCollisionMask(3);
  705. body->setLinearVelocity(camera->getUpVector() + camera->getForwardVector() * 10.0f);
  706. StaticModel* object = new StaticModel(octree);
  707. object->setModel(mCache->getResource<Model>("Models/Box.mdl"));
  708. object->setMaterial(mCache->getResource<Material>("Materials/Test.xml"));
  709. object->setCastShadows(true);
  710. object->setShadowDistance(75.0f);
  711. object->setDrawDistance(100.0f);
  712. body->addChild(object);
  713. newEntity->addComponent(body);
  714. newEntity->addComponent(object);
  715. }
  716. }
  717. }
  718. void Application::handleMouseButtonUp(StringHash eventType, VariantMap& eventData)
  719. {
  720. using namespace MouseButtonDown;
  721. if (eventData[P_BUTTON].getInt() == MOUSEB_RIGHT)
  722. {
  723. UIElement* cursor = mEngine->getUICursor();
  724. if (cursor)
  725. cursor->setVisible(true);
  726. }
  727. }
  728. void Application::handleMouseMove(StringHash eventType, VariantMap& eventData)
  729. {
  730. using namespace MouseMove;
  731. if (eventData[P_BUTTONS].getInt() & MOUSEB_RIGHT)
  732. {
  733. int mousedx = eventData[P_X].getInt();
  734. int mousedy = eventData[P_Y].getInt();
  735. yaw += mousedx / 10.0f;
  736. pitch += mousedy / 10.0f;
  737. if (pitch < -90.0f)
  738. pitch = -90.0f;
  739. if (pitch > 90.0f)
  740. pitch = 90.0f;
  741. if (mCameraEntity)
  742. mCameraEntity->getComponent<Camera>()->setRotation(Quaternion(yaw, Vector3::sUp) * Quaternion(pitch, Vector3::sRight));
  743. }
  744. }
  745. void calculateTangents(float* vertexData, unsigned vertexCount, const unsigned short* indexData, unsigned indexCount)
  746. {
  747. // Tangent generation from
  748. // http://www.terathon.com/code/tangent.html
  749. static const int V_OFS = 0;
  750. static const int N_OFS = 3;
  751. static const int UV_OFS = 6;
  752. static const int T_OFS = 8;
  753. static const int V_SIZE = 12;
  754. Vector3 *tan1 = new Vector3[vertexCount * 2];
  755. Vector3 *tan2 = tan1 + vertexCount;
  756. memset(tan1, 0, sizeof(Vector3) * vertexCount * 2);
  757. for (unsigned a = 0; a < indexCount; a += 3)
  758. {
  759. unsigned short i1 = indexData[a+0];
  760. unsigned short i2 = indexData[a+1];
  761. unsigned short i3 = indexData[a+2];
  762. const Vector3 v1 = Vector3(&vertexData[i1 * V_SIZE + V_OFS]);
  763. const Vector3 v2 = Vector3(&vertexData[i2 * V_SIZE + V_OFS]);
  764. const Vector3 v3 = Vector3 (&vertexData[i3 * V_SIZE + V_OFS]);
  765. const Vector2 w1 = Vector2(&vertexData[i1 * V_SIZE + UV_OFS]);
  766. const Vector2 w2 = Vector2(&vertexData[i2 * V_SIZE + UV_OFS]);
  767. const Vector2 w3 = Vector2(&vertexData[i3 * V_SIZE + UV_OFS]);
  768. float x1 = v2.mX - v1.mX;
  769. float x2 = v3.mX - v1.mX;
  770. float y1 = v2.mY - v1.mY;
  771. float y2 = v3.mY - v1.mY;
  772. float z1 = v2.mZ - v1.mZ;
  773. float z2 = v3.mZ - v1.mZ;
  774. float s1 = w2.mX - w1.mX;
  775. float s2 = w3.mX - w1.mX;
  776. float t1 = w2.mY - w1.mY;
  777. float t2 = w3.mY - w1.mY;
  778. float r = 1.0f / (s1 * t2 - s2 * t1);
  779. Vector3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
  780. (t2 * z1 - t1 * z2) * r);
  781. Vector3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
  782. (s1 * z2 - s2 * z1) * r);
  783. tan1[i1] += sdir;
  784. tan1[i2] += sdir;
  785. tan1[i3] += sdir;
  786. tan2[i1] += tdir;
  787. tan2[i2] += tdir;
  788. tan2[i3] += tdir;
  789. }
  790. for (unsigned a = 0; a < vertexCount; a++)
  791. {
  792. const Vector3 n = Vector3(&vertexData[a * V_SIZE + N_OFS]);
  793. const Vector3 t = Vector3(tan1[a]);
  794. Vector3 xyz;
  795. float w;
  796. // Gram-Schmidt orthogonalize
  797. xyz = (t - n * n.dotProduct(t)).getNormalized();
  798. // Calculate handedness
  799. w = n.crossProduct(t).dotProduct(tan2[a]) < 0.0f ? -1.0f : 1.0f;
  800. vertexData[a * V_SIZE + T_OFS] = xyz.mX;
  801. vertexData[a * V_SIZE + T_OFS + 1] = xyz.mY;
  802. vertexData[a * V_SIZE + T_OFS + 2] = xyz.mZ;
  803. vertexData[a * V_SIZE + T_OFS + 3] = w;
  804. }
  805. delete[] tan1;
  806. }