scatterSky.cpp 45 KB

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