decalRoad.cpp 46 KB

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