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