sun.cpp 16 KB

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