BakeLight.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // Copyright (c) 2014-2017, THUNDERBEAST GAMES LLC All rights reserved
  2. // Portions Copyright (c) 2015 Dmitry Sovetov
  3. // Copyright 2009-2017 Intel Corporation
  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 <Atomic/IO/Log.h>
  24. #include <Atomic/Graphics/Zone.h>
  25. #include <AtomicGlow/Common/GlowSettings.h>
  26. #include "EmbreeScene.h"
  27. #include "LightRay.h"
  28. #include "BakeLight.h"
  29. #include "BakeMesh.h"
  30. #include "SceneBaker.h"
  31. namespace AtomicGlow
  32. {
  33. BakeLight::BakeLight(Context* context, SceneBaker* sceneBaker) : BakeNode(context, sceneBaker),
  34. color_(Color::WHITE),
  35. intensity_( 0.0f ),
  36. castsShadow_( false )
  37. {
  38. }
  39. BakeLight::~BakeLight()
  40. {
  41. }
  42. LightCutoff* BakeLight::GetCutoffModel( void ) const
  43. {
  44. return cutoffModel_;
  45. }
  46. void BakeLight::SetCutoffModel( LightCutoff* value )
  47. {
  48. cutoffModel_ = value;
  49. }
  50. LightInfluence* BakeLight::GetInfluenceModel( void ) const
  51. {
  52. return influenceModel_;
  53. }
  54. void BakeLight::SetInfluenceModel( LightInfluence* value )
  55. {
  56. influenceModel_ = value;
  57. }
  58. LightVertexGenerator* BakeLight::GetVertexGenerator( void ) const
  59. {
  60. return vertexGenerator_;
  61. }
  62. void BakeLight::SetVertexGenerator( LightVertexGenerator* value )
  63. {
  64. vertexGenerator_ = value;
  65. }
  66. LightAttenuation* BakeLight::GetAttenuationModel( void ) const
  67. {
  68. return attenuationModel_;
  69. }
  70. void BakeLight::SetAttenuationModel( LightAttenuation* value )
  71. {
  72. attenuationModel_ = value;
  73. }
  74. PhotonEmitter* BakeLight::GetPhotonEmitter( void ) const
  75. {
  76. return photonEmitter_;
  77. }
  78. void BakeLight::SetPhotonEmitter( PhotonEmitter* value )
  79. {
  80. photonEmitter_ = value;
  81. }
  82. const Vector3& BakeLight::GetPosition( void ) const
  83. {
  84. return position_;
  85. }
  86. void BakeLight::SetPosition( const Vector3& value )
  87. {
  88. position_ = value;
  89. }
  90. const Color& BakeLight::GetColor( void ) const
  91. {
  92. return color_;
  93. }
  94. void BakeLight::SetColor( const Color& value )
  95. {
  96. color_ = value;
  97. }
  98. float BakeLight::GetIntensity( void ) const
  99. {
  100. return intensity_;
  101. }
  102. void BakeLight::SetIntensity( float value )
  103. {
  104. intensity_ = value;
  105. }
  106. bool BakeLight::GetCastsShadow( void ) const
  107. {
  108. return castsShadow_;
  109. }
  110. void BakeLight::SetCastsShadow( bool value )
  111. {
  112. castsShadow_ = value;
  113. }
  114. BakeLight* BakeLight::CreateZoneLight( SceneBaker* baker, const Color& color)
  115. {
  116. BakeLight* light = new BakeLight(baker->GetContext(), baker);
  117. light->SetCastsShadow( false );
  118. light->SetColor( color );
  119. light->SetIntensity(1.0f);
  120. if (GlobalGlowSettings.aoEnabled_)
  121. {
  122. light->SetInfluenceModel( new AmbientOcclusionInfluence( light ) );
  123. }
  124. return light;
  125. }
  126. BakeLight* BakeLight::CreatePointLight( SceneBaker* baker, const Vector3& position, float radius, const Color& color, float intensity, bool castsShadow )
  127. {
  128. BakeLight* light = new BakeLight(baker->GetContext(), baker);
  129. light->SetInfluenceModel( new LightInfluence( light ) );
  130. light->SetAttenuationModel( new LinearLightAttenuation( light, radius ) );
  131. light->SetCutoffModel( new LightCutoff( light ) );
  132. light->SetPhotonEmitter( new PhotonEmitter( light ) );
  133. light->SetCastsShadow( castsShadow );
  134. light->SetPosition( position );
  135. light->SetColor( color );
  136. light->SetIntensity( intensity );
  137. return light;
  138. }
  139. BakeLight* BakeLight::CreateSpotLight( SceneBaker* baker, const Vector3& position, const Vector3& direction, float cutoff, float radius, const Color& color, float intensity, bool castsShadow )
  140. {
  141. BakeLight* light = new BakeLight(baker->GetContext(), baker);
  142. light->SetInfluenceModel( new LightInfluence( light ) );
  143. light->SetAttenuationModel( new LinearLightAttenuation( light, radius ) );
  144. light->SetCutoffModel( new LightSpotCutoff( light, direction, cutoff, 1.0f ) );
  145. light->SetPhotonEmitter( new PhotonEmitter( light ) );
  146. light->SetCastsShadow( castsShadow );
  147. light->SetPosition( position );
  148. light->SetColor( color );
  149. light->SetIntensity( intensity );
  150. return light;
  151. }
  152. BakeLight* BakeLight::CreateDirectionalLight( SceneBaker* baker, const Vector3& direction, const Color& color, float intensity, bool castsShadow )
  153. {
  154. BakeLight* light = new BakeLight(baker->GetContext(), baker);
  155. light->SetInfluenceModel( new DirectionalLightInfluence( light, direction ) );
  156. light->SetPhotonEmitter( new DirectionalPhotonEmitter( light, direction ) );
  157. light->SetCastsShadow( castsShadow );
  158. light->SetColor( color );
  159. light->SetIntensity( intensity );
  160. return light;
  161. }
  162. BakeLight* BakeLight::CreateAreaLight( SceneBaker* baker, BakeMesh* bakeMesh, const Vector3& position, const Color& color, float intensity, bool castsShadow )
  163. {
  164. BakeLight* light = new BakeLight(baker->GetContext(), baker);
  165. light->SetInfluenceModel( new LightInfluence( light ) );
  166. const BoundingBox bbox = bakeMesh->GetBoundingBox();
  167. float volume = 7.25f; /*(bbox.max_.x_ - bbox.min_.x_) * (bbox.max_.y_ - bbox.min_.y_) * (bbox.max_.z_ - bbox.min_.z_)*/;
  168. light->SetAttenuationModel( new LinearLightAttenuation( light, volume ) );
  169. light->SetPhotonEmitter( new PhotonEmitter( light ) );
  170. light->SetCutoffModel( new LightCutoff( light ) );
  171. light->SetVertexGenerator( new FaceLightVertexGenerator( bakeMesh, true, 0 ) );
  172. light->SetCastsShadow( castsShadow );
  173. light->SetPosition( position );
  174. light->SetColor( color );
  175. light->SetIntensity( intensity );
  176. light->GetVertexGenerator()->Generate();
  177. return light;
  178. }
  179. // ------------------------------------------------------- LightInfluence --------------------------------------------------------- //
  180. LightInfluence::LightInfluence( const BakeLight* light ) :
  181. light_( light )
  182. {
  183. }
  184. float LightInfluence::Calculate(LightRay* lightRay, const Vector3& light, float& distance ) const
  185. {
  186. LightRay::SamplePoint& source = lightRay->samplePoint_;
  187. Vector3 direction = light - source.position;
  188. distance = direction.Length();
  189. direction.Normalize();
  190. // ** Calculate Lambert's cosine law intensity
  191. float intensity = GetLambert( direction, source.normal );
  192. if( intensity <= 0.001f ) {
  193. return 0.0f;
  194. }
  195. // ** Cast shadow to point
  196. if( light_->GetCastsShadow() )
  197. {
  198. LightRay::SamplePoint& source = lightRay->samplePoint_;
  199. // clean this mess up
  200. RTCScene scene = source.bakeMesh->GetSceneBaker()->GetEmbreeScene()->GetRTCScene();
  201. lightRay->SetupRay(source.position, direction, .001f, distance);
  202. rtcOccluded(scene, lightRay->rtcRay_);
  203. // obstructed? TODO: glass, etc
  204. if (lightRay->rtcRay_.geomID != RTC_INVALID_GEOMETRY_ID)
  205. {
  206. return 0.0f;
  207. }
  208. }
  209. return intensity;
  210. }
  211. float LightInfluence::GetLambert( const Vector3& direction, const Vector3& normal )
  212. {
  213. float dp = direction.DotProduct(normal);
  214. return dp < 0.0f ? 0.0f : dp;
  215. }
  216. // --------------------------------------------------- DirectionalLightInfluence -------------------------------------------------- //
  217. DirectionalLightInfluence::DirectionalLightInfluence( const BakeLight* light, const Vector3& direction )
  218. : LightInfluence( light ), direction_( direction )
  219. {
  220. }
  221. float DirectionalLightInfluence::Calculate(LightRay* lightRay, const Vector3& light, float& distance ) const
  222. {
  223. LightRay::SamplePoint& source = lightRay->samplePoint_;
  224. float intensity = GetLambert( -direction_, source.normal );
  225. if( intensity <= 0.001f )
  226. {
  227. return 0.0f;
  228. }
  229. // clean this mess up
  230. RTCScene scene = source.bakeMesh->GetSceneBaker()->GetEmbreeScene()->GetRTCScene();
  231. lightRay->SetupRay(source.position, -direction_, .001f, LIGHT_LARGE_DISTANCE);
  232. rtcOccluded(scene, lightRay->rtcRay_);
  233. // obstructed? TODO: glass, etc
  234. if (lightRay->rtcRay_.geomID != RTC_INVALID_GEOMETRY_ID)
  235. {
  236. return 0.0f;
  237. }
  238. return intensity;
  239. }
  240. // --------------------------------------------------- AmbientOcclusionInfluence -------------------------------------------------- //
  241. AmbientOcclusionInfluence::AmbientOcclusionInfluence( const BakeLight* light )
  242. : LightInfluence( light )
  243. {
  244. }
  245. float AmbientOcclusionInfluence::Calculate(LightRay* lightRay, const Vector3& light, float& distance ) const
  246. {
  247. LightRay::SamplePoint& source = lightRay->samplePoint_;
  248. if (source.normal == Vector3::ZERO)
  249. return 1.0f;
  250. // clean this mess up
  251. RTCScene scene = source.bakeMesh->GetSceneBaker()->GetEmbreeScene()->GetRTCScene();
  252. const Color& color = light_->GetColor();
  253. Vector3 rad(color.r_, color.g_, color.b_);
  254. if (!GlobalGlowSettings.aoEnabled_)
  255. {
  256. return 1.0f;
  257. }
  258. // TODO: AO using ray packets/streams
  259. RTCRay& ray = lightRay->rtcRay_;
  260. unsigned nsamples = GlobalGlowSettings.nsamples_;
  261. // this needs to be based on model/scale likely?
  262. float aoDepth = GlobalGlowSettings.aoDepth_;
  263. // smallest percent of ao value to use
  264. float aoMin = GlobalGlowSettings.aoMin_;
  265. // brightness control
  266. float multiply = GlobalGlowSettings.aoMultiply_;
  267. // Shoot rays through the differential hemisphere.
  268. int nhits = 0;
  269. float avgDepth = 0.0f;
  270. for (unsigned nsamp = 0; nsamp < nsamples; nsamp++)
  271. {
  272. Vector3 rayDir;
  273. Vector3::GetRandomHemisphereDirection(rayDir, source.normal);
  274. float dotp = source.normal.x_ * rayDir.x_ +
  275. source.normal.y_ * rayDir.y_ +
  276. source.normal.z_ * rayDir.z_;
  277. if (dotp < 0.1f)
  278. {
  279. continue;
  280. }
  281. float variance = 0.0f;//nsamples <= 32 ? 0.0f : aoDepth * ((float) rand() / (float) RAND_MAX) * 0.25f;
  282. float depth = aoDepth + variance;
  283. lightRay->SetupRay(source.position, rayDir, .001f, depth);
  284. rtcOccluded(scene, ray);
  285. if (ray.geomID != RTC_INVALID_GEOMETRY_ID)
  286. {
  287. avgDepth += Min<float>(ray.tfar, aoDepth);
  288. nhits++;
  289. }
  290. }
  291. if (nhits)// && (nsamples <= 32 ? true : nhits > 4))
  292. {
  293. avgDepth /= float(nhits);
  294. avgDepth /= aoDepth;
  295. avgDepth = Clamp<float>(avgDepth, 0.1f, 1.0f) * 100.0f;
  296. avgDepth *= avgDepth;
  297. float ao = avgDepth / 10000.0f;
  298. ao = aoMin + ao/2.0f;
  299. ao *= multiply;
  300. ao = Clamp<float>(ao, aoMin, 1.0f);
  301. return ao;
  302. }
  303. return 1.0f;
  304. }
  305. // --------------------------------------------------------- LightCutoff ---------------------------------------------------------- //
  306. LightCutoff::LightCutoff( const BakeLight* light ) : light_( light )
  307. {
  308. }
  309. float LightCutoff::Calculate( const Vector3& point ) const
  310. {
  311. return 1.0f;
  312. }
  313. float LightCutoff::GetCutoffForDirection( const Vector3& direction ) const
  314. {
  315. return 1.0f;
  316. }
  317. // ------------------------------------------------------- LightSpotCutoff -------------------------------------------------------- //
  318. LightSpotCutoff::LightSpotCutoff( const BakeLight* light, const Vector3& direction, float cutoff, float exponent ) :
  319. LightCutoff( light ), direction_( direction ), cutoff_( cutoff ), exponent_( exponent )
  320. {
  321. }
  322. float LightSpotCutoff::Calculate( const Vector3& point ) const
  323. {
  324. Vector3 dir = point - light_->GetPosition();
  325. dir.Normalize();
  326. return GetCutoffForDirection( dir );
  327. }
  328. float LightSpotCutoff::GetCutoffForDirection( const Vector3& direction ) const
  329. {
  330. float value = direction.DotProduct(direction_);
  331. if( value <= cutoff_ ) {
  332. return 0.0f;
  333. }
  334. value = (1.0f - (1.0f - value) * 1.0f / (1.0f - cutoff_));
  335. if( fabs( 1.0f - exponent_ ) > 0.01f ) {
  336. value = powf( value, exponent_ );
  337. }
  338. return value;
  339. }
  340. // ------------------------------------------------------- LightAttenuation ------------------------------------------------------- //
  341. LightAttenuation::LightAttenuation( const BakeLight* light ) : light_( light )
  342. {
  343. }
  344. // ---------------------------------------------------- LinearLightAttenuation ---------------------------------------------------- //
  345. LinearLightAttenuation::LinearLightAttenuation( const BakeLight* light, float radius, float constant, float linear, float quadratic )
  346. : LightAttenuation( light ), radius_( radius ), constant_( constant ), linear_( linear ), quadratic_( quadratic )
  347. {
  348. }
  349. float LinearLightAttenuation::Calculate( float distance ) const
  350. {
  351. if (fabs(radius_) < 0.01f)
  352. return 0.0f;
  353. float r = distance / radius_;
  354. return Max<float>( 1.0f / (1.0f + constant_ + linear_ * r + quadratic_ * r * r), 0.0f );
  355. }
  356. // -------------------------------------------------------- PhotonEmitter --------------------------------------------------------- //
  357. PhotonEmitter::PhotonEmitter( const BakeLight* light ) :
  358. light_( light )
  359. {
  360. }
  361. int PhotonEmitter::GetPhotonCount( void ) const
  362. {
  363. return static_cast<int>( light_->GetIntensity() * 25000 );
  364. }
  365. void PhotonEmitter::Emit( SceneBaker* sceneBaker, Vector3& position, Vector3& direction ) const
  366. {
  367. position = light_->GetPosition();
  368. Vector3::GetRandomDirection(direction);
  369. }
  370. // --------------------------------------------------- DirectinalPhotonEmitter ---------------------------------------------------- //
  371. DirectionalPhotonEmitter::DirectionalPhotonEmitter( const BakeLight* light, const Vector3& direction ) :
  372. PhotonEmitter( light ), direction_( direction )
  373. {
  374. plane_.Define(direction.Normalized(), light->GetPosition()); // = Plane::calculate( direction, light->position() );
  375. }
  376. void DirectionalPhotonEmitter::Emit( SceneBaker* sceneBaker, Vector3& position, Vector3& direction ) const
  377. {
  378. const BoundingBox& bounds = sceneBaker->GetSceneBounds();
  379. Vector3 randomPoint(Lerp<float>(bounds.min_.x_, bounds.max_.x_, RandZeroOne()),
  380. Lerp<float>(bounds.min_.y_, bounds.max_.y_, RandZeroOne()),
  381. Lerp<float>(bounds.min_.z_, bounds.max_.z_, RandZeroOne()));
  382. position = plane_.Project(randomPoint) - direction_ * ( LIGHT_LARGE_DISTANCE * 0.5f);
  383. direction = direction_;
  384. }
  385. // ---------------------------------------------------- LightVertexGenerator ------------------------------------------------------ //
  386. LightVertexGenerator::LightVertexGenerator( BakeMesh* bakeMesh ) : mesh_( bakeMesh )
  387. {
  388. }
  389. unsigned LightVertexGenerator::GetVertexCount( void ) const
  390. {
  391. return vertices_.Size();
  392. }
  393. const LightVertexVector& LightVertexGenerator::GetVertices( void ) const
  394. {
  395. return vertices_;
  396. }
  397. void LightVertexGenerator::Clear( void )
  398. {
  399. vertices_.Clear();
  400. }
  401. void LightVertexGenerator::Generate( void )
  402. {
  403. Clear();
  404. unsigned numVertices;
  405. const SharedArrayPtr<BakeMesh::MMVertex>& vertices = mesh_->GetVertices(numVertices);
  406. LightVertex lightVertex;
  407. for( unsigned i = 0; i < numVertices; i++ )
  408. {
  409. lightVertex.position_ = vertices[i].position_;
  410. lightVertex.normal_ = vertices[i].normal_;
  411. Push( lightVertex ) ;
  412. }
  413. }
  414. void LightVertexGenerator::Push(const LightVertex &vertex )
  415. {
  416. vertices_.Push( vertex );
  417. }
  418. // ------------------------------------------------- FaceLightVertexGenerator --------------------------------------------------- //
  419. FaceLightVertexGenerator::FaceLightVertexGenerator( BakeMesh* bakeMesh, bool excludeVertices, int maxSubdivisions )
  420. : LightVertexGenerator( bakeMesh ),
  421. excludeVertices_( excludeVertices ),
  422. maxSubdivisions_( maxSubdivisions )
  423. {
  424. }
  425. void FaceLightVertexGenerator::Generate( void )
  426. {
  427. Clear();
  428. if( !excludeVertices_ ) {
  429. LightVertexGenerator::Generate();
  430. }
  431. unsigned numVertices;
  432. const SharedArrayPtr<BakeMesh::MMVertex>& vertices = mesh_->GetVertices(numVertices);
  433. unsigned numTriangles;
  434. const SharedArrayPtr<BakeMesh::MMTriangle>& triangles = mesh_->GetTriangles(numTriangles);
  435. for( unsigned i = 0; i < numTriangles; i++ )
  436. {
  437. const BakeMesh::MMTriangle& mtri = triangles[i];
  438. LightVertex verts[3];
  439. for (int j = 0; j < 3; j++)
  440. {
  441. verts[j].position_ = vertices[mtri.indices_[j]].position_;
  442. verts[j].normal_ = vertices[mtri.indices_[j]].normal_;
  443. }
  444. LightTriangle triangle(verts[0], verts[1], verts[2]);
  445. GenerateFromTriangle( triangle, 0 );
  446. }
  447. }
  448. void FaceLightVertexGenerator::GenerateFromTriangle( const LightTriangle& triangle, int subdivision )
  449. {
  450. // Generate light vertex from triangle centroid
  451. Push( triangle.GetCentroid() );
  452. // The maximum subdivisions exceeded
  453. if( subdivision >= maxSubdivisions_ ) {
  454. return;
  455. }
  456. // Tesselate a triangle
  457. LightTriangle center, corners[3];
  458. triangle.Tesselate( center, corners );
  459. // Process corner triangles
  460. for( int i = 0; i < 3; i++ )
  461. {
  462. GenerateFromTriangle( corners[i], subdivision + 1 );
  463. }
  464. }
  465. // ---------------------------------------------- Triangle ---------------------------------------------- //
  466. LightTriangle::LightTriangle( const LightVertex& a, const LightVertex& b, const LightVertex& c ) :
  467. a_( a ),
  468. b_( b ),
  469. c_( c )
  470. {
  471. centroid_.position_ = (a_.position_ + b_.position_ + c_.position_) / 3.0f;
  472. centroid_.normal_ = (a_.normal_ + b_.normal_ + c_.normal_) / 3.0f;
  473. centroid_.normal_.Normalize();
  474. }
  475. const LightVertex& LightTriangle::GetCentroid( void ) const
  476. {
  477. return centroid_;
  478. }
  479. void LightTriangle::Tesselate( LightTriangle& center, LightTriangle triangles[3] ) const
  480. {
  481. LightVertex xA = LightVertex::Interpolate( a_, b_, 0.5f );
  482. LightVertex xB = LightVertex::Interpolate( b_, c_, 0.5f );
  483. LightVertex xC = LightVertex::Interpolate( c_, a_, 0.5f );
  484. triangles[0] = LightTriangle( a_, xA, xC );
  485. triangles[1] = LightTriangle( xA, b_, xB );
  486. triangles[2] = LightTriangle( xC, xB, c_ );
  487. center = LightTriangle( xA, xB, xC );
  488. }
  489. }