SceneBaker.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. // Copyright (c) 2014-2017, THUNDERBEAST GAMES LLC All rights reserved
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. //
  21. #include <xmmintrin.h>
  22. #include <pmmintrin.h>
  23. #include <cmath>
  24. #include <cfloat>
  25. #include <ThirdParty/STB/stb_rect_pack.h>
  26. #include <Atomic/Core/WorkQueue.h>
  27. #include <Atomic/IO/Log.h>
  28. #include <Atomic/IO/FileSystem.h>
  29. #include <Atomic/Resource/ResourceCache.h>
  30. #include <Atomic/Graphics/Zone.h>
  31. #include <Atomic/Graphics/Light.h>
  32. #include <Atomic/Graphics/StaticModel.h>
  33. #include "LightRay.h"
  34. #include "BakeModel.h"
  35. #include "BakeMesh.h"
  36. #include "BakeLight.h"
  37. #include "EmbreeScene.h"
  38. #include "LightMapPacker.h"
  39. #include "SceneBaker.h"
  40. #include "Photons.h"
  41. namespace AtomicGlow
  42. {
  43. SceneBaker::SceneBaker(Context* context, const String &projectPath) : Object(context),
  44. currentLightMode_(GLOW_LIGHTMODE_UNDEFINED),
  45. currentGIPass_(0),
  46. projectPath_(AddTrailingSlash(projectPath)),
  47. standaloneMode_(true)
  48. {
  49. embreeScene_ = new EmbreeScene(context_);
  50. }
  51. SceneBaker::~SceneBaker()
  52. {
  53. }
  54. bool SceneBaker::SaveLitScene()
  55. {
  56. if (!standaloneMode_)
  57. {
  58. ATOMIC_LOGERROR("SceneBaker::SaveLitScene() - only supported in standalone mode");
  59. return false;
  60. }
  61. String sceneFilename = AddTrailingSlash(projectPath_) + "Resources/" + scene_->GetFileName();
  62. File saveFile(context_, sceneFilename, FILE_WRITE);
  63. return scene_->SaveXML(saveFile);
  64. }
  65. bool SceneBaker::WriteBakeData(VectorBuffer& buffer)
  66. {
  67. buffer.Clear();
  68. // protocol is very simple right now, can easily be expanded
  69. buffer.WriteUInt(bakeMeshes_.Size());
  70. for (unsigned i = 0; i < bakeMeshes_.Size(); i++)
  71. {
  72. BakeMesh* bakeMesh = bakeMeshes_[i];
  73. Node* node = bakeMesh->GetNode();
  74. StaticModel* staticModel = bakeMesh->GetStaticModel();
  75. buffer.WriteUInt(node->GetID());
  76. buffer.WriteUInt(staticModel->GetID());
  77. buffer.WriteUInt(staticModel->GetLightMask());
  78. buffer.WriteUInt(staticModel->GetLightmapIndex());
  79. buffer.WriteVector4(staticModel->GetLightmapTilingOffset());
  80. }
  81. return true;
  82. }
  83. bool SceneBaker::GenerateLightmaps()
  84. {
  85. ATOMIC_LOGINFO("Generating Lightmaps");
  86. for (unsigned i = 0; i < bakeMeshes_.Size(); i++)
  87. {
  88. BakeMesh* mesh = bakeMeshes_[i];
  89. mesh->GenerateRadianceMap();
  90. }
  91. SharedPtr<LightMapPacker> packer(new LightMapPacker(context_));
  92. for (unsigned i = 0; i < bakeMeshes_.Size(); i++)
  93. {
  94. BakeMesh* mesh = bakeMeshes_[i];
  95. SharedPtr<RadianceMap> radianceMap = mesh->GetRadianceMap();
  96. if (radianceMap.NotNull())
  97. {
  98. packer->AddRadianceMap(radianceMap);
  99. }
  100. }
  101. packer->Pack();
  102. if (!packer->SaveLightmaps(projectPath_, scene_->GetFileName()))
  103. {
  104. return false;
  105. }
  106. if (standaloneMode_)
  107. {
  108. if (!SaveLitScene())
  109. return false;
  110. }
  111. return WriteBakeData(bakeData_);
  112. }
  113. void SceneBaker::TraceRay(LightRay* lightRay, const PODVector<BakeLight*>& bakeLights)
  114. {
  115. if (currentLightMode_ == GLOW_LIGHTMODE_DIRECT)
  116. {
  117. DirectLight(lightRay, bakeLights);
  118. }
  119. else
  120. {
  121. IndirectLight(lightRay);
  122. }
  123. }
  124. bool SceneBaker::LightDirect()
  125. {
  126. // Direct Lighting
  127. currentLightMode_ = GLOW_LIGHTMODE_DIRECT;
  128. if (!bakeMeshes_.Size())
  129. {
  130. ATOMIC_LOGINFO("SceneBaker::LightDirect() - No bake meshes found");
  131. bakeLights_.Clear();
  132. return false;
  133. }
  134. for (unsigned i = 0; i < bakeMeshes_.Size(); i++)
  135. {
  136. BakeMesh* mesh = bakeMeshes_[i];
  137. mesh->Light(GLOW_LIGHTMODE_DIRECT);
  138. }
  139. return true;
  140. }
  141. void SceneBaker::LightDirectFinish()
  142. {
  143. }
  144. bool SceneBaker::EmitPhotons()
  145. {
  146. Photons photons(this, GlobalGlowSettings.photonPassCount_, GlobalGlowSettings.photonBounceCount_,
  147. GlobalGlowSettings.photonEnergyThreshold_, GlobalGlowSettings.photonMaxDistance_);
  148. int numPhotons = photons.Emit(bakeLights_);
  149. ATOMIC_LOGINFOF("SceneBaker::EmitPhotons() - %i photons emitted", numPhotons);
  150. if (!numPhotons)
  151. {
  152. return false;
  153. }
  154. for( unsigned i = 0; i < bakeMeshes_.Size(); i++ )
  155. {
  156. if( PhotonMap* photons = bakeMeshes_[i]->GetPhotonMap() )
  157. {
  158. photons->Gather( GlobalGlowSettings.finalGatherRadius_ );
  159. }
  160. }
  161. return true;
  162. }
  163. bool SceneBaker::LightGI()
  164. {
  165. // Indirect Lighting
  166. currentLightMode_ = GLOW_LIGHTMODE_INDIRECT;
  167. // We currently only need one GI pass
  168. if (!GlobalGlowSettings.giEnabled_ || currentGIPass_ >= 1)
  169. {
  170. return false;
  171. }
  172. ATOMIC_LOGINFOF("GI Pass #%i of %i", currentGIPass_ + 1, 1);
  173. bool photons = EmitPhotons();
  174. if (!photons)
  175. return false;
  176. for (unsigned i = 0; i < bakeMeshes_.Size(); i++)
  177. {
  178. BakeMesh* mesh = bakeMeshes_[i];
  179. mesh->Light(GLOW_LIGHTMODE_INDIRECT);
  180. }
  181. return true;
  182. }
  183. void SceneBaker::LightGIFinish()
  184. {
  185. currentGIPass_++;
  186. }
  187. bool SceneBaker::Light(const GlowLightMode lightMode)
  188. {
  189. if (lightMode == GLOW_LIGHTMODE_DIRECT)
  190. {
  191. if (!LightDirect())
  192. {
  193. currentLightMode_ = GLOW_LIGHTMODE_COMPLETE;
  194. ATOMIC_LOGINFO("Cycle: Direct Lighting - no work to be done");
  195. return false;
  196. }
  197. ATOMIC_LOGINFO("Cycle: Direct Lighting");
  198. return true;
  199. }
  200. if (lightMode == GLOW_LIGHTMODE_INDIRECT)
  201. {
  202. if (!LightGI())
  203. {
  204. currentLightMode_ = GLOW_LIGHTMODE_COMPLETE;
  205. // We currently only need one GI pass
  206. if (GlobalGlowSettings.giEnabled_ && currentGIPass_ == 0)
  207. {
  208. ATOMIC_LOGINFO("Cycle: GI - no work to be done");
  209. }
  210. return false;
  211. }
  212. return true;
  213. }
  214. return true;
  215. }
  216. void SceneBaker::LightFinishCycle()
  217. {
  218. if (currentLightMode_ == GLOW_LIGHTMODE_DIRECT)
  219. {
  220. LightDirectFinish();
  221. }
  222. if (currentLightMode_ == GLOW_LIGHTMODE_INDIRECT)
  223. {
  224. LightGIFinish();
  225. }
  226. }
  227. void SceneBaker::QueryLights(const BoundingBox& bbox, PODVector<BakeLight*>& lights)
  228. {
  229. lights.Clear();
  230. for (unsigned i = 0; i < bakeLights_.Size(); i++)
  231. {
  232. // TODO: filter on zone, range, groups
  233. lights.Push(bakeLights_[i]);
  234. }
  235. }
  236. bool SceneBaker::Preprocess()
  237. {
  238. Vector<SharedPtr<BakeMesh>>::Iterator itr = bakeMeshes_.Begin();
  239. while (itr != bakeMeshes_.End())
  240. {
  241. (*itr)->Preprocess();
  242. itr++;
  243. }
  244. embreeScene_->Commit();
  245. return true;
  246. }
  247. bool SceneBaker::LoadScene(const String& filename)
  248. {
  249. ResourceCache* cache = GetSubsystem<ResourceCache>();
  250. SharedPtr<File> file = cache->GetFile(filename);
  251. if (!file || !file->IsOpen())
  252. {
  253. return false;
  254. }
  255. scene_ = new Scene(context_);
  256. if (!scene_->LoadXML(*file))
  257. {
  258. scene_ = 0;
  259. return false;
  260. }
  261. // IMPORTANT!, if scene updates are enabled
  262. // the Octree component will add work queue items
  263. // and will call WorkQueue->Complete(), see Octree::HandleRenderUpdate
  264. scene_->SetUpdateEnabled(false);
  265. // Zones
  266. PODVector<Node*> zoneNodes;
  267. PODVector<Zone*> zones;
  268. scene_->GetChildrenWithComponent<Zone>(zoneNodes, true);
  269. for (unsigned i = 0; i < zoneNodes.Size(); i++)
  270. {
  271. Zone* zone = zoneNodes[i]->GetComponent<Zone>();
  272. if (!zone->GetNode()->IsEnabled() || !zone->IsEnabled())
  273. continue;
  274. zones.Push(zone);;
  275. BakeLight* bakeLight = BakeLight::CreateZoneLight(this, zone->GetAmbientColor());
  276. bakeLights_.Push(SharedPtr<BakeLight>(bakeLight));
  277. }
  278. // Lights
  279. PODVector<Node*> lightNodes;
  280. scene_->GetChildrenWithComponent<Atomic::Light>(lightNodes, true);
  281. for (unsigned i = 0; i < lightNodes.Size(); i++)
  282. {
  283. Node* lightNode = lightNodes[i];
  284. Atomic::Light* light = lightNode->GetComponent<Atomic::Light>();
  285. if (!lightNode->IsEnabled() || !light->IsEnabled())
  286. continue;
  287. if (light->GetLightType() == LIGHT_DIRECTIONAL)
  288. {
  289. /*
  290. SharedPtr<DirectionalBakeLight> dlight(new DirectionalBakeLight(context_, this));
  291. dlight->SetLight(light);
  292. bakeLights_.Push(dlight);
  293. */
  294. }
  295. else if (light->GetLightType() == LIGHT_POINT)
  296. {
  297. BakeLight* bakeLight = BakeLight::CreatePointLight(this, lightNode->GetWorldPosition(), light->GetRange(), light->GetColor(), 1.0f, light->GetCastShadows());
  298. bakeLights_.Push(SharedPtr<BakeLight>(bakeLight));
  299. }
  300. }
  301. // Static Models
  302. PODVector<StaticModel*> staticModels;
  303. scene_->GetComponents<StaticModel>(staticModels, true);
  304. for (unsigned i = 0; i < staticModels.Size(); i++)
  305. {
  306. StaticModel* staticModel = staticModels[i];
  307. if (!staticModel->GetNode()->IsEnabled() || !staticModel->IsEnabled())
  308. continue;
  309. Vector3 center = staticModel->GetWorldBoundingBox().Center();
  310. int bestPriority = M_MIN_INT;
  311. Zone* newZone = 0;
  312. for (PODVector<Zone*>::Iterator i = zones.Begin(); i != zones.End(); ++i)
  313. {
  314. Zone* zone = *i;
  315. int priority = zone->GetPriority();
  316. if (priority > bestPriority && (staticModel->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  317. {
  318. newZone = zone;
  319. bestPriority = priority;
  320. }
  321. }
  322. staticModel->SetZone(newZone, false);
  323. if (staticModel->GetModel() && (staticModel->GetLightmap() ||staticModel->GetCastShadows()))
  324. {
  325. Model* model = staticModel->GetModel();
  326. for (unsigned i = 0; i < model->GetNumGeometries(); i++)
  327. {
  328. Geometry* geo = model->GetGeometry(i, 0);
  329. if (!geo)
  330. {
  331. ATOMIC_LOGERRORF("SceneBaker::LoadScene - model without geometry: %s", model->GetName().CString());
  332. return false;
  333. }
  334. const unsigned char* indexData = 0;
  335. unsigned indexSize = 0;
  336. unsigned vertexSize = 0;
  337. const unsigned char* vertexData = 0;
  338. const PODVector<VertexElement>* elements = 0;
  339. geo->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  340. if (!indexData || !indexSize || !vertexData || !vertexSize || !elements)
  341. {
  342. ATOMIC_LOGERRORF("SceneBaker::LoadScene - Unable to inspect geometry elements: %s", model->GetName().CString());
  343. return false;
  344. }
  345. int texcoords = 0;
  346. for (unsigned i = 0; i < elements->Size(); i++)
  347. {
  348. const VertexElement& element = elements->At(i);
  349. if (element.type_ == TYPE_VECTOR2 && element.semantic_ == SEM_TEXCOORD)
  350. {
  351. texcoords++;
  352. }
  353. }
  354. if (texcoords < 2)
  355. {
  356. ATOMIC_LOGERRORF("SceneBaker::LoadScene - Model without lightmap UV set, skipping: %s", model->GetName().CString());
  357. continue;
  358. }
  359. }
  360. SharedPtr<BakeMesh> meshMap (new BakeMesh(context_, this));
  361. meshMap->SetStaticModel(staticModel);
  362. bakeMeshes_.Push(meshMap);
  363. }
  364. }
  365. return Preprocess();
  366. }
  367. // DIRECT LIGHT
  368. void SceneBaker::DirectLight( LightRay* lightRay, const PODVector<BakeLight*>& bakeLights )
  369. {
  370. for (unsigned i = 0; i < bakeLights.Size(); i++)
  371. {
  372. BakeLight* bakeLight = bakeLights[i];
  373. Color influence;
  374. // if (light->GetVertexGenerator())
  375. //{
  376. // influence = DirectLightFromPointSet( lightRay, bakeLight );
  377. //}
  378. //else
  379. {
  380. influence = DirectLightFromPoint( lightRay, bakeLight );
  381. }
  382. if (influence.r_ || influence.g_ || influence.b_ )
  383. {
  384. lightRay->samplePoint_.bakeMesh->ContributeRadiance(lightRay, influence.ToVector3());
  385. }
  386. }
  387. }
  388. Color SceneBaker::DirectLightFromPoint( LightRay* lightRay, const BakeLight* light ) const
  389. {
  390. float influence = DirectLightInfluenceFromPoint( lightRay, light->GetPosition(), light );
  391. if( influence > 0.0f )
  392. {
  393. return light->GetColor() * light->GetIntensity() * influence;
  394. }
  395. return Color::BLACK;
  396. }
  397. Color SceneBaker::DirectLightFromPointSet( LightRay* lightRay, const BakeLight* light ) const
  398. {
  399. /*
  400. LightVertexGenerator* vertexGenerator = light->vertexGenerator();
  401. // ** No light vertices generated - just exit
  402. if( vertexGenerator->vertexCount() == 0 ) {
  403. return Rgb( 0, 0, 0 );
  404. }
  405. const LightVertexBuffer& vertices = vertexGenerator->vertices();
  406. Rgb color = Rgb( 0, 0, 0 );
  407. for( int i = 0, n = vertexGenerator->vertexCount(); i < n; i++ ) {
  408. const LightVertex& vertex = vertices[i];
  409. float influence = influenceFromPoint( lumel, vertex.m_position + light->position(), light );
  410. // ** We have a non-zero light influence - add a light color to final result
  411. if( influence > 0.0f ) {
  412. color += light->color() * light->intensity() * influence;
  413. }
  414. }
  415. return color / static_cast<float>( vertexGenerator->vertexCount() );
  416. */
  417. return Color::BLACK;
  418. }
  419. // ** DirectLight::influenceFromPoint
  420. float SceneBaker::DirectLightInfluenceFromPoint(LightRay* lightRay, const Vector3 &point, const BakeLight* light ) const
  421. {
  422. float inf = 1.0f;
  423. float att = 1.0f;
  424. float cut = 1.0f;
  425. float distance = 0.0f;
  426. // Calculate light influence.
  427. if( const LightInfluence* influence = light->GetInfluenceModel() )
  428. {
  429. inf = influence->Calculate( lightRay, point, distance );
  430. }
  431. // Calculate light cutoff.
  432. if( const LightCutoff* cutoff = light->GetCutoffModel() )
  433. {
  434. cut = cutoff->Calculate( lightRay->samplePoint_.position);
  435. }
  436. // Calculate light attenuation
  437. if( const LightAttenuation* attenuation = light->GetAttenuationModel() )
  438. {
  439. att = attenuation->Calculate( distance );
  440. }
  441. // Return final influence
  442. return inf * att * cut;
  443. }
  444. // INDIRECT LIGHT
  445. void SceneBaker::IndirectLight( LightRay* lightRay)
  446. {
  447. BakeMesh* bakeMesh = 0;
  448. LightRay::SamplePoint& source = lightRay->samplePoint_;
  449. Vector3 gathered;
  450. int nsamples = GlobalGlowSettings.finalGatherSamples_;
  451. float maxDistance = GlobalGlowSettings.finalGatherDistance_; // , settings.m_finalGatherRadius, settings.m_skyColor, settings.m_ambientColor
  452. for( int k = 0; k <nsamples; k++ )
  453. {
  454. Vector3 dir;
  455. Vector3::GetRandomHemisphereDirection(dir, source.normal);
  456. float influence = Max<float>( source.normal.DotProduct(dir), 0.0f );
  457. if (influence > 1.0f)
  458. {
  459. // ATOMIC_LOGINFO("This shouldn't happen");
  460. }
  461. RTCRay& ray = lightRay->rtcRay_;
  462. lightRay->SetupRay(source.position, dir, .001f, maxDistance);
  463. rtcIntersect(GetEmbreeScene()->GetRTCScene(), ray);
  464. if (ray.geomID == RTC_INVALID_GEOMETRY_ID)
  465. {
  466. // gathered += skyColor * influence + ambientColor;
  467. continue;
  468. }
  469. bakeMesh = GetEmbreeScene()->GetBakeMesh(ray.geomID);
  470. if (!bakeMesh)
  471. {
  472. continue;
  473. }
  474. if (bakeMesh == source.bakeMesh && ray.primID == source.triangle)
  475. {
  476. // do not self light
  477. continue;
  478. }
  479. const BakeMesh::MMTriangle* tri = bakeMesh->GetTriangle(ray.primID);
  480. // TODO: interpolate normal, if artifacting
  481. if( dir.DotProduct(tri->normal_) >= 0.0f )
  482. {
  483. continue;
  484. }
  485. PhotonMap* photonMap = bakeMesh->GetPhotonMap();
  486. if (!photonMap)
  487. {
  488. continue;
  489. }
  490. Vector3 bary(ray.u, ray.v, 1.0f-ray.u-ray.v);
  491. Vector2 st;
  492. bakeMesh->GetST(ray.primID, 1, bary, st);
  493. int photons;
  494. Color pcolor;
  495. Color gcolor;
  496. if (!photonMap->GetPhoton( (int) ray.primID, st, pcolor, photons, gcolor, true))
  497. {
  498. continue;
  499. }
  500. gathered += gcolor.ToVector3() * influence;// + ambientColor;
  501. }
  502. gathered /= static_cast<float>( nsamples );
  503. if (gathered.x_ >= 0.01f || gathered.y_ >= 0.01f || gathered.z_ >= 0.01f )
  504. {
  505. source.bakeMesh->ContributeRadiance(lightRay, gathered, GLOW_LIGHTMODE_INDIRECT);
  506. }
  507. }
  508. }