fxFoliageReplicator.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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. // Written by Melvyn May, Started on 4th August 2002.
  23. //
  24. // "My code is written for the Torque community, so do your worst with it,
  25. // just don't rip-it-off and call it your own without even thanking me".
  26. //
  27. // - Melv.
  28. //
  29. //
  30. // Conversion to TSE By Brian "bzztbomb" Richardson 9/2005
  31. // This was a neat piece of code! Thanks Melv!
  32. // I've switched this to use one large indexed primitive buffer. All animation
  33. // is then done in the vertex shader. This means we have a static vertex/primitive
  34. // buffer that never changes! How spiff! Because of this, the culling code was
  35. // changed to render out full quadtree nodes, we don't try to cull each individual
  36. // node ourselves anymore. This means to get good performance, you probably need to do the
  37. // following:
  38. // 1. If it's a small area to cover, turn off culling completely.
  39. // 2. You want to tune the parameters to make sure there are a lot of billboards within
  40. // each quadrant.
  41. //
  42. // POTENTIAL TODO LIST:
  43. // TODO: Clamp item alpha to fog alpha
  44. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  45. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  46. // Copyright (C) 2015 Faust Logic, Inc.
  47. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  48. #include "platform/platform.h"
  49. #include "T3D/fx/fxFoliageReplicator.h"
  50. #include "gfx/gfxDevice.h"
  51. #include "gfx/primBuilder.h" // Used for debug / mission edit rendering
  52. #include "console/consoleTypes.h"
  53. #include "core/stream/bitStream.h"
  54. #include "math/mRandom.h"
  55. #include "math/mathIO.h"
  56. #include "console/simBase.h"
  57. #include "scene/sceneManager.h"
  58. #include "renderInstance/renderPassManager.h"
  59. #include "scene/sceneRenderState.h"
  60. #include "sim/netConnection.h"
  61. #include "materials/shaderData.h"
  62. #include "console/engineAPI.h"
  63. const U32 AlphaTexLen = 1024;
  64. GFXImplementVertexFormat( GFXVertexFoliage )
  65. {
  66. addElement( "POSITION", GFXDeclType_Float3 );
  67. addElement( "NORMAL", GFXDeclType_Float3 );
  68. addElement( "TEXCOORD", GFXDeclType_Float2, 0 );
  69. addElement( "TEXCOORD", GFXDeclType_Float2, 1 );
  70. }
  71. //------------------------------------------------------------------------------
  72. //
  73. // Put the function in /example/common/editor/ObjectBuilderGui.gui [around line 458] ...
  74. //
  75. // function ObjectBuilderGui::buildfxFoliageReplicator(%this)
  76. // {
  77. // %this.className = "fxFoliageReplicator";
  78. // %this.process();
  79. // }
  80. //
  81. //------------------------------------------------------------------------------
  82. //
  83. // Put this in /example/common/editor/EditorGui.cs in [function Creator::init( %this )]
  84. //
  85. // %Environment_Item[8] = "fxFoliageReplicator"; <-- ADD THIS.
  86. //
  87. //------------------------------------------------------------------------------
  88. //
  89. // Put this in /example/common/client/missionDownload.cs in [function clientCmdMissionStartPhase3(%seq,%missionName)] (line 65)
  90. // after codeline 'onPhase2Complete();'.
  91. //
  92. // StartFoliageReplication();
  93. //
  94. //------------------------------------------------------------------------------
  95. //
  96. // Put this in /engine/console/simBase.h (around line 509) in
  97. //
  98. // namespace Sim
  99. // {
  100. // DeclareNamedSet(fxFoliageSet) <-- ADD THIS (Note no semi-colon).
  101. //
  102. //------------------------------------------------------------------------------
  103. //
  104. // Put this in /engine/console/simBase.cc (around line 19) in
  105. //
  106. // ImplementNamedSet(fxFoliageSet) <-- ADD THIS (Note no semi-colon).
  107. //
  108. //------------------------------------------------------------------------------
  109. //
  110. // Put this in /engine/console/simManager.cc [function void init()] (around line 269).
  111. //
  112. // namespace Sim
  113. // {
  114. // InstantiateNamedSet(fxFoliageSet); <-- ADD THIS (Including Semi-colon).
  115. //
  116. //------------------------------------------------------------------------------
  117. extern bool gEditingMission;
  118. //------------------------------------------------------------------------------
  119. IMPLEMENT_CO_NETOBJECT_V1(fxFoliageReplicator);
  120. ConsoleDocClass( fxFoliageReplicator,
  121. "@brief An emitter to replicate fxFoliageItem objects across an area.\n"
  122. "@ingroup Foliage\n"
  123. );
  124. //------------------------------------------------------------------------------
  125. //
  126. // Trig Table Lookups.
  127. //
  128. //------------------------------------------------------------------------------
  129. const F32 PeriodLenMinus = (F32) (2.0f * M_PI) - 0.01f;
  130. //------------------------------------------------------------------------------
  131. //
  132. // Class: fxFoliageRenderList
  133. //
  134. //------------------------------------------------------------------------------
  135. void fxFoliageRenderList::SetupClipPlanes( SceneRenderState* state, const F32 farClipPlane )
  136. {
  137. const F32 nearPlane = state->getNearPlane();
  138. const F32 farPlane = farClipPlane;
  139. const Frustum& frustum = state->getCullingFrustum();
  140. // [rene, 23-Feb-11] Why isn't this preserving the ortho state of the original frustum?
  141. mFrustum.set( false,//zoneState.frustum.isOrtho(),
  142. frustum.getNearLeft(),
  143. frustum.getNearRight(),
  144. frustum.getNearTop(),
  145. frustum.getNearBottom(),
  146. nearPlane,
  147. farPlane,
  148. frustum.getTransform()
  149. );
  150. mBox = mFrustum.getBounds();
  151. }
  152. //------------------------------------------------------------------------------
  153. inline void fxFoliageRenderList::DrawQuadBox(const Box3F& QuadBox, const LinearColorF Colour)
  154. {
  155. // Define our debug box.
  156. static Point3F BoxPnts[] = {
  157. Point3F(0,0,0),
  158. Point3F(0,0,1),
  159. Point3F(0,1,0),
  160. Point3F(0,1,1),
  161. Point3F(1,0,0),
  162. Point3F(1,0,1),
  163. Point3F(1,1,0),
  164. Point3F(1,1,1)
  165. };
  166. static U32 BoxVerts[][4] = {
  167. {0,2,3,1}, // -x
  168. {7,6,4,5}, // +x
  169. {0,1,5,4}, // -y
  170. {3,2,6,7}, // +y
  171. {0,4,6,2}, // -z
  172. {3,7,5,1} // +z
  173. };
  174. // Project our Box Points.
  175. Point3F ProjectionPoints[8];
  176. for( U32 i=0; i<8; i++ )
  177. {
  178. ProjectionPoints[i].set(BoxPnts[i].x ? QuadBox.maxExtents.x : QuadBox.minExtents.x,
  179. BoxPnts[i].y ? QuadBox.maxExtents.y : QuadBox.minExtents.y,
  180. BoxPnts[i].z ? (mHeightLerp * QuadBox.maxExtents.z) + (1-mHeightLerp) * QuadBox.minExtents.z : QuadBox.minExtents.z);
  181. }
  182. PrimBuild::color(Colour);
  183. // Draw the Box.
  184. for(U32 x = 0; x < 6; x++)
  185. {
  186. // Draw a line-loop.
  187. PrimBuild::begin(GFXLineStrip, 5);
  188. for(U32 y = 0; y < 4; y++)
  189. {
  190. PrimBuild::vertex3f(ProjectionPoints[BoxVerts[x][y]].x,
  191. ProjectionPoints[BoxVerts[x][y]].y,
  192. ProjectionPoints[BoxVerts[x][y]].z);
  193. }
  194. PrimBuild::vertex3f(ProjectionPoints[BoxVerts[x][0]].x,
  195. ProjectionPoints[BoxVerts[x][0]].y,
  196. ProjectionPoints[BoxVerts[x][0]].z);
  197. PrimBuild::end();
  198. }
  199. }
  200. //------------------------------------------------------------------------------
  201. bool fxFoliageRenderList::IsQuadrantVisible(const Box3F VisBox, const MatrixF& RenderTransform)
  202. {
  203. // Can we trivially accept the visible box?
  204. if ( !mFrustum.isCulled( VisBox ) )
  205. return true;
  206. // Not visible.
  207. return false;
  208. }
  209. //------------------------------------------------------------------------------
  210. //
  211. // Class: fxFoliageCulledList
  212. //
  213. //------------------------------------------------------------------------------
  214. fxFoliageCulledList::fxFoliageCulledList(Box3F SearchBox, fxFoliageCulledList* InVec)
  215. {
  216. // Find the Candidates.
  217. FindCandidates(SearchBox, InVec);
  218. }
  219. //------------------------------------------------------------------------------
  220. void fxFoliageCulledList::FindCandidates(const Box3F& SearchBox, fxFoliageCulledList* InVec)
  221. {
  222. // Search the Culled List.
  223. for (U32 i = 0; i < InVec->GetListCount(); i++)
  224. {
  225. // Is this Box overlapping our search box?
  226. if (SearchBox.isOverlapped(InVec->GetElement(i)->FoliageBox))
  227. {
  228. // Yes, so add it to our culled list.
  229. mCulledObjectSet.push_back(InVec->GetElement(i));
  230. }
  231. }
  232. }
  233. //------------------------------------------------------------------------------
  234. //
  235. // Class: fxFoliageReplicator
  236. //
  237. //------------------------------------------------------------------------------
  238. fxFoliageReplicator::fxFoliageReplicator()
  239. {
  240. // Setup NetObject.
  241. mTypeMask |= StaticObjectType;
  242. mNetFlags.set(Ghostable | ScopeAlways);
  243. // Reset Client Replication Started.
  244. mClientReplicationStarted = false;
  245. // Reset Foliage Count.
  246. mCurrentFoliageCount = 0;
  247. // Reset Creation Area Angle Animation.
  248. mCreationAreaAngle = 0;
  249. // Reset Last Render Time.
  250. mLastRenderTime = 0;
  251. // Reset Foliage Nodes.
  252. mPotentialFoliageNodes = 0;
  253. // Reset Billboards Acquired.
  254. mBillboardsAcquired = 0;
  255. // Reset Frame Serial ID.
  256. mFrameSerialID = 0;
  257. mAlphaLookup = NULL;
  258. mDirty = true;
  259. mFoliageShaderProjectionSC = NULL;
  260. mFoliageShaderWorldSC = NULL;
  261. mFoliageShaderGlobalSwayPhaseSC = NULL;
  262. mFoliageShaderSwayMagnitudeSideSC = NULL;
  263. mFoliageShaderSwayMagnitudeFrontSC = NULL;
  264. mFoliageShaderGlobalLightPhaseSC = NULL;
  265. mFoliageShaderLuminanceMagnitudeSC = NULL;
  266. mFoliageShaderLuminanceMidpointSC = NULL;
  267. mFoliageShaderDistanceRangeSC = NULL;
  268. mFoliageShaderCameraPosSC = NULL;
  269. mFoliageShaderTrueBillboardSC = NULL;
  270. mFoliageShaderGroundAlphaSC = NULL;
  271. mFoliageShaderAmbientColorSC = NULL;
  272. mShaderData = NULL;
  273. }
  274. //------------------------------------------------------------------------------
  275. fxFoliageReplicator::~fxFoliageReplicator()
  276. {
  277. if (mAlphaLookup)
  278. delete mAlphaLookup;
  279. mPlacementSB = NULL;
  280. }
  281. //------------------------------------------------------------------------------
  282. void fxFoliageReplicator::initPersistFields()
  283. {
  284. // Add out own persistent fields.
  285. addGroup( "Debugging" ); // MM: Added Group Header.
  286. addField( "UseDebugInfo", TypeBool, Offset( mFieldData.mUseDebugInfo, fxFoliageReplicator ), "Culling bins are drawn when set to true." );
  287. addField( "DebugBoxHeight", TypeF32, Offset( mFieldData.mDebugBoxHeight, fxFoliageReplicator ), "Height multiplier for drawn culling bins.");
  288. addField( "HideFoliage", TypeBool, Offset( mFieldData.mHideFoliage, fxFoliageReplicator ), "Foliage is hidden when set to true." );
  289. addField( "ShowPlacementArea", TypeBool, Offset( mFieldData.mShowPlacementArea, fxFoliageReplicator ), "Draw placement rings when set to true." );
  290. addField( "PlacementAreaHeight", TypeS32, Offset( mFieldData.mPlacementBandHeight, fxFoliageReplicator ), "Height of the placement ring in world units." );
  291. addField( "PlacementColour", TypeColorF, Offset( mFieldData.mPlaceAreaColour, fxFoliageReplicator ), "Color of the placement ring." );
  292. endGroup( "Debugging" ); // MM: Added Group Footer.
  293. addGroup( "Media" ); // MM: Added Group Header.
  294. addField( "Seed", TypeS32, Offset( mFieldData.mSeed, fxFoliageReplicator ), "Random seed for foliage placement." );
  295. addField( "FoliageFile", TypeFilename, Offset( mFieldData.mFoliageFile, fxFoliageReplicator ), "Image file for the foliage texture." );
  296. addField( "FoliageCount", TypeS32, Offset( mFieldData.mFoliageCount, fxFoliageReplicator ), "Maximum foliage instance count." );
  297. addField( "FoliageRetries", TypeS32, Offset( mFieldData.mFoliageRetries, fxFoliageReplicator ), "Number of times to try placing a foliage instance before giving up." );
  298. endGroup( "Media" ); // MM: Added Group Footer.
  299. addGroup( "Area" ); // MM: Added Group Header.
  300. addField( "InnerRadiusX", TypeS32, Offset( mFieldData.mInnerRadiusX, fxFoliageReplicator ), "Placement area inner radius on the X axis" );
  301. addField( "InnerRadiusY", TypeS32, Offset( mFieldData.mInnerRadiusY, fxFoliageReplicator ), "Placement area inner radius on the Y axis" );
  302. addField( "OuterRadiusX", TypeS32, Offset( mFieldData.mOuterRadiusX, fxFoliageReplicator ), "Placement area outer radius on the X axis" );
  303. addField( "OuterRadiusY", TypeS32, Offset( mFieldData.mOuterRadiusY, fxFoliageReplicator ), "Placement area outer radius on the Y axis" );
  304. endGroup( "Area" ); // MM: Added Group Footer.
  305. addGroup( "Dimensions" ); // MM: Added Group Header.
  306. addField( "MinWidth", TypeF32, Offset( mFieldData.mMinWidth, fxFoliageReplicator ), "Minimum width of foliage billboards" );
  307. addField( "MaxWidth", TypeF32, Offset( mFieldData.mMaxWidth, fxFoliageReplicator ), "Maximum width of foliage billboards" );
  308. addField( "MinHeight", TypeF32, Offset( mFieldData.mMinHeight, fxFoliageReplicator ), "Minimum height of foliage billboards" );
  309. addField( "MaxHeight", TypeF32, Offset( mFieldData.mMaxHeight, fxFoliageReplicator ), "Maximum height of foliage billboards" );
  310. addField( "FixAspectRatio", TypeBool, Offset( mFieldData.mFixAspectRatio, fxFoliageReplicator ), "Maintain aspect ratio of image if true. This option ignores MaxWidth." );
  311. addField( "FixSizeToMax", TypeBool, Offset( mFieldData.mFixSizeToMax, fxFoliageReplicator ), "Use only MaxWidth and MaxHeight for billboard size. Ignores MinWidth and MinHeight." );
  312. addField( "OffsetZ", TypeF32, Offset( mFieldData.mOffsetZ, fxFoliageReplicator ), "Offset billboards by this amount vertically." );
  313. addField( "RandomFlip", TypeBool, Offset( mFieldData.mRandomFlip, fxFoliageReplicator ), "Randomly flip billboards left-to-right." );
  314. addField( "UseTrueBillboards", TypeBool, Offset( mFieldData.mUseTrueBillboards, fxFoliageReplicator ), "Use camera facing billboards ( including the z axis )." );
  315. endGroup( "Dimensions" ); // MM: Added Group Footer.
  316. addGroup( "Culling" ); // MM: Added Group Header.
  317. addField( "UseCulling", TypeBool, Offset( mFieldData.mUseCulling, fxFoliageReplicator ), "Use culling bins when enabled." );
  318. addField( "CullResolution", TypeS32, Offset( mFieldData.mCullResolution, fxFoliageReplicator ), "Minimum size of culling bins. Must be >= 8 and <= OuterRadius." );
  319. addField( "ViewDistance", TypeF32, Offset( mFieldData.mViewDistance, fxFoliageReplicator ), "Maximum distance from camera where foliage appears." );
  320. addField( "ViewClosest", TypeF32, Offset( mFieldData.mViewClosest, fxFoliageReplicator ), "Minimum distance from camera where foliage appears." );
  321. addField( "FadeInRegion", TypeF32, Offset( mFieldData.mFadeInRegion, fxFoliageReplicator ), "Region beyond ViewDistance where foliage fades in/out." );
  322. addField( "FadeOutRegion", TypeF32, Offset( mFieldData.mFadeOutRegion, fxFoliageReplicator ), "Region before ViewClosest where foliage fades in/out." );
  323. addField( "AlphaCutoff", TypeF32, Offset( mFieldData.mAlphaCutoff, fxFoliageReplicator ), "Minimum alpha value allowed on foliage instances." );
  324. addField( "GroundAlpha", TypeF32, Offset( mFieldData.mGroundAlpha, fxFoliageReplicator ), "Alpha of the foliage at ground level. 0 = transparent, 1 = opaque." );
  325. endGroup( "Culling" ); // MM: Added Group Footer.
  326. addGroup( "Animation" ); // MM: Added Group Header.
  327. addField( "SwayOn", TypeBool, Offset( mFieldData.mSwayOn, fxFoliageReplicator ), "Foliage should sway randomly when true." );
  328. addField( "SwaySync", TypeBool, Offset( mFieldData.mSwaySync, fxFoliageReplicator ), "Foliage instances should sway together when true and SwayOn is enabled." );
  329. addField( "SwayMagSide", TypeF32, Offset( mFieldData.mSwayMagnitudeSide, fxFoliageReplicator ), "Left-to-right sway magnitude." );
  330. addField( "SwayMagFront", TypeF32, Offset( mFieldData.mSwayMagnitudeFront, fxFoliageReplicator ), "Front-to-back sway magnitude." );
  331. addField( "MinSwayTime", TypeF32, Offset( mFieldData.mMinSwayTime, fxFoliageReplicator ), "Minumum sway cycle time in seconds." );
  332. addField( "MaxSwayTime", TypeF32, Offset( mFieldData.mMaxSwayTime, fxFoliageReplicator ), "Maximum sway cycle time in seconds." );
  333. endGroup( "Animation" ); // MM: Added Group Footer.
  334. addGroup( "Lighting" ); // MM: Added Group Header.
  335. addField( "LightOn", TypeBool, Offset( mFieldData.mLightOn, fxFoliageReplicator ), "Foliage should be illuminated with changing lights when true." );
  336. addField( "LightSync", TypeBool, Offset( mFieldData.mLightSync, fxFoliageReplicator ), "Foliage instances have the same lighting when set and LightOn is set." );
  337. addField( "MinLuminance", TypeF32, Offset( mFieldData.mMinLuminance, fxFoliageReplicator ), "Minimum luminance for foliage instances." );
  338. addField( "MaxLuminance", TypeF32, Offset( mFieldData.mMaxLuminance, fxFoliageReplicator ), "Maximum luminance for foliage instances." );
  339. addField( "LightTime", TypeF32, Offset( mFieldData.mLightTime, fxFoliageReplicator ), "Time before foliage illumination cycle repeats." );
  340. endGroup( "Lighting" ); // MM: Added Group Footer.
  341. addGroup( "Restrictions" ); // MM: Added Group Header.
  342. addField( "AllowOnTerrain", TypeBool, Offset( mFieldData.mAllowOnTerrain, fxFoliageReplicator ), "Foliage will be placed on terrain when set." );
  343. addField( "AllowOnStatics", TypeBool, Offset( mFieldData.mAllowStatics, fxFoliageReplicator ), "Foliage will be placed on Static shapes when set." );
  344. addField( "AllowOnWater", TypeBool, Offset( mFieldData.mAllowOnWater, fxFoliageReplicator ), "Foliage will be placed on/under water when set." );
  345. addField( "AllowWaterSurface", TypeBool, Offset( mFieldData.mAllowWaterSurface, fxFoliageReplicator ), "Foliage will be placed on water when set. Requires AllowOnWater." );
  346. addField( "AllowedTerrainSlope", TypeS32, Offset( mFieldData.mAllowedTerrainSlope, fxFoliageReplicator ), "Maximum surface angle allowed for foliage instances." );
  347. endGroup( "Restrictions" ); // MM: Added Group Footer.
  348. addGroup( "AFX" );
  349. addField( "AmbientModulationBias", TypeF32, Offset( mFieldData.mAmbientModulationBias,fxFoliageReplicator ), "Multiplier controling amount foliage is modulated by sun's ambient." );
  350. endGroup( "AFX" );
  351. // Initialise parents' persistent fields.
  352. Parent::initPersistFields();
  353. }
  354. //------------------------------------------------------------------------------
  355. void fxFoliageReplicator::CreateFoliage(void)
  356. {
  357. F32 HypX, HypY;
  358. F32 Angle;
  359. U32 RelocationRetry;
  360. Point3F FoliagePosition;
  361. Point3F FoliageStart;
  362. Point3F FoliageEnd;
  363. Point3F FoliageScale;
  364. bool CollisionResult;
  365. RayInfo RayEvent;
  366. // Let's get a minimum bounding volume.
  367. Point3F MinPoint( -0.5, -0.5, -0.5 );
  368. Point3F MaxPoint( 0.5, 0.5, 0.5 );
  369. // Check Host.
  370. AssertFatal(isClientObject(), "Trying to create Foliage on Server, this is bad!");
  371. // Cannot continue without Foliage Texture!
  372. if (dStrlen(mFieldData.mFoliageFile) == 0)
  373. return;
  374. // Check that we can position somewhere!
  375. if (!( mFieldData.mAllowOnTerrain ||
  376. mFieldData.mAllowStatics ||
  377. mFieldData.mAllowOnWater))
  378. {
  379. // Problem ...
  380. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could not place Foliage, All alloweds are off!");
  381. // Return here.
  382. return;
  383. }
  384. // Destroy Foliage if we've already got some.
  385. if (mCurrentFoliageCount != 0) DestroyFoliage();
  386. // Inform the user if culling has been disabled!
  387. if (!mFieldData.mUseCulling)
  388. {
  389. // Console Output.
  390. Con::printf("fxFoliageReplicator - Culling has been disabled!");
  391. }
  392. // ----------------------------------------------------------------------------------------------------------------------
  393. // > Calculate the Potential Foliage Nodes Required to achieve the selected culling resolution.
  394. // > Populate Quad-tree structure to depth determined by culling resolution.
  395. //
  396. // A little explanation is called for here ...
  397. //
  398. // The approach to this problem has been choosen to make it *much* easier for
  399. // the user to control the quad-tree culling resolution. The user enters a single
  400. // world-space value 'mCullResolution' which controls the highest resolution at
  401. // which the replicator will check visibility culling.
  402. //
  403. // example: If 'mCullResolution' is 32 and the size of the replicated area is 128 radius
  404. // (256 diameter) then this results in the replicator creating a quad-tree where
  405. // there are 256/32 = 8x8 blocks. Each of these can be checked to see if they
  406. // reside within the viewing frustum and if not then they get culled therefore
  407. // removing the need to parse all the billboards that occcupy that region.
  408. // Most of the time you will get better than this as the culling algorithm will
  409. // check the culling pyramid from the top to bottom e.g. the follow 'blocks'
  410. // will be checked:-
  411. //
  412. // 1 x 256 x 256 (All of replicated area)
  413. // 4 x 128 x 128 (4 corners of above)
  414. // 16 x 64 x 64 (16 x 4 corners of above)
  415. // etc.
  416. //
  417. //
  418. // 1. First-up, the replicator needs to create a fixed-list of quad-tree nodes to work with.
  419. //
  420. // To calculate this we take the largest outer-radius value set in the replicator and
  421. // calculate how many quad-tree levels are required to achieve the selected 'mCullResolution'.
  422. // One of the initial problems is that the replicator has seperate radii values for X & Y.
  423. // This can lead to a culling resolution smaller in one axis than the other if there is a
  424. // difference between the Outer-Radii. Unfortunately, we just live with this as there is
  425. // not much we can do here if we still want to allow the user to have this kind of
  426. // elliptical placement control.
  427. //
  428. // To calculate the number of nodes needed we using the following equation:-
  429. //
  430. // Note:- We are changing the Logarithmic bases from 10 -> 2 ... grrrr!
  431. //
  432. // Cr = mCullResolution
  433. // Rs = Maximum Radii Diameter
  434. //
  435. //
  436. // ( Log10( Rs / Cr ) )
  437. // int ( ---------------- + 0.5 )
  438. // ( Log10( 2 ) )
  439. //
  440. // ---------|
  441. // |
  442. // | n
  443. // / 4
  444. // /
  445. // ---------|
  446. // n = 0
  447. //
  448. //
  449. // So basically we calculate the number of blocks in 1D at the highest resolution, then
  450. // calculate the inverse exponential (base 2 - 1D) to achieve that quantity of blocks.
  451. // We round that upto the next highest integer = e. We then sum 4 to the power 0->e
  452. // which gives us the correct number of nodes required. e is also stored as the starting
  453. // level value for populating the quad-tree (see 3. below).
  454. //
  455. // 2. We then proceed to calculate the billboard positions as normal and calculate and assign
  456. // each billboard a basic volume (rather than treat each as a point). We need to take into
  457. // account possible front/back swaying as well as the basic plane dimensions here.
  458. // When all the billboards have been choosen we then proceed to populate the quad-tree.
  459. //
  460. // 3. To populate the quad-tree we start with a box which completely encapsulates the volume
  461. // occupied by all the billboards and enter into a recursive procedure to process that node.
  462. // Processing this node involves splitting it into quadrants in X/Y untouched (for now).
  463. // We then find candidate billboards with each of these quadrants searching using the
  464. // current subset of shapes from the parent (this reduces the searching to a minimum and
  465. // is very efficient).
  466. //
  467. // If a quadrant does not enclose any billboards then the node is dropped otherwise it
  468. // is processed again using the same procedure.
  469. //
  470. // This happens until we have recursed through the maximum number of levels as calculated
  471. // using the summation max (see equation above). When level 0 is reached, the current list
  472. // of enclosed objects is stored within the node (for the rendering algorithm).
  473. //
  474. // 4. When this is complete we have finished here. The next stage is when rendering takes place.
  475. // An algorithm steps through the quad-tree from the top and does visibility culling on
  476. // each box (with respect to the viewing frustum) and culls as appropriate. If the box is
  477. // visible then the next level is checked until we reach level 0 where the node contains
  478. // a complete subset of billboards enclosed by the visible box.
  479. //
  480. //
  481. // Using the above algorithm we can now generate *massive* quantities of billboards and (using the
  482. // appropriate 'mCullResolution') only visible blocks of billboards will be processed.
  483. //
  484. // - Melv.
  485. //
  486. // ----------------------------------------------------------------------------------------------------------------------
  487. // ----------------------------------------------------------------------------------------------------------------------
  488. // Step 1.
  489. // ----------------------------------------------------------------------------------------------------------------------
  490. // Calculate the maximum dimension.
  491. F32 MaxDimension = 2.0f * ( (mFieldData.mOuterRadiusX > mFieldData.mOuterRadiusY) ? mFieldData.mOuterRadiusX : mFieldData.mOuterRadiusY );
  492. // Let's check that our cull resolution is not greater than half our maximum dimension (and less than 1).
  493. if (mFieldData.mCullResolution > (MaxDimension/2) || mFieldData.mCullResolution < 8)
  494. {
  495. // Problem ...
  496. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could create Foliage, invalid Culling Resolution!");
  497. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Culling Resolution *must* be >=8 or <= %0.2f!", (MaxDimension/2));
  498. // Return here.
  499. return;
  500. }
  501. // Take first Timestamp.
  502. F32 mStartCreationTime = (F32) Platform::getRealMilliseconds();
  503. // Calculate the quad-tree levels needed for selected 'mCullResolution'.
  504. mQuadTreeLevels = (U32)(mCeil(mLog( MaxDimension / mFieldData.mCullResolution ) / mLog( 2.0f )));
  505. // Calculate the number of potential nodes required.
  506. mPotentialFoliageNodes = 0;
  507. for (U32 n = 0; n <= mQuadTreeLevels; n++)
  508. mPotentialFoliageNodes += (U32)(mCeil(mPow(4.0f, (F32) n))); // Ceil to be safe!
  509. // ----------------------------------------------------------------------------------------------------------------------
  510. // Step 2.
  511. // ----------------------------------------------------------------------------------------------------------------------
  512. // Set Seed.
  513. RandomGen.setSeed(mFieldData.mSeed);
  514. // Add Foliage.
  515. for (U32 idx = 0; idx < mFieldData.mFoliageCount; idx++)
  516. {
  517. fxFoliageItem* pFoliageItem;
  518. Point3F FoliageOffsetPos;
  519. // Reset Relocation Retry.
  520. RelocationRetry = mFieldData.mFoliageRetries;
  521. // Find it a home ...
  522. do
  523. {
  524. // Get the fxFoliageReplicator Position.
  525. FoliagePosition = getPosition();
  526. // Calculate a random offset
  527. HypX = RandomGen.randF((F32) mFieldData.mInnerRadiusX < mFieldData.mOuterRadiusX ? mFieldData.mInnerRadiusX : mFieldData.mOuterRadiusX, (F32) mFieldData.mOuterRadiusX);
  528. HypY = RandomGen.randF((F32) mFieldData.mInnerRadiusY < mFieldData.mOuterRadiusY ? mFieldData.mInnerRadiusY : mFieldData.mOuterRadiusY, (F32) mFieldData.mOuterRadiusY);
  529. Angle = RandomGen.randF(0, (F32) M_2PI);
  530. // Calcualte the new position.
  531. FoliagePosition.x += HypX * mCos(Angle);
  532. FoliagePosition.y += HypY * mSin(Angle);
  533. // Initialise RayCast Search Start/End Positions.
  534. FoliageStart = FoliageEnd = FoliagePosition;
  535. FoliageStart.z = 2000.f;
  536. FoliageEnd.z= -2000.f;
  537. // Perform Ray Cast Collision on Client.
  538. CollisionResult = gClientContainer.castRay( FoliageStart, FoliageEnd, FXFOLIAGEREPLICATOR_COLLISION_MASK, &RayEvent);
  539. // Did we hit anything?
  540. if (CollisionResult)
  541. {
  542. // For now, let's pretend we didn't get a collision.
  543. CollisionResult = false;
  544. // Yes, so get it's type.
  545. U32 CollisionType = RayEvent.object->getTypeMask();
  546. // Check Illegal Placements, fail if we hit a disallowed type.
  547. if (((CollisionType & TerrainObjectType) && !mFieldData.mAllowOnTerrain) ||
  548. ((CollisionType & StaticShapeObjectType ) && !mFieldData.mAllowStatics) ||
  549. ((CollisionType & WaterObjectType) && !mFieldData.mAllowOnWater) ) continue;
  550. // If we collided with water and are not allowing on the water surface then let's find the
  551. // terrain underneath and pass this on as the original collision else fail.
  552. if ((CollisionType & WaterObjectType) && !mFieldData.mAllowWaterSurface &&
  553. !gClientContainer.castRay( FoliageStart, FoliageEnd, FXFOLIAGEREPLICATOR_NOWATER_COLLISION_MASK, &RayEvent)) continue;
  554. // We passed with flying colour so carry on.
  555. CollisionResult = true;
  556. }
  557. // Invalidate if we are below Allowed Terrain Angle.
  558. if (RayEvent.normal.z < mSin(mDegToRad(90.0f-mFieldData.mAllowedTerrainSlope))) CollisionResult = false;
  559. // Wait until we get a collision.
  560. } while(!CollisionResult && --RelocationRetry);
  561. // Check for Relocation Problem.
  562. if (RelocationRetry > 0)
  563. {
  564. // Adjust Impact point.
  565. RayEvent.point.z += mFieldData.mOffsetZ;
  566. // Set New Position.
  567. FoliagePosition = RayEvent.point;
  568. }
  569. else
  570. {
  571. // Warning.
  572. Con::warnf(ConsoleLogEntry::General, "fxFoliageReplicator - Could not find satisfactory position for Foliage!");
  573. // Skip to next.
  574. continue;
  575. }
  576. // Monitor the total volume.
  577. FoliageOffsetPos = FoliagePosition - getPosition();
  578. MinPoint.setMin(FoliageOffsetPos);
  579. MaxPoint.setMax(FoliageOffsetPos);
  580. // Create our Foliage Item.
  581. pFoliageItem = new fxFoliageItem;
  582. // Reset Frame Serial.
  583. pFoliageItem->LastFrameSerialID = 0;
  584. // Reset Transform.
  585. pFoliageItem->Transform.identity();
  586. // Set Position.
  587. pFoliageItem->Transform.setColumn(3, FoliagePosition);
  588. // Are we fixing size @ max?
  589. if (mFieldData.mFixSizeToMax)
  590. {
  591. // Yes, so set height maximum height.
  592. pFoliageItem->Height = mFieldData.mMaxHeight;
  593. // Is the Aspect Ratio Fixed?
  594. if (mFieldData.mFixAspectRatio)
  595. // Yes, so lock to height.
  596. pFoliageItem->Width = pFoliageItem->Height;
  597. else
  598. // No, so set width to maximum width.
  599. pFoliageItem->Width = mFieldData.mMaxWidth;
  600. }
  601. else
  602. {
  603. // No, so choose a new Scale.
  604. pFoliageItem->Height = RandomGen.randF(mFieldData.mMinHeight, mFieldData.mMaxHeight);
  605. // Is the Aspect Ratio Fixed?
  606. if (mFieldData.mFixAspectRatio)
  607. // Yes, so lock to height.
  608. pFoliageItem->Width = pFoliageItem->Height;
  609. else
  610. // No, so choose a random width.
  611. pFoliageItem->Width = RandomGen.randF(mFieldData.mMinWidth, mFieldData.mMaxWidth);
  612. }
  613. // Are we randomly flipping horizontally?
  614. if (mFieldData.mRandomFlip)
  615. // Yes, so choose a random flip for this object.
  616. pFoliageItem->Flipped = (RandomGen.randF(0, 1000) < 500.0f) ? false : true;
  617. else
  618. // No, so turn-off flipping.
  619. pFoliageItem->Flipped = false;
  620. // Calculate Foliage Item World Box.
  621. // NOTE:- We generate a psuedo-volume here. It's basically the volume to which the
  622. // plane can move and this includes swaying!
  623. //
  624. // Is Sway On?
  625. if (mFieldData.mSwayOn)
  626. {
  627. // Yes, so take swaying into account...
  628. pFoliageItem->FoliageBox.minExtents = FoliagePosition +
  629. Point3F(-pFoliageItem->Width / 2.0f - mFieldData.mSwayMagnitudeSide,
  630. -0.5f - mFieldData.mSwayMagnitudeFront,
  631. pFoliageItem->Height );
  632. pFoliageItem->FoliageBox.maxExtents = FoliagePosition +
  633. Point3F(+pFoliageItem->Width / 2.0f + mFieldData.mSwayMagnitudeSide,
  634. +0.5f + mFieldData.mSwayMagnitudeFront,
  635. pFoliageItem->Height );
  636. }
  637. else
  638. {
  639. // No, so give it a minimum volume...
  640. pFoliageItem->FoliageBox.minExtents = FoliagePosition +
  641. Point3F(-pFoliageItem->Width / 2.0f,
  642. -0.5f,
  643. pFoliageItem->Height );
  644. pFoliageItem->FoliageBox.maxExtents = FoliagePosition +
  645. Point3F(+pFoliageItem->Width / 2.0f,
  646. +0.5f,
  647. pFoliageItem->Height );
  648. }
  649. // Store Shape in Replicated Shapes Vector.
  650. mReplicatedFoliage.push_back(pFoliageItem);
  651. // Increase Foliage Count.
  652. mCurrentFoliageCount++;
  653. }
  654. // Is Lighting On?
  655. if (mFieldData.mLightOn)
  656. {
  657. // Yes, so reset Global Light phase.
  658. mGlobalLightPhase = 0.0f;
  659. // Set Global Light Time Ratio.
  660. mGlobalLightTimeRatio = PeriodLenMinus / mFieldData.mLightTime;
  661. // Yes, so step through Foliage.
  662. for (U32 idx = 0; idx < mCurrentFoliageCount; idx++)
  663. {
  664. fxFoliageItem* pFoliageItem;
  665. // Fetch the Foliage Item.
  666. pFoliageItem = mReplicatedFoliage[idx];
  667. // Do we have an item?
  668. if (pFoliageItem)
  669. {
  670. // Yes, so are lights syncronised?
  671. if (mFieldData.mLightSync)
  672. {
  673. pFoliageItem->LightTimeRatio = 1.0f;
  674. pFoliageItem->LightPhase = 0.0f;
  675. }
  676. else
  677. {
  678. // No, so choose a random Light phase.
  679. pFoliageItem->LightPhase = RandomGen.randF(0, PeriodLenMinus);
  680. // Set Light Time Ratio.
  681. pFoliageItem->LightTimeRatio = PeriodLenMinus / mFieldData.mLightTime;
  682. }
  683. }
  684. }
  685. }
  686. // Is Swaying Enabled?
  687. if (mFieldData.mSwayOn)
  688. {
  689. // Yes, so reset Global Sway phase.
  690. mGlobalSwayPhase = 0.0f;
  691. // Always set Global Sway Time Ratio.
  692. mGlobalSwayTimeRatio = PeriodLenMinus / RandomGen.randF(mFieldData.mMinSwayTime, mFieldData.mMaxSwayTime);
  693. // Yes, so step through Foliage.
  694. for (U32 idx = 0; idx < mCurrentFoliageCount; idx++)
  695. {
  696. fxFoliageItem* pFoliageItem;
  697. // Fetch the Foliage Item.
  698. pFoliageItem = mReplicatedFoliage[idx];
  699. // Do we have an item?
  700. if (pFoliageItem)
  701. {
  702. // Are we using Sway Sync?
  703. if (mFieldData.mSwaySync)
  704. {
  705. pFoliageItem->SwayPhase = 0;
  706. pFoliageItem->SwayTimeRatio = mGlobalSwayTimeRatio;
  707. }
  708. else
  709. {
  710. // No, so choose a random Sway phase.
  711. pFoliageItem->SwayPhase = RandomGen.randF(0, PeriodLenMinus);
  712. // Set to random Sway Time.
  713. pFoliageItem->SwayTimeRatio = PeriodLenMinus / RandomGen.randF(mFieldData.mMinSwayTime, mFieldData.mMaxSwayTime);
  714. }
  715. }
  716. }
  717. }
  718. // Update our Object Volume.
  719. mObjBox.minExtents.set(MinPoint);
  720. mObjBox.maxExtents.set(MaxPoint);
  721. setTransform(mObjToWorld);
  722. // ----------------------------------------------------------------------------------------------------------------------
  723. // Step 3.
  724. // ----------------------------------------------------------------------------------------------------------------------
  725. // Reset Next Allocated Node to Stack base.
  726. mNextAllocatedNodeIdx = 0;
  727. // Allocate a new Node.
  728. fxFoliageQuadrantNode* pNewNode = new fxFoliageQuadrantNode;
  729. // Store it in the Quad-tree.
  730. mFoliageQuadTree.push_back(pNewNode);
  731. // Populate Initial Node.
  732. //
  733. // Set Start Level.
  734. pNewNode->Level = mQuadTreeLevels;
  735. // Calculate Total Foliage Area.
  736. pNewNode->QuadrantBox = getWorldBox();
  737. // Reset Quadrant child nodes.
  738. pNewNode->QuadrantChildNode[0] =
  739. pNewNode->QuadrantChildNode[1] =
  740. pNewNode->QuadrantChildNode[2] =
  741. pNewNode->QuadrantChildNode[3] = NULL;
  742. // Create our initial cull list with *all* billboards into.
  743. fxFoliageCulledList CullList;
  744. CullList.mCulledObjectSet = mReplicatedFoliage;
  745. // Move to next node Index.
  746. mNextAllocatedNodeIdx++;
  747. // Let's start this thing going by recursing it's children.
  748. ProcessNodeChildren(pNewNode, &CullList);
  749. // Calculate Elapsed Time and take new Timestamp.
  750. F32 ElapsedTime = (Platform::getRealMilliseconds() - mStartCreationTime) * 0.001f;
  751. // Console Output.
  752. Con::printf("fxFoliageReplicator - Lev: %d PotNodes: %d Used: %d Objs: %d Time: %0.4fs.",
  753. mQuadTreeLevels,
  754. mPotentialFoliageNodes,
  755. mNextAllocatedNodeIdx-1,
  756. mBillboardsAcquired,
  757. ElapsedTime);
  758. // Dump (*very*) approximate allocated memory.
  759. F32 MemoryAllocated = (F32) ((mNextAllocatedNodeIdx-1) * sizeof(fxFoliageQuadrantNode));
  760. MemoryAllocated += mCurrentFoliageCount * sizeof(fxFoliageItem);
  761. MemoryAllocated += mCurrentFoliageCount * sizeof(fxFoliageItem*);
  762. Con::printf("fxFoliageReplicator - Approx. %0.2fMb allocated.", MemoryAllocated / 1048576.0f);
  763. // ----------------------------------------------------------------------------------------------------------------------
  764. SetupBuffers();
  765. // Take first Timestamp.
  766. mLastRenderTime = Platform::getVirtualMilliseconds();
  767. }
  768. void fxFoliageReplicator::SetupShader()
  769. {
  770. if ( !mShaderData )
  771. {
  772. if ( !Sim::findObject( "fxFoliageReplicatorShader", mShaderData ) )
  773. {
  774. Con::errorf( "fxFoliageReplicator::SetupShader - could not find ShaderData named fxFoliageReplicatorShader" );
  775. return;
  776. }
  777. }
  778. Vector<GFXShaderMacro> macros;
  779. if ( mFieldData.mUseTrueBillboards )
  780. macros.push_back( GFXShaderMacro( "TRUE_BILLBOARD" ) );
  781. mShader = mShaderData->getShader( macros );
  782. if ( !mShader )
  783. return;
  784. mFoliageShaderConsts = mShader->allocConstBuffer();
  785. mFoliageShaderProjectionSC = mShader->getShaderConstHandle( "$projection" );
  786. mFoliageShaderWorldSC = mShader->getShaderConstHandle( "$world" );
  787. mFoliageShaderGlobalSwayPhaseSC = mShader->getShaderConstHandle( "$GlobalSwayPhase" );
  788. mFoliageShaderSwayMagnitudeSideSC = mShader->getShaderConstHandle( "$SwayMagnitudeSide" );
  789. mFoliageShaderSwayMagnitudeFrontSC = mShader->getShaderConstHandle( "$SwayMagnitudeFront" );
  790. mFoliageShaderGlobalLightPhaseSC = mShader->getShaderConstHandle( "$GlobalLightPhase" );
  791. mFoliageShaderLuminanceMagnitudeSC = mShader->getShaderConstHandle( "$LuminanceMagnitude" );
  792. mFoliageShaderLuminanceMidpointSC = mShader->getShaderConstHandle( "$LuminanceMidpoint" );
  793. mFoliageShaderDistanceRangeSC = mShader->getShaderConstHandle( "$DistanceRange" );
  794. mFoliageShaderCameraPosSC = mShader->getShaderConstHandle( "$CameraPos" );
  795. mFoliageShaderTrueBillboardSC = mShader->getShaderConstHandle( "$TrueBillboard" );
  796. mFoliageShaderGroundAlphaSC = mShader->getShaderConstHandle( "$groundAlpha" );
  797. mFoliageShaderAmbientColorSC = mShader->getShaderConstHandle( "$ambient" );
  798. mDiffuseTextureSC = mShader->getShaderConstHandle( "$diffuseMap" );
  799. mAlphaMapTextureSC = mShader->getShaderConstHandle( "$alphaMap" );
  800. }
  801. // Ok, what we do is let the older code setup the FoliageItem list and the QuadTree.
  802. // Then we build the Vertex and Primitive buffers here. It would probably be
  803. // slightly more memory efficient to build the buffers directly, but we
  804. // want to sort the items within the buffer by the quadtreenodes
  805. void fxFoliageReplicator::SetupBuffers()
  806. {
  807. // Following two arrays are used to build the vertex and primitive buffers.
  808. Point3F basePoints[8];
  809. basePoints[0] = Point3F(-0.5f, 0.0f, 1.0f);
  810. basePoints[1] = Point3F(-0.5f, 0.0f, 0.0f);
  811. basePoints[2] = Point3F(0.5f, 0.0f, 0.0f);
  812. basePoints[3] = Point3F(0.5f, 0.0f, 1.0f);
  813. Point2F texCoords[4];
  814. texCoords[0] = Point2F(0.0, 0.0);
  815. texCoords[1] = Point2F(0.0, 1.0);
  816. texCoords[2] = Point2F(1.0, 1.0);
  817. texCoords[3] = Point2F(1.0, 0.0);
  818. // Init our Primitive Buffer
  819. U32 indexSize = mFieldData.mFoliageCount * 6;
  820. U16* indices = new U16[indexSize];
  821. // Two triangles per particle
  822. for (U16 i = 0; i < mFieldData.mFoliageCount; i++) {
  823. U16* idx = &indices[i*6]; // hey, no offset math below, neat
  824. U16 vertOffset = i*4;
  825. idx[0] = vertOffset + 0;
  826. idx[1] = vertOffset + 1;
  827. idx[2] = vertOffset + 2;
  828. idx[3] = vertOffset + 2;
  829. idx[4] = vertOffset + 3;
  830. idx[5] = vertOffset + 0;
  831. }
  832. // Init the prim buffer and copy our indexes over
  833. U16 *ibIndices;
  834. mPrimBuffer.set(GFX, indexSize, 0, GFXBufferTypeStatic);
  835. mPrimBuffer.lock(&ibIndices);
  836. dMemcpy(ibIndices, indices, indexSize * sizeof(U16));
  837. mPrimBuffer.unlock();
  838. delete[] indices;
  839. // Now, let's init the vertex buffer
  840. U32 currPrimitiveStartIndex = 0;
  841. mVertexBuffer.set(GFX, mFieldData.mFoliageCount * 4, GFXBufferTypeStatic);
  842. mVertexBuffer.lock();
  843. U32 idx = 0;
  844. for (S32 qtIdx = 0; qtIdx < mFoliageQuadTree.size(); qtIdx++) {
  845. fxFoliageQuadrantNode* quadNode = mFoliageQuadTree[qtIdx];
  846. if (quadNode->Level == 0) {
  847. quadNode->startIndex = currPrimitiveStartIndex;
  848. quadNode->primitiveCount = 0;
  849. // Ok, there should be data in here!
  850. for (S32 i = 0; i < quadNode->RenderList.size(); i++) {
  851. fxFoliageItem* pFoliageItem = quadNode->RenderList[i];
  852. if (pFoliageItem->LastFrameSerialID == 0) {
  853. pFoliageItem->LastFrameSerialID++;
  854. // Dump it into the vertex buffer
  855. for (U32 vertIndex = 0; vertIndex < 4; vertIndex++) {
  856. GFXVertexFoliage *vert = &mVertexBuffer[(idx*4) + vertIndex];
  857. // This is the position of the billboard.
  858. vert->point = pFoliageItem->Transform.getPosition();
  859. // Normal contains the point of the billboard (except for the y component, see below)
  860. vert->normal = basePoints[vertIndex];
  861. vert->normal.x *= pFoliageItem->Width;
  862. vert->normal.z *= pFoliageItem->Height;
  863. // Handle texture coordinates
  864. vert->texCoord = texCoords[vertIndex];
  865. if (pFoliageItem->Flipped)
  866. vert->texCoord.x = 1.0f - vert->texCoord.x;
  867. // Handle sway. Sway is stored in a texture coord. The x coordinate is the sway phase multiplier,
  868. // the y coordinate determines if this vertex actually sways or not.
  869. if ((vertIndex == 0) || (vertIndex == 3)) {
  870. vert->texCoord2.set(pFoliageItem->SwayTimeRatio / mGlobalSwayTimeRatio, 1.0f);
  871. } else {
  872. vert->texCoord2.set(0.0f, 0.0f);
  873. }
  874. // Handle lighting, lighting happens at the same time as global so this is just an offset.
  875. vert->normal.y = pFoliageItem->LightPhase;
  876. }
  877. idx++;
  878. quadNode->primitiveCount += 2;
  879. currPrimitiveStartIndex += 6;
  880. }
  881. }
  882. }
  883. }
  884. mVertexBuffer.unlock();
  885. DestroyFoliageItems();
  886. }
  887. //------------------------------------------------------------------------------
  888. Box3F fxFoliageReplicator::FetchQuadrant(const Box3F& Box, U32 Quadrant)
  889. {
  890. Box3F QuadrantBox;
  891. // Select Quadrant.
  892. switch(Quadrant)
  893. {
  894. // UL.
  895. case 0:
  896. QuadrantBox.minExtents = Box.minExtents + Point3F(0, Box.len_y()/2, 0);
  897. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  898. break;
  899. // UR.
  900. case 1:
  901. QuadrantBox.minExtents = Box.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, 0);
  902. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  903. break;
  904. // LL.
  905. case 2:
  906. QuadrantBox.minExtents = Box.minExtents;
  907. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  908. break;
  909. // LR.
  910. case 3:
  911. QuadrantBox.minExtents = Box.minExtents + Point3F(Box.len_x()/2, 0, 0);
  912. QuadrantBox.maxExtents = QuadrantBox.minExtents + Point3F(Box.len_x()/2, Box.len_y()/2, Box.len_z());
  913. break;
  914. default:
  915. return Box;
  916. }
  917. return QuadrantBox;
  918. }
  919. //------------------------------------------------------------------------------
  920. void fxFoliageReplicator::ProcessNodeChildren(fxFoliageQuadrantNode* pParentNode, fxFoliageCulledList* pCullList)
  921. {
  922. // ---------------------------------------------------------------
  923. // Split Node into Quadrants and Process each.
  924. // ---------------------------------------------------------------
  925. // Process All Quadrants (UL/UR/LL/LR).
  926. for (U32 q = 0; q < 4; q++)
  927. ProcessQuadrant(pParentNode, pCullList, q);
  928. }
  929. //------------------------------------------------------------------------------
  930. void fxFoliageReplicator::ProcessQuadrant(fxFoliageQuadrantNode* pParentNode, fxFoliageCulledList* pCullList, U32 Quadrant)
  931. {
  932. // Fetch Quadrant Box.
  933. const Box3F QuadrantBox = FetchQuadrant(pParentNode->QuadrantBox, Quadrant);
  934. // Create our new Cull List.
  935. fxFoliageCulledList CullList(QuadrantBox, pCullList);
  936. // Did we get any objects?
  937. if (CullList.GetListCount() > 0)
  938. {
  939. // Yes, so allocate a new Node.
  940. fxFoliageQuadrantNode* pNewNode = new fxFoliageQuadrantNode;
  941. // Store it in the Quad-tree.
  942. mFoliageQuadTree.push_back(pNewNode);
  943. // Move to next node Index.
  944. mNextAllocatedNodeIdx++;
  945. // Populate Quadrant Node.
  946. //
  947. // Next Sub-level.
  948. pNewNode->Level = pParentNode->Level - 1;
  949. // Calculate Quadrant Box.
  950. pNewNode->QuadrantBox = QuadrantBox;
  951. // Reset Child Nodes.
  952. pNewNode->QuadrantChildNode[0] =
  953. pNewNode->QuadrantChildNode[1] =
  954. pNewNode->QuadrantChildNode[2] =
  955. pNewNode->QuadrantChildNode[3] = NULL;
  956. // Put a reference in parent.
  957. pParentNode->QuadrantChildNode[Quadrant] = pNewNode;
  958. // If we're not at sub-level 0 then process this nodes children.
  959. if (pNewNode->Level != 0) ProcessNodeChildren(pNewNode, &CullList);
  960. // If we've reached sub-level 0 then store Cull List (for rendering).
  961. if (pNewNode->Level == 0)
  962. {
  963. // Store the render list from our culled object set.
  964. pNewNode->RenderList = CullList.mCulledObjectSet;
  965. // Keep track of the total billboard acquired.
  966. mBillboardsAcquired += CullList.GetListCount();
  967. }
  968. }
  969. }
  970. //------------------------------------------------------------------------------
  971. void fxFoliageReplicator::SyncFoliageReplicators(void)
  972. {
  973. // Check Host.
  974. AssertFatal(isServerObject(), "We *MUST* be on server when Synchronising Foliage!");
  975. // Find the Replicator Set.
  976. SimSet *fxFoliageSet = dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"));
  977. // Return if Error.
  978. if (!fxFoliageSet)
  979. {
  980. // Console Warning.
  981. Con::warnf("fxFoliageReplicator - Cannot locate the 'fxFoliageSet', this is bad!");
  982. // Return here.
  983. return;
  984. }
  985. // Parse Replication Object(s).
  986. for (SimSetIterator itr(fxFoliageSet); *itr; ++itr)
  987. {
  988. // Fetch the Replicator Object.
  989. fxFoliageReplicator* Replicator = static_cast<fxFoliageReplicator*>(*itr);
  990. // Set Foliage Replication Mask.
  991. if (Replicator->isServerObject())
  992. {
  993. Con::printf("fxFoliageReplicator - Restarting fxFoliageReplicator Object...");
  994. Replicator->setMaskBits(FoliageReplicationMask);
  995. }
  996. }
  997. // Info ...
  998. Con::printf("fxFoliageReplicator - Client Foliage Sync has completed.");
  999. }
  1000. //------------------------------------------------------------------------------
  1001. // Lets chill our memory requirements out a little
  1002. void fxFoliageReplicator::DestroyFoliageItems()
  1003. {
  1004. // Remove shapes.
  1005. for (S32 idx = 0; idx < mReplicatedFoliage.size(); idx++)
  1006. {
  1007. fxFoliageItem* pFoliageItem;
  1008. // Fetch the Foliage Item.
  1009. pFoliageItem = mReplicatedFoliage[idx];
  1010. // Delete Shape.
  1011. if (pFoliageItem) delete pFoliageItem;
  1012. }
  1013. // Clear the Replicated Foliage Vector.
  1014. mReplicatedFoliage.clear();
  1015. // Clear out old references also
  1016. for (S32 qtIdx = 0; qtIdx < mFoliageQuadTree.size(); qtIdx++) {
  1017. fxFoliageQuadrantNode* quadNode = mFoliageQuadTree[qtIdx];
  1018. if (quadNode->Level == 0) {
  1019. quadNode->RenderList.clear();
  1020. }
  1021. }
  1022. }
  1023. void fxFoliageReplicator::DestroyFoliage(void)
  1024. {
  1025. // Check Host.
  1026. AssertFatal(isClientObject(), "Trying to destroy Foliage on Server, this is bad!");
  1027. // Destroy Quad-tree.
  1028. mPotentialFoliageNodes = 0;
  1029. // Reset Billboards Acquired.
  1030. mBillboardsAcquired = 0;
  1031. // Finish if we didn't create any shapes.
  1032. if (mCurrentFoliageCount == 0) return;
  1033. DestroyFoliageItems();
  1034. // Let's remove the Quad-Tree allocations.
  1035. for ( Vector<fxFoliageQuadrantNode*>::iterator QuadNodeItr = mFoliageQuadTree.begin();
  1036. QuadNodeItr != mFoliageQuadTree.end();
  1037. QuadNodeItr++ )
  1038. {
  1039. // Remove the node.
  1040. delete *QuadNodeItr;
  1041. }
  1042. // Clear the Foliage Quad-Tree Vector.
  1043. mFoliageQuadTree.clear();
  1044. // Clear the Frustum Render Set Vector.
  1045. mFrustumRenderSet.mVisObjectSet.clear();
  1046. // Reset Foliage Count.
  1047. mCurrentFoliageCount = 0;
  1048. }
  1049. //------------------------------------------------------------------------------
  1050. void fxFoliageReplicator::StartUp(void)
  1051. {
  1052. // Flag, Client Replication Started.
  1053. mClientReplicationStarted = true;
  1054. // Create foliage on Client.
  1055. if (isClientObject()) CreateFoliage();
  1056. }
  1057. //------------------------------------------------------------------------------
  1058. bool fxFoliageReplicator::onAdd()
  1059. {
  1060. if(!Parent::onAdd()) return(false);
  1061. // Add the Replicator to the Replicator Set.
  1062. dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"))->addObject(this);
  1063. // Set Default Object Box.
  1064. mObjBox.minExtents.set( -0.5, -0.5, -0.5 );
  1065. mObjBox.maxExtents.set( 0.5, 0.5, 0.5 );
  1066. resetWorldBox();
  1067. setRenderTransform(mObjToWorld);
  1068. // Add to Scene.
  1069. addToScene();
  1070. // Are we on the client?
  1071. if ( isClientObject() )
  1072. {
  1073. // Yes, so load foliage texture.
  1074. if( mFieldData.mFoliageFile != NULL && dStrlen(mFieldData.mFoliageFile) > 0 )
  1075. mFieldData.mFoliageTexture = GFXTexHandle( mFieldData.mFoliageFile, &GFXStaticTextureSRGBProfile, avar("%s() - mFieldData.mFoliageTexture (line %d)", __FUNCTION__, __LINE__) );
  1076. if ((GFXTextureObject*) mFieldData.mFoliageTexture == NULL)
  1077. Con::printf("fxFoliageReplicator: %s is an invalid or missing foliage texture file.", mFieldData.mFoliageFile);
  1078. mAlphaLookup = new GBitmap(AlphaTexLen, 1);
  1079. computeAlphaTex();
  1080. // Register for notification when GhostAlways objects are done loading
  1081. NetConnection::smGhostAlwaysDone.notify( this, &fxFoliageReplicator::onGhostAlwaysDone );
  1082. SetupShader();
  1083. }
  1084. // Return OK.
  1085. return(true);
  1086. }
  1087. //------------------------------------------------------------------------------
  1088. void fxFoliageReplicator::onRemove()
  1089. {
  1090. // Remove the Replicator from the Replicator Set.
  1091. dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"))->removeObject(this);
  1092. NetConnection::smGhostAlwaysDone.remove( this, &fxFoliageReplicator::onGhostAlwaysDone );
  1093. // Remove from Scene.
  1094. removeFromScene();
  1095. // Are we on the Client?
  1096. if (isClientObject())
  1097. {
  1098. // Yes, so destroy Foliage.
  1099. DestroyFoliage();
  1100. // Remove Texture.
  1101. mFieldData.mFoliageTexture = NULL;
  1102. mShader = NULL;
  1103. }
  1104. // Do Parent.
  1105. Parent::onRemove();
  1106. }
  1107. //------------------------------------------------------------------------------
  1108. void fxFoliageReplicator::onGhostAlwaysDone()
  1109. {
  1110. if ( isClientObject() )
  1111. CreateFoliage();
  1112. }
  1113. //------------------------------------------------------------------------------
  1114. void fxFoliageReplicator::inspectPostApply()
  1115. {
  1116. // Set Parent.
  1117. Parent::inspectPostApply();
  1118. // Set Foliage Replication Mask (this object only).
  1119. setMaskBits(FoliageReplicationMask);
  1120. mDirty = true;
  1121. }
  1122. //------------------------------------------------------------------------------
  1123. DefineEngineFunction(StartFoliageReplication, void,(),, "Activates the foliage replicator.\n"
  1124. "@tsexample\n"
  1125. "// Call the function\n"
  1126. "StartFoliageReplication();\n"
  1127. "@endtsexample\n"
  1128. "@ingroup Foliage")
  1129. {
  1130. // Find the Replicator Set.
  1131. SimSet *fxFoliageSet = dynamic_cast<SimSet*>(Sim::findObject("fxFoliageSet"));
  1132. // Return if Error.
  1133. if (!fxFoliageSet)
  1134. {
  1135. // Console Warning.
  1136. Con::warnf("fxFoliageReplicator - Cannot locate the 'fxFoliageSet', this is bad!");
  1137. // Return here.
  1138. return;
  1139. }
  1140. // Parse Replication Object(s).
  1141. U32 startupCount = 0;
  1142. for (SimSetIterator itr(fxFoliageSet); *itr; ++itr)
  1143. {
  1144. // Fetch the Replicator Object.
  1145. fxFoliageReplicator* Replicator = static_cast<fxFoliageReplicator*>(*itr);
  1146. // Start Client Objects Only.
  1147. if (Replicator->isClientObject())
  1148. {
  1149. Replicator->StartUp();
  1150. startupCount++;
  1151. }
  1152. }
  1153. // Info ...
  1154. Con::printf("fxFoliageReplicator - replicated client foliage for %d objects", startupCount);
  1155. }
  1156. //------------------------------------------------------------------------------
  1157. void fxFoliageReplicator::prepRenderImage( SceneRenderState* state )
  1158. {
  1159. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1160. ri->renderDelegate.bind(this, &fxFoliageReplicator::renderObject);
  1161. ri->type = RenderPassManager::RIT_Foliage;
  1162. state->getRenderPass()->addInst( ri );
  1163. }
  1164. //
  1165. // RENDERING
  1166. //
  1167. void fxFoliageReplicator::computeAlphaTex()
  1168. {
  1169. // Distances used in alpha
  1170. const F32 ClippedViewDistance = mFieldData.mViewDistance;
  1171. const F32 MaximumViewDistance = ClippedViewDistance + mFieldData.mFadeInRegion;
  1172. // This is used for the alpha computation in the shader.
  1173. for (U32 i = 0; i < AlphaTexLen; i++) {
  1174. F32 Distance = ((float) i / (float) AlphaTexLen) * MaximumViewDistance;
  1175. F32 ItemAlpha = 1.0f;
  1176. // Are we fading out?
  1177. if (Distance < mFieldData.mViewClosest)
  1178. {
  1179. // Yes, so set fade-out.
  1180. ItemAlpha = 1.0f - ((mFieldData.mViewClosest - Distance) * mFadeOutGradient);
  1181. }
  1182. // No, so are we fading in?
  1183. else if (Distance > ClippedViewDistance)
  1184. {
  1185. // Yes, so set fade-in
  1186. ItemAlpha = 1.0f - ((Distance - ClippedViewDistance) * mFadeInGradient);
  1187. }
  1188. // Set texture info
  1189. ColorI c((U8) (255.0f * ItemAlpha), 0, 0);
  1190. mAlphaLookup->setColor(i, 0, c);
  1191. }
  1192. mAlphaTexture.set(mAlphaLookup, &GFXStaticTextureSRGBProfile, false, String("fxFoliage Replicator Alpha Texture") );
  1193. }
  1194. // Renders a triangle stripped oval
  1195. void fxFoliageReplicator::renderArc(const F32 fRadiusX, const F32 fRadiusY)
  1196. {
  1197. PrimBuild::begin(GFXTriangleStrip, 720);
  1198. for (U32 Angle = mCreationAreaAngle; Angle < (mCreationAreaAngle+360); Angle++)
  1199. {
  1200. F32 XPos, YPos;
  1201. // Calculate Position.
  1202. XPos = fRadiusX * mCos(mDegToRad(-(F32)Angle));
  1203. YPos = fRadiusY * mSin(mDegToRad(-(F32)Angle));
  1204. // Set Colour.
  1205. PrimBuild::color4f(mFieldData.mPlaceAreaColour.red,
  1206. mFieldData.mPlaceAreaColour.green,
  1207. mFieldData.mPlaceAreaColour.blue,
  1208. AREA_ANIMATION_ARC * (Angle-mCreationAreaAngle));
  1209. PrimBuild::vertex3f(XPos, YPos, -(F32)mFieldData.mPlacementBandHeight/2.0f);
  1210. PrimBuild::vertex3f(XPos, YPos, +(F32)mFieldData.mPlacementBandHeight/2.0f);
  1211. }
  1212. PrimBuild::end();
  1213. }
  1214. // This currently uses the primbuilder, could convert out, but why allocate the buffer if we
  1215. // never edit the misison?
  1216. void fxFoliageReplicator::renderPlacementArea(const F32 ElapsedTime)
  1217. {
  1218. if (gEditingMission && mFieldData.mShowPlacementArea)
  1219. {
  1220. GFX->pushWorldMatrix();
  1221. GFX->multWorld(getTransform());
  1222. if (!mPlacementSB)
  1223. {
  1224. GFXStateBlockDesc transparent;
  1225. transparent.setCullMode(GFXCullNone);
  1226. transparent.alphaTestEnable = true;
  1227. transparent.setZReadWrite(true);
  1228. transparent.zWriteEnable = false;
  1229. transparent.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1230. mPlacementSB = GFX->createStateBlock( transparent );
  1231. }
  1232. GFX->setStateBlock(mPlacementSB);
  1233. // Do we need to draw the Outer Radius?
  1234. if (mFieldData.mOuterRadiusX || mFieldData.mOuterRadiusY)
  1235. renderArc((F32) mFieldData.mOuterRadiusX, (F32) mFieldData.mOuterRadiusY);
  1236. // Inner radius?
  1237. if (mFieldData.mInnerRadiusX || mFieldData.mInnerRadiusY)
  1238. renderArc((F32) mFieldData.mInnerRadiusX, (F32) mFieldData.mInnerRadiusY);
  1239. GFX->popWorldMatrix();
  1240. mCreationAreaAngle = (U32)(mCreationAreaAngle + (1000 * ElapsedTime));
  1241. mCreationAreaAngle = mCreationAreaAngle % 360;
  1242. }
  1243. }
  1244. void fxFoliageReplicator::renderObject(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* overrideMat)
  1245. {
  1246. if (overrideMat)
  1247. return;
  1248. if ( !mShader )
  1249. return;
  1250. // If we're rendering and we haven't placed any foliage yet - do it.
  1251. if(!mClientReplicationStarted)
  1252. {
  1253. Con::warnf("fxFoliageReplicator::renderObject - tried to render a non replicated fxFoliageReplicator; replicating it now...");
  1254. StartUp();
  1255. }
  1256. // Calculate Elapsed Time and take new Timestamp.
  1257. S32 Time = Platform::getVirtualMilliseconds();
  1258. F32 ElapsedTime = (Time - mLastRenderTime) * 0.001f;
  1259. mLastRenderTime = Time;
  1260. renderPlacementArea(ElapsedTime);
  1261. if (mCurrentFoliageCount > 0) {
  1262. if ( mRenderSB.isNull() || mDirty)
  1263. {
  1264. mDirty = false;
  1265. GFXStateBlockDesc desc;
  1266. // Debug SB
  1267. desc.samplersDefined = true;
  1268. desc.samplers[0].textureColorOp = GFXTOPDisable;
  1269. desc.samplers[1].textureColorOp = GFXTOPDisable;
  1270. mDebugSB = GFX->createStateBlock(desc);
  1271. // Render SB
  1272. desc.samplers[0].textureColorOp = GFXTOPModulate;
  1273. desc.samplers[1].textureColorOp = GFXTOPModulate;
  1274. desc.samplers[1].addressModeU = GFXAddressClamp;
  1275. desc.samplers[1].addressModeV = GFXAddressClamp;
  1276. desc.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1277. desc.setAlphaTest(true, GFXCmpGreater, (U8) (255.0f * mFieldData.mAlphaCutoff));
  1278. desc.setCullMode(GFXCullNone);
  1279. mRenderSB = GFX->createStateBlock(desc);
  1280. }
  1281. if (!mFieldData.mHideFoliage) {
  1282. // Animate Global Sway Phase (Modulus).
  1283. mGlobalSwayPhase = mGlobalSwayPhase + (mGlobalSwayTimeRatio * ElapsedTime);
  1284. // Animate Global Light Phase (Modulus).
  1285. mGlobalLightPhase = mGlobalLightPhase + (mGlobalLightTimeRatio * ElapsedTime);
  1286. // Compute other light parameters
  1287. const F32 LuminanceMidPoint = (mFieldData.mMinLuminance + mFieldData.mMaxLuminance) / 2.0f;
  1288. const F32 LuminanceMagnitude = mFieldData.mMaxLuminance - LuminanceMidPoint;
  1289. // Distances used in alpha
  1290. const F32 ClippedViewDistance = mFieldData.mViewDistance;
  1291. const F32 MaximumViewDistance = ClippedViewDistance + mFieldData.mFadeInRegion;
  1292. if (mFoliageShaderConsts.isValid())
  1293. {
  1294. mFoliageShaderConsts->setSafe(mFoliageShaderGlobalSwayPhaseSC, mGlobalSwayPhase);
  1295. mFoliageShaderConsts->setSafe(mFoliageShaderSwayMagnitudeSideSC, mFieldData.mSwayMagnitudeSide);
  1296. mFoliageShaderConsts->setSafe(mFoliageShaderSwayMagnitudeFrontSC, mFieldData.mSwayMagnitudeFront);
  1297. mFoliageShaderConsts->setSafe(mFoliageShaderGlobalLightPhaseSC, mGlobalLightPhase);
  1298. mFoliageShaderConsts->setSafe(mFoliageShaderLuminanceMagnitudeSC, LuminanceMagnitude);
  1299. mFoliageShaderConsts->setSafe(mFoliageShaderLuminanceMidpointSC, LuminanceMidPoint);
  1300. // Set up our shader constants
  1301. // Projection matrix
  1302. MatrixF proj = GFX->getProjectionMatrix();
  1303. //proj.transpose();
  1304. mFoliageShaderConsts->setSafe(mFoliageShaderProjectionSC, proj);
  1305. // World transform matrix
  1306. MatrixF world = GFX->getWorldMatrix();
  1307. //world.transpose();
  1308. mFoliageShaderConsts->setSafe(mFoliageShaderWorldSC, world);
  1309. Point3F camPos = state->getCameraPosition();
  1310. mFoliageShaderConsts->setSafe(mFoliageShaderDistanceRangeSC, MaximumViewDistance);
  1311. mFoliageShaderConsts->setSafe(mFoliageShaderCameraPosSC, camPos);
  1312. mFoliageShaderConsts->setSafe(mFoliageShaderTrueBillboardSC, mFieldData.mUseTrueBillboards ? 1.0f : 0.0f );
  1313. mFoliageShaderConsts->setSafe(mFoliageShaderGroundAlphaSC, Point4F(mFieldData.mGroundAlpha, mFieldData.mGroundAlpha, mFieldData.mGroundAlpha, mFieldData.mGroundAlpha));
  1314. if (mFoliageShaderAmbientColorSC->isValid())
  1315. {
  1316. LinearColorF ambient = state->getAmbientLightColor();
  1317. LinearColorF ambient_inv(1.0f-ambient.red, 1.0f-ambient.green, 1.0f-ambient.blue, 0.0f);
  1318. ambient += ambient_inv*(1.0f - mFieldData.mAmbientModulationBias);
  1319. mFoliageShaderConsts->set(mFoliageShaderAmbientColorSC, ambient);
  1320. }
  1321. GFX->setShaderConstBuffer(mFoliageShaderConsts);
  1322. }
  1323. // Blend ops
  1324. // Set up our texture and color ops.
  1325. GFX->setStateBlock(mRenderSB);
  1326. GFX->setShader( mShader );
  1327. GFX->setTexture(mDiffuseTextureSC->getSamplerRegister(), mFieldData.mFoliageTexture);
  1328. // computeAlphaTex(); // Uncomment if we figure out how to clamp to fogAndHaze
  1329. GFX->setTexture(mAlphaMapTextureSC->getSamplerRegister(), mAlphaTexture);
  1330. // Setup our buffers
  1331. GFX->setVertexBuffer(mVertexBuffer);
  1332. GFX->setPrimitiveBuffer(mPrimBuffer);
  1333. // If we use culling, we're going to send chunks of our buffers to the card
  1334. if (mFieldData.mUseCulling)
  1335. {
  1336. // Setup the Clip-Planes.
  1337. F32 FarClipPlane = getMin((F32)state->getFarPlane(),
  1338. mFieldData.mViewDistance + mFieldData.mFadeInRegion);
  1339. mFrustumRenderSet.SetupClipPlanes(state, FarClipPlane);
  1340. renderQuad(mFoliageQuadTree[0], getRenderTransform(), false);
  1341. // Multipass, don't want to interrupt the vb state
  1342. if (mFieldData.mUseDebugInfo)
  1343. {
  1344. // hey man, we're done, so it doesn't matter if we kill it to render the next part
  1345. GFX->setStateBlock(mDebugSB);
  1346. renderQuad(mFoliageQuadTree[0], getRenderTransform(), true);
  1347. }
  1348. }
  1349. else
  1350. {
  1351. // Draw the whole shebang!
  1352. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, mVertexBuffer->mNumVerts,
  1353. 0, mPrimBuffer->mIndexCount / 3);
  1354. }
  1355. }
  1356. }
  1357. }
  1358. void fxFoliageReplicator::renderQuad(fxFoliageQuadrantNode* quadNode, const MatrixF& RenderTransform, const bool UseDebug)
  1359. {
  1360. if (quadNode != NULL) {
  1361. if (mFrustumRenderSet.IsQuadrantVisible(quadNode->QuadrantBox, RenderTransform))
  1362. {
  1363. // Draw the Quad Box (Debug Only).
  1364. if (UseDebug)
  1365. mFrustumRenderSet.DrawQuadBox(quadNode->QuadrantBox, LinearColorF(0.0f, 1.0f, 0.1f, 1.0f));
  1366. if (quadNode->Level != 0) {
  1367. for (U32 i = 0; i < 4; i++)
  1368. renderQuad(quadNode->QuadrantChildNode[i], RenderTransform, UseDebug);
  1369. } else {
  1370. if (!UseDebug)
  1371. if(quadNode->primitiveCount)
  1372. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, mVertexBuffer->mNumVerts,
  1373. quadNode->startIndex, quadNode->primitiveCount);
  1374. }
  1375. } else {
  1376. // Use a different color to say "I think I'm not visible!"
  1377. if (UseDebug)
  1378. mFrustumRenderSet.DrawQuadBox(quadNode->QuadrantBox, LinearColorF(1.0f, 0.8f, 0.1f, 1.0f));
  1379. }
  1380. }
  1381. }
  1382. //------------------------------------------------------------------------------
  1383. // NETWORK
  1384. //------------------------------------------------------------------------------
  1385. U32 fxFoliageReplicator::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  1386. {
  1387. // Pack Parent.
  1388. U32 retMask = Parent::packUpdate(con, mask, stream);
  1389. // Write Foliage Replication Flag.
  1390. if (stream->writeFlag(mask & FoliageReplicationMask))
  1391. {
  1392. stream->writeAffineTransform(mObjToWorld); // Foliage Master-Object Position.
  1393. stream->writeFlag(mFieldData.mUseDebugInfo); // Foliage Debug Information Flag.
  1394. stream->write(mFieldData.mDebugBoxHeight); // Foliage Debug Height.
  1395. stream->write(mFieldData.mSeed); // Foliage Seed.
  1396. stream->write(mFieldData.mFoliageCount); // Foliage Count.
  1397. stream->write(mFieldData.mFoliageRetries); // Foliage Retries.
  1398. stream->writeString(mFieldData.mFoliageFile); // Foliage File.
  1399. stream->write(mFieldData.mInnerRadiusX); // Foliage Inner Radius X.
  1400. stream->write(mFieldData.mInnerRadiusY); // Foliage Inner Radius Y.
  1401. stream->write(mFieldData.mOuterRadiusX); // Foliage Outer Radius X.
  1402. stream->write(mFieldData.mOuterRadiusY); // Foliage Outer Radius Y.
  1403. stream->write(mFieldData.mMinWidth); // Foliage Minimum Width.
  1404. stream->write(mFieldData.mMaxWidth); // Foliage Maximum Width.
  1405. stream->write(mFieldData.mMinHeight); // Foliage Minimum Height.
  1406. stream->write(mFieldData.mMaxHeight); // Foliage Maximum Height.
  1407. stream->write(mFieldData.mFixAspectRatio); // Foliage Fix Aspect Ratio.
  1408. stream->write(mFieldData.mFixSizeToMax); // Foliage Fix Size to Max.
  1409. stream->write(mFieldData.mOffsetZ); // Foliage Offset Z.
  1410. stream->writeFlag(mFieldData.mRandomFlip); // Foliage Random Flip.
  1411. stream->writeFlag(mFieldData.mUseTrueBillboards); // Foliage faces the camera (including z axis)
  1412. stream->write(mFieldData.mUseCulling); // Foliage Use Culling.
  1413. stream->write(mFieldData.mCullResolution); // Foliage Cull Resolution.
  1414. stream->write(mFieldData.mViewDistance); // Foliage View Distance.
  1415. stream->write(mFieldData.mViewClosest); // Foliage View Closest.
  1416. stream->write(mFieldData.mFadeInRegion); // Foliage Fade-In Region.
  1417. stream->write(mFieldData.mFadeOutRegion); // Foliage Fade-Out Region.
  1418. stream->write(mFieldData.mAlphaCutoff); // Foliage Alpha Cutoff.
  1419. stream->write(mFieldData.mGroundAlpha); // Foliage Ground Alpha.
  1420. stream->writeFlag(mFieldData.mSwayOn); // Foliage Sway On Flag.
  1421. stream->writeFlag(mFieldData.mSwaySync); // Foliage Sway Sync Flag.
  1422. stream->write(mFieldData.mSwayMagnitudeSide); // Foliage Sway Magnitude Side2Side.
  1423. stream->write(mFieldData.mSwayMagnitudeFront); // Foliage Sway Magnitude Front2Back.
  1424. stream->write(mFieldData.mMinSwayTime); // Foliage Minimum Sway Time.
  1425. stream->write(mFieldData.mMaxSwayTime); // Foliage Maximum way Time.
  1426. stream->writeFlag(mFieldData.mLightOn); // Foliage Light On Flag.
  1427. stream->writeFlag(mFieldData.mLightSync); // Foliage Light Sync
  1428. stream->write(mFieldData.mMinLuminance); // Foliage Minimum Luminance.
  1429. stream->write(mFieldData.mMaxLuminance); // Foliage Maximum Luminance.
  1430. stream->write(mFieldData.mLightTime); // Foliage Light Time.
  1431. stream->writeFlag(mFieldData.mAllowOnTerrain); // Allow on Terrain.
  1432. stream->writeFlag(mFieldData.mAllowStatics); // Allow on Statics.
  1433. stream->writeFlag(mFieldData.mAllowOnWater); // Allow on Water.
  1434. stream->writeFlag(mFieldData.mAllowWaterSurface); // Allow on Water Surface.
  1435. stream->write(mFieldData.mAllowedTerrainSlope); // Foliage Offset Z.
  1436. stream->writeFlag(mFieldData.mHideFoliage); // Hide Foliage.
  1437. stream->writeFlag(mFieldData.mShowPlacementArea); // Show Placement Area Flag.
  1438. stream->write(mFieldData.mPlacementBandHeight); // Placement Area Height.
  1439. stream->write(mFieldData.mPlaceAreaColour); // Placement Area Colour.
  1440. stream->write(mFieldData.mAmbientModulationBias);
  1441. }
  1442. // Were done ...
  1443. return(retMask);
  1444. }
  1445. //------------------------------------------------------------------------------
  1446. void fxFoliageReplicator::unpackUpdate(NetConnection * con, BitStream * stream)
  1447. {
  1448. // Unpack Parent.
  1449. Parent::unpackUpdate(con, stream);
  1450. // Read Replication Details.
  1451. if(stream->readFlag())
  1452. {
  1453. MatrixF ReplicatorObjectMatrix;
  1454. stream->readAffineTransform(&ReplicatorObjectMatrix); // Foliage Master Object Position.
  1455. mFieldData.mUseDebugInfo = stream->readFlag(); // Foliage Debug Information Flag.
  1456. stream->read(&mFieldData.mDebugBoxHeight); // Foliage Debug Height.
  1457. stream->read(&mFieldData.mSeed); // Foliage Seed.
  1458. stream->read(&mFieldData.mFoliageCount); // Foliage Count.
  1459. stream->read(&mFieldData.mFoliageRetries); // Foliage Retries.
  1460. mFieldData.mFoliageFile = stream->readSTString(); // Foliage File.
  1461. stream->read(&mFieldData.mInnerRadiusX); // Foliage Inner Radius X.
  1462. stream->read(&mFieldData.mInnerRadiusY); // Foliage Inner Radius Y.
  1463. stream->read(&mFieldData.mOuterRadiusX); // Foliage Outer Radius X.
  1464. stream->read(&mFieldData.mOuterRadiusY); // Foliage Outer Radius Y.
  1465. stream->read(&mFieldData.mMinWidth); // Foliage Minimum Width.
  1466. stream->read(&mFieldData.mMaxWidth); // Foliage Maximum Width.
  1467. stream->read(&mFieldData.mMinHeight); // Foliage Minimum Height.
  1468. stream->read(&mFieldData.mMaxHeight); // Foliage Maximum Height.
  1469. stream->read(&mFieldData.mFixAspectRatio); // Foliage Fix Aspect Ratio.
  1470. stream->read(&mFieldData.mFixSizeToMax); // Foliage Fix Size to Max.
  1471. stream->read(&mFieldData.mOffsetZ); // Foliage Offset Z.
  1472. mFieldData.mRandomFlip = stream->readFlag(); // Foliage Random Flip.
  1473. bool wasTrueBB = mFieldData.mUseTrueBillboards;
  1474. mFieldData.mUseTrueBillboards = stream->readFlag(); // Foliage is camera facing (including z axis).
  1475. stream->read(&mFieldData.mUseCulling); // Foliage Use Culling.
  1476. stream->read(&mFieldData.mCullResolution); // Foliage Cull Resolution.
  1477. stream->read(&mFieldData.mViewDistance); // Foliage View Distance.
  1478. stream->read(&mFieldData.mViewClosest); // Foliage View Closest.
  1479. stream->read(&mFieldData.mFadeInRegion); // Foliage Fade-In Region.
  1480. stream->read(&mFieldData.mFadeOutRegion); // Foliage Fade-Out Region.
  1481. stream->read(&mFieldData.mAlphaCutoff); // Foliage Alpha Cutoff.
  1482. stream->read(&mFieldData.mGroundAlpha); // Foliage Ground Alpha.
  1483. mFieldData.mSwayOn = stream->readFlag(); // Foliage Sway On Flag.
  1484. mFieldData.mSwaySync = stream->readFlag(); // Foliage Sway Sync Flag.
  1485. stream->read(&mFieldData.mSwayMagnitudeSide); // Foliage Sway Magnitude Side2Side.
  1486. stream->read(&mFieldData.mSwayMagnitudeFront); // Foliage Sway Magnitude Front2Back.
  1487. stream->read(&mFieldData.mMinSwayTime); // Foliage Minimum Sway Time.
  1488. stream->read(&mFieldData.mMaxSwayTime); // Foliage Maximum way Time.
  1489. mFieldData.mLightOn = stream->readFlag(); // Foliage Light On Flag.
  1490. mFieldData.mLightSync = stream->readFlag(); // Foliage Light Sync
  1491. stream->read(&mFieldData.mMinLuminance); // Foliage Minimum Luminance.
  1492. stream->read(&mFieldData.mMaxLuminance); // Foliage Maximum Luminance.
  1493. stream->read(&mFieldData.mLightTime); // Foliage Light Time.
  1494. mFieldData.mAllowOnTerrain = stream->readFlag(); // Allow on Terrain.
  1495. mFieldData.mAllowStatics = stream->readFlag(); // Allow on Statics.
  1496. mFieldData.mAllowOnWater = stream->readFlag(); // Allow on Water.
  1497. mFieldData.mAllowWaterSurface = stream->readFlag(); // Allow on Water Surface.
  1498. stream->read(&mFieldData.mAllowedTerrainSlope); // Allowed Terrain Slope.
  1499. mFieldData.mHideFoliage = stream->readFlag(); // Hide Foliage.
  1500. mFieldData.mShowPlacementArea = stream->readFlag(); // Show Placement Area Flag.
  1501. stream->read(&mFieldData.mPlacementBandHeight); // Placement Area Height.
  1502. stream->read(&mFieldData.mPlaceAreaColour);
  1503. stream->read(&mFieldData.mAmbientModulationBias);
  1504. // Calculate Fade-In/Out Gradients.
  1505. mFadeInGradient = 1.0f / mFieldData.mFadeInRegion;
  1506. mFadeOutGradient = 1.0f / mFieldData.mFadeOutRegion;
  1507. // Set Transform.
  1508. setTransform(ReplicatorObjectMatrix);
  1509. // Load Foliage Texture on the client.
  1510. if( mFieldData.mFoliageFile != NULL && dStrlen(mFieldData.mFoliageFile) > 0 )
  1511. mFieldData.mFoliageTexture = GFXTexHandle( mFieldData.mFoliageFile, &GFXStaticTextureSRGBProfile, avar("%s() - mFieldData.mFoliageTexture (line %d)", __FUNCTION__, __LINE__) );
  1512. if ((GFXTextureObject*) mFieldData.mFoliageTexture == NULL)
  1513. Con::printf("fxFoliageReplicator: %s is an invalid or missing foliage texture file.", mFieldData.mFoliageFile);
  1514. // Set Quad-Tree Box Height Lerp.
  1515. mFrustumRenderSet.mHeightLerp = mFieldData.mDebugBoxHeight;
  1516. // Create Foliage (if Replication has begun).
  1517. if (mClientReplicationStarted)
  1518. {
  1519. CreateFoliage();
  1520. mDirty = true;
  1521. }
  1522. if ( isProperlyAdded() && mFieldData.mUseTrueBillboards != wasTrueBB )
  1523. SetupShader();
  1524. }
  1525. }