scatterSky.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "scatterSky.h"
  24. #include "core/stream/bitStream.h"
  25. #include "console/consoleTypes.h"
  26. #include "console/engineAPI.h"
  27. #include "sim/netConnection.h"
  28. #include "math/util/sphereMesh.h"
  29. #include "math/mathUtils.h"
  30. #include "math/util/matrixSet.h"
  31. #include "scene/sceneRenderState.h"
  32. #include "lighting/lightInfo.h"
  33. #include "gfx/sim/gfxStateBlockData.h"
  34. #include "gfx/gfxTransformSaver.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "gfx/sim/cubemapData.h"
  37. #include "materials/shaderData.h"
  38. #include "materials/materialManager.h"
  39. #include "materials/baseMatInstance.h"
  40. #include "materials/sceneData.h"
  41. #include "environment/timeOfDay.h"
  42. ConsoleDocClass( ScatterSky,
  43. "@brief Represents both the sun and sky for scenes with a dynamic time of day.\n\n"
  44. "%ScatterSky renders as a dome shaped mesh which is camera relative and always overhead. "
  45. "It is intended to be part of the background of your scene and renders before all "
  46. "other objects types.\n\n"
  47. "%ScatterSky is designed for outdoor scenes which need to transition fluidly "
  48. "between radically different times of day. It will respond to time changes "
  49. "originating from a TimeOfDay object or the elevation field can be directly "
  50. "adjusted.\n\n"
  51. "During day, %ScatterSky uses atmosphereic sunlight scattering "
  52. "aproximations to generate a sky gradient and sun corona. It also calculates "
  53. "the fog color, ambient color, and sun color, which are used for scene "
  54. "lighting. This is user controlled by fields within the ScatterSky group.\n\n"
  55. "During night, %ScatterSky supports can transition to a night sky cubemap and "
  56. "moon sprite. The user can control this and night time colors used for scene "
  57. "lighting with fields within the Night group.\n\n"
  58. "A scene with a ScatterSky should not have any other sky or sun objects "
  59. "as it already fulfills both roles.\n\n"
  60. "%ScatterSky is intended to be used with CloudLayer and TimeOfDay as part of "
  61. "a scene with dynamic lighting. Having a %ScatterSky without a changing "
  62. "time of day would unnecessarily give up artistic control compared and fillrate "
  63. "compared to a SkyBox + Sun setup.\n\n"
  64. "@ingroup Atmosphere"
  65. );
  66. IMPLEMENT_CO_NETOBJECT_V1(ScatterSky);
  67. const F32 ScatterSky::smEarthRadius = (6378.0f * 1000.0f);
  68. const F32 ScatterSky::smAtmosphereRadius = 200000.0f;
  69. const F32 ScatterSky::smViewerHeight = 1.0f;
  70. GFXImplementVertexFormat( ScatterSkyVertex )
  71. {
  72. addElement( "POSITION", GFXDeclType_Float3 );
  73. addElement( "NORMAL", GFXDeclType_Float3 );
  74. addElement( "COLOR", GFXDeclType_Color );
  75. }
  76. ScatterSky::ScatterSky()
  77. {
  78. mPrimCount = 0;
  79. mVertCount = 0;
  80. // Rayleigh scattering constant.
  81. mRayleighScattering = 0.0035f;
  82. mRayleighScattering4PI = mRayleighScattering * 4.0f * M_PI_F;
  83. // Mie scattering constant.
  84. mMieScattering = 0.0045f;
  85. mMieScattering4PI = mMieScattering * 4.0f * M_PI_F;
  86. // Overall scatter scalar.
  87. mSkyBrightness = 25.0f;
  88. // The Mie phase asymmetry factor.
  89. mMiePhaseAssymetry = -0.75f;
  90. mSphereInnerRadius = 1.0f;
  91. mSphereOuterRadius = 1.0f * 1.025f;
  92. mScale = 1.0f / (mSphereOuterRadius - mSphereInnerRadius);
  93. // 650 nm for red
  94. // 570 nm for green
  95. // 475 nm for blue
  96. mWavelength.set( 0.650f, 0.570f, 0.475f, 0 );
  97. mWavelength4[0] = mPow(mWavelength[0], 4.0f);
  98. mWavelength4[1] = mPow(mWavelength[1], 4.0f);
  99. mWavelength4[2] = mPow(mWavelength[2], 4.0f);
  100. mRayleighScaleDepth = 0.25f;
  101. mMieScaleDepth = 0.1f;
  102. mAmbientColor.set( 0, 0, 0, 1.0f );
  103. mAmbientScale.set( 1.0f, 1.0f, 1.0f, 1.0f );
  104. mSunColor.set( 0, 0, 0, 1.0f );
  105. mSunScale = ColorF::WHITE;
  106. mFogColor.set( 0, 0, 0, 1.0f );
  107. mFogScale = ColorF::WHITE;
  108. mExposure = 1.0f;
  109. mNightInterpolant = 0;
  110. mShader = NULL;
  111. mTimeOfDay = 0;
  112. mSunAzimuth = 0.0f;
  113. mSunElevation = 35.0f;
  114. mMoonAzimuth = 0.0f;
  115. mMoonElevation = 45.0f;
  116. mBrightness = 1.0f;
  117. mCastShadows = true;
  118. mDirty = true;
  119. mLight = LightManager::createLightInfo();
  120. mLight->setType( LightInfo::Vector );
  121. mFlareData = NULL;
  122. mFlareState.clear();
  123. mFlareScale = 1.0f;
  124. mMoonEnabled = true;
  125. mMoonScale = 0.2f;
  126. mMoonTint.set( 0.192157f, 0.192157f, 0.192157f, 1.0f );
  127. MathUtils::getVectorFromAngles( mMoonLightDir, 0.0f, 45.0f );
  128. mMoonLightDir.normalize();
  129. mMoonLightDir = -mMoonLightDir;
  130. mNightCubemap = NULL;
  131. mNightColor.set( 0.0196078f, 0.0117647f, 0.109804f, 1.0f );
  132. mNightFogColor = mNightColor;
  133. mUseNightCubemap = false;
  134. mSunSize = 1.0f;
  135. mMoonMatInst = NULL;
  136. mNetFlags.set( Ghostable | ScopeAlways );
  137. mTypeMask |= EnvironmentObjectType | LightObjectType | StaticObjectType;
  138. _generateSkyPoints();
  139. mMatrixSet = reinterpret_cast<MatrixSet *>(dMalloc_aligned(sizeof(MatrixSet), 16));
  140. constructInPlace(mMatrixSet);
  141. mColorizeAmt = 0;
  142. mColorize.set(0,0,0);
  143. }
  144. ScatterSky::~ScatterSky()
  145. {
  146. SAFE_DELETE( mLight );
  147. SAFE_DELETE( mMoonMatInst );
  148. dFree_aligned(mMatrixSet);
  149. }
  150. bool ScatterSky::onAdd()
  151. {
  152. PROFILE_SCOPE(ScatterSky_onAdd);
  153. // onNewDatablock for the server is called here
  154. // for the client it is called in unpackUpdate
  155. if ( !Parent::onAdd() )
  156. return false;
  157. if ( isClientObject() )
  158. TimeOfDay::getTimeOfDayUpdateSignal().notify( this, &ScatterSky::_updateTimeOfDay );
  159. setGlobalBounds();
  160. resetWorldBox();
  161. addToScene();
  162. if ( isClientObject() )
  163. {
  164. _initMoon();
  165. Sim::findObject( mNightCubemapName, mNightCubemap );
  166. }
  167. return true;
  168. }
  169. void ScatterSky::onRemove()
  170. {
  171. removeFromScene();
  172. if ( isClientObject() )
  173. TimeOfDay::getTimeOfDayUpdateSignal().remove( this, &ScatterSky::_updateTimeOfDay );
  174. Parent::onRemove();
  175. }
  176. void ScatterSky::_conformLights()
  177. {
  178. _initCurves();
  179. F32 val = mCurves[0].getVal( mTimeOfDay );
  180. mNightInterpolant = 1.0f - val;
  181. VectorF lightDirection;
  182. F32 brightness;
  183. // Build the light direction from the azimuth and elevation.
  184. F32 yaw = mDegToRad(mClampF(mSunAzimuth,0,359));
  185. F32 pitch = mDegToRad(mClampF(mSunElevation,-360,+360));
  186. MathUtils::getVectorFromAngles(lightDirection, yaw, pitch);
  187. lightDirection.normalize();
  188. mSunDir = -lightDirection;
  189. yaw = mDegToRad(mClampF(mMoonAzimuth,0,359));
  190. pitch = mDegToRad(mClampF(mMoonElevation,-360,+360));
  191. MathUtils::getVectorFromAngles( mMoonLightDir, yaw, pitch );
  192. mMoonLightDir.normalize();
  193. mMoonLightDir = -mMoonLightDir;
  194. brightness = mCurves[2].getVal( mTimeOfDay );
  195. if ( mNightInterpolant >= 1.0f )
  196. lightDirection = -mMoonLightDir;
  197. mLight->setDirection( -lightDirection );
  198. mLight->setBrightness( brightness * mBrightness );
  199. mLightDir = lightDirection;
  200. // Have to do interpolation
  201. // after the light direction is set
  202. // otherwise the sun color will be invalid.
  203. _interpolateColors();
  204. mLight->setAmbient( mAmbientColor );
  205. mLight->setColor( mSunColor );
  206. mLight->setCastShadows( mCastShadows );
  207. FogData fog = getSceneManager()->getFogData();
  208. fog.color = mFogColor;
  209. getSceneManager()->setFogData( fog );
  210. }
  211. void ScatterSky::submitLights( LightManager *lm, bool staticLighting )
  212. {
  213. if ( mDirty )
  214. {
  215. _conformLights();
  216. mDirty = false;
  217. }
  218. // The sun is a special light and needs special registration.
  219. lm->setSpecialLight( LightManager::slSunLightType, mLight );
  220. }
  221. void ScatterSky::setAzimuth( F32 azimuth )
  222. {
  223. mSunAzimuth = azimuth;
  224. mDirty = true;
  225. setMaskBits( TimeMask );
  226. }
  227. void ScatterSky::setElevation( F32 elevation )
  228. {
  229. mSunElevation = elevation;
  230. while( elevation < 0 )
  231. elevation += 360.0f;
  232. while( elevation >= 360.0f )
  233. elevation -= 360.0f;
  234. mTimeOfDay = elevation / 180.0f;
  235. mDirty = true;
  236. setMaskBits( TimeMask );
  237. }
  238. void ScatterSky::inspectPostApply()
  239. {
  240. mDirty = true;
  241. setMaskBits( 0xFFFFFFFF );
  242. }
  243. void ScatterSky::initPersistFields()
  244. {
  245. addGroup( "ScatterSky",
  246. "Only azimuth and elevation are networked fields. To trigger a full update of all other fields use the applyChanges ConsoleMethod." );
  247. addField( "skyBrightness", TypeF32, Offset( mSkyBrightness, ScatterSky ),
  248. "Global brightness and intensity applied to the sky and objects in the level." );
  249. addField( "sunSize", TypeF32, Offset( mSunSize, ScatterSky ),
  250. "Affects the size of the sun's disk." );
  251. addField( "colorizeAmount", TypeF32, Offset( mColorizeAmt, ScatterSky ),
  252. "Controls how much the the alpha component of colorize brigthens the sky. Setting to 0 returns default behavior." );
  253. addField( "colorize", TypeColorF, Offset( mColorize, ScatterSky ),
  254. "Tints the sky the color specified, the alpha controls the brigthness. The brightness is multipled by the value of colorizeAmt." );
  255. addField( "rayleighScattering", TypeF32, Offset( mRayleighScattering, ScatterSky ),
  256. "Controls how blue the atmosphere is during the day." );
  257. addField( "sunScale", TypeColorF, Offset( mSunScale, ScatterSky ),
  258. "Modulates the directional color of sunlight." );
  259. addField( "ambientScale", TypeColorF, Offset( mAmbientScale, ScatterSky ),
  260. "Modulates the ambient color of sunlight." );
  261. addField( "fogScale", TypeColorF, Offset( mFogScale, ScatterSky ),
  262. "Modulates the fog color. Note that this overrides the LevelInfo.fogColor "
  263. "property, so you should not use LevelInfo.fogColor if the level contains "
  264. "a ScatterSky object." );
  265. addField( "exposure", TypeF32, Offset( mExposure, ScatterSky ),
  266. "Controls the contrast of the sky and sun during daytime." );
  267. endGroup( "ScatterSky" );
  268. addGroup( "Orbit" );
  269. addProtectedField( "azimuth", TypeF32, Offset( mSunAzimuth, ScatterSky ), &ScatterSky::ptSetAzimuth, &defaultProtectedGetFn,
  270. "The horizontal angle of the sun measured clockwise from the positive Y world axis. This field is networked." );
  271. addProtectedField( "elevation", TypeF32, Offset( mSunElevation, ScatterSky ), &ScatterSky::ptSetElevation, &defaultProtectedGetFn,
  272. "The elevation angle of the sun above or below the horizon. This field is networked." );
  273. addField( "moonAzimuth", TypeF32, Offset( mMoonAzimuth, ScatterSky ),
  274. "The horizontal angle of the moon measured clockwise from the positive Y world axis. This is not animated by time or networked." );
  275. addField( "moonElevation", TypeF32, Offset( mMoonElevation, ScatterSky ),
  276. "The elevation angle of the moon above or below the horizon. This is not animated by time or networked." );
  277. endGroup( "Orbit" );
  278. // We only add the basic lighting options that all lighting
  279. // systems would use... the specific lighting system options
  280. // are injected at runtime by the lighting system itself.
  281. addGroup( "Lighting" );
  282. addField( "castShadows", TypeBool, Offset( mCastShadows, ScatterSky ),
  283. "Enables/disables shadows cast by objects due to ScatterSky light." );
  284. addField( "brightness", TypeF32, Offset( mBrightness, ScatterSky ),
  285. "The brightness of the ScatterSky's light object." );
  286. endGroup( "Lighting" );
  287. addGroup( "Misc" );
  288. addField( "flareType", TYPEID< LightFlareData >(), Offset( mFlareData, ScatterSky ),
  289. "Datablock for the flare produced by the ScatterSky." );
  290. addField( "flareScale", TypeF32, Offset( mFlareScale, ScatterSky ),
  291. "Changes the size and intensity of the flare." );
  292. endGroup( "Misc" );
  293. addGroup( "Night" );
  294. addField( "nightColor", TypeColorF, Offset( mNightColor, ScatterSky ),
  295. "The ambient color during night. Also used for the sky color if useNightCubemap is false." );
  296. addField( "nightFogColor", TypeColorF, Offset( mNightFogColor, ScatterSky ),
  297. "The fog color during night." );
  298. addField( "moonEnabled", TypeBool, Offset( mMoonEnabled, ScatterSky ),
  299. "Enable or disable rendering of the moon sprite during night." );
  300. addField( "moonMat", TypeMaterialName, Offset( mMoonMatName, ScatterSky ),
  301. "Material for the moon sprite." );
  302. addField( "moonScale", TypeF32, Offset( mMoonScale, ScatterSky ),
  303. "Controls size the moon sprite renders, specified as a fractional amount of the screen height." );
  304. addField( "moonLightColor", TypeColorF, Offset( mMoonTint, ScatterSky ),
  305. "Color of light cast by the directional light during night." );
  306. addField( "useNightCubemap", TypeBool, Offset( mUseNightCubemap, ScatterSky ),
  307. "Transition to the nightCubemap during night. If false we use nightColor." );
  308. addField( "nightCubemap", TypeCubemapName, Offset( mNightCubemapName, ScatterSky ),
  309. "Cubemap visible during night." );
  310. endGroup( "Night" );
  311. // Now inject any light manager specific fields.
  312. LightManager::initLightFields();
  313. Parent::initPersistFields();
  314. }
  315. U32 ScatterSky::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  316. {
  317. U32 retMask = Parent::packUpdate(con, mask, stream);
  318. if ( stream->writeFlag( mask & TimeMask ) )
  319. {
  320. stream->write( mSunAzimuth );
  321. stream->write( mSunElevation );
  322. }
  323. if ( stream->writeFlag( mask & UpdateMask ) )
  324. {
  325. stream->write( mRayleighScattering );
  326. mRayleighScattering4PI = mRayleighScattering * 4.0f * M_PI_F;
  327. stream->write( mRayleighScattering4PI );
  328. stream->write( mMieScattering );
  329. mMieScattering4PI = mMieScattering * 4.0f * M_PI_F;
  330. stream->write( mMieScattering4PI );
  331. stream->write( mSunSize );
  332. stream->write( mSkyBrightness );
  333. stream->write( mMiePhaseAssymetry );
  334. stream->write( mSphereInnerRadius );
  335. stream->write( mSphereOuterRadius );
  336. stream->write( mScale );
  337. stream->write( mWavelength );
  338. stream->write( mWavelength4[0] );
  339. stream->write( mWavelength4[1] );
  340. stream->write( mWavelength4[2] );
  341. stream->write( mRayleighScaleDepth );
  342. stream->write( mMieScaleDepth );
  343. stream->write( mNightColor );
  344. stream->write( mNightFogColor );
  345. stream->write( mAmbientScale );
  346. stream->write( mSunScale );
  347. stream->write( mFogScale );
  348. stream->write( mColorizeAmt );
  349. stream->write( mColorize );
  350. stream->write( mExposure );
  351. stream->write( mBrightness );
  352. stream->writeFlag( mCastShadows );
  353. stream->write( mFlareScale );
  354. if ( stream->writeFlag( mFlareData ) )
  355. {
  356. stream->writeRangedU32( mFlareData->getId(),
  357. DataBlockObjectIdFirst,
  358. DataBlockObjectIdLast );
  359. }
  360. stream->writeFlag( mMoonEnabled );
  361. stream->write( mMoonMatName );
  362. stream->write( mMoonScale );
  363. stream->write( mMoonTint );
  364. stream->writeFlag( mUseNightCubemap );
  365. stream->write( mNightCubemapName );
  366. stream->write( mMoonAzimuth );
  367. stream->write( mMoonElevation );
  368. mLight->packExtended( stream );
  369. }
  370. return retMask;
  371. }
  372. void ScatterSky::unpackUpdate(NetConnection *con, BitStream *stream)
  373. {
  374. Parent::unpackUpdate(con, stream);
  375. if ( stream->readFlag() ) // TimeMask
  376. {
  377. F32 temp = 0;
  378. stream->read( &temp );
  379. setAzimuth( temp );
  380. stream->read( &temp );
  381. setElevation( temp );
  382. }
  383. if ( stream->readFlag() ) // UpdateMask
  384. {
  385. stream->read( &mRayleighScattering );
  386. stream->read( &mRayleighScattering4PI );
  387. stream->read( &mMieScattering );
  388. stream->read( &mMieScattering4PI );
  389. stream->read( &mSunSize );
  390. stream->read( &mSkyBrightness );
  391. stream->read( &mMiePhaseAssymetry );
  392. stream->read( &mSphereInnerRadius );
  393. stream->read( &mSphereOuterRadius );
  394. stream->read( &mScale );
  395. ColorF tmpColor( 0, 0, 0 );
  396. stream->read( &tmpColor );
  397. stream->read( &mWavelength4[0] );
  398. stream->read( &mWavelength4[1] );
  399. stream->read( &mWavelength4[2] );
  400. stream->read( &mRayleighScaleDepth );
  401. stream->read( &mMieScaleDepth );
  402. stream->read( &mNightColor );
  403. stream->read( &mNightFogColor );
  404. stream->read( &mAmbientScale );
  405. stream->read( &mSunScale );
  406. stream->read( &mFogScale );
  407. F32 colorizeAmt;
  408. stream->read( &colorizeAmt );
  409. if(mColorizeAmt != colorizeAmt) {
  410. mColorizeAmt = colorizeAmt;
  411. mShader = NULL; //forces shader refresh
  412. }
  413. stream->read( &mColorize );
  414. if ( tmpColor != mWavelength )
  415. {
  416. mWavelength = tmpColor;
  417. mWavelength4[0] = mPow(mWavelength[0], 4.0f);
  418. mWavelength4[1] = mPow(mWavelength[1], 4.0f);
  419. mWavelength4[2] = mPow(mWavelength[2], 4.0f);
  420. }
  421. stream->read( &mExposure );
  422. stream->read( &mBrightness );
  423. mCastShadows = stream->readFlag();
  424. stream->read( &mFlareScale );
  425. if ( stream->readFlag() )
  426. {
  427. SimObjectId id = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  428. LightFlareData *datablock = NULL;
  429. if ( Sim::findObject( id, datablock ) )
  430. mFlareData = datablock;
  431. else
  432. {
  433. con->setLastError( "ScatterSky::unpackUpdate() - invalid LightFlareData!" );
  434. mFlareData = NULL;
  435. }
  436. }
  437. else
  438. mFlareData = NULL;
  439. mMoonEnabled = stream->readFlag();
  440. stream->read( &mMoonMatName );
  441. stream->read( &mMoonScale );
  442. stream->read( &mMoonTint );
  443. mUseNightCubemap = stream->readFlag();
  444. stream->read( &mNightCubemapName );
  445. stream->read( &mMoonAzimuth );
  446. stream->read( &mMoonElevation );
  447. mLight->unpackExtended( stream );
  448. if ( isProperlyAdded() )
  449. {
  450. mDirty = true;
  451. _initMoon();
  452. Sim::findObject( mNightCubemapName, mNightCubemap );
  453. }
  454. }
  455. }
  456. void ScatterSky::prepRenderImage( SceneRenderState *state )
  457. {
  458. // Only render into diffuse and reflect passes.
  459. if( !state->isDiffusePass() &&
  460. !state->isReflectPass() )
  461. return;
  462. // Regular sky render instance.
  463. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  464. ri->renderDelegate.bind( this, &ScatterSky::_render );
  465. ri->type = RenderPassManager::RIT_Sky;
  466. ri->defaultKey = 10;
  467. ri->defaultKey2 = 0;
  468. state->getRenderPass()->addInst( ri );
  469. // Debug render instance.
  470. /*
  471. if ( Con::getBoolVariable( "$ScatterSky::debug", false ) )
  472. {
  473. ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  474. ri->renderDelegate.bind( this, &ScatterSky::_debugRender );
  475. ri->type = RenderPassManager::RIT_Editor;
  476. state->getRenderPass()->addInst( ri );
  477. }
  478. */
  479. // Light flare effect render instance.
  480. if ( mFlareData && mNightInterpolant != 1.0f )
  481. {
  482. mFlareState.fullBrightness = mBrightness;
  483. mFlareState.scale = mFlareScale;
  484. mFlareState.lightInfo = mLight;
  485. Point3F lightPos = state->getCameraPosition() - state->getFarPlane() * mLight->getDirection() * 0.9f;
  486. mFlareState.lightMat.identity();
  487. mFlareState.lightMat.setPosition( lightPos );
  488. F32 dist = ( lightPos - state->getCameraPosition( ) ).len( );
  489. F32 coronaScale = 0.5f;
  490. F32 screenRadius = GFX->getViewport( ).extent.y * coronaScale * 0.5f;
  491. mFlareState.worldRadius = screenRadius * dist / state->getWorldToScreenScale( ).y;
  492. mFlareData->prepRender( state, &mFlareState );
  493. }
  494. // Render instances for Night effects.
  495. if ( mNightInterpolant <= 0.0f )
  496. return;
  497. // Render instance for Moon sprite.
  498. if ( mMoonEnabled && mMoonMatInst )
  499. {
  500. mMatrixSet->setSceneView(GFX->getWorldMatrix());
  501. mMatrixSet->setSceneProjection(GFX->getProjectionMatrix());
  502. mMatrixSet->setWorld(GFX->getWorldMatrix());
  503. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  504. ri->renderDelegate.bind( this, &ScatterSky::_renderMoon );
  505. ri->type = RenderPassManager::RIT_Sky;
  506. // Render after sky objects and before CloudLayer!
  507. ri->defaultKey = 5;
  508. ri->defaultKey2 = 0;
  509. state->getRenderPass()->addInst( ri );
  510. }
  511. }
  512. bool ScatterSky::_initShader()
  513. {
  514. ShaderData *shaderData;
  515. if ( !Sim::findObject( "ScatterSkyShaderData", shaderData ) )
  516. {
  517. Con::warnf( "ScatterSky::_initShader - failed to locate shader ScatterSkyShaderData!" );
  518. return false;
  519. }
  520. Vector<GFXShaderMacro> macros;
  521. if ( mColorizeAmt )
  522. macros.push_back( GFXShaderMacro( "USE_COLORIZE" ) );
  523. mShader = shaderData->getShader( macros );
  524. if ( !mShader )
  525. return false;
  526. if ( mStateBlock.isNull() )
  527. {
  528. GFXStateBlockData *data = NULL;
  529. if ( !Sim::findObject( "ScatterSkySBData", data ) )
  530. Con::warnf( "ScatterSky::_initShader - failed to locate ScatterSkySBData!" );
  531. else
  532. mStateBlock = GFX->createStateBlock( data->getState() );
  533. }
  534. if ( !mStateBlock )
  535. return false;
  536. mShaderConsts = mShader->allocConstBuffer();
  537. mModelViewProjSC = mShader->getShaderConstHandle( "$modelView" );
  538. // Camera height, cam height squared, scale and scale over depth.
  539. mMiscSC = mShader->getShaderConstHandle( "$misc" );
  540. // Inner and out radius, and inner and outer radius squared.
  541. mSphereRadiiSC = mShader->getShaderConstHandle( "$sphereRadii" );
  542. // Rayleigh sun brightness, mie sun brightness and 4 * PI * coefficients.
  543. mScatteringCoefficientsSC = mShader->getShaderConstHandle( "$scatteringCoeffs" );
  544. mCamPosSC = mShader->getShaderConstHandle( "$camPos" );
  545. mLightDirSC = mShader->getShaderConstHandle( "$lightDir" );
  546. mSunDirSC = mShader->getShaderConstHandle( "$sunDir" );
  547. mNightColorSC = mShader->getShaderConstHandle( "$nightColor" );
  548. mInverseWavelengthSC = mShader->getShaderConstHandle( "$invWaveLength" );
  549. mNightInterpolantAndExposureSC = mShader->getShaderConstHandle( "$nightInterpAndExposure" );
  550. mUseCubemapSC = mShader->getShaderConstHandle( "$useCubemap" );
  551. mColorizeSC = mShader->getShaderConstHandle( "$colorize" );
  552. return true;
  553. }
  554. void ScatterSky::_initVBIB()
  555. {
  556. // Vertex Buffer...
  557. U32 vertStride = 50;
  558. U32 strideMinusOne = vertStride - 1;
  559. mVertCount = vertStride * vertStride;
  560. mPrimCount = strideMinusOne * strideMinusOne * 2;
  561. Point3F vertScale( 16.0f, 16.0f, 4.0f );
  562. F32 zOffset = -( mCos( mSqrt( 1.0f ) ) + 0.01f );
  563. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  564. ScatterSkyVertex *pVert = mVB.lock();
  565. if(!pVert) return;
  566. for ( U32 y = 0; y < vertStride; y++ )
  567. {
  568. F32 v = ( (F32)y / (F32)strideMinusOne - 0.5f ) * 2.0f;
  569. for ( U32 x = 0; x < vertStride; x++ )
  570. {
  571. F32 u = ( (F32)x / (F32)strideMinusOne - 0.5f ) * 2.0f;
  572. F32 sx = u;
  573. F32 sy = v;
  574. F32 sz = (mCos( mSqrt( sx*sx + sy*sy ) ) * 1.0f) + zOffset;
  575. //F32 sz = 1.0f;
  576. pVert->point.set( sx, sy, sz );
  577. pVert->point *= vertScale;
  578. pVert->point.normalize();
  579. pVert->point *= 200000.0f;
  580. pVert++;
  581. }
  582. }
  583. mVB.unlock();
  584. // Primitive Buffer...
  585. mPrimBuffer.set( GFX, mPrimCount * 3, mPrimCount, GFXBufferTypeStatic );
  586. U16 *pIdx = NULL;
  587. mPrimBuffer.lock(&pIdx);
  588. U32 curIdx = 0;
  589. for ( U32 y = 0; y < strideMinusOne; y++ )
  590. {
  591. for ( U32 x = 0; x < strideMinusOne; x++ )
  592. {
  593. U32 offset = x + y * vertStride;
  594. pIdx[curIdx] = offset;
  595. curIdx++;
  596. pIdx[curIdx] = offset + 1;
  597. curIdx++;
  598. pIdx[curIdx] = offset + vertStride + 1;
  599. curIdx++;
  600. pIdx[curIdx] = offset;
  601. curIdx++;
  602. pIdx[curIdx] = offset + vertStride + 1;
  603. curIdx++;
  604. pIdx[curIdx] = offset + vertStride;
  605. curIdx++;
  606. }
  607. }
  608. mPrimBuffer.unlock();
  609. }
  610. void ScatterSky::_initMoon()
  611. {
  612. if ( isServerObject() )
  613. return;
  614. if ( mMoonMatInst )
  615. SAFE_DELETE( mMoonMatInst );
  616. if ( mMoonMatName.isNotEmpty() )
  617. mMoonMatInst = MATMGR->createMatInstance( mMoonMatName, MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPCT>() );
  618. }
  619. void ScatterSky::_initCurves()
  620. {
  621. if ( mCurves->getSampleCount() > 0 )
  622. return;
  623. // Takes time of day (0-2) and returns
  624. // the night interpolant (0-1) day/night factor.
  625. // moonlight = 0, sunlight > 0
  626. mCurves[0].clear();
  627. mCurves[0].addPoint( 0.0f, 0.5f );// Sunrise
  628. mCurves[0].addPoint( 0.025f, 1.0f );//
  629. mCurves[0].addPoint( 0.975f, 1.0f );//
  630. mCurves[0].addPoint( 1.0f, 0.5f );//Sunset
  631. mCurves[0].addPoint( 1.02f, 0.0f );//Sunlight ends
  632. mCurves[0].addPoint( 1.98f, 0.0f );//Sunlight begins
  633. mCurves[0].addPoint( 2.0f, 0.5f );// Sunrise
  634. // Takes time of day (0-2) and returns mieScattering factor
  635. // Regulates the size of the sun's disk
  636. mCurves[1].clear();
  637. mCurves[1].addPoint( 0.0f, 0.0006f );
  638. mCurves[1].addPoint( 0.01f, 0.00035f );
  639. mCurves[1].addPoint( 0.03f, 0.00023f );
  640. mCurves[1].addPoint( 0.1f, 0.00022f );
  641. mCurves[1].addPoint( 0.2f, 0.00043f );
  642. mCurves[1].addPoint( 0.3f, 0.00062f );
  643. mCurves[1].addPoint( 0.4f, 0.0008f );
  644. mCurves[1].addPoint( 0.5f, 0.00086f );// High noon
  645. mCurves[1].addPoint( 0.6f, 0.0008f );
  646. mCurves[1].addPoint( 0.7f, 0.00062f );
  647. mCurves[1].addPoint( 0.8f, 0.00043f );
  648. mCurves[1].addPoint( 0.9f, 0.00022f );
  649. mCurves[1].addPoint( 0.97f, 0.00023f );
  650. mCurves[1].addPoint( 0.99f, 0.00035f );
  651. mCurves[1].addPoint( 1.0f, 0.0006f );
  652. mCurves[1].addPoint( 2.0f, 0.0006f );
  653. // Takes time of day and returns brightness
  654. // Controls sunlight and moonlight brightness
  655. mCurves[2].clear();
  656. mCurves[2].addPoint( 0.0f, 0.2f );// Sunrise
  657. mCurves[2].addPoint( 0.1f, 1.0f );
  658. mCurves[2].addPoint( 0.9f, 1.0f );// Sunset
  659. mCurves[2].addPoint( 1.008f, 0.0f );//Adjust end of sun's reflection
  660. mCurves[2].addPoint( 1.02001f, 0.0f );
  661. mCurves[2].addPoint( 1.05f, 0.5f );// Turn brightness up for moonlight
  662. mCurves[2].addPoint( 1.93f, 0.5f );
  663. mCurves[2].addPoint( 1.97999f, 0.0f );// No brightness when sunlight starts
  664. mCurves[2].addPoint( 1.992f, 0.0f );//Adjust start of sun's reflection
  665. mCurves[2].addPoint( 2.0f, 0.2f ); // Sunrise
  666. // Interpolation of day/night color sets
  667. // 0/1 ambient/nightcolor
  668. // 0 = day colors only anytime
  669. // 1 = night colors only anytime
  670. // between 0 and 1 renders both color sets anytime
  671. mCurves[3].clear();
  672. mCurves[3].addPoint( 0.0f, 0.8f );//Sunrise
  673. mCurves[3].addPoint( 0.1f, 0.0f );
  674. mCurves[3].addPoint( 0.99f, 0.0f );
  675. mCurves[3].addPoint( 1.0f, 0.8f );// Sunset
  676. mCurves[3].addPoint( 1.01999f, 1.0f );//
  677. mCurves[3].addPoint( 1.98001f, 1.0f );// Sunlight begins with full night colors
  678. mCurves[3].addPoint( 2.0f, 0.8f ); //Sunrise
  679. // Takes time of day (0-2) and returns smoothing factor
  680. // Interpolates between mMoonTint color and mNightColor
  681. mCurves[4].clear();
  682. mCurves[4].addPoint( 0.0f, 1.0f );
  683. mCurves[4].addPoint( 0.96f, 1.0f );
  684. mCurves[4].addPoint( 1.01999f, 0.5f );
  685. mCurves[4].addPoint( 1.02001f, 0.5f );
  686. mCurves[4].addPoint( 1.08f, 1.0f );
  687. mCurves[4].addPoint( 1.92f, 1.0f );
  688. mCurves[4].addPoint( 1.97999f, 0.5f );
  689. mCurves[4].addPoint( 1.98001f, 0.5f );
  690. mCurves[4].addPoint( 2.0f, 1.0f );
  691. }
  692. void ScatterSky::_updateTimeOfDay( TimeOfDay *timeOfDay, F32 time )
  693. {
  694. setElevation( timeOfDay->getElevationDegrees() );
  695. setAzimuth( timeOfDay->getAzimuthDegrees() );
  696. }
  697. void ScatterSky::_render( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  698. {
  699. if ( overrideMat || (!mShader && !_initShader()) )
  700. return;
  701. GFXTransformSaver saver;
  702. if ( mVB.isNull() || mPrimBuffer.isNull() )
  703. _initVBIB();
  704. GFX->setShader( mShader );
  705. GFX->setShaderConstBuffer( mShaderConsts );
  706. Point4F sphereRadii( mSphereOuterRadius, mSphereOuterRadius * mSphereOuterRadius,
  707. mSphereInnerRadius, mSphereInnerRadius * mSphereInnerRadius );
  708. Point4F scatteringCoeffs( mRayleighScattering * mSkyBrightness, mRayleighScattering4PI,
  709. mMieScattering * mSkyBrightness, mMieScattering4PI );
  710. Point4F invWavelength( 1.0f / mWavelength4[0],
  711. 1.0f / mWavelength4[1],
  712. 1.0f / mWavelength4[2], 1.0f );
  713. Point3F camPos( 0, 0, smViewerHeight );
  714. Point4F miscParams( camPos.z, camPos.z * camPos.z, mScale, mScale / mRayleighScaleDepth );
  715. Frustum frust = state->getCameraFrustum();
  716. frust.setFarDist( smEarthRadius + smAtmosphereRadius );
  717. MatrixF proj( true );
  718. frust.getProjectionMatrix( &proj );
  719. Point3F camPos2 = state->getCameraPosition();
  720. MatrixF xfm(true);
  721. xfm.setPosition(camPos2);//-Point3F( 0, 0, 200000.0f));
  722. GFX->multWorld(xfm);
  723. MatrixF xform(proj);//GFX->getProjectionMatrix());
  724. xform *= GFX->getViewMatrix();
  725. xform *= GFX->getWorldMatrix();
  726. mShaderConsts->setSafe( mModelViewProjSC, xform );
  727. mShaderConsts->setSafe( mMiscSC, miscParams );
  728. mShaderConsts->setSafe( mSphereRadiiSC, sphereRadii );
  729. mShaderConsts->setSafe( mScatteringCoefficientsSC, scatteringCoeffs );
  730. mShaderConsts->setSafe( mCamPosSC, camPos );
  731. mShaderConsts->setSafe( mLightDirSC, mLightDir );
  732. mShaderConsts->setSafe( mSunDirSC, mSunDir );
  733. mShaderConsts->setSafe( mNightColorSC, mNightColor );
  734. mShaderConsts->setSafe( mInverseWavelengthSC, invWavelength );
  735. mShaderConsts->setSafe( mNightInterpolantAndExposureSC, Point2F( mExposure, mNightInterpolant ) );
  736. mShaderConsts->setSafe( mColorizeSC, mColorize*mColorizeAmt );
  737. if ( GFXDevice::getWireframe() )
  738. {
  739. GFXStateBlockDesc desc( mStateBlock->getDesc() );
  740. desc.setFillModeWireframe();
  741. GFX->setStateBlockByDesc( desc );
  742. }
  743. else
  744. GFX->setStateBlock( mStateBlock );
  745. if ( mUseNightCubemap && mNightCubemap )
  746. {
  747. mShaderConsts->setSafe( mUseCubemapSC, 1.0f );
  748. if ( !mNightCubemap->mCubemap )
  749. mNightCubemap->createMap();
  750. GFX->setCubeTexture( 0, mNightCubemap->mCubemap );
  751. }
  752. else
  753. {
  754. GFX->setCubeTexture( 0, NULL );
  755. mShaderConsts->setSafe( mUseCubemapSC, 0.0f );
  756. }
  757. GFX->setPrimitiveBuffer( mPrimBuffer );
  758. GFX->setVertexBuffer( mVB );
  759. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, mVertCount, 0, mPrimCount );
  760. }
  761. void ScatterSky::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  762. {
  763. GFXStateBlockDesc desc;
  764. desc.fillMode = GFXFillSolid;
  765. desc.setBlend( false, GFXBlendOne, GFXBlendZero );
  766. desc.setZReadWrite( false, false );
  767. GFXStateBlockRef sb = GFX->GFX->createStateBlock( desc );
  768. GFX->setStateBlock( sb );
  769. PrimBuild::begin( GFXLineStrip, mSkyPoints.size() );
  770. PrimBuild::color3i( 255, 0, 255 );
  771. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  772. {
  773. Point3F pnt = mSkyPoints[i];
  774. pnt.normalize();
  775. pnt *= 500;
  776. pnt += state->getCameraPosition();
  777. PrimBuild::vertex3fv( pnt );
  778. }
  779. PrimBuild::end();
  780. }
  781. void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  782. {
  783. if ( !mMoonMatInst )
  784. return;
  785. Point3F moonlightPosition = state->getCameraPosition() - /*mLight->getDirection()*/ mMoonLightDir * state->getFarPlane() * 0.9f;
  786. F32 dist = (moonlightPosition - state->getCameraPosition()).len();
  787. // worldRadius = screenRadius * dist / worldToScreen
  788. // screenRadius = worldRadius / dist * worldToScreen
  789. //
  790. F32 screenRadius = GFX->getViewport().extent.y * mMoonScale * 0.5f;
  791. F32 worldRadius = screenRadius * dist / state->getWorldToScreenScale().y;
  792. // Calculate Billboard Radius (in world units) to be constant, independent of distance.
  793. // Takes into account distance, viewport size, and specified size in editor
  794. F32 BBRadius = worldRadius;
  795. mMatrixSet->restoreSceneViewProjection();
  796. if ( state->isReflectPass() )
  797. mMatrixSet->setProjection( state->getSceneManager()->getNonClipProjection() );
  798. mMatrixSet->setWorld( MatrixF::Identity );
  799. // Initialize points with basic info
  800. Point3F points[4];
  801. points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
  802. points[1] = Point3F( -BBRadius, 0.0, BBRadius);
  803. points[2] = Point3F( BBRadius, 0.0, BBRadius);
  804. points[3] = Point3F( BBRadius, 0.0, -BBRadius);
  805. static const Point2F sCoords[4] =
  806. {
  807. Point2F( 0.0f, 0.0f ),
  808. Point2F( 0.0f, 1.0f ),
  809. Point2F( 1.0f, 1.0f ),
  810. Point2F( 1.0f, 0.0f )
  811. };
  812. // Get info we need to adjust points
  813. const MatrixF &camView = state->getCameraTransform();
  814. // Finalize points
  815. for(S32 i = 0; i < 4; i++)
  816. {
  817. // align with camera
  818. camView.mulV(points[i]);
  819. // offset
  820. points[i] += moonlightPosition;
  821. }
  822. // Vertex color.
  823. ColorF moonVertColor( 1.0f, 1.0f, 1.0f, mNightInterpolant );
  824. // Copy points to buffer.
  825. GFXVertexBufferHandle< GFXVertexPCT > vb;
  826. vb.set( GFX, 4, GFXBufferTypeVolatile );
  827. GFXVertexPCT *pVert = vb.lock();
  828. if(!pVert) return;
  829. for ( S32 i = 0; i < 4; i++ )
  830. {
  831. pVert->color.set( moonVertColor );
  832. pVert->point.set( points[i] );
  833. pVert->texCoord.set( sCoords[i].x, sCoords[i].y );
  834. pVert++;
  835. }
  836. vb.unlock();
  837. // Setup SceneData struct.
  838. SceneData sgData;
  839. sgData.wireframe = GFXDevice::getWireframe();
  840. sgData.visibility = 1.0f;
  841. // Draw it
  842. while ( mMoonMatInst->setupPass( state, sgData ) )
  843. {
  844. mMoonMatInst->setTransforms( *mMatrixSet, state );
  845. mMoonMatInst->setSceneInfo( state, sgData );
  846. GFX->setVertexBuffer( vb );
  847. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  848. }
  849. }
  850. void ScatterSky::_generateSkyPoints()
  851. {
  852. U32 rings=60, segments=20;//rings=160, segments=20;
  853. Point3F tmpPoint( 0, 0, 0 );
  854. // Establish constants used in sphere generation.
  855. F32 deltaRingAngle = ( M_PI_F / (F32)(rings * 2) );
  856. F32 deltaSegAngle = ( 2.0f * M_PI_F / (F32)segments );
  857. // Generate the group of rings for the sphere.
  858. for( S32 ring = 0; ring < 2; ring++ )
  859. {
  860. F32 r0 = mSin( ring * deltaRingAngle );
  861. F32 y0 = mCos( ring * deltaRingAngle );
  862. // Generate the group of segments for the current ring.
  863. for( S32 seg = 0; seg < segments + 1 ; seg++ )
  864. {
  865. F32 x0 = r0 * sinf( seg * deltaSegAngle );
  866. F32 z0 = r0 * cosf( seg * deltaSegAngle );
  867. tmpPoint.set( x0, z0, y0 );
  868. tmpPoint.normalizeSafe();
  869. tmpPoint.x *= smEarthRadius + smAtmosphereRadius;
  870. tmpPoint.y *= smEarthRadius + smAtmosphereRadius;
  871. tmpPoint.z *= smEarthRadius + smAtmosphereRadius;
  872. tmpPoint.z -= smEarthRadius;
  873. if ( ring == 1 )
  874. mSkyPoints.push_back( tmpPoint );
  875. }
  876. }
  877. }
  878. void ScatterSky::_interpolateColors()
  879. {
  880. mFogColor.set( 0, 0, 0, 0 );
  881. mAmbientColor.set( 0, 0, 0, 0 );
  882. mSunColor.set( 0, 0, 0, 0 );
  883. _getFogColor( &mFogColor );
  884. _getAmbientColor( &mAmbientColor );
  885. _getSunColor( &mSunColor );
  886. mAmbientColor *= mAmbientScale;
  887. mSunColor *= mSunScale;
  888. mFogColor *= mFogScale;
  889. mMieScattering = (mCurves[1].getVal( mTimeOfDay) * mSunSize ); //Scale the size of the sun's disk
  890. ColorF moonTemp = mMoonTint;
  891. ColorF nightTemp = mNightColor;
  892. moonTemp.interpolate( mNightColor, mMoonTint, mCurves[4].getVal( mTimeOfDay ) );
  893. nightTemp.interpolate( mMoonTint, mNightColor, mCurves[4].getVal( mTimeOfDay ) );
  894. mFogColor.interpolate( mFogColor, mNightFogColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  895. mFogColor.alpha = 1.0f;
  896. mAmbientColor.interpolate( mAmbientColor, mNightColor, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  897. mSunColor.interpolate( mSunColor, mMoonTint, mCurves[3].getVal( mTimeOfDay ) );//mNightInterpolant );
  898. }
  899. void ScatterSky::_getSunColor( ColorF *outColor )
  900. {
  901. PROFILE_SCOPE( ScatterSky_GetSunColor );
  902. U32 count = 0;
  903. ColorF tmpColor( 0, 0, 0 );
  904. VectorF tmpVec( 0, 0, 0 );
  905. tmpVec = mLightDir;
  906. tmpVec.x *= smEarthRadius + smAtmosphereRadius;
  907. tmpVec.y *= smEarthRadius + smAtmosphereRadius;
  908. tmpVec.z *= smEarthRadius + smAtmosphereRadius;
  909. tmpVec.z -= smAtmosphereRadius;
  910. for ( U32 i = 0; i < 10; i++ )
  911. {
  912. _getColor( tmpVec, &tmpColor );
  913. (*outColor) += tmpColor;
  914. tmpVec.x += (smEarthRadius * 0.5f) + (smAtmosphereRadius * 0.5f);
  915. count++;
  916. }
  917. if ( count > 0 )
  918. (*outColor) /= count;
  919. }
  920. void ScatterSky::_getAmbientColor( ColorF *outColor )
  921. {
  922. PROFILE_SCOPE( ScatterSky_GetAmbientColor );
  923. ColorF tmpColor( 0, 0, 0, 0 );
  924. U32 count = 0;
  925. // Disable mieScattering for purposes of calculating the ambient color.
  926. F32 oldMieScattering = mMieScattering;
  927. mMieScattering = 0.0f;
  928. for ( U32 i = 0; i < mSkyPoints.size(); i++ )
  929. {
  930. Point3F pnt( mSkyPoints[i] );
  931. _getColor( pnt, &tmpColor );
  932. (*outColor) += tmpColor;
  933. count++;
  934. }
  935. if ( count > 0 )
  936. (*outColor) /= count;
  937. mMieScattering = oldMieScattering;
  938. }
  939. void ScatterSky::_getFogColor( ColorF *outColor )
  940. {
  941. PROFILE_SCOPE( ScatterSky_GetFogColor );
  942. VectorF scatterPos( 0, 0, 0 );
  943. F32 sunBrightness = mSkyBrightness;
  944. mSkyBrightness *= 0.25f;
  945. F32 yaw = 0, pitch = 0, originalYaw = 0;
  946. VectorF fwd( 0, 1.0f, 0 );
  947. MathUtils::getAnglesFromVector( fwd, yaw, pitch );
  948. originalYaw = yaw;
  949. pitch = mDegToRad( 10.0f );
  950. ColorF tmpColor( 0, 0, 0 );
  951. U32 i = 0;
  952. for ( i = 0; i < 10; i++ )
  953. {
  954. MathUtils::getVectorFromAngles( scatterPos, yaw, pitch );
  955. scatterPos.x *= smEarthRadius + smAtmosphereRadius;
  956. scatterPos.y *= smEarthRadius + smAtmosphereRadius;
  957. scatterPos.z *= smEarthRadius + smAtmosphereRadius;
  958. scatterPos.y -= smEarthRadius;
  959. _getColor( scatterPos, &tmpColor );
  960. (*outColor) += tmpColor;
  961. if ( i <= 5 )
  962. yaw += mDegToRad( 5.0f );
  963. else
  964. {
  965. originalYaw += mDegToRad( -5.0f );
  966. yaw = originalYaw;
  967. }
  968. yaw = mFmod( yaw, M_2PI_F );
  969. }
  970. if ( i > 0 )
  971. (*outColor) /= i;
  972. mSkyBrightness = sunBrightness;
  973. }
  974. F32 ScatterSky::_vernierScale( F32 fCos )
  975. {
  976. F32 x = 1.0 - fCos;
  977. return 0.25f * exp( -0.00287f + x * (0.459f + x * (3.83f + x * ((-6.80f + (x * 5.25f))))) );
  978. }
  979. F32 ScatterSky::_getMiePhase( F32 fCos, F32 fCos2, F32 g, F32 g2)
  980. {
  981. return 1.5f * ((1.0f - g2) / (2.0f + g2)) * (1.0f + fCos2) / mPow(mFabs(1.0f + g2 - 2.0f*g*fCos), 1.5f);
  982. }
  983. F32 ScatterSky::_getRayleighPhase( F32 fCos2 )
  984. {
  985. return 0.75 + 0.75 * fCos2;
  986. }
  987. void ScatterSky::_getColor( const Point3F &pos, ColorF *outColor )
  988. {
  989. PROFILE_SCOPE( ScatterSky_GetColor );
  990. F32 scaleOverScaleDepth = mScale / mRayleighScaleDepth;
  991. F32 rayleighBrightness = mRayleighScattering * mSkyBrightness;
  992. F32 mieBrightness = mMieScattering * mSkyBrightness;
  993. Point3F invWaveLength( 1.0f / mWavelength4[0],
  994. 1.0f / mWavelength4[1],
  995. 1.0f / mWavelength4[2] );
  996. Point3F v3Pos = pos / 6378000.0f;
  997. v3Pos.z += mSphereInnerRadius;
  998. Point3F newCamPos( 0, 0, smViewerHeight );
  999. VectorF v3Ray = v3Pos - newCamPos;
  1000. F32 fFar = v3Ray.len();
  1001. v3Ray / fFar;
  1002. v3Ray.normalizeSafe();
  1003. Point3F v3Start = newCamPos;
  1004. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight ) );
  1005. F32 fStartAngle = mDot( v3Ray, v3Start );
  1006. F32 fStartOffset = fDepth * _vernierScale( fStartAngle );
  1007. F32 fSampleLength = fFar / 2.0f;
  1008. F32 fScaledLength = fSampleLength * mScale;
  1009. VectorF v3SampleRay = v3Ray * fSampleLength;
  1010. Point3F v3SamplePoint = v3Start + v3SampleRay * 0.5f;
  1011. Point3F v3FrontColor( 0, 0, 0 );
  1012. for ( U32 i = 0; i < 2; i++ )
  1013. {
  1014. F32 fHeight = v3SamplePoint.len();
  1015. F32 fDepth = mExp( scaleOverScaleDepth * (mSphereInnerRadius - smViewerHeight) );
  1016. F32 fLightAngle = mDot( mLightDir, v3SamplePoint ) / fHeight;
  1017. F32 fCameraAngle = mDot( v3Ray, v3SamplePoint ) / fHeight;
  1018. F32 fScatter = (fStartOffset + fDepth * ( _vernierScale( fLightAngle ) - _vernierScale( fCameraAngle ) ));
  1019. Point3F v3Attenuate( 0, 0, 0 );
  1020. F32 tmp = mExp( -fScatter * (invWaveLength[0] * mRayleighScattering4PI + mMieScattering4PI) );
  1021. v3Attenuate.x = tmp;
  1022. tmp = mExp( -fScatter * (invWaveLength[1] * mRayleighScattering4PI + mMieScattering4PI) );
  1023. v3Attenuate.y = tmp;
  1024. tmp = mExp( -fScatter * (invWaveLength[2] * mRayleighScattering4PI + mMieScattering4PI) );
  1025. v3Attenuate.z = tmp;
  1026. v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
  1027. v3SamplePoint += v3SampleRay;
  1028. }
  1029. Point3F mieColor = v3FrontColor * mieBrightness;
  1030. Point3F rayleighColor = v3FrontColor * (invWaveLength * rayleighBrightness);
  1031. Point3F v3Direction = newCamPos - v3Pos;
  1032. v3Direction.normalize();
  1033. F32 fCos = mDot( mLightDir, v3Direction ) / v3Direction.len();
  1034. F32 fCos2 = fCos * fCos;
  1035. F32 g = -0.991f;
  1036. F32 g2 = g * g;
  1037. F32 miePhase = _getMiePhase( fCos, fCos2, g, g2 );
  1038. Point3F color = rayleighColor + (miePhase * mieColor);
  1039. ColorF tmp( color.x, color.y, color.z, color.y );
  1040. Point3F expColor( 0, 0, 0 );
  1041. expColor.x = 1.0f - exp(-mExposure * color.x);
  1042. expColor.y = 1.0f - exp(-mExposure * color.y);
  1043. expColor.z = 1.0f - exp(-mExposure * color.z);
  1044. tmp.set( expColor.x, expColor.y, expColor.z, 1.0f );
  1045. if ( !tmp.isValidColor() )
  1046. {
  1047. F32 len = expColor.len();
  1048. if ( len > 0 )
  1049. expColor /= len;
  1050. }
  1051. outColor->set( expColor.x, expColor.y, expColor.z, 1.0f );
  1052. }
  1053. // Static protected field set methods
  1054. bool ScatterSky::ptSetElevation( void *object, const char *index, const char *data )
  1055. {
  1056. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1057. F32 val = dAtof( data );
  1058. sky->setElevation( val );
  1059. // we already set the field
  1060. return false;
  1061. }
  1062. bool ScatterSky::ptSetAzimuth( void *object, const char *index, const char *data )
  1063. {
  1064. ScatterSky *sky = static_cast<ScatterSky*>( object );
  1065. F32 val = dAtof( data );
  1066. sky->setAzimuth( val );
  1067. // we already set the field
  1068. return false;
  1069. }
  1070. void ScatterSky::_onSelected()
  1071. {
  1072. #ifdef TORQUE_DEBUG
  1073. // Enable debug rendering on the light.
  1074. if( isClientObject() )
  1075. mLight->enableDebugRendering( true );
  1076. #endif
  1077. Parent::_onSelected();
  1078. }
  1079. void ScatterSky::_onUnselected()
  1080. {
  1081. #ifdef TORQUE_DEBUG
  1082. // Disable debug rendering on the light.
  1083. if( isClientObject() )
  1084. mLight->enableDebugRendering( false );
  1085. #endif
  1086. Parent::_onUnselected();
  1087. }
  1088. // ConsoleMethods
  1089. DefineEngineMethod( ScatterSky, applyChanges, void, (),,
  1090. "Apply a full network update of all fields to all clients."
  1091. )
  1092. {
  1093. object->inspectPostApply();
  1094. }