decalRoad.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  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. mTriangleCount(0),
  221. mVertCount(0),
  222. mUpdateEventId( -1 ),
  223. mLastEvent(NULL),
  224. mTerrainUpdateRect( Box3F::Invalid )
  225. {
  226. // Setup NetObject.
  227. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  228. mNetFlags.set(Ghostable);
  229. INIT_ASSET(Material);
  230. mMaterialInst = nullptr;
  231. }
  232. DecalRoad::~DecalRoad()
  233. {
  234. }
  235. IMPLEMENT_CO_NETOBJECT_V1(DecalRoad);
  236. // ConsoleObject
  237. void DecalRoad::initPersistFields()
  238. {
  239. addGroup( "DecalRoad" );
  240. INITPERSISTFIELD_MATERIALASSET(Material, DecalRoad, "Material used for rendering.");
  241. addProtectedField( "textureLength", TypeF32, Offset( mTextureLength, DecalRoad ), &DecalRoad::ptSetTextureLength, &defaultProtectedGetFn,
  242. "The length in meters of textures mapped to the DecalRoad" );
  243. addProtectedField( "breakAngle", TypeF32, Offset( mBreakAngle, DecalRoad ), &DecalRoad::ptSetBreakAngle, &defaultProtectedGetFn,
  244. "Angle in degrees - DecalRoad will subdivided the spline if its curve is greater than this threshold." );
  245. addField( "renderPriority", TypeS32, Offset( mRenderPriority, DecalRoad ),
  246. "DecalRoad(s) are rendered in descending renderPriority order." );
  247. endGroup( "DecalRoad" );
  248. addGroup( "Internal" );
  249. addProtectedField( "node", TypeString, 0, &addNodeFromField, &emptyStringProtectedGetFn,
  250. "Do not modify, for internal use." );
  251. endGroup( "Internal" );
  252. Parent::initPersistFields();
  253. }
  254. void DecalRoad::consoleInit()
  255. {
  256. Parent::consoleInit();
  257. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  258. Con::addVariable( "$DecalRoad::EditorOpen", TypeBool, &DecalRoad::smEditorOpen, "For use by the Decal Editor.\n\n"
  259. "@ingroup Editors\n" );
  260. Con::addVariable( "$DecalRoad::wireframe", TypeBool, &DecalRoad::smWireframe, "For use by the Decal Editor.\n\n"
  261. "@ingroup Editors\n" );
  262. Con::addVariable( "$DecalRoad::showBatches", TypeBool, &DecalRoad::smShowBatches, "For use by the Decal Editor.\n\n"
  263. "@ingroup Editors\n" );
  264. Con::addVariable( "$DecalRoad::discardAll", TypeBool, &DecalRoad::smDiscardAll, "For use by the Decal Editor.\n\n"
  265. "@ingroup Editors\n");
  266. Con::addVariable( "$DecalRoad::showSpline", TypeBool, &DecalRoad::smShowSpline, "For use by the Decal Editor.\n\n"
  267. "@ingroup Editors\n" );
  268. Con::addVariable( "$DecalRoad::showRoad", TypeBool, &DecalRoad::smShowRoad, "For use by the Decal Editor.\n\n"
  269. "@ingroup Editors\n" );
  270. Con::addVariable( "$DecalRoad::updateDelay", TypeS32, &DecalRoad::smUpdateDelay, "For use by the Decal Editor.\n\n"
  271. "@ingroup Editors\n" );
  272. }
  273. // SimObject
  274. bool DecalRoad::onAdd()
  275. {
  276. if ( !Parent::onAdd() )
  277. return false;
  278. // DecalRoad is at position zero when created,
  279. // it sets its own position to the first node inside
  280. // _generateEdges but until it has at least one node
  281. // it will be at 0,0,0.
  282. MatrixF mat(true);
  283. Parent::setTransform( mat );
  284. // The client side calculates bounds based on clipped geometry. It would
  285. // be wasteful for the server to do this so the server uses global bounds.
  286. if ( isServerObject() )
  287. {
  288. setGlobalBounds();
  289. resetWorldBox();
  290. }
  291. // Set the Render Transform.
  292. setRenderTransform(mObjToWorld);
  293. // Add to Scene.
  294. addToScene();
  295. if ( isServerObject() )
  296. getServerSet()->addObject( this );
  297. //
  298. TerrainBlock::smUpdateSignal.notify( this, &DecalRoad::_onTerrainChanged );
  299. //
  300. if ( isClientObject() )
  301. _initMaterial();
  302. _generateEdges();
  303. _captureVerts();
  304. return true;
  305. }
  306. void DecalRoad::onRemove()
  307. {
  308. SAFE_DELETE( mMaterialInst );
  309. TerrainBlock::smUpdateSignal.remove( this, &DecalRoad::_onTerrainChanged );
  310. removeFromScene();
  311. Parent::onRemove();
  312. }
  313. void DecalRoad::inspectPostApply()
  314. {
  315. Parent::inspectPostApply();
  316. setMaskBits( DecalRoadMask );
  317. }
  318. void DecalRoad::onStaticModified( const char* slotName, const char*newValue )
  319. {
  320. Parent::onStaticModified( slotName, newValue );
  321. /*
  322. if ( isProperlyAdded() &&
  323. dStricmp( slotName, "material" ) == 0 )
  324. {
  325. setMaskBits( DecalRoadMask );
  326. }
  327. */
  328. if ( dStricmp( slotName, "renderPriority" ) == 0 )
  329. {
  330. mRenderPriority = getMax( dAtoi(newValue), (S32)1 );
  331. }
  332. }
  333. SimSet* DecalRoad::getServerSet()
  334. {
  335. if ( !smServerDecalRoadSet )
  336. {
  337. smServerDecalRoadSet = new SimSet();
  338. smServerDecalRoadSet->registerObject( "ServerDecalRoadSet" );
  339. Sim::getRootGroup()->addObject( smServerDecalRoadSet );
  340. }
  341. return smServerDecalRoadSet;
  342. }
  343. void DecalRoad::writeFields( Stream &stream, U32 tabStop )
  344. {
  345. Parent::writeFields( stream, tabStop );
  346. // Now write all nodes
  347. stream.write(2, "\r\n");
  348. for ( U32 i = 0; i < mNodes.size(); i++ )
  349. {
  350. const RoadNode &node = mNodes[i];
  351. stream.writeTabs(tabStop);
  352. char buffer[1024];
  353. dMemset( buffer, 0, 1024 );
  354. dSprintf( buffer, 1024, "Node = \"%f %f %f %f\";", node.point.x, node.point.y, node.point.z, node.width );
  355. stream.writeLine( (const U8*)buffer );
  356. }
  357. }
  358. bool DecalRoad::writeField( StringTableEntry fieldname, const char *value )
  359. {
  360. if ( fieldname == StringTable->insert("node") )
  361. return false;
  362. return Parent::writeField( fieldname, value );
  363. }
  364. void DecalRoad::onEditorEnable()
  365. {
  366. }
  367. void DecalRoad::onEditorDisable()
  368. {
  369. }
  370. // NetObject
  371. U32 DecalRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  372. {
  373. // Pack Parent.
  374. U32 retMask = Parent::packUpdate(con, mask, stream);
  375. if ( stream->writeFlag( mask & DecalRoadMask ) )
  376. {
  377. // Write Texture Name.
  378. PACK_ASSET(con, Material);
  379. stream->write( mBreakAngle );
  380. stream->write( mSegmentsPerBatch );
  381. stream->write( mTextureLength );
  382. stream->write( mRenderPriority );
  383. }
  384. if ( stream->writeFlag( mask & NodeMask ) )
  385. {
  386. //stream->writeInt( mNodes.size(), 16 );
  387. //for ( U32 i = 0; i < mNodes.size(); i++ )
  388. //{
  389. // mathWrite( *stream, mNodes[i].point );
  390. // stream->write( mNodes[i].width );
  391. //}
  392. const U32 nodeByteSize = 16; // Based on sending all of a node's parameters
  393. // Test if we can fit all of our nodes within the current stream.
  394. // We make sure we leave 100 bytes still free in the stream for whatever
  395. // may follow us.
  396. S32 allowedBytes = stream->getWriteByteSize() - 100;
  397. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  398. {
  399. // All nodes should fit, so send them out now.
  400. stream->writeInt( mNodes.size(), 16 );
  401. for ( U32 i = 0; i < mNodes.size(); i++ )
  402. {
  403. mathWrite( *stream, mNodes[i].point );
  404. stream->write( mNodes[i].width );
  405. }
  406. }
  407. else
  408. {
  409. // There isn't enough space left in the stream for all of the
  410. // nodes. Batch them up into NetEvents.
  411. U32 id = gServerNodeListManager->nextListId();
  412. U32 count = 0;
  413. U32 index = 0;
  414. while (count < mNodes.size())
  415. {
  416. count += NodeListManager::smMaximumNodesPerEvent;
  417. if (count > mNodes.size())
  418. {
  419. count = mNodes.size();
  420. }
  421. DecalRoadNodeEvent* event = new DecalRoadNodeEvent();
  422. event->mId = id;
  423. event->mTotalNodes = mNodes.size();
  424. event->mLocalListStart = index;
  425. for (; index<count; ++index)
  426. {
  427. event->mPositions.push_back( mNodes[index].point );
  428. event->mWidths.push_back( mNodes[index].width );
  429. }
  430. con->postNetEvent( event );
  431. }
  432. stream->write( id );
  433. }
  434. }
  435. stream->writeFlag( mask & GenEdgesMask );
  436. stream->writeFlag( mask & ReClipMask );
  437. stream->writeFlag( mask & TerrainChangedMask );
  438. // Were done ...
  439. return retMask;
  440. }
  441. void DecalRoad::unpackUpdate( NetConnection *con, BitStream *stream )
  442. {
  443. // Unpack Parent.
  444. Parent::unpackUpdate( con, stream );
  445. // DecalRoadMask
  446. if ( stream->readFlag() )
  447. {
  448. UNPACK_ASSET(con, Material);
  449. if (isProperlyAdded())
  450. _initMaterial();
  451. stream->read( &mBreakAngle );
  452. stream->read( &mSegmentsPerBatch );
  453. stream->read( &mTextureLength );
  454. stream->read( &mRenderPriority );
  455. }
  456. // NodeMask
  457. if ( stream->readFlag() )
  458. {
  459. //U32 count = stream->readInt( 16 );
  460. //mNodes.clear();
  461. //Point3F pos;
  462. //F32 width;
  463. //for ( U32 i = 0; i < count; i++ )
  464. //{
  465. // mathRead( *stream, &pos );
  466. // stream->read( &width );
  467. // _addNode( pos, width );
  468. //}
  469. if (stream->readFlag())
  470. {
  471. // Nodes have been passed in this update
  472. U32 count = stream->readInt( 16 );
  473. mNodes.clear();
  474. Point3F pos;
  475. F32 width;
  476. for ( U32 i = 0; i < count; i++ )
  477. {
  478. mathRead( *stream, &pos );
  479. stream->read( &width );
  480. _addNode( pos, width );
  481. }
  482. }
  483. else
  484. {
  485. // Nodes will arrive as events
  486. U32 id;
  487. stream->read( &id );
  488. // Check if the road's nodes made it here before we did.
  489. NodeListManager::NodeList* list = NULL;
  490. if ( gClientNodeListManager->findListById( id, &list, true) )
  491. {
  492. // Work with the completed list
  493. DecalRoadNodeList* roadList = dynamic_cast<DecalRoadNodeList*>( list );
  494. if (roadList)
  495. buildNodesFromList( roadList );
  496. delete list;
  497. }
  498. else
  499. {
  500. // Nodes have not yet arrived, so register our interest in the list
  501. DecalRoadNodeListNotify* notify = new DecalRoadNodeListNotify( this, id );
  502. gClientNodeListManager->registerNotification( notify );
  503. }
  504. }
  505. }
  506. // GenEdgesMask
  507. if ( stream->readFlag() && isProperlyAdded() )
  508. _generateEdges();
  509. // ReClipMask
  510. if ( stream->readFlag() && isProperlyAdded() )
  511. _captureVerts();
  512. // TerrainChangedMask
  513. if ( stream->readFlag() )
  514. {
  515. if ( isProperlyAdded() )
  516. {
  517. if ( mTerrainUpdateRect.isOverlapped( getWorldBox() ) )
  518. {
  519. _generateEdges();
  520. _captureVerts();
  521. // Clear out the mTerrainUpdateRect since we have updated its
  522. // region and we now need to store future terrain changes
  523. // in it.
  524. mTerrainUpdateRect = Box3F::Invalid;
  525. }
  526. }
  527. }
  528. }
  529. void DecalRoad::prepRenderImage( SceneRenderState* state )
  530. {
  531. PROFILE_SCOPE( DecalRoad_prepRenderImage );
  532. if ( mNodes.size() <= 1 ||
  533. mBatches.size() == 0 ||
  534. !mMaterialInst ||
  535. state->isShadowPass() )
  536. return;
  537. // If we don't have a material instance after the override then
  538. // we can skip rendering all together.
  539. BaseMatInstance *matInst = state->getOverrideMaterial(mMaterialInst);
  540. if ( !matInst )
  541. return;
  542. RenderPassManager *renderPass = state->getRenderPass();
  543. // Debug RenderInstance
  544. // Only when editor is open.
  545. if ( smEditorOpen )
  546. {
  547. ObjectRenderInst *ri = renderPass->allocInst<ObjectRenderInst>();
  548. ri->type = RenderPassManager::RIT_Editor;
  549. ri->renderDelegate.bind( this, &DecalRoad::_debugRender );
  550. state->getRenderPass()->addInst( ri );
  551. }
  552. // Normal Road RenderInstance
  553. // Always rendered when the editor is not open
  554. // otherwise obey the smShowRoad flag
  555. if ( !smShowRoad && smEditorOpen )
  556. return;
  557. const Frustum &frustum = state->getCameraFrustum();
  558. MeshRenderInst coreRI;
  559. coreRI.clear();
  560. coreRI.objectToWorld = &MatrixF::Identity;
  561. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  562. MatrixF *tempMat = renderPass->allocUniqueXform( MatrixF( true ) );
  563. MathUtils::getZBiasProjectionMatrix( gDecalBias, frustum, tempMat );
  564. coreRI.projection = tempMat;
  565. coreRI.type = RenderPassManager::RIT_DecalRoad;
  566. coreRI.vertBuff = &mVB;
  567. coreRI.primBuff = &mPB;
  568. coreRI.matInst = matInst;
  569. // Make it the sort distance the max distance so that
  570. // it renders after all the other opaque geometry in
  571. // the deferred bin.
  572. coreRI.sortDistSq = F32_MAX;
  573. // If we need lights then set them up.
  574. if ( matInst->isForwardLit() && !coreRI.lights[0])
  575. {
  576. LightQuery query;
  577. query.init( getWorldSphere() );
  578. query.getLights( coreRI.lights, 8 );
  579. }
  580. U32 startBatchIdx = -1;
  581. U32 endBatchIdx = 0;
  582. for ( U32 i = 0; i < mBatches.size(); i++ )
  583. {
  584. const RoadBatch &batch = mBatches[i];
  585. const bool isVisible = !frustum.isCulled( batch.bounds );
  586. if ( isVisible )
  587. {
  588. // If this is the start of a set of batches.
  589. if ( startBatchIdx == -1 )
  590. endBatchIdx = startBatchIdx = i;
  591. // Else we're extending the end batch index.
  592. else
  593. ++endBatchIdx;
  594. // If this isn't the last batch then continue.
  595. if ( i < mBatches.size()-1 )
  596. continue;
  597. }
  598. // We we still don't have a start batch, so skip.
  599. if ( startBatchIdx == -1 )
  600. continue;
  601. // Render this set of batches.
  602. const RoadBatch &startBatch = mBatches[startBatchIdx];
  603. const RoadBatch &endBatch = mBatches[endBatchIdx];
  604. U32 startVert = startBatch.startVert;
  605. U32 startIdx = startBatch.startIndex;
  606. U32 vertCount = endBatch.endVert - startVert;
  607. U32 idxCount = ( endBatch.endIndex - startIdx ) + 1;
  608. U32 triangleCount = idxCount / 3;
  609. AssertFatal( startVert + vertCount <= mVertCount, "DecalRoad, bad draw call!" );
  610. AssertFatal( startIdx + triangleCount < mTriangleCount * 3, "DecalRoad, bad draw call!" );
  611. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  612. *ri = coreRI;
  613. ri->matInst = matInst;
  614. ri->prim = renderPass->allocPrim();
  615. ri->prim->type = GFXTriangleList;
  616. ri->prim->minIndex = 0;
  617. ri->prim->startIndex = startIdx;
  618. ri->prim->numPrimitives = triangleCount;
  619. ri->prim->startVertex = 0;
  620. ri->prim->numVertices = endBatch.endVert + 1;
  621. ri->translucentSort = !matInst->getMaterial()->isTranslucent();
  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. _setMaterial(getMaterial());
  817. if (mMaterialAsset.notNull())
  818. {
  819. if (mMaterialInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMaterialInst->getMaterial()->getName(), String::NoCase))
  820. return;
  821. SAFE_DELETE(mMaterialInst);
  822. Material* tMat = nullptr;
  823. if (!Sim::findObject(mMaterialAsset->getMaterialDefinitionName(), tMat))
  824. Con::errorf("DecalRoad::_initMaterial - Material %s was not found.", mMaterialAsset->getMaterialDefinitionName());
  825. mMaterial = tMat;
  826. if (mMaterial)
  827. mMaterialInst = mMaterial->createMatInstance();
  828. else
  829. mMaterialInst = MATMGR->createMatInstance("WarningMaterial");
  830. if (!mMaterialInst)
  831. Con::errorf("DecalRoad::_initMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  832. }
  833. if (!mMaterialInst)
  834. return;
  835. GFXStateBlockDesc desc;
  836. desc.setZReadWrite( true, false );
  837. mMaterialInst->addStateBlockDesc( desc );
  838. mMaterialInst->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTBT>() );
  839. }
  840. void DecalRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  841. {
  842. //if ( mStateBlock.isNull() )
  843. // return;
  844. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  845. GFXTransformSaver saver;
  846. //GFX->setStateBlock( mStateBlock );
  847. Point3F size(1,1,1);
  848. ColorI color( 255, 0, 0, 255 );
  849. GFXStateBlockDesc desc;
  850. desc.setZReadWrite( true, false );
  851. desc.setBlend( true );
  852. desc.fillMode = GFXFillWireframe;
  853. if ( smShowBatches )
  854. {
  855. for ( U32 i = 0; i < mBatches.size(); i++ )
  856. {
  857. const Box3F &box = mBatches[i].bounds;
  858. GFX->getDrawUtil()->drawCube( desc, box, ColorI(255,100,100,255) );
  859. }
  860. }
  861. //GFX->leaveDebugEvent();
  862. }
  863. void DecalRoad::_generateEdges()
  864. {
  865. PROFILE_SCOPE( DecalRoad_generateEdges );
  866. //Con::warnf( "%s - generateEdges", isServerObject() ? "server" : "client" );
  867. if ( mNodes.size() > 0 )
  868. {
  869. // Set our object position to the first node.
  870. const Point3F &nodePt = mNodes.first().point;
  871. MatrixF mat( true );
  872. mat.setPosition( nodePt );
  873. Parent::setTransform( mat );
  874. // The server object has global bounds, which Parent::setTransform
  875. // messes up so we must reset it.
  876. if ( isServerObject() )
  877. {
  878. mObjBox.minExtents.set(-1e10, -1e10, -1e10);
  879. mObjBox.maxExtents.set( 1e10, 1e10, 1e10);
  880. }
  881. }
  882. if ( mNodes.size() < 2 )
  883. return;
  884. // Ensure nodes are above the terrain height at their xy position
  885. for ( U32 i = 0; i < mNodes.size(); i++ )
  886. {
  887. _getTerrainHeight( mNodes[i].point );
  888. }
  889. // Now start generating edges...
  890. U32 nodeCount = mNodes.size();
  891. Point3F *positions = new Point3F[nodeCount];
  892. for ( U32 i = 0; i < nodeCount; i++ )
  893. {
  894. const RoadNode &node = mNodes[i];
  895. positions[i].set( node.point.x, node.point.y, node.width );
  896. }
  897. CatmullRom<Point3F> spline;
  898. spline.initialize( nodeCount, positions );
  899. delete [] positions;
  900. mEdges.clear();
  901. Point3F lastBreakVector(0,0,0);
  902. RoadEdge slice;
  903. Point3F lastBreakNode;
  904. lastBreakNode = spline.evaluate(0.0f);
  905. for ( U32 i = 1; i < mNodes.size(); i++ )
  906. {
  907. F32 t1 = spline.getTime(i);
  908. F32 t0 = spline.getTime(i-1);
  909. F32 segLength = spline.arcLength( t0, t1 );
  910. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  911. numSegments = getMax( numSegments, (U32)1 );
  912. F32 tstep = ( t1 - t0 ) / numSegments;
  913. U32 startIdx = 0;
  914. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  915. for ( U32 j = startIdx; j < endIdx; j++ )
  916. {
  917. F32 t = t0 + tstep * j;
  918. Point3F splineNode = spline.evaluate(t);
  919. F32 width = splineNode.z;
  920. _getTerrainHeight( splineNode );
  921. Point3F toNodeVec = splineNode - lastBreakNode;
  922. toNodeVec.normalizeSafe();
  923. if ( lastBreakVector.isZero() )
  924. lastBreakVector = toNodeVec;
  925. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  926. if ( j == startIdx ||
  927. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  928. angle > mBreakAngle )
  929. {
  930. // Push back a spline node
  931. //slice.p1.set( splineNode.x, splineNode.y, 0.0f );
  932. //_getTerrainHeight( slice.p1 );
  933. slice.p1 = splineNode;
  934. slice.uvec.set(0,0,1);
  935. slice.width = width;
  936. slice.parentNodeIdx = i-1;
  937. mEdges.push_back( slice );
  938. lastBreakVector = splineNode - lastBreakNode;
  939. lastBreakVector.normalizeSafe();
  940. lastBreakNode = splineNode;
  941. }
  942. }
  943. }
  944. /*
  945. for ( U32 i = 1; i < nodeCount; i++ )
  946. {
  947. F32 t0 = spline.getTime( i-1 );
  948. F32 t1 = spline.getTime( i );
  949. F32 segLength = spline.arcLength( t0, t1 );
  950. U32 numSegments = mCeil( segLength / mBreakAngle );
  951. numSegments = getMax( numSegments, (U32)1 );
  952. F32 tstep = ( t1 - t0 ) / numSegments;
  953. AssertFatal( numSegments > 0, "DecalRoad::_generateEdges, got zero segments!" );
  954. U32 startIdx = 0;
  955. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  956. for ( U32 j = startIdx; j < endIdx; j++ )
  957. {
  958. F32 t = t0 + tstep * j;
  959. Point3F val = spline.evaluate(t);
  960. RoadEdge edge;
  961. edge.p1.set( val.x, val.y, 0.0f );
  962. _getTerrainHeight( val.x, val.y, edge.p1.z );
  963. edge.uvec.set(0,0,1);
  964. edge.width = val.z;
  965. edge.parentNodeIdx = i-1;
  966. mEdges.push_back( edge );
  967. }
  968. }
  969. */
  970. //
  971. // Calculate fvec and rvec for all edges
  972. //
  973. RoadEdge *edge = NULL;
  974. RoadEdge *nextEdge = NULL;
  975. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  976. {
  977. edge = &mEdges[i];
  978. nextEdge = &mEdges[i+1];
  979. edge->fvec = nextEdge->p1 - edge->p1;
  980. edge->fvec.normalize();
  981. edge->rvec = mCross( edge->fvec, edge->uvec );
  982. edge->rvec.normalize();
  983. }
  984. // Must do the last edge outside the loop
  985. RoadEdge *lastEdge = &mEdges[mEdges.size()-1];
  986. RoadEdge *prevEdge = &mEdges[mEdges.size()-2];
  987. lastEdge->fvec = prevEdge->fvec;
  988. lastEdge->rvec = prevEdge->rvec;
  989. //
  990. // Calculate p0/p2 for all edges
  991. //
  992. for ( U32 i = 0; i < mEdges.size(); i++ )
  993. {
  994. edge = &mEdges[i];
  995. edge->p0 = edge->p1 - edge->rvec * edge->width * 0.5f;
  996. edge->p2 = edge->p1 + edge->rvec * edge->width * 0.5f;
  997. _getTerrainHeight( edge->p0 );
  998. _getTerrainHeight( edge->p2 );
  999. }
  1000. }
  1001. void DecalRoad::_captureVerts()
  1002. {
  1003. PROFILE_SCOPE( DecalRoad_captureVerts );
  1004. //Con::warnf( "%s - captureVerts", isServerObject() ? "server" : "client" );
  1005. if ( isServerObject() )
  1006. {
  1007. //Con::errorf( "DecalRoad::_captureVerts - called on the server side!" );
  1008. return;
  1009. }
  1010. if ( mEdges.size() == 0 )
  1011. return;
  1012. //
  1013. // Construct ClippedPolyList objects for each pair
  1014. // of roadEdges.
  1015. // Use them to capture Terrain verts.
  1016. //
  1017. SphereF sphere;
  1018. RoadEdge *edge = NULL;
  1019. RoadEdge *nextEdge = NULL;
  1020. mTriangleCount = 0;
  1021. mVertCount = 0;
  1022. Vector<ClippedPolyList> clipperList;
  1023. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1024. {
  1025. Box3F box;
  1026. edge = &mEdges[i];
  1027. nextEdge = &mEdges[i+1];
  1028. box.minExtents = edge->p1;
  1029. box.maxExtents = edge->p1;
  1030. box.extend( edge->p0 );
  1031. box.extend( edge->p2 );
  1032. box.extend( nextEdge->p0 );
  1033. box.extend( nextEdge->p1 );
  1034. box.extend( nextEdge->p2 );
  1035. box.minExtents.z -= 5.0f;
  1036. box.maxExtents.z += 5.0f;
  1037. sphere.center = ( nextEdge->p1 + edge->p1 ) * 0.5f;
  1038. sphere.radius = 100.0f; // NOTE: no idea how to calculate this
  1039. ClippedPolyList clipper;
  1040. clipper.mNormal.set(0.0f, 0.0f, 0.0f);
  1041. VectorF n;
  1042. PlaneF plane0, plane1;
  1043. // Construct Back Plane
  1044. n = edge->p2 - edge->p0;
  1045. n.normalize();
  1046. n = mCross( n, edge->uvec );
  1047. plane0.set( edge->p0, n );
  1048. clipper.mPlaneList.push_back( plane0 );
  1049. // Construct Front Plane
  1050. n = nextEdge->p2 - nextEdge->p0;
  1051. n.normalize();
  1052. n = -mCross( edge->uvec, n );
  1053. plane1.set( nextEdge->p0, -n );
  1054. //clipper.mPlaneList.push_back( plane1 );
  1055. // Test if / where the planes intersect.
  1056. bool discardLeft = false;
  1057. bool discardRight = false;
  1058. Point3F iPos;
  1059. VectorF iDir;
  1060. if ( plane0.intersect( plane1, iPos, iDir ) )
  1061. {
  1062. Point2F iPos2F( iPos.x, iPos.y );
  1063. Point2F cPos2F( edge->p1.x, edge->p1.y );
  1064. Point2F rVec2F( edge->rvec.x, edge->rvec.y );
  1065. Point2F iVec2F = iPos2F - cPos2F;
  1066. F32 iLen = iVec2F.len();
  1067. iVec2F.normalize();
  1068. if ( iLen < edge->width * 0.5f )
  1069. {
  1070. F32 dot = mDot( rVec2F, iVec2F );
  1071. // The clipping planes intersected on the right side,
  1072. // discard the right side clipping plane.
  1073. if ( dot > 0.0f )
  1074. discardRight = true;
  1075. // The clipping planes intersected on the left side,
  1076. // discard the left side clipping plane.
  1077. else
  1078. discardLeft = true;
  1079. }
  1080. }
  1081. // Left Plane
  1082. if ( !discardLeft )
  1083. {
  1084. n = ( nextEdge->p0 - edge->p0 );
  1085. n.normalize();
  1086. n = mCross( edge->uvec, n );
  1087. clipper.mPlaneList.push_back( PlaneF(edge->p0, n) );
  1088. }
  1089. else
  1090. {
  1091. nextEdge->p0 = edge->p0;
  1092. }
  1093. // Right Plane
  1094. if ( !discardRight )
  1095. {
  1096. n = ( nextEdge->p2 - edge->p2 );
  1097. n.normalize();
  1098. n = -mCross( n, edge->uvec );
  1099. clipper.mPlaneList.push_back( PlaneF(edge->p2, -n) );
  1100. }
  1101. else
  1102. {
  1103. nextEdge->p2 = edge->p2;
  1104. }
  1105. n = nextEdge->p2 - nextEdge->p0;
  1106. n.normalize();
  1107. n = -mCross( edge->uvec, n );
  1108. plane1.set( nextEdge->p0, -n );
  1109. clipper.mPlaneList.push_back( plane1 );
  1110. // We have constructed the clipping planes,
  1111. // now grab/clip the terrain geometry
  1112. getContainer()->buildPolyList( PLC_Decal, box, TerrainObjectType, &clipper );
  1113. clipper.cullUnusedVerts();
  1114. clipper.triangulate();
  1115. clipper.generateNormals();
  1116. // If we got something, add it to the ClippedPolyList Vector
  1117. if ( !clipper.isEmpty() && !( smDiscardAll && ( discardRight || discardLeft ) ) )
  1118. {
  1119. clipperList.push_back( clipper );
  1120. mVertCount += clipper.mVertexList.size();
  1121. mTriangleCount += clipper.mPolyList.size();
  1122. }
  1123. }
  1124. //
  1125. // Set the roadEdge height to be flush with terrain
  1126. // This is not really necessary but makes the debug spline rendering better.
  1127. //
  1128. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1129. {
  1130. edge = &mEdges[i];
  1131. _getTerrainHeight( edge->p0.x, edge->p0.y, edge->p0.z );
  1132. _getTerrainHeight( edge->p2.x, edge->p2.y, edge->p2.z );
  1133. }
  1134. //
  1135. // Allocate the RoadBatch(s)
  1136. //
  1137. // If we captured no verts, then we can return here without
  1138. // allocating any RoadBatches or the Vert/Index Buffers.
  1139. // PreprenderImage will not allocate a render instance while
  1140. // mBatches.size() is zero.
  1141. U32 numClippers = clipperList.size();
  1142. if ( numClippers == 0 )
  1143. return;
  1144. mBatches.clear();
  1145. // Allocate the VertexBuffer and PrimitiveBuffer
  1146. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  1147. mPB.set( GFX, mTriangleCount * 3, 0, GFXBufferTypeStatic );
  1148. // Lock the VertexBuffer
  1149. GFXVertexPNTBT *vertPtr = mVB.lock();
  1150. if(!vertPtr) return;
  1151. U32 vertIdx = 0;
  1152. //
  1153. // Fill the VertexBuffer and vertex data for the RoadBatches
  1154. // Loop through the ClippedPolyList Vector
  1155. //
  1156. RoadBatch *batch = NULL;
  1157. F32 texStart = 0.0f;
  1158. F32 texEnd;
  1159. for ( U32 i = 0; i < clipperList.size(); i++ )
  1160. {
  1161. ClippedPolyList *clipper = &clipperList[i];
  1162. edge = &mEdges[i];
  1163. nextEdge = &mEdges[i+1];
  1164. VectorF segFvec = nextEdge->p1 - edge->p1;
  1165. F32 segLen = segFvec.len();
  1166. segFvec.normalize();
  1167. F32 texLen = segLen / mTextureLength;
  1168. texEnd = texStart + texLen;
  1169. BiQuadToSqr quadToSquare( Point2F( edge->p0.x, edge->p0.y ),
  1170. Point2F( edge->p2.x, edge->p2.y ),
  1171. Point2F( nextEdge->p2.x, nextEdge->p2.y ),
  1172. Point2F( nextEdge->p0.x, nextEdge->p0.y ) );
  1173. //
  1174. if ( i % mSegmentsPerBatch == 0 )
  1175. {
  1176. mBatches.increment();
  1177. batch = &mBatches.last();
  1178. batch->bounds.minExtents = clipper->mVertexList[0].point;
  1179. batch->bounds.maxExtents = clipper->mVertexList[0].point;
  1180. batch->startVert = vertIdx;
  1181. }
  1182. // Loop through each ClippedPolyList
  1183. for ( U32 j = 0; j < clipper->mVertexList.size(); j++ )
  1184. {
  1185. // Add each vert to the VertexBuffer
  1186. Point3F pos = clipper->mVertexList[j].point;
  1187. vertPtr[vertIdx].point = pos;
  1188. vertPtr[vertIdx].normal = clipper->mNormalList[j];
  1189. Point2F uv = quadToSquare.transform( Point2F(pos.x,pos.y) );
  1190. vertPtr[vertIdx].texCoord.x = uv.x;
  1191. vertPtr[vertIdx].texCoord.y = -(( texEnd - texStart ) * uv.y + texStart);
  1192. vertPtr[vertIdx].tangent = mCross( segFvec, clipper->mNormalList[j] );
  1193. vertPtr[vertIdx].binormal = segFvec;
  1194. vertIdx++;
  1195. // Expand the RoadBatch bounds to contain this vertex
  1196. batch->bounds.extend( pos );
  1197. }
  1198. batch->endVert = vertIdx - 1;
  1199. texStart = texEnd;
  1200. }
  1201. // Unlock the VertexBuffer, we are done filling it.
  1202. mVB.unlock();
  1203. // Lock the PrimitiveBuffer
  1204. U16 *idxBuff;
  1205. mPB.lock(&idxBuff);
  1206. U32 curIdx = 0;
  1207. U16 vertOffset = 0;
  1208. batch = NULL;
  1209. S32 batchIdx = -1;
  1210. // Fill the PrimitiveBuffer
  1211. // Loop through each ClippedPolyList in the Vector
  1212. for ( U32 i = 0; i < clipperList.size(); i++ )
  1213. {
  1214. ClippedPolyList *clipper = &clipperList[i];
  1215. if ( i % mSegmentsPerBatch == 0 )
  1216. {
  1217. batchIdx++;
  1218. batch = &mBatches[batchIdx];
  1219. batch->startIndex = curIdx;
  1220. }
  1221. for ( U32 j = 0; j < clipper->mPolyList.size(); j++ )
  1222. {
  1223. // Write indices for each Poly
  1224. ClippedPolyList::Poly *poly = &clipper->mPolyList[j];
  1225. AssertFatal( poly->vertexCount == 3, "Got non-triangle poly!" );
  1226. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart] + vertOffset;
  1227. curIdx++;
  1228. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 1] + vertOffset;
  1229. curIdx++;
  1230. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 2] + vertOffset;
  1231. curIdx++;
  1232. }
  1233. batch->endIndex = curIdx - 1;
  1234. vertOffset += clipper->mVertexList.size();
  1235. }
  1236. // Unlock the PrimitiveBuffer, we are done filling it.
  1237. mPB.unlock();
  1238. // Generate the object/world bounds
  1239. // Is the union of all batch bounding boxes.
  1240. Box3F box;
  1241. for ( U32 i = 0; i < mBatches.size(); i++ )
  1242. {
  1243. batch = &mBatches[i];
  1244. if ( i == 0 )
  1245. box = batch->bounds;
  1246. else
  1247. box.intersect( batch->bounds );
  1248. }
  1249. mWorldBox = box;
  1250. resetObjectBox();
  1251. // Make sure we are in the correct bins given our world box.
  1252. if( getSceneManager() != NULL )
  1253. getSceneManager()->notifyObjectDirty( this );
  1254. }
  1255. U32 DecalRoad::_addNode( const Point3F &pos, F32 width )
  1256. {
  1257. mNodes.increment();
  1258. RoadNode &node = mNodes.last();
  1259. node.point = pos;
  1260. node.width = width;
  1261. return mNodes.size() - 1;
  1262. }
  1263. U32 DecalRoad::_insertNode( const Point3F &pos, const F32 &width, const U32 &idx )
  1264. {
  1265. U32 ret;
  1266. RoadNode *node;
  1267. if ( idx == U32_MAX )
  1268. {
  1269. mNodes.increment();
  1270. node = &mNodes.last();
  1271. ret = mNodes.size() - 1;
  1272. }
  1273. else
  1274. {
  1275. mNodes.insert( idx );
  1276. node = &mNodes[idx];
  1277. ret = idx;
  1278. }
  1279. node->point = pos;
  1280. //node->t = -1.0f;
  1281. //node->rot.identity();
  1282. node->width = width;
  1283. return ret;
  1284. }
  1285. bool DecalRoad::_getTerrainHeight( Point3F &pos )
  1286. {
  1287. return _getTerrainHeight( pos.x, pos.y, pos.z );
  1288. }
  1289. bool DecalRoad::_getTerrainHeight( const Point2F &pos, F32 &height )
  1290. {
  1291. return _getTerrainHeight( pos.x, pos.y, height );
  1292. }
  1293. bool DecalRoad::_getTerrainHeight( const F32 &x, const F32 &y, F32 &height )
  1294. {
  1295. Point3F startPnt( x, y, 10000.0f );
  1296. Point3F endPnt( x, y, -10000.0f );
  1297. RayInfo ri;
  1298. bool hit;
  1299. hit = getContainer()->castRay(startPnt, endPnt, TerrainObjectType, &ri);
  1300. if ( hit )
  1301. height = ri.point.z;
  1302. return hit;
  1303. }
  1304. void DecalRoad::_onTerrainChanged( U32 type, TerrainBlock* tblock, const Point2I &min, const Point2I &max )
  1305. {
  1306. // The client side object just stores the area that has changed
  1307. // and waits for the (delayed) update event from the server
  1308. // to actually perform the update.
  1309. if ( isClientObject() && tblock->isClientObject() )
  1310. {
  1311. // Convert the min and max into world space.
  1312. const F32 size = tblock->getSquareSize();
  1313. const Point3F pos = tblock->getPosition();
  1314. // TODO: I don't think this works right with tiling!
  1315. Box3F dirty( F32( min.x * size ) + pos.x, F32( min.y * size ) + pos.y, -F32_MAX,
  1316. F32( max.x * size ) + pos.x, F32( max.y * size ) + pos.y, F32_MAX );
  1317. if ( !mTerrainUpdateRect.isValidBox() )
  1318. mTerrainUpdateRect = dirty;
  1319. else
  1320. mTerrainUpdateRect.intersect( dirty );
  1321. }
  1322. // The server object only updates edges (doesn't clip to geometry)
  1323. // and schedules an update to be sent to the client.
  1324. else if ( isServerObject() && tblock->isServerObject() )
  1325. {
  1326. //_generateEdges();
  1327. scheduleUpdate( TerrainChangedMask );
  1328. }
  1329. }
  1330. // Static protected field set methods
  1331. bool DecalRoad::ptSetBreakAngle( void *object, const char *index, const char *data )
  1332. {
  1333. DecalRoad *road = static_cast<DecalRoad*>( object );
  1334. F32 val = dAtof( data );
  1335. road->setBreakAngle( val );
  1336. // we already set the field
  1337. return false;
  1338. }
  1339. bool DecalRoad::ptSetTextureLength( void *object, const char *index, const char *data )
  1340. {
  1341. DecalRoad *road = static_cast<DecalRoad*>( object );
  1342. F32 val = dAtof( data );
  1343. road->setTextureLength( val );
  1344. // we already set the field
  1345. return false;
  1346. }
  1347. // ConsoleMethods
  1348. DefineEngineMethod( DecalRoad, regenerate, void, (),,
  1349. "Intended as a helper to developers and editor scripts.\n"
  1350. "Force DecalRoad to update it's spline and reclip geometry."
  1351. )
  1352. {
  1353. object->regenerate();
  1354. }
  1355. DefineEngineMethod( DecalRoad, postApply, void, (),,
  1356. "Intended as a helper to developers and editor scripts.\n"
  1357. "Force trigger an inspectPostApply. This will transmit "
  1358. "the material and other fields ( not including nodes ) "
  1359. "to client objects."
  1360. )
  1361. {
  1362. object->inspectPostApply();
  1363. }