scatterSky.cpp 44 KB

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