decalRoad.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "environment/decalRoad.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "util/catmullRom.h"
  27. #include "math/util/quadTransforms.h"
  28. #include "scene/sceneRenderState.h"
  29. #include "scene/sceneManager.h"
  30. #include "core/stream/bitStream.h"
  31. #include "gfx/gfxDrawUtil.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "math/mathIO.h"
  34. #include "math/mathUtils.h"
  35. #include "terrain/terrData.h"
  36. #include "materials/materialDefinition.h"
  37. #include "materials/materialManager.h"
  38. #include "materials/baseMatInstance.h"
  39. #include "environment/nodeListManager.h"
  40. #include "lighting/lightQuery.h"
  41. extern F32 gDecalBias;
  42. extern bool gEditingMission;
  43. //-----------------------------------------------------------------------------
  44. // DecalRoadNodeList Struct
  45. //-----------------------------------------------------------------------------
  46. struct DecalRoadNodeList : public NodeListManager::NodeList
  47. {
  48. Vector<Point3F> mPositions;
  49. Vector<F32> mWidths;
  50. DecalRoadNodeList() { }
  51. virtual ~DecalRoadNodeList() { }
  52. };
  53. //-----------------------------------------------------------------------------
  54. // DecalRoadNodeEvent Class
  55. //-----------------------------------------------------------------------------
  56. class DecalRoadNodeEvent : public NodeListEvent
  57. {
  58. typedef NodeListEvent Parent;
  59. public:
  60. Vector<Point3F> mPositions;
  61. Vector<F32> mWidths;
  62. public:
  63. DecalRoadNodeEvent() { mNodeList = NULL; }
  64. virtual ~DecalRoadNodeEvent() { }
  65. virtual void pack(NetConnection*, BitStream*);
  66. virtual void unpack(NetConnection*, BitStream*);
  67. virtual void copyIntoList(NodeListManager::NodeList* copyInto);
  68. virtual void padListToSize();
  69. DECLARE_CONOBJECT(DecalRoadNodeEvent);
  70. };
  71. void DecalRoadNodeEvent::pack(NetConnection* conn, BitStream* stream)
  72. {
  73. Parent::pack( conn, stream );
  74. stream->writeInt( mPositions.size(), 16 );
  75. for (U32 i=0; i<mPositions.size(); ++i)
  76. {
  77. mathWrite( *stream, mPositions[i] );
  78. stream->write( mWidths[i] );
  79. }
  80. }
  81. void DecalRoadNodeEvent::unpack(NetConnection* conn, BitStream* stream)
  82. {
  83. mNodeList = new DecalRoadNodeList();
  84. Parent::unpack( conn, stream );
  85. U32 count = stream->readInt( 16 );
  86. Point3F pos;
  87. F32 width;
  88. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  89. for (U32 i=0; i<count; ++i)
  90. {
  91. mathRead( *stream, &pos );
  92. stream->read( &width );
  93. list->mPositions.push_back( pos );
  94. list->mWidths.push_back( width );
  95. }
  96. list->mTotalValidNodes = count;
  97. // Do we have a complete list?
  98. if (list->mPositions.size() >= mTotalNodes)
  99. list->mListComplete = true;
  100. }
  101. void DecalRoadNodeEvent::copyIntoList(NodeListManager::NodeList* copyInto)
  102. {
  103. DecalRoadNodeList* prevList = static_cast<DecalRoadNodeList*>(copyInto);
  104. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  105. // Merge our list with the old list.
  106. for (U32 i=mLocalListStart, index=0; i<mLocalListStart+list->mPositions.size(); ++i, ++index)
  107. {
  108. prevList->mPositions[i] = list->mPositions[index];
  109. prevList->mWidths[i] = list->mWidths[index];
  110. }
  111. }
  112. void DecalRoadNodeEvent::padListToSize()
  113. {
  114. DecalRoadNodeList* list = static_cast<DecalRoadNodeList*>(mNodeList);
  115. U32 totalValidNodes = list->mTotalValidNodes;
  116. // Pad our list front?
  117. if (mLocalListStart)
  118. {
  119. DecalRoadNodeList* newlist = new DecalRoadNodeList();
  120. newlist->mPositions.increment(mLocalListStart);
  121. newlist->mWidths.increment(mLocalListStart);
  122. newlist->mPositions.merge(list->mPositions);
  123. newlist->mWidths.merge(list->mWidths);
  124. delete list;
  125. mNodeList = list = newlist;
  126. }
  127. // Pad our list end?
  128. if (list->mPositions.size() < mTotalNodes)
  129. {
  130. U32 delta = mTotalNodes - list->mPositions.size();
  131. list->mPositions.increment(delta);
  132. list->mWidths.increment(delta);
  133. }
  134. list->mTotalValidNodes = totalValidNodes;
  135. }
  136. IMPLEMENT_CO_NETEVENT_V1(DecalRoadNodeEvent);
  137. ConsoleDocClass( DecalRoadNodeEvent,
  138. "@brief Sends messages to the Decal Road Editor\n\n"
  139. "Editor use only.\n\n"
  140. "@internal"
  141. );
  142. //-----------------------------------------------------------------------------
  143. // DecalRoadNodeListNotify Class
  144. //-----------------------------------------------------------------------------
  145. class DecalRoadNodeListNotify : public NodeListNotify
  146. {
  147. typedef NodeListNotify Parent;
  148. protected:
  149. SimObjectPtr<DecalRoad> mRoad;
  150. public:
  151. DecalRoadNodeListNotify( DecalRoad* road, U32 listId ) { mRoad = road; mListId = listId; }
  152. virtual ~DecalRoadNodeListNotify() { mRoad = NULL; }
  153. virtual void sendNotification( NodeListManager::NodeList* list );
  154. };
  155. void DecalRoadNodeListNotify::sendNotification( NodeListManager::NodeList* list )
  156. {
  157. if (mRoad.isValid())
  158. {
  159. // Build the road's nodes
  160. DecalRoadNodeList* roadList = dynamic_cast<DecalRoadNodeList*>( list );
  161. if (roadList)
  162. mRoad->buildNodesFromList( roadList );
  163. }
  164. }
  165. //-----------------------------------------------------------------------------
  166. // DecalRoadUpdateEvent Class
  167. //-----------------------------------------------------------------------------
  168. void DecalRoadUpdateEvent::process( SimObject *object )
  169. {
  170. DecalRoad *road = dynamic_cast<DecalRoad*>( object );
  171. AssertFatal( road, "DecalRoadRegenEvent::process - wasn't a DecalRoad" );
  172. // Inform clients to perform the update.
  173. road->setMaskBits( mMask );
  174. if ( !road->isProperlyAdded() )
  175. return;
  176. // Perform the server side update.
  177. if ( mMask & DecalRoad::TerrainChangedMask )
  178. {
  179. road->_generateEdges();
  180. }
  181. if ( mMask & DecalRoad::GenEdgesMask )
  182. {
  183. // Server has already done this.
  184. //road->_generateEdges();
  185. }
  186. if ( mMask & DecalRoad::ReClipMask )
  187. {
  188. // Server does not need to capture verts.
  189. road->_captureVerts();
  190. }
  191. }
  192. //------------------------------------------------------------------------------
  193. // Class: DecalRoad
  194. //------------------------------------------------------------------------------
  195. ConsoleDocClass( DecalRoad,
  196. "@brief A strip shaped decal defined by spine nodes which clips against Terrain objects.\n\n"
  197. "DecalRoad is for representing a road or path ( or other inventive things ) across "
  198. "a TerrainBlock. It renders as a decal and is therefore only for features that do "
  199. "not need geometric depth.\n\n"
  200. "The Material assigned to DecalRoad should tile vertically.\n\n"
  201. "@ingroup Terrain"
  202. );
  203. // Init Statics
  204. // Static ConsoleVars for toggling debug rendering
  205. bool DecalRoad::smEditorOpen = false;
  206. bool DecalRoad::smWireframe = true;
  207. bool DecalRoad::smShowBatches = false;
  208. bool DecalRoad::smDiscardAll = false;
  209. bool DecalRoad::smShowSpline = true;
  210. bool DecalRoad::smShowRoad = true;
  211. S32 DecalRoad::smUpdateDelay = 500;
  212. SimObjectPtr<SimSet> DecalRoad::smServerDecalRoadSet = NULL;
  213. // Constructors
  214. DecalRoad::DecalRoad()
  215. : mBreakAngle( 3.0f ),
  216. mSegmentsPerBatch( 10 ),
  217. mTextureLength( 5.0f ),
  218. mRenderPriority( 10 ),
  219. mLoadRenderData( true ),
  220. mMaterial( NULL ),
  221. mMatInst( NULL ),
  222. mTriangleCount(0),
  223. mVertCount(0),
  224. mUpdateEventId( -1 ),
  225. mLastEvent(NULL),
  226. mTerrainUpdateRect( Box3F::Invalid )
  227. {
  228. // Setup NetObject.
  229. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  230. mNetFlags.set(Ghostable);
  231. initMaterialAsset(Material);
  232. }
  233. DecalRoad::~DecalRoad()
  234. {
  235. }
  236. IMPLEMENT_CO_NETOBJECT_V1(DecalRoad);
  237. // ConsoleObject
  238. void DecalRoad::initPersistFields()
  239. {
  240. addGroup( "DecalRoad" );
  241. addProtectedField("materialAsset", TypeMaterialAssetId, Offset(mMaterialAssetId, DecalRoad), &DecalRoad::_setMaterialAsset, &defaultProtectedGetFn, "Material Asset used for rendering.");
  242. addProtectedField( "material", TypeMaterialName, Offset( mMaterialName, DecalRoad ), &DecalRoad::_setMaterialName, &defaultProtectedGetFn, "Material used for rendering." );
  243. addProtectedField( "textureLength", TypeF32, Offset( mTextureLength, DecalRoad ), &DecalRoad::ptSetTextureLength, &defaultProtectedGetFn,
  244. "The length in meters of textures mapped to the DecalRoad" );
  245. addProtectedField( "breakAngle", TypeF32, Offset( mBreakAngle, DecalRoad ), &DecalRoad::ptSetBreakAngle, &defaultProtectedGetFn,
  246. "Angle in degrees - DecalRoad will subdivided the spline if its curve is greater than this threshold." );
  247. addField( "renderPriority", TypeS32, Offset( mRenderPriority, DecalRoad ),
  248. "DecalRoad(s) are rendered in descending renderPriority order." );
  249. endGroup( "DecalRoad" );
  250. addGroup( "Internal" );
  251. addProtectedField( "node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn,
  252. "Do not modify, for internal use." );
  253. endGroup( "Internal" );
  254. Parent::initPersistFields();
  255. }
  256. void DecalRoad::consoleInit()
  257. {
  258. Parent::consoleInit();
  259. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  260. Con::addVariable( "$DecalRoad::EditorOpen", TypeBool, &DecalRoad::smEditorOpen, "For use by the Decal Editor.\n\n"
  261. "@ingroup Editors\n" );
  262. Con::addVariable( "$DecalRoad::wireframe", TypeBool, &DecalRoad::smWireframe, "For use by the Decal Editor.\n\n"
  263. "@ingroup Editors\n" );
  264. Con::addVariable( "$DecalRoad::showBatches", TypeBool, &DecalRoad::smShowBatches, "For use by the Decal Editor.\n\n"
  265. "@ingroup Editors\n" );
  266. Con::addVariable( "$DecalRoad::discardAll", TypeBool, &DecalRoad::smDiscardAll, "For use by the Decal Editor.\n\n"
  267. "@ingroup Editors\n");
  268. Con::addVariable( "$DecalRoad::showSpline", TypeBool, &DecalRoad::smShowSpline, "For use by the Decal Editor.\n\n"
  269. "@ingroup Editors\n" );
  270. Con::addVariable( "$DecalRoad::showRoad", TypeBool, &DecalRoad::smShowRoad, "For use by the Decal Editor.\n\n"
  271. "@ingroup Editors\n" );
  272. Con::addVariable( "$DecalRoad::updateDelay", TypeS32, &DecalRoad::smUpdateDelay, "For use by the Decal Editor.\n\n"
  273. "@ingroup Editors\n" );
  274. }
  275. // SimObject
  276. bool DecalRoad::onAdd()
  277. {
  278. if ( !Parent::onAdd() )
  279. return false;
  280. // DecalRoad is at position zero when created,
  281. // it sets its own position to the first node inside
  282. // _generateEdges but until it has at least one node
  283. // it will be at 0,0,0.
  284. MatrixF mat(true);
  285. Parent::setTransform( mat );
  286. // The client side calculates bounds based on clipped geometry. It would
  287. // be wasteful for the server to do this so the server uses global bounds.
  288. if ( isServerObject() )
  289. {
  290. setGlobalBounds();
  291. resetWorldBox();
  292. }
  293. // Set the Render Transform.
  294. setRenderTransform(mObjToWorld);
  295. // Add to Scene.
  296. addToScene();
  297. if ( isServerObject() )
  298. getServerSet()->addObject( this );
  299. //
  300. TerrainBlock::smUpdateSignal.notify( this, &DecalRoad::_onTerrainChanged );
  301. //
  302. if ( isClientObject() )
  303. _initMaterial();
  304. _generateEdges();
  305. _captureVerts();
  306. return true;
  307. }
  308. void DecalRoad::onRemove()
  309. {
  310. SAFE_DELETE( mMatInst );
  311. TerrainBlock::smUpdateSignal.remove( this, &DecalRoad::_onTerrainChanged );
  312. removeFromScene();
  313. Parent::onRemove();
  314. }
  315. void DecalRoad::inspectPostApply()
  316. {
  317. Parent::inspectPostApply();
  318. setMaskBits( DecalRoadMask );
  319. }
  320. void DecalRoad::onStaticModified( const char* slotName, const char*newValue )
  321. {
  322. Parent::onStaticModified( slotName, newValue );
  323. /*
  324. if ( isProperlyAdded() &&
  325. dStricmp( slotName, "material" ) == 0 )
  326. {
  327. setMaskBits( DecalRoadMask );
  328. }
  329. */
  330. if ( dStricmp( slotName, "renderPriority" ) == 0 )
  331. {
  332. mRenderPriority = getMax( dAtoi(newValue), (S32)1 );
  333. }
  334. }
  335. SimSet* DecalRoad::getServerSet()
  336. {
  337. if ( !smServerDecalRoadSet )
  338. {
  339. smServerDecalRoadSet = new SimSet();
  340. smServerDecalRoadSet->registerObject( "ServerDecalRoadSet" );
  341. Sim::getRootGroup()->addObject( smServerDecalRoadSet );
  342. }
  343. return smServerDecalRoadSet;
  344. }
  345. void DecalRoad::writeFields( Stream &stream, U32 tabStop )
  346. {
  347. Parent::writeFields( stream, tabStop );
  348. // Now write all nodes
  349. stream.write(2, "\r\n");
  350. for ( U32 i = 0; i < mNodes.size(); i++ )
  351. {
  352. const RoadNode &node = mNodes[i];
  353. stream.writeTabs(tabStop);
  354. char buffer[1024];
  355. dMemset( buffer, 0, 1024 );
  356. dSprintf( buffer, 1024, "Node = \"%f %f %f %f\";", node.point.x, node.point.y, node.point.z, node.width );
  357. stream.writeLine( (const U8*)buffer );
  358. }
  359. }
  360. bool DecalRoad::writeField( StringTableEntry fieldname, const char *value )
  361. {
  362. if ( fieldname == StringTable->insert("node") )
  363. return false;
  364. return Parent::writeField( fieldname, value );
  365. }
  366. void DecalRoad::onEditorEnable()
  367. {
  368. }
  369. void DecalRoad::onEditorDisable()
  370. {
  371. }
  372. // NetObject
  373. U32 DecalRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  374. {
  375. // Pack Parent.
  376. U32 retMask = Parent::packUpdate(con, mask, stream);
  377. if ( stream->writeFlag( mask & DecalRoadMask ) )
  378. {
  379. // Write Texture Name.
  380. packMaterialAsset(con, Material);
  381. stream->write( mBreakAngle );
  382. stream->write( mSegmentsPerBatch );
  383. stream->write( mTextureLength );
  384. stream->write( mRenderPriority );
  385. }
  386. if ( stream->writeFlag( mask & NodeMask ) )
  387. {
  388. //stream->writeInt( mNodes.size(), 16 );
  389. //for ( U32 i = 0; i < mNodes.size(); i++ )
  390. //{
  391. // mathWrite( *stream, mNodes[i].point );
  392. // stream->write( mNodes[i].width );
  393. //}
  394. const U32 nodeByteSize = 16; // Based on sending all of a node's parameters
  395. // Test if we can fit all of our nodes within the current stream.
  396. // We make sure we leave 100 bytes still free in the stream for whatever
  397. // may follow us.
  398. S32 allowedBytes = stream->getWriteByteSize() - 100;
  399. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  400. {
  401. // All nodes should fit, so send them out now.
  402. stream->writeInt( mNodes.size(), 16 );
  403. for ( U32 i = 0; i < mNodes.size(); i++ )
  404. {
  405. mathWrite( *stream, mNodes[i].point );
  406. stream->write( mNodes[i].width );
  407. }
  408. }
  409. else
  410. {
  411. // There isn't enough space left in the stream for all of the
  412. // nodes. Batch them up into NetEvents.
  413. U32 id = gServerNodeListManager->nextListId();
  414. U32 count = 0;
  415. U32 index = 0;
  416. while (count < mNodes.size())
  417. {
  418. count += NodeListManager::smMaximumNodesPerEvent;
  419. if (count > mNodes.size())
  420. {
  421. count = mNodes.size();
  422. }
  423. DecalRoadNodeEvent* event = new DecalRoadNodeEvent();
  424. event->mId = id;
  425. event->mTotalNodes = mNodes.size();
  426. event->mLocalListStart = index;
  427. for (; index<count; ++index)
  428. {
  429. event->mPositions.push_back( mNodes[index].point );
  430. event->mWidths.push_back( mNodes[index].width );
  431. }
  432. con->postNetEvent( event );
  433. }
  434. stream->write( id );
  435. }
  436. }
  437. stream->writeFlag( mask & GenEdgesMask );
  438. stream->writeFlag( mask & ReClipMask );
  439. stream->writeFlag( mask & TerrainChangedMask );
  440. // Were done ...
  441. return retMask;
  442. }
  443. void DecalRoad::unpackUpdate( NetConnection *con, BitStream *stream )
  444. {
  445. // Unpack Parent.
  446. Parent::unpackUpdate( con, stream );
  447. // DecalRoadMask
  448. if ( stream->readFlag() )
  449. {
  450. unpackMaterialAsset(con, Material);
  451. if (isProperlyAdded())
  452. _initMaterial();
  453. stream->read( &mBreakAngle );
  454. stream->read( &mSegmentsPerBatch );
  455. stream->read( &mTextureLength );
  456. stream->read( &mRenderPriority );
  457. }
  458. // NodeMask
  459. if ( stream->readFlag() )
  460. {
  461. //U32 count = stream->readInt( 16 );
  462. //mNodes.clear();
  463. //Point3F pos;
  464. //F32 width;
  465. //for ( U32 i = 0; i < count; i++ )
  466. //{
  467. // mathRead( *stream, &pos );
  468. // stream->read( &width );
  469. // _addNode( pos, width );
  470. //}
  471. if (stream->readFlag())
  472. {
  473. // Nodes have been passed in this update
  474. U32 count = stream->readInt( 16 );
  475. mNodes.clear();
  476. Point3F pos;
  477. F32 width;
  478. for ( U32 i = 0; i < count; i++ )
  479. {
  480. mathRead( *stream, &pos );
  481. stream->read( &width );
  482. _addNode( pos, width );
  483. }
  484. }
  485. else
  486. {
  487. // Nodes will arrive as events
  488. U32 id;
  489. stream->read( &id );
  490. // Check if the road's nodes made it here before we did.
  491. NodeListManager::NodeList* list = NULL;
  492. if ( gClientNodeListManager->findListById( id, &list, true) )
  493. {
  494. // Work with the completed list
  495. DecalRoadNodeList* roadList = dynamic_cast<DecalRoadNodeList*>( list );
  496. if (roadList)
  497. buildNodesFromList( roadList );
  498. delete list;
  499. }
  500. else
  501. {
  502. // Nodes have not yet arrived, so register our interest in the list
  503. DecalRoadNodeListNotify* notify = new DecalRoadNodeListNotify( this, id );
  504. gClientNodeListManager->registerNotification( notify );
  505. }
  506. }
  507. }
  508. // GenEdgesMask
  509. if ( stream->readFlag() && isProperlyAdded() )
  510. _generateEdges();
  511. // ReClipMask
  512. if ( stream->readFlag() && isProperlyAdded() )
  513. _captureVerts();
  514. // TerrainChangedMask
  515. if ( stream->readFlag() )
  516. {
  517. if ( isProperlyAdded() )
  518. {
  519. if ( mTerrainUpdateRect.isOverlapped( getWorldBox() ) )
  520. {
  521. _generateEdges();
  522. _captureVerts();
  523. // Clear out the mTerrainUpdateRect since we have updated its
  524. // region and we now need to store future terrain changes
  525. // in it.
  526. mTerrainUpdateRect = Box3F::Invalid;
  527. }
  528. }
  529. }
  530. }
  531. void DecalRoad::prepRenderImage( SceneRenderState* state )
  532. {
  533. PROFILE_SCOPE( DecalRoad_prepRenderImage );
  534. if ( mNodes.size() <= 1 ||
  535. mBatches.size() == 0 ||
  536. !mMatInst ||
  537. state->isShadowPass() )
  538. return;
  539. // If we don't have a material instance after the override then
  540. // we can skip rendering all together.
  541. BaseMatInstance *matInst = state->getOverrideMaterial( mMatInst );
  542. if ( !matInst )
  543. return;
  544. RenderPassManager *renderPass = state->getRenderPass();
  545. // Debug RenderInstance
  546. // Only when editor is open.
  547. if ( smEditorOpen )
  548. {
  549. ObjectRenderInst *ri = renderPass->allocInst<ObjectRenderInst>();
  550. ri->type = RenderPassManager::RIT_Editor;
  551. ri->renderDelegate.bind( this, &DecalRoad::_debugRender );
  552. state->getRenderPass()->addInst( ri );
  553. }
  554. // Normal Road RenderInstance
  555. // Always rendered when the editor is not open
  556. // otherwise obey the smShowRoad flag
  557. if ( !smShowRoad && smEditorOpen )
  558. return;
  559. const Frustum &frustum = state->getCameraFrustum();
  560. MeshRenderInst coreRI;
  561. coreRI.clear();
  562. coreRI.objectToWorld = &MatrixF::Identity;
  563. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  564. MatrixF *tempMat = renderPass->allocUniqueXform( MatrixF( true ) );
  565. MathUtils::getZBiasProjectionMatrix( gDecalBias, frustum, tempMat );
  566. coreRI.projection = tempMat;
  567. coreRI.type = RenderPassManager::RIT_DecalRoad;
  568. coreRI.vertBuff = &mVB;
  569. coreRI.primBuff = &mPB;
  570. coreRI.matInst = matInst;
  571. // Make it the sort distance the max distance so that
  572. // it renders after all the other opaque geometry in
  573. // the deferred bin.
  574. coreRI.sortDistSq = F32_MAX;
  575. // If we need lights then set them up.
  576. if ( matInst->isForwardLit() )
  577. {
  578. LightQuery query;
  579. query.init( getWorldSphere() );
  580. query.getLights( coreRI.lights, 8 );
  581. }
  582. U32 startBatchIdx = -1;
  583. U32 endBatchIdx = 0;
  584. for ( U32 i = 0; i < mBatches.size(); i++ )
  585. {
  586. const RoadBatch &batch = mBatches[i];
  587. const bool isVisible = !frustum.isCulled( batch.bounds );
  588. if ( isVisible )
  589. {
  590. // If this is the start of a set of batches.
  591. if ( startBatchIdx == -1 )
  592. endBatchIdx = startBatchIdx = i;
  593. // Else we're extending the end batch index.
  594. else
  595. ++endBatchIdx;
  596. // If this isn't the last batch then continue.
  597. if ( i < mBatches.size()-1 )
  598. continue;
  599. }
  600. // We we still don't have a start batch, so skip.
  601. if ( startBatchIdx == -1 )
  602. continue;
  603. // Render this set of batches.
  604. const RoadBatch &startBatch = mBatches[startBatchIdx];
  605. const RoadBatch &endBatch = mBatches[endBatchIdx];
  606. U32 startVert = startBatch.startVert;
  607. U32 startIdx = startBatch.startIndex;
  608. U32 vertCount = endBatch.endVert - startVert;
  609. U32 idxCount = ( endBatch.endIndex - startIdx ) + 1;
  610. U32 triangleCount = idxCount / 3;
  611. AssertFatal( startVert + vertCount <= mVertCount, "DecalRoad, bad draw call!" );
  612. AssertFatal( startIdx + triangleCount < mTriangleCount * 3, "DecalRoad, bad draw call!" );
  613. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  614. *ri = coreRI;
  615. ri->prim = renderPass->allocPrim();
  616. ri->prim->type = GFXTriangleList;
  617. ri->prim->minIndex = 0;
  618. ri->prim->startIndex = startIdx;
  619. ri->prim->numPrimitives = triangleCount;
  620. ri->prim->startVertex = 0;
  621. ri->prim->numVertices = endBatch.endVert + 1;
  622. // For sorting we first sort by render priority
  623. // and then by objectId.
  624. //
  625. // Since a road can submit more than one render instance, we want all
  626. // draw calls for a single road to occur consecutively, since they
  627. // could use the same vertex buffer.
  628. ri->defaultKey = mRenderPriority << 0 | mId << 16;
  629. ri->defaultKey2 = 0;
  630. renderPass->addInst( ri );
  631. // Reset the batching.
  632. startBatchIdx = -1;
  633. }
  634. }
  635. void DecalRoad::setTransform( const MatrixF &mat )
  636. {
  637. // We ignore transform requests from the editor
  638. // right now.
  639. }
  640. void DecalRoad::setScale( const VectorF &scale )
  641. {
  642. // We ignore scale requests from the editor
  643. // right now.
  644. }
  645. // DecalRoad Public Methods
  646. bool DecalRoad::getClosestNode( const Point3F &pos, U32 &idx )
  647. {
  648. F32 closestDist = F32_MAX;
  649. for ( U32 i = 0; i < mNodes.size(); i++ )
  650. {
  651. F32 dist = ( mNodes[i].point - pos ).len();
  652. if ( dist < closestDist )
  653. {
  654. closestDist = dist;
  655. idx = i;
  656. }
  657. }
  658. return closestDist != F32_MAX;
  659. }
  660. bool DecalRoad::containsPoint( const Point3F &worldPos, U32 *nodeIdx ) const
  661. {
  662. // This is just for making selections in the editor, we use the
  663. // client-side road because it has the proper edge's.
  664. if ( isServerObject() && getClientObject() )
  665. return ((DecalRoad*)getClientObject())->containsPoint( worldPos, nodeIdx );
  666. // If point isn't in the world box,
  667. // it's definitely not in the road.
  668. //if ( !getWorldBox().isContained( worldPos ) )
  669. // return false;
  670. if ( mEdges.size() < 2 )
  671. return false;
  672. Point2F testPt( worldPos.x,
  673. worldPos.y );
  674. Point2F poly[4];
  675. // Look through all edges, does the polygon
  676. // formed from adjacent edge's contain the worldPos?
  677. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  678. {
  679. const RoadEdge &edge0 = mEdges[i];
  680. const RoadEdge &edge1 = mEdges[i+1];
  681. poly[0].set( edge0.p0.x, edge0.p0.y );
  682. poly[1].set( edge0.p2.x, edge0.p2.y );
  683. poly[2].set( edge1.p2.x, edge1.p2.y );
  684. poly[3].set( edge1.p0.x, edge1.p0.y );
  685. if ( MathUtils::pointInPolygon( poly, 4, testPt ) )
  686. {
  687. if ( nodeIdx )
  688. *nodeIdx = edge0.parentNodeIdx;
  689. return true;
  690. }
  691. }
  692. return false;
  693. }
  694. bool DecalRoad::castray( const Point3F &start, const Point3F &end ) const
  695. {
  696. // We just cast against the object box for the editor.
  697. return mWorldBox.collideLine( start, end );
  698. }
  699. Point3F DecalRoad::getNodePosition( U32 idx )
  700. {
  701. if ( mNodes.size() - 1 < idx )
  702. return Point3F();
  703. return mNodes[idx].point;
  704. }
  705. void DecalRoad::setNodePosition( U32 idx, const Point3F &pos )
  706. {
  707. if ( mNodes.size() - 1 < idx )
  708. return;
  709. mNodes[idx].point = pos;
  710. _generateEdges();
  711. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  712. }
  713. U32 DecalRoad::addNode( const Point3F &pos, F32 width )
  714. {
  715. U32 idx = _addNode( pos, width );
  716. _generateEdges();
  717. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  718. return idx;
  719. }
  720. U32 DecalRoad::insertNode(const Point3F &pos, const F32 &width, const U32 &idx)
  721. {
  722. U32 ret = _insertNode( pos, width, idx );
  723. _generateEdges();
  724. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  725. return ret;
  726. }
  727. void DecalRoad::setNodeWidth( U32 idx, F32 width )
  728. {
  729. if ( mNodes.size() - 1 < idx )
  730. return;
  731. mNodes[idx].width = width;
  732. _generateEdges();
  733. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  734. }
  735. F32 DecalRoad::getNodeWidth( U32 idx )
  736. {
  737. if ( mNodes.size() - 1 < idx )
  738. return -1.0f;
  739. return mNodes[idx].width;
  740. }
  741. void DecalRoad::deleteNode( U32 idx )
  742. {
  743. if ( mNodes.size() - 1 < idx )
  744. return;
  745. mNodes.erase(idx);
  746. _generateEdges();
  747. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  748. }
  749. void DecalRoad::buildNodesFromList( DecalRoadNodeList* list )
  750. {
  751. mNodes.clear();
  752. for (U32 i=0; i<list->mPositions.size(); ++i)
  753. {
  754. _addNode( list->mPositions[i], list->mWidths[i] );
  755. }
  756. _generateEdges();
  757. _captureVerts();
  758. }
  759. void DecalRoad::setTextureLength( F32 meters )
  760. {
  761. meters = getMax( meters, 0.1f );
  762. if ( mTextureLength == meters )
  763. return;
  764. mTextureLength = meters;
  765. _generateEdges();
  766. scheduleUpdate( DecalRoadMask | ReClipMask );
  767. }
  768. void DecalRoad::setBreakAngle( F32 degrees )
  769. {
  770. //meters = getMax( meters, MIN_METERS_PER_SEGMENT );
  771. //if ( mBreakAngle == meters )
  772. // return;
  773. mBreakAngle = degrees;
  774. _generateEdges();
  775. scheduleUpdate( DecalRoadMask | GenEdgesMask | ReClipMask );
  776. }
  777. void DecalRoad::scheduleUpdate( U32 updateMask )
  778. {
  779. scheduleUpdate( updateMask, smUpdateDelay, true );
  780. }
  781. void DecalRoad::scheduleUpdate( U32 updateMask, U32 delayMs, bool restartTimer )
  782. {
  783. if ( Sim::isEventPending( mUpdateEventId ) )
  784. {
  785. if ( !restartTimer )
  786. {
  787. mLastEvent->mMask |= updateMask;
  788. return;
  789. }
  790. else
  791. {
  792. Sim::cancelEvent( mUpdateEventId );
  793. }
  794. }
  795. mLastEvent = new DecalRoadUpdateEvent( updateMask, delayMs );
  796. mUpdateEventId = Sim::postEvent( this, mLastEvent, Sim::getCurrentTime() + delayMs );
  797. }
  798. void DecalRoad::regenerate()
  799. {
  800. _generateEdges();
  801. _captureVerts();
  802. setMaskBits( NodeMask | GenEdgesMask | ReClipMask );
  803. }
  804. bool DecalRoad::addNodeFromField( void *object, const char *index, const char *data )
  805. {
  806. DecalRoad *pObj = static_cast<DecalRoad*>(object);
  807. F32 x,y,z,width;
  808. U32 result = dSscanf( data, "%f %f %f %f", &x, &y, &z, &width );
  809. if ( result == 4 )
  810. pObj->_addNode( Point3F(x,y,z), width );
  811. return false;
  812. }
  813. // Internal Helper Methods
  814. void DecalRoad::_initMaterial()
  815. {
  816. if (mMaterialAsset.notNull())
  817. {
  818. if (mMatInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMatInst->getMaterial()->getName(), String::NoCase))
  819. return;
  820. SAFE_DELETE(mMatInst);
  821. Material* tMat = nullptr;
  822. if (!Sim::findObject(mMaterialAsset->getMaterialDefinitionName(), tMat))
  823. Con::errorf("DecalRoad::_initMaterial - Material %s was not found.", mMaterialAsset->getMaterialDefinitionName());
  824. mMaterial = tMat;
  825. if (mMaterial)
  826. mMatInst = mMaterial->createMatInstance();
  827. else
  828. mMatInst = MATMGR->createMatInstance("WarningMaterial");
  829. if (!mMatInst)
  830. Con::errorf("DecalRoad::_initMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  831. }
  832. if (!mMatInst)
  833. return;
  834. GFXStateBlockDesc desc;
  835. desc.setZReadWrite( true, false );
  836. mMatInst->addStateBlockDesc( desc );
  837. mMatInst->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTBT>() );
  838. }
  839. void DecalRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  840. {
  841. //if ( mStateBlock.isNull() )
  842. // return;
  843. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  844. GFXTransformSaver saver;
  845. //GFX->setStateBlock( mStateBlock );
  846. Point3F size(1,1,1);
  847. ColorI color( 255, 0, 0, 255 );
  848. GFXStateBlockDesc desc;
  849. desc.setZReadWrite( true, false );
  850. desc.setBlend( true );
  851. desc.fillMode = GFXFillWireframe;
  852. if ( smShowBatches )
  853. {
  854. for ( U32 i = 0; i < mBatches.size(); i++ )
  855. {
  856. const Box3F &box = mBatches[i].bounds;
  857. GFX->getDrawUtil()->drawCube( desc, box, ColorI(255,100,100,255) );
  858. }
  859. }
  860. //GFX->leaveDebugEvent();
  861. }
  862. void DecalRoad::_generateEdges()
  863. {
  864. PROFILE_SCOPE( DecalRoad_generateEdges );
  865. //Con::warnf( "%s - generateEdges", isServerObject() ? "server" : "client" );
  866. if ( mNodes.size() > 0 )
  867. {
  868. // Set our object position to the first node.
  869. const Point3F &nodePt = mNodes.first().point;
  870. MatrixF mat( true );
  871. mat.setPosition( nodePt );
  872. Parent::setTransform( mat );
  873. // The server object has global bounds, which Parent::setTransform
  874. // messes up so we must reset it.
  875. if ( isServerObject() )
  876. {
  877. mObjBox.minExtents.set(-1e10, -1e10, -1e10);
  878. mObjBox.maxExtents.set( 1e10, 1e10, 1e10);
  879. }
  880. }
  881. if ( mNodes.size() < 2 )
  882. return;
  883. // Ensure nodes are above the terrain height at their xy position
  884. for ( U32 i = 0; i < mNodes.size(); i++ )
  885. {
  886. _getTerrainHeight( mNodes[i].point );
  887. }
  888. // Now start generating edges...
  889. U32 nodeCount = mNodes.size();
  890. Point3F *positions = new Point3F[nodeCount];
  891. for ( U32 i = 0; i < nodeCount; i++ )
  892. {
  893. const RoadNode &node = mNodes[i];
  894. positions[i].set( node.point.x, node.point.y, node.width );
  895. }
  896. CatmullRom<Point3F> spline;
  897. spline.initialize( nodeCount, positions );
  898. delete [] positions;
  899. mEdges.clear();
  900. Point3F lastBreakVector(0,0,0);
  901. RoadEdge slice;
  902. Point3F lastBreakNode;
  903. lastBreakNode = spline.evaluate(0.0f);
  904. for ( U32 i = 1; i < mNodes.size(); i++ )
  905. {
  906. F32 t1 = spline.getTime(i);
  907. F32 t0 = spline.getTime(i-1);
  908. F32 segLength = spline.arcLength( t0, t1 );
  909. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  910. numSegments = getMax( numSegments, (U32)1 );
  911. F32 tstep = ( t1 - t0 ) / numSegments;
  912. U32 startIdx = 0;
  913. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  914. for ( U32 j = startIdx; j < endIdx; j++ )
  915. {
  916. F32 t = t0 + tstep * j;
  917. Point3F splineNode = spline.evaluate(t);
  918. F32 width = splineNode.z;
  919. _getTerrainHeight( splineNode );
  920. Point3F toNodeVec = splineNode - lastBreakNode;
  921. toNodeVec.normalizeSafe();
  922. if ( lastBreakVector.isZero() )
  923. lastBreakVector = toNodeVec;
  924. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  925. if ( j == startIdx ||
  926. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  927. angle > mBreakAngle )
  928. {
  929. // Push back a spline node
  930. //slice.p1.set( splineNode.x, splineNode.y, 0.0f );
  931. //_getTerrainHeight( slice.p1 );
  932. slice.p1 = splineNode;
  933. slice.uvec.set(0,0,1);
  934. slice.width = width;
  935. slice.parentNodeIdx = i-1;
  936. mEdges.push_back( slice );
  937. lastBreakVector = splineNode - lastBreakNode;
  938. lastBreakVector.normalizeSafe();
  939. lastBreakNode = splineNode;
  940. }
  941. }
  942. }
  943. /*
  944. for ( U32 i = 1; i < nodeCount; i++ )
  945. {
  946. F32 t0 = spline.getTime( i-1 );
  947. F32 t1 = spline.getTime( i );
  948. F32 segLength = spline.arcLength( t0, t1 );
  949. U32 numSegments = mCeil( segLength / mBreakAngle );
  950. numSegments = getMax( numSegments, (U32)1 );
  951. F32 tstep = ( t1 - t0 ) / numSegments;
  952. AssertFatal( numSegments > 0, "DecalRoad::_generateEdges, got zero segments!" );
  953. U32 startIdx = 0;
  954. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  955. for ( U32 j = startIdx; j < endIdx; j++ )
  956. {
  957. F32 t = t0 + tstep * j;
  958. Point3F val = spline.evaluate(t);
  959. RoadEdge edge;
  960. edge.p1.set( val.x, val.y, 0.0f );
  961. _getTerrainHeight( val.x, val.y, edge.p1.z );
  962. edge.uvec.set(0,0,1);
  963. edge.width = val.z;
  964. edge.parentNodeIdx = i-1;
  965. mEdges.push_back( edge );
  966. }
  967. }
  968. */
  969. //
  970. // Calculate fvec and rvec for all edges
  971. //
  972. RoadEdge *edge = NULL;
  973. RoadEdge *nextEdge = NULL;
  974. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  975. {
  976. edge = &mEdges[i];
  977. nextEdge = &mEdges[i+1];
  978. edge->fvec = nextEdge->p1 - edge->p1;
  979. edge->fvec.normalize();
  980. edge->rvec = mCross( edge->fvec, edge->uvec );
  981. edge->rvec.normalize();
  982. }
  983. // Must do the last edge outside the loop
  984. RoadEdge *lastEdge = &mEdges[mEdges.size()-1];
  985. RoadEdge *prevEdge = &mEdges[mEdges.size()-2];
  986. lastEdge->fvec = prevEdge->fvec;
  987. lastEdge->rvec = prevEdge->rvec;
  988. //
  989. // Calculate p0/p2 for all edges
  990. //
  991. for ( U32 i = 0; i < mEdges.size(); i++ )
  992. {
  993. edge = &mEdges[i];
  994. edge->p0 = edge->p1 - edge->rvec * edge->width * 0.5f;
  995. edge->p2 = edge->p1 + edge->rvec * edge->width * 0.5f;
  996. _getTerrainHeight( edge->p0 );
  997. _getTerrainHeight( edge->p2 );
  998. }
  999. }
  1000. void DecalRoad::_captureVerts()
  1001. {
  1002. PROFILE_SCOPE( DecalRoad_captureVerts );
  1003. //Con::warnf( "%s - captureVerts", isServerObject() ? "server" : "client" );
  1004. if ( isServerObject() )
  1005. {
  1006. //Con::errorf( "DecalRoad::_captureVerts - called on the server side!" );
  1007. return;
  1008. }
  1009. if ( mEdges.size() == 0 )
  1010. return;
  1011. //
  1012. // Construct ClippedPolyList objects for each pair
  1013. // of roadEdges.
  1014. // Use them to capture Terrain verts.
  1015. //
  1016. SphereF sphere;
  1017. RoadEdge *edge = NULL;
  1018. RoadEdge *nextEdge = NULL;
  1019. mTriangleCount = 0;
  1020. mVertCount = 0;
  1021. Vector<ClippedPolyList> clipperList;
  1022. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1023. {
  1024. Box3F box;
  1025. edge = &mEdges[i];
  1026. nextEdge = &mEdges[i+1];
  1027. box.minExtents = edge->p1;
  1028. box.maxExtents = edge->p1;
  1029. box.extend( edge->p0 );
  1030. box.extend( edge->p2 );
  1031. box.extend( nextEdge->p0 );
  1032. box.extend( nextEdge->p1 );
  1033. box.extend( nextEdge->p2 );
  1034. box.minExtents.z -= 5.0f;
  1035. box.maxExtents.z += 5.0f;
  1036. sphere.center = ( nextEdge->p1 + edge->p1 ) * 0.5f;
  1037. sphere.radius = 100.0f; // NOTE: no idea how to calculate this
  1038. ClippedPolyList clipper;
  1039. clipper.mNormal.set(0.0f, 0.0f, 0.0f);
  1040. VectorF n;
  1041. PlaneF plane0, plane1;
  1042. // Construct Back Plane
  1043. n = edge->p2 - edge->p0;
  1044. n.normalize();
  1045. n = mCross( n, edge->uvec );
  1046. plane0.set( edge->p0, n );
  1047. clipper.mPlaneList.push_back( plane0 );
  1048. // Construct Front Plane
  1049. n = nextEdge->p2 - nextEdge->p0;
  1050. n.normalize();
  1051. n = -mCross( edge->uvec, n );
  1052. plane1.set( nextEdge->p0, -n );
  1053. //clipper.mPlaneList.push_back( plane1 );
  1054. // Test if / where the planes intersect.
  1055. bool discardLeft = false;
  1056. bool discardRight = false;
  1057. Point3F iPos;
  1058. VectorF iDir;
  1059. if ( plane0.intersect( plane1, iPos, iDir ) )
  1060. {
  1061. Point2F iPos2F( iPos.x, iPos.y );
  1062. Point2F cPos2F( edge->p1.x, edge->p1.y );
  1063. Point2F rVec2F( edge->rvec.x, edge->rvec.y );
  1064. Point2F iVec2F = iPos2F - cPos2F;
  1065. F32 iLen = iVec2F.len();
  1066. iVec2F.normalize();
  1067. if ( iLen < edge->width * 0.5f )
  1068. {
  1069. F32 dot = mDot( rVec2F, iVec2F );
  1070. // The clipping planes intersected on the right side,
  1071. // discard the right side clipping plane.
  1072. if ( dot > 0.0f )
  1073. discardRight = true;
  1074. // The clipping planes intersected on the left side,
  1075. // discard the left side clipping plane.
  1076. else
  1077. discardLeft = true;
  1078. }
  1079. }
  1080. // Left Plane
  1081. if ( !discardLeft )
  1082. {
  1083. n = ( nextEdge->p0 - edge->p0 );
  1084. n.normalize();
  1085. n = mCross( edge->uvec, n );
  1086. clipper.mPlaneList.push_back( PlaneF(edge->p0, n) );
  1087. }
  1088. else
  1089. {
  1090. nextEdge->p0 = edge->p0;
  1091. }
  1092. // Right Plane
  1093. if ( !discardRight )
  1094. {
  1095. n = ( nextEdge->p2 - edge->p2 );
  1096. n.normalize();
  1097. n = -mCross( n, edge->uvec );
  1098. clipper.mPlaneList.push_back( PlaneF(edge->p2, -n) );
  1099. }
  1100. else
  1101. {
  1102. nextEdge->p2 = edge->p2;
  1103. }
  1104. n = nextEdge->p2 - nextEdge->p0;
  1105. n.normalize();
  1106. n = -mCross( edge->uvec, n );
  1107. plane1.set( nextEdge->p0, -n );
  1108. clipper.mPlaneList.push_back( plane1 );
  1109. // We have constructed the clipping planes,
  1110. // now grab/clip the terrain geometry
  1111. getContainer()->buildPolyList( PLC_Decal, box, TerrainObjectType, &clipper );
  1112. clipper.cullUnusedVerts();
  1113. clipper.triangulate();
  1114. clipper.generateNormals();
  1115. // If we got something, add it to the ClippedPolyList Vector
  1116. if ( !clipper.isEmpty() && !( smDiscardAll && ( discardRight || discardLeft ) ) )
  1117. {
  1118. clipperList.push_back( clipper );
  1119. mVertCount += clipper.mVertexList.size();
  1120. mTriangleCount += clipper.mPolyList.size();
  1121. }
  1122. }
  1123. //
  1124. // Set the roadEdge height to be flush with terrain
  1125. // This is not really necessary but makes the debug spline rendering better.
  1126. //
  1127. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1128. {
  1129. edge = &mEdges[i];
  1130. _getTerrainHeight( edge->p0.x, edge->p0.y, edge->p0.z );
  1131. _getTerrainHeight( edge->p2.x, edge->p2.y, edge->p2.z );
  1132. }
  1133. //
  1134. // Allocate the RoadBatch(s)
  1135. //
  1136. // If we captured no verts, then we can return here without
  1137. // allocating any RoadBatches or the Vert/Index Buffers.
  1138. // PreprenderImage will not allocate a render instance while
  1139. // mBatches.size() is zero.
  1140. U32 numClippers = clipperList.size();
  1141. if ( numClippers == 0 )
  1142. return;
  1143. mBatches.clear();
  1144. // Allocate the VertexBuffer and PrimitiveBuffer
  1145. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  1146. mPB.set( GFX, mTriangleCount * 3, 0, GFXBufferTypeStatic );
  1147. // Lock the VertexBuffer
  1148. GFXVertexPNTBT *vertPtr = mVB.lock();
  1149. if(!vertPtr) return;
  1150. U32 vertIdx = 0;
  1151. //
  1152. // Fill the VertexBuffer and vertex data for the RoadBatches
  1153. // Loop through the ClippedPolyList Vector
  1154. //
  1155. RoadBatch *batch = NULL;
  1156. F32 texStart = 0.0f;
  1157. F32 texEnd;
  1158. for ( U32 i = 0; i < clipperList.size(); i++ )
  1159. {
  1160. ClippedPolyList *clipper = &clipperList[i];
  1161. edge = &mEdges[i];
  1162. nextEdge = &mEdges[i+1];
  1163. VectorF segFvec = nextEdge->p1 - edge->p1;
  1164. F32 segLen = segFvec.len();
  1165. segFvec.normalize();
  1166. F32 texLen = segLen / mTextureLength;
  1167. texEnd = texStart + texLen;
  1168. BiQuadToSqr quadToSquare( Point2F( edge->p0.x, edge->p0.y ),
  1169. Point2F( edge->p2.x, edge->p2.y ),
  1170. Point2F( nextEdge->p2.x, nextEdge->p2.y ),
  1171. Point2F( nextEdge->p0.x, nextEdge->p0.y ) );
  1172. //
  1173. if ( i % mSegmentsPerBatch == 0 )
  1174. {
  1175. mBatches.increment();
  1176. batch = &mBatches.last();
  1177. batch->bounds.minExtents = clipper->mVertexList[0].point;
  1178. batch->bounds.maxExtents = clipper->mVertexList[0].point;
  1179. batch->startVert = vertIdx;
  1180. }
  1181. // Loop through each ClippedPolyList
  1182. for ( U32 j = 0; j < clipper->mVertexList.size(); j++ )
  1183. {
  1184. // Add each vert to the VertexBuffer
  1185. Point3F pos = clipper->mVertexList[j].point;
  1186. vertPtr[vertIdx].point = pos;
  1187. vertPtr[vertIdx].normal = clipper->mNormalList[j];
  1188. Point2F uv = quadToSquare.transform( Point2F(pos.x,pos.y) );
  1189. vertPtr[vertIdx].texCoord.x = uv.x;
  1190. vertPtr[vertIdx].texCoord.y = -(( texEnd - texStart ) * uv.y + texStart);
  1191. vertPtr[vertIdx].tangent = mCross( segFvec, clipper->mNormalList[j] );
  1192. vertPtr[vertIdx].binormal = segFvec;
  1193. vertIdx++;
  1194. // Expand the RoadBatch bounds to contain this vertex
  1195. batch->bounds.extend( pos );
  1196. }
  1197. batch->endVert = vertIdx - 1;
  1198. texStart = texEnd;
  1199. }
  1200. // Unlock the VertexBuffer, we are done filling it.
  1201. mVB.unlock();
  1202. // Lock the PrimitiveBuffer
  1203. U16 *idxBuff;
  1204. mPB.lock(&idxBuff);
  1205. U32 curIdx = 0;
  1206. U16 vertOffset = 0;
  1207. batch = NULL;
  1208. S32 batchIdx = -1;
  1209. // Fill the PrimitiveBuffer
  1210. // Loop through each ClippedPolyList in the Vector
  1211. for ( U32 i = 0; i < clipperList.size(); i++ )
  1212. {
  1213. ClippedPolyList *clipper = &clipperList[i];
  1214. if ( i % mSegmentsPerBatch == 0 )
  1215. {
  1216. batchIdx++;
  1217. batch = &mBatches[batchIdx];
  1218. batch->startIndex = curIdx;
  1219. }
  1220. for ( U32 j = 0; j < clipper->mPolyList.size(); j++ )
  1221. {
  1222. // Write indices for each Poly
  1223. ClippedPolyList::Poly *poly = &clipper->mPolyList[j];
  1224. AssertFatal( poly->vertexCount == 3, "Got non-triangle poly!" );
  1225. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart] + vertOffset;
  1226. curIdx++;
  1227. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 1] + vertOffset;
  1228. curIdx++;
  1229. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 2] + vertOffset;
  1230. curIdx++;
  1231. }
  1232. batch->endIndex = curIdx - 1;
  1233. vertOffset += clipper->mVertexList.size();
  1234. }
  1235. // Unlock the PrimitiveBuffer, we are done filling it.
  1236. mPB.unlock();
  1237. // Generate the object/world bounds
  1238. // Is the union of all batch bounding boxes.
  1239. Box3F box;
  1240. for ( U32 i = 0; i < mBatches.size(); i++ )
  1241. {
  1242. batch = &mBatches[i];
  1243. if ( i == 0 )
  1244. box = batch->bounds;
  1245. else
  1246. box.intersect( batch->bounds );
  1247. }
  1248. mWorldBox = box;
  1249. resetObjectBox();
  1250. // Make sure we are in the correct bins given our world box.
  1251. if( getSceneManager() != NULL )
  1252. getSceneManager()->notifyObjectDirty( this );
  1253. }
  1254. U32 DecalRoad::_addNode( const Point3F &pos, F32 width )
  1255. {
  1256. mNodes.increment();
  1257. RoadNode &node = mNodes.last();
  1258. node.point = pos;
  1259. node.width = width;
  1260. return mNodes.size() - 1;
  1261. }
  1262. U32 DecalRoad::_insertNode( const Point3F &pos, const F32 &width, const U32 &idx )
  1263. {
  1264. U32 ret;
  1265. RoadNode *node;
  1266. if ( idx == U32_MAX )
  1267. {
  1268. mNodes.increment();
  1269. node = &mNodes.last();
  1270. ret = mNodes.size() - 1;
  1271. }
  1272. else
  1273. {
  1274. mNodes.insert( idx );
  1275. node = &mNodes[idx];
  1276. ret = idx;
  1277. }
  1278. node->point = pos;
  1279. //node->t = -1.0f;
  1280. //node->rot.identity();
  1281. node->width = width;
  1282. return ret;
  1283. }
  1284. bool DecalRoad::_getTerrainHeight( Point3F &pos )
  1285. {
  1286. return _getTerrainHeight( pos.x, pos.y, pos.z );
  1287. }
  1288. bool DecalRoad::_getTerrainHeight( const Point2F &pos, F32 &height )
  1289. {
  1290. return _getTerrainHeight( pos.x, pos.y, height );
  1291. }
  1292. bool DecalRoad::_getTerrainHeight( const F32 &x, const F32 &y, F32 &height )
  1293. {
  1294. Point3F startPnt( x, y, 10000.0f );
  1295. Point3F endPnt( x, y, -10000.0f );
  1296. RayInfo ri;
  1297. bool hit;
  1298. hit = getContainer()->castRay(startPnt, endPnt, TerrainObjectType, &ri);
  1299. if ( hit )
  1300. height = ri.point.z;
  1301. return hit;
  1302. }
  1303. void DecalRoad::_onTerrainChanged( U32 type, TerrainBlock* tblock, const Point2I &min, const Point2I &max )
  1304. {
  1305. // The client side object just stores the area that has changed
  1306. // and waits for the (delayed) update event from the server
  1307. // to actually perform the update.
  1308. if ( isClientObject() && tblock->isClientObject() )
  1309. {
  1310. // Convert the min and max into world space.
  1311. const F32 size = tblock->getSquareSize();
  1312. const Point3F pos = tblock->getPosition();
  1313. // TODO: I don't think this works right with tiling!
  1314. Box3F dirty( F32( min.x * size ) + pos.x, F32( min.y * size ) + pos.y, -F32_MAX,
  1315. F32( max.x * size ) + pos.x, F32( max.y * size ) + pos.y, F32_MAX );
  1316. if ( !mTerrainUpdateRect.isValidBox() )
  1317. mTerrainUpdateRect = dirty;
  1318. else
  1319. mTerrainUpdateRect.intersect( dirty );
  1320. }
  1321. // The server object only updates edges (doesn't clip to geometry)
  1322. // and schedules an update to be sent to the client.
  1323. else if ( isServerObject() && tblock->isServerObject() )
  1324. {
  1325. //_generateEdges();
  1326. scheduleUpdate( TerrainChangedMask );
  1327. }
  1328. }
  1329. // Static protected field set methods
  1330. bool DecalRoad::ptSetBreakAngle( void *object, const char *index, const char *data )
  1331. {
  1332. DecalRoad *road = static_cast<DecalRoad*>( object );
  1333. F32 val = dAtof( data );
  1334. road->setBreakAngle( val );
  1335. // we already set the field
  1336. return false;
  1337. }
  1338. bool DecalRoad::ptSetTextureLength( void *object, const char *index, const char *data )
  1339. {
  1340. DecalRoad *road = static_cast<DecalRoad*>( object );
  1341. F32 val = dAtof( data );
  1342. road->setTextureLength( val );
  1343. // we already set the field
  1344. return false;
  1345. }
  1346. // ConsoleMethods
  1347. DefineEngineMethod( DecalRoad, regenerate, void, (),,
  1348. "Intended as a helper to developers and editor scripts.\n"
  1349. "Force DecalRoad to update it's spline and reclip geometry."
  1350. )
  1351. {
  1352. object->regenerate();
  1353. }
  1354. DefineEngineMethod( DecalRoad, postApply, void, (),,
  1355. "Intended as a helper to developers and editor scripts.\n"
  1356. "Force trigger an inspectPostApply. This will transmit "
  1357. "the material and other fields ( not including nodes ) "
  1358. "to client objects."
  1359. )
  1360. {
  1361. object->inspectPostApply();
  1362. }