scatterSky.cpp 43 KB

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