fxFoliageReplicator.cpp 75 KB

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