sun.cpp 17 KB

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