scatterSky.cpp 45 KB

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