sun.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 "environment/sun.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "math/mathIO.h"
  26. #include "core/stream/bitStream.h"
  27. #include "console/consoleTypes.h"
  28. #include "console/engineAPI.h"
  29. #include "scene/sceneManager.h"
  30. #include "math/mathUtils.h"
  31. #include "lighting/lightInfo.h"
  32. #include "lighting/lightManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "renderInstance/renderPassManager.h"
  35. #include "sim/netConnection.h"
  36. #include "environment/timeOfDay.h"
  37. #include "gfx/gfxTransformSaver.h"
  38. #include "materials/materialManager.h"
  39. #include "materials/baseMatInstance.h"
  40. #include "materials/sceneData.h"
  41. #include "math/util/matrixSet.h"
  42. IMPLEMENT_CO_NETOBJECT_V1(Sun);
  43. ConsoleDocClass( Sun,
  44. "@brief A global light affecting your entire scene and optionally renders a corona effect.\n\n"
  45. "Sun is both the directional and ambient light for your entire scene.\n\n"
  46. "@ingroup Atmosphere"
  47. );
  48. //-----------------------------------------------------------------------------
  49. Sun::Sun()
  50. {
  51. mNetFlags.set(Ghostable | ScopeAlways);
  52. mTypeMask = EnvironmentObjectType | LightObjectType | StaticObjectType;
  53. mLightColor.set(0.7f, 0.7f, 0.7f);
  54. mLightAmbient.set(0.3f, 0.3f, 0.3f);
  55. mBrightness = 1.0f;
  56. mSunAzimuth = 0.0f;
  57. mSunElevation = 35.0f;
  58. mCastShadows = true;
  59. mStaticRefreshFreq = 250;
  60. mDynamicRefreshFreq = 8;
  61. mAnimateSun = false;
  62. mTotalTime = 0.0f;
  63. mCurrTime = 0.0f;
  64. mStartAzimuth = 0.0f;
  65. mEndAzimuth = 0.0f;
  66. mStartElevation = 0.0f;
  67. mEndElevation = 0.0f;
  68. mLight = LightManager::createLightInfo();
  69. mLight->setType( LightInfo::Vector );
  70. mFlareData = NULL;
  71. mFlareState.clear();
  72. mFlareScale = 1.0f;
  73. mCoronaEnabled = true;
  74. mCoronaScale = 0.5f;
  75. mCoronaTint.set( 1.0f, 1.0f, 1.0f, 1.0f );
  76. mCoronaUseLightColor = true;
  77. mCoronaMatInst = NULL;
  78. INIT_ASSET(CoronaMaterial);
  79. mMatrixSet = reinterpret_cast<MatrixSet *>(dMalloc_aligned(sizeof(MatrixSet), 16));
  80. constructInPlace(mMatrixSet);
  81. mCoronaWorldRadius = 0.0f;
  82. mLightWorldPos = Point3F::Zero;
  83. }
  84. Sun::~Sun()
  85. {
  86. SAFE_DELETE( mLight );
  87. SAFE_DELETE( mCoronaMatInst );
  88. dFree_aligned(mMatrixSet);
  89. }
  90. bool Sun::onAdd()
  91. {
  92. if ( !Parent::onAdd() )
  93. return false;
  94. // Register as listener to TimeOfDay update events
  95. TimeOfDay::getTimeOfDayUpdateSignal().notify( this, &Sun::_updateTimeOfDay );
  96. // Make this thing have a global bounds so that its
  97. // always returned from spatial light queries.
  98. setGlobalBounds();
  99. resetWorldBox();
  100. setRenderTransform( mObjToWorld );
  101. addToScene();
  102. _initCorona();
  103. // Update the light parameters.
  104. _conformLights();
  105. setProcessTick( true );
  106. return true;
  107. }
  108. void Sun::onRemove()
  109. {
  110. TimeOfDay::getTimeOfDayUpdateSignal().remove( this, &Sun::_updateTimeOfDay );
  111. removeFromScene();
  112. Parent::onRemove();
  113. }
  114. void Sun::initPersistFields()
  115. {
  116. addGroup( "Orbit" );
  117. addField( "azimuth", TypeF32, Offset( mSunAzimuth, Sun ),
  118. "The horizontal angle of the sun measured clockwise from the positive Y world axis." );
  119. addField( "elevation", TypeF32, Offset( mSunElevation, Sun ),
  120. "The elevation angle of the sun above or below the horizon." );
  121. endGroup( "Orbit" );
  122. // We only add the basic lighting options that all lighting
  123. // systems would use... the specific lighting system options
  124. // are injected at runtime by the lighting system itself.
  125. addGroup( "Lighting" );
  126. addField( "color", TypeColorF, Offset( mLightColor, Sun ),
  127. "Color shading applied to surfaces in direct contact with light source.");
  128. addField( "ambient", TypeColorF, Offset( mLightAmbient, Sun ), "Color shading applied to surfaces not "
  129. "in direct contact with light source, such as in the shadows or interiors.");
  130. addField( "brightness", TypeF32, Offset( mBrightness, Sun ),
  131. "Adjust the Sun's global contrast/intensity");
  132. addField( "castShadows", TypeBool, Offset( mCastShadows, Sun ),
  133. "Enables/disables shadows cast by objects due to Sun light");
  134. //addField("staticRefreshFreq", TypeS32, Offset(mStaticRefreshFreq, Sun), "static shadow refresh rate (milliseconds)");
  135. //addField("dynamicRefreshFreq", TypeS32, Offset(mDynamicRefreshFreq, Sun), "dynamic shadow refresh rate (milliseconds)");
  136. endGroup( "Lighting" );
  137. addGroup( "Corona" );
  138. addField( "coronaEnabled", TypeBool, Offset( mCoronaEnabled, Sun ),
  139. "Enable or disable rendering of the corona sprite." );
  140. INITPERSISTFIELD_MATERIALASSET(CoronaMaterial, Sun, "Material for the corona sprite.");
  141. addField( "coronaScale", TypeF32, Offset( mCoronaScale, Sun ),
  142. "Controls size the corona sprite renders, specified as a fractional amount of the screen height." );
  143. addField( "coronaTint", TypeColorF, Offset( mCoronaTint, Sun ),
  144. "Modulates the corona sprite color ( if coronaUseLightColor is false )." );
  145. addField( "coronaUseLightColor", TypeBool, Offset( mCoronaUseLightColor, Sun ),
  146. "Modulate the corona sprite color by the color of the light ( overrides coronaTint )." );
  147. endGroup( "Corona" );
  148. addGroup( "Misc" );
  149. addField( "flareType", TYPEID< LightFlareData >(), Offset( mFlareData, Sun ),
  150. "Datablock for the flare produced by the Sun" );
  151. addField( "flareScale", TypeF32, Offset( mFlareScale, Sun ),
  152. "Changes the size and intensity of the flare." );
  153. endGroup( "Misc" );
  154. // Now inject any light manager specific fields.
  155. LightManager::initLightFields();
  156. Parent::initPersistFields();
  157. }
  158. void Sun::inspectPostApply()
  159. {
  160. _conformLights();
  161. setMaskBits(UpdateMask);
  162. }
  163. U32 Sun::packUpdate(NetConnection *conn, U32 mask, BitStream *stream )
  164. {
  165. U32 retMask = Parent::packUpdate( conn, mask, stream );
  166. if ( stream->writeFlag( mask & UpdateMask ) )
  167. {
  168. stream->write( mSunAzimuth );
  169. stream->write( mSunElevation );
  170. stream->write( mLightColor );
  171. stream->write( mLightAmbient );
  172. stream->write( mBrightness );
  173. stream->writeFlag( mCastShadows );
  174. stream->write(mStaticRefreshFreq);
  175. stream->write(mDynamicRefreshFreq);
  176. stream->write( mFlareScale );
  177. if ( stream->writeFlag( mFlareData ) )
  178. {
  179. stream->writeRangedU32( mFlareData->getId(),
  180. DataBlockObjectIdFirst,
  181. DataBlockObjectIdLast );
  182. }
  183. stream->writeFlag( mCoronaEnabled );
  184. PACK_ASSET(conn, CoronaMaterial);
  185. stream->write( mCoronaScale );
  186. stream->write( mCoronaTint );
  187. stream->writeFlag( mCoronaUseLightColor );
  188. mLight->packExtended( stream );
  189. }
  190. return retMask;
  191. }
  192. void Sun::unpackUpdate( NetConnection *conn, BitStream *stream )
  193. {
  194. Parent::unpackUpdate( conn, stream );
  195. if ( stream->readFlag() ) // UpdateMask
  196. {
  197. stream->read( &mSunAzimuth );
  198. stream->read( &mSunElevation );
  199. stream->read( &mLightColor );
  200. stream->read( &mLightAmbient );
  201. stream->read( &mBrightness );
  202. mCastShadows = stream->readFlag();
  203. stream->read(&mStaticRefreshFreq);
  204. stream->read(&mDynamicRefreshFreq);
  205. stream->read( &mFlareScale );
  206. if ( stream->readFlag() )
  207. {
  208. SimObjectId id = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  209. LightFlareData *datablock = NULL;
  210. if ( Sim::findObject( id, datablock ) )
  211. mFlareData = datablock;
  212. else
  213. {
  214. conn->setLastError( "Sun::unpackUpdate() - invalid LightFlareData!" );
  215. mFlareData = NULL;
  216. }
  217. }
  218. else
  219. mFlareData = NULL;
  220. mCoronaEnabled = stream->readFlag();
  221. UNPACK_ASSET(conn, CoronaMaterial);
  222. stream->read( &mCoronaScale );
  223. stream->read( &mCoronaTint );
  224. mCoronaUseLightColor = stream->readFlag();
  225. mLight->unpackExtended( stream );
  226. }
  227. if ( isProperlyAdded() )
  228. {
  229. _initCorona();
  230. _conformLights();
  231. }
  232. }
  233. void Sun::submitLights( LightManager *lm, bool staticLighting )
  234. {
  235. // The sun is a special light and needs special registration.
  236. lm->setSpecialLight( LightManager::slSunLightType, mLight );
  237. }
  238. void Sun::advanceTime( F32 timeDelta )
  239. {
  240. if (mAnimateSun)
  241. {
  242. if (mCurrTime >= mTotalTime)
  243. {
  244. mAnimateSun = false;
  245. mCurrTime = 0.0f;
  246. }
  247. else
  248. {
  249. mCurrTime += timeDelta;
  250. F32 fract = mCurrTime / mTotalTime;
  251. F32 inverse = 1.0f - fract;
  252. F32 newAzimuth = mStartAzimuth * inverse + mEndAzimuth * fract;
  253. F32 newElevation = mStartElevation * inverse + mEndElevation * fract;
  254. if (newAzimuth > 360.0f)
  255. newAzimuth -= 360.0f;
  256. if (newElevation > 360.0f)
  257. newElevation -= 360.0f;
  258. setAzimuth(newAzimuth);
  259. setElevation(newElevation);
  260. }
  261. }
  262. }
  263. void Sun::prepRenderImage( SceneRenderState *state )
  264. {
  265. // Only render into diffuse and reflect passes.
  266. if( !state->isDiffusePass() &&
  267. !state->isReflectPass() )
  268. return;
  269. mLightWorldPos = state->getCameraPosition() - state->getFarPlane() * mLight->getDirection() * 0.9f;
  270. F32 dist = ( mLightWorldPos - state->getCameraPosition() ).len();
  271. F32 screenRadius = GFX->getViewport().extent.y * mCoronaScale * 0.5f;
  272. mCoronaWorldRadius = screenRadius * dist / state->getWorldToScreenScale().y;
  273. // Render instance for Corona effect.
  274. if ( mCoronaEnabled && mCoronaMatInst )
  275. {
  276. mMatrixSet->setSceneProjection( GFX->getProjectionMatrix() );
  277. mMatrixSet->setSceneView( GFX->getViewMatrix() );
  278. mMatrixSet->setWorld( GFX->getWorldMatrix() );
  279. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  280. ri->renderDelegate.bind( this, &Sun::_renderCorona );
  281. ri->type = RenderPassManager::RIT_Sky;
  282. // Render after sky objects and before CloudLayer!
  283. ri->defaultKey = 5;
  284. ri->defaultKey2 = 0;
  285. state->getRenderPass()->addInst( ri );
  286. }
  287. // LightFlareData handles rendering flare effects.
  288. if ( mFlareData )
  289. {
  290. mFlareState.fullBrightness = mBrightness;
  291. mFlareState.scale = mFlareScale;
  292. mFlareState.lightInfo = mLight;
  293. mFlareState.worldRadius = mCoronaWorldRadius;
  294. mFlareState.lightMat.identity();
  295. mFlareState.lightMat.setPosition( mLightWorldPos );
  296. mFlareData->prepRender( state, &mFlareState );
  297. }
  298. }
  299. void Sun::setAzimuth( F32 azimuth )
  300. {
  301. mSunAzimuth = azimuth;
  302. _conformLights();
  303. setMaskBits( UpdateMask ); // TODO: Break out the masks to save bandwidth!
  304. }
  305. void Sun::setElevation( F32 elevation )
  306. {
  307. mSunElevation = elevation;
  308. _conformLights();
  309. setMaskBits( UpdateMask ); // TODO: Break out the masks to save some space!
  310. }
  311. void Sun::setColor( const LinearColorF &color )
  312. {
  313. mLightColor = color;
  314. _conformLights();
  315. setMaskBits( UpdateMask ); // TODO: Break out the masks to save some space!
  316. }
  317. void Sun::animate( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation )
  318. {
  319. mAnimateSun = true;
  320. mCurrTime = 0.0f;
  321. mTotalTime = duration;
  322. mStartAzimuth = startAzimuth;
  323. mEndAzimuth = endAzimuth;
  324. mStartElevation = startElevation;
  325. mEndElevation = endElevation;
  326. }
  327. void Sun::_conformLights()
  328. {
  329. // Build the light direction from the azimuth and elevation.
  330. F32 yaw = mDegToRad(mClampF(mSunAzimuth,0,359));
  331. F32 pitch = mDegToRad(mClampF(mSunElevation,-360,+360));
  332. VectorF lightDirection;
  333. MathUtils::getVectorFromAngles(lightDirection, yaw, pitch);
  334. lightDirection.normalize();
  335. mLight->setDirection( -lightDirection );
  336. mLight->setBrightness( mBrightness );
  337. // Now make sure the colors are within range.
  338. mLightColor.clamp();
  339. mLight->setColor( mLightColor );
  340. mLightAmbient.clamp();
  341. mLight->setAmbient( mLightAmbient );
  342. // Optimization... disable shadows if the ambient and
  343. // directional color are the same.
  344. bool castShadows = mLightColor != mLightAmbient && mCastShadows;
  345. mLight->setCastShadows( castShadows );
  346. mLight->setStaticRefreshFreq(mStaticRefreshFreq);
  347. mLight->setDynamicRefreshFreq(mDynamicRefreshFreq);
  348. }
  349. void Sun::_initCorona()
  350. {
  351. if ( isServerObject() )
  352. return;
  353. SAFE_DELETE( mCoronaMatInst );
  354. if (mCoronaMaterialAsset.notNull())
  355. {
  356. mCoronaMatInst = MATMGR->createMatInstance(mCoronaMaterialAsset->getMaterialDefinitionName(), MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPCT>());
  357. }
  358. }
  359. void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  360. {
  361. // Calculate Billboard Radius (in world units) to be constant, independent of distance.
  362. // Takes into account distance, viewport size, and specified size in editor
  363. F32 BBRadius = mCoronaWorldRadius;
  364. mMatrixSet->restoreSceneViewProjection();
  365. if ( state->isReflectPass() )
  366. mMatrixSet->setProjection( state->getSceneManager()->getNonClipProjection() );
  367. //mMatrixSet->setWorld( MatrixF::Identity );
  368. // Initialize points with basic info
  369. Point3F points[4];
  370. points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
  371. points[1] = Point3F( -BBRadius, 0.0, BBRadius);
  372. points[2] = Point3F( BBRadius, 0.0, -BBRadius);
  373. points[3] = Point3F(BBRadius, 0.0, BBRadius);
  374. static const Point2F sCoords[4] =
  375. {
  376. Point2F( 0.0f, 0.0f ),
  377. Point2F( 0.0f, 1.0f ),
  378. Point2F( 1.0f, 0.0f ),
  379. Point2F(1.0f, 1.0f)
  380. };
  381. // Get info we need to adjust points
  382. const MatrixF &camView = state->getCameraTransform();
  383. // Finalize points
  384. for(S32 i = 0; i < 4; i++)
  385. {
  386. // align with camera
  387. camView.mulV(points[i]);
  388. // offset
  389. points[i] += mLightWorldPos;
  390. }
  391. LinearColorF vertColor;
  392. if ( mCoronaUseLightColor )
  393. vertColor = mLightColor;
  394. else
  395. vertColor = mCoronaTint;
  396. GFXVertexBufferHandle< GFXVertexPCT > vb;
  397. vb.set( GFX, 4, GFXBufferTypeVolatile );
  398. GFXVertexPCT *pVert = vb.lock();
  399. if(!pVert) return;
  400. for ( S32 i = 0; i < 4; i++ )
  401. {
  402. pVert->color.set( vertColor.toColorI());
  403. pVert->point.set( points[i] );
  404. pVert->texCoord.set( sCoords[i].x, sCoords[i].y );
  405. pVert++;
  406. }
  407. vb.unlock();
  408. // Setup SceneData struct.
  409. SceneData sgData;
  410. sgData.wireframe = GFXDevice::getWireframe();
  411. sgData.visibility = 1.0f;
  412. // Draw it
  413. while ( mCoronaMatInst->setupPass( state, sgData ) )
  414. {
  415. mCoronaMatInst->setTransforms( *mMatrixSet, state );
  416. mCoronaMatInst->setSceneInfo( state, sgData );
  417. GFX->setVertexBuffer( vb );
  418. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  419. }
  420. }
  421. void Sun::_updateTimeOfDay( TimeOfDay *timeOfDay, F32 time )
  422. {
  423. setElevation( timeOfDay->getElevationDegrees() );
  424. setAzimuth( timeOfDay->getAzimuthDegrees() );
  425. }
  426. void Sun::_onSelected()
  427. {
  428. #ifdef TORQUE_DEBUG
  429. // Enable debug rendering on the light.
  430. if( isClientObject() )
  431. mLight->enableDebugRendering( true );
  432. #endif
  433. Parent::_onSelected();
  434. }
  435. void Sun::_onUnselected()
  436. {
  437. #ifdef TORQUE_DEBUG
  438. // Disable debug rendering on the light.
  439. if( isClientObject() )
  440. mLight->enableDebugRendering( false );
  441. #endif
  442. Parent::_onUnselected();
  443. }
  444. DefineEngineMethod(Sun, apply, void, (), , "")
  445. {
  446. object->inspectPostApply();
  447. }
  448. DefineEngineMethod(Sun, animate, void, ( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation ), , "animate( F32 duration, F32 startAzimuth, F32 endAzimuth, F32 startElevation, F32 endElevation )")
  449. {
  450. object->animate(duration, startAzimuth, endAzimuth, startElevation, endElevation);
  451. }