scatterSky.cpp 46 KB

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