decalRoad.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  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_MATERIALASSET(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, NULL, &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_MATERIALASSET(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_MATERIALASSET(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() )
  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->prim = renderPass->allocPrim();
  614. ri->prim->type = GFXTriangleList;
  615. ri->prim->minIndex = 0;
  616. ri->prim->startIndex = startIdx;
  617. ri->prim->numPrimitives = triangleCount;
  618. ri->prim->startVertex = 0;
  619. ri->prim->numVertices = endBatch.endVert + 1;
  620. // For sorting we first sort by render priority
  621. // and then by objectId.
  622. //
  623. // Since a road can submit more than one render instance, we want all
  624. // draw calls for a single road to occur consecutively, since they
  625. // could use the same vertex buffer.
  626. ri->defaultKey = mRenderPriority << 0 | mId << 16;
  627. ri->defaultKey2 = 0;
  628. renderPass->addInst( ri );
  629. // Reset the batching.
  630. startBatchIdx = -1;
  631. }
  632. }
  633. void DecalRoad::setTransform( const MatrixF &mat )
  634. {
  635. // We ignore transform requests from the editor
  636. // right now.
  637. }
  638. void DecalRoad::setScale( const VectorF &scale )
  639. {
  640. // We ignore scale requests from the editor
  641. // right now.
  642. }
  643. // DecalRoad Public Methods
  644. bool DecalRoad::getClosestNode( const Point3F &pos, U32 &idx )
  645. {
  646. F32 closestDist = F32_MAX;
  647. for ( U32 i = 0; i < mNodes.size(); i++ )
  648. {
  649. F32 dist = ( mNodes[i].point - pos ).len();
  650. if ( dist < closestDist )
  651. {
  652. closestDist = dist;
  653. idx = i;
  654. }
  655. }
  656. return closestDist != F32_MAX;
  657. }
  658. bool DecalRoad::containsPoint( const Point3F &worldPos, U32 *nodeIdx ) const
  659. {
  660. // This is just for making selections in the editor, we use the
  661. // client-side road because it has the proper edge's.
  662. if ( isServerObject() && getClientObject() )
  663. return ((DecalRoad*)getClientObject())->containsPoint( worldPos, nodeIdx );
  664. // If point isn't in the world box,
  665. // it's definitely not in the road.
  666. //if ( !getWorldBox().isContained( worldPos ) )
  667. // return false;
  668. if ( mEdges.size() < 2 )
  669. return false;
  670. Point2F testPt( worldPos.x,
  671. worldPos.y );
  672. Point2F poly[4];
  673. // Look through all edges, does the polygon
  674. // formed from adjacent edge's contain the worldPos?
  675. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  676. {
  677. const RoadEdge &edge0 = mEdges[i];
  678. const RoadEdge &edge1 = mEdges[i+1];
  679. poly[0].set( edge0.p0.x, edge0.p0.y );
  680. poly[1].set( edge0.p2.x, edge0.p2.y );
  681. poly[2].set( edge1.p2.x, edge1.p2.y );
  682. poly[3].set( edge1.p0.x, edge1.p0.y );
  683. if ( MathUtils::pointInPolygon( poly, 4, testPt ) )
  684. {
  685. if ( nodeIdx )
  686. *nodeIdx = edge0.parentNodeIdx;
  687. return true;
  688. }
  689. }
  690. return false;
  691. }
  692. bool DecalRoad::castray( const Point3F &start, const Point3F &end ) const
  693. {
  694. // We just cast against the object box for the editor.
  695. return mWorldBox.collideLine( start, end );
  696. }
  697. Point3F DecalRoad::getNodePosition( U32 idx )
  698. {
  699. if ( mNodes.size() - 1 < idx )
  700. return Point3F();
  701. return mNodes[idx].point;
  702. }
  703. void DecalRoad::setNodePosition( U32 idx, const Point3F &pos )
  704. {
  705. if ( mNodes.size() - 1 < idx )
  706. return;
  707. mNodes[idx].point = pos;
  708. _generateEdges();
  709. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  710. }
  711. U32 DecalRoad::addNode( const Point3F &pos, F32 width )
  712. {
  713. U32 idx = _addNode( pos, width );
  714. _generateEdges();
  715. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  716. return idx;
  717. }
  718. U32 DecalRoad::insertNode(const Point3F &pos, const F32 &width, const U32 &idx)
  719. {
  720. U32 ret = _insertNode( pos, width, idx );
  721. _generateEdges();
  722. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  723. return ret;
  724. }
  725. void DecalRoad::setNodeWidth( U32 idx, F32 width )
  726. {
  727. if ( mNodes.size() - 1 < idx )
  728. return;
  729. mNodes[idx].width = width;
  730. _generateEdges();
  731. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  732. }
  733. F32 DecalRoad::getNodeWidth( U32 idx )
  734. {
  735. if ( mNodes.size() - 1 < idx )
  736. return -1.0f;
  737. return mNodes[idx].width;
  738. }
  739. void DecalRoad::deleteNode( U32 idx )
  740. {
  741. if ( mNodes.size() - 1 < idx )
  742. return;
  743. mNodes.erase(idx);
  744. _generateEdges();
  745. scheduleUpdate( GenEdgesMask | ReClipMask | NodeMask );
  746. }
  747. void DecalRoad::buildNodesFromList( DecalRoadNodeList* list )
  748. {
  749. mNodes.clear();
  750. for (U32 i=0; i<list->mPositions.size(); ++i)
  751. {
  752. _addNode( list->mPositions[i], list->mWidths[i] );
  753. }
  754. _generateEdges();
  755. _captureVerts();
  756. }
  757. void DecalRoad::setTextureLength( F32 meters )
  758. {
  759. meters = getMax( meters, 0.1f );
  760. if ( mTextureLength == meters )
  761. return;
  762. mTextureLength = meters;
  763. _generateEdges();
  764. scheduleUpdate( DecalRoadMask | ReClipMask );
  765. }
  766. void DecalRoad::setBreakAngle( F32 degrees )
  767. {
  768. //meters = getMax( meters, MIN_METERS_PER_SEGMENT );
  769. //if ( mBreakAngle == meters )
  770. // return;
  771. mBreakAngle = degrees;
  772. _generateEdges();
  773. scheduleUpdate( DecalRoadMask | GenEdgesMask | ReClipMask );
  774. }
  775. void DecalRoad::scheduleUpdate( U32 updateMask )
  776. {
  777. scheduleUpdate( updateMask, smUpdateDelay, true );
  778. }
  779. void DecalRoad::scheduleUpdate( U32 updateMask, U32 delayMs, bool restartTimer )
  780. {
  781. if ( Sim::isEventPending( mUpdateEventId ) )
  782. {
  783. if ( !restartTimer )
  784. {
  785. mLastEvent->mMask |= updateMask;
  786. return;
  787. }
  788. else
  789. {
  790. Sim::cancelEvent( mUpdateEventId );
  791. }
  792. }
  793. mLastEvent = new DecalRoadUpdateEvent( updateMask, delayMs );
  794. mUpdateEventId = Sim::postEvent( this, mLastEvent, Sim::getCurrentTime() + delayMs );
  795. }
  796. void DecalRoad::regenerate()
  797. {
  798. _generateEdges();
  799. _captureVerts();
  800. setMaskBits( NodeMask | GenEdgesMask | ReClipMask );
  801. }
  802. bool DecalRoad::addNodeFromField( void *object, const char *index, const char *data )
  803. {
  804. DecalRoad *pObj = static_cast<DecalRoad*>(object);
  805. F32 x,y,z,width;
  806. U32 result = dSscanf( data, "%f %f %f %f", &x, &y, &z, &width );
  807. if ( result == 4 )
  808. pObj->_addNode( Point3F(x,y,z), width );
  809. return false;
  810. }
  811. // Internal Helper Methods
  812. void DecalRoad::_initMaterial()
  813. {
  814. _setMaterial(getMaterial());
  815. if (mMaterialAsset.notNull())
  816. {
  817. if (mMaterialInst && String(mMaterialAsset->getMaterialDefinitionName()).equal(mMaterialInst->getMaterial()->getName(), String::NoCase))
  818. return;
  819. SAFE_DELETE(mMaterialInst);
  820. Material* tMat = nullptr;
  821. if (!Sim::findObject(mMaterialAsset->getMaterialDefinitionName(), tMat))
  822. Con::errorf("DecalRoad::_initMaterial - Material %s was not found.", mMaterialAsset->getMaterialDefinitionName());
  823. mMaterial = tMat;
  824. if (mMaterial)
  825. mMaterialInst = mMaterial->createMatInstance();
  826. else
  827. mMaterialInst = MATMGR->createMatInstance("WarningMaterial");
  828. if (!mMaterialInst)
  829. Con::errorf("DecalRoad::_initMaterial - no Material called '%s'", mMaterialAsset->getMaterialDefinitionName());
  830. }
  831. if (!mMaterialInst)
  832. return;
  833. GFXStateBlockDesc desc;
  834. desc.setZReadWrite( true, false );
  835. mMaterialInst->addStateBlockDesc( desc );
  836. mMaterialInst->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTBT>() );
  837. }
  838. void DecalRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  839. {
  840. //if ( mStateBlock.isNull() )
  841. // return;
  842. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  843. GFXTransformSaver saver;
  844. //GFX->setStateBlock( mStateBlock );
  845. Point3F size(1,1,1);
  846. ColorI color( 255, 0, 0, 255 );
  847. GFXStateBlockDesc desc;
  848. desc.setZReadWrite( true, false );
  849. desc.setBlend( true );
  850. desc.fillMode = GFXFillWireframe;
  851. if ( smShowBatches )
  852. {
  853. for ( U32 i = 0; i < mBatches.size(); i++ )
  854. {
  855. const Box3F &box = mBatches[i].bounds;
  856. GFX->getDrawUtil()->drawCube( desc, box, ColorI(255,100,100,255) );
  857. }
  858. }
  859. //GFX->leaveDebugEvent();
  860. }
  861. void DecalRoad::_generateEdges()
  862. {
  863. PROFILE_SCOPE( DecalRoad_generateEdges );
  864. //Con::warnf( "%s - generateEdges", isServerObject() ? "server" : "client" );
  865. if ( mNodes.size() > 0 )
  866. {
  867. // Set our object position to the first node.
  868. const Point3F &nodePt = mNodes.first().point;
  869. MatrixF mat( true );
  870. mat.setPosition( nodePt );
  871. Parent::setTransform( mat );
  872. // The server object has global bounds, which Parent::setTransform
  873. // messes up so we must reset it.
  874. if ( isServerObject() )
  875. {
  876. mObjBox.minExtents.set(-1e10, -1e10, -1e10);
  877. mObjBox.maxExtents.set( 1e10, 1e10, 1e10);
  878. }
  879. }
  880. if ( mNodes.size() < 2 )
  881. return;
  882. // Ensure nodes are above the terrain height at their xy position
  883. for ( U32 i = 0; i < mNodes.size(); i++ )
  884. {
  885. _getTerrainHeight( mNodes[i].point );
  886. }
  887. // Now start generating edges...
  888. U32 nodeCount = mNodes.size();
  889. Point3F *positions = new Point3F[nodeCount];
  890. for ( U32 i = 0; i < nodeCount; i++ )
  891. {
  892. const RoadNode &node = mNodes[i];
  893. positions[i].set( node.point.x, node.point.y, node.width );
  894. }
  895. CatmullRom<Point3F> spline;
  896. spline.initialize( nodeCount, positions );
  897. delete [] positions;
  898. mEdges.clear();
  899. Point3F lastBreakVector(0,0,0);
  900. RoadEdge slice;
  901. Point3F lastBreakNode;
  902. lastBreakNode = spline.evaluate(0.0f);
  903. for ( U32 i = 1; i < mNodes.size(); i++ )
  904. {
  905. F32 t1 = spline.getTime(i);
  906. F32 t0 = spline.getTime(i-1);
  907. F32 segLength = spline.arcLength( t0, t1 );
  908. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  909. numSegments = getMax( numSegments, (U32)1 );
  910. F32 tstep = ( t1 - t0 ) / numSegments;
  911. U32 startIdx = 0;
  912. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  913. for ( U32 j = startIdx; j < endIdx; j++ )
  914. {
  915. F32 t = t0 + tstep * j;
  916. Point3F splineNode = spline.evaluate(t);
  917. F32 width = splineNode.z;
  918. _getTerrainHeight( splineNode );
  919. Point3F toNodeVec = splineNode - lastBreakNode;
  920. toNodeVec.normalizeSafe();
  921. if ( lastBreakVector.isZero() )
  922. lastBreakVector = toNodeVec;
  923. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  924. if ( j == startIdx ||
  925. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  926. angle > mBreakAngle )
  927. {
  928. // Push back a spline node
  929. //slice.p1.set( splineNode.x, splineNode.y, 0.0f );
  930. //_getTerrainHeight( slice.p1 );
  931. slice.p1 = splineNode;
  932. slice.uvec.set(0,0,1);
  933. slice.width = width;
  934. slice.parentNodeIdx = i-1;
  935. mEdges.push_back( slice );
  936. lastBreakVector = splineNode - lastBreakNode;
  937. lastBreakVector.normalizeSafe();
  938. lastBreakNode = splineNode;
  939. }
  940. }
  941. }
  942. /*
  943. for ( U32 i = 1; i < nodeCount; i++ )
  944. {
  945. F32 t0 = spline.getTime( i-1 );
  946. F32 t1 = spline.getTime( i );
  947. F32 segLength = spline.arcLength( t0, t1 );
  948. U32 numSegments = mCeil( segLength / mBreakAngle );
  949. numSegments = getMax( numSegments, (U32)1 );
  950. F32 tstep = ( t1 - t0 ) / numSegments;
  951. AssertFatal( numSegments > 0, "DecalRoad::_generateEdges, got zero segments!" );
  952. U32 startIdx = 0;
  953. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  954. for ( U32 j = startIdx; j < endIdx; j++ )
  955. {
  956. F32 t = t0 + tstep * j;
  957. Point3F val = spline.evaluate(t);
  958. RoadEdge edge;
  959. edge.p1.set( val.x, val.y, 0.0f );
  960. _getTerrainHeight( val.x, val.y, edge.p1.z );
  961. edge.uvec.set(0,0,1);
  962. edge.width = val.z;
  963. edge.parentNodeIdx = i-1;
  964. mEdges.push_back( edge );
  965. }
  966. }
  967. */
  968. //
  969. // Calculate fvec and rvec for all edges
  970. //
  971. RoadEdge *edge = NULL;
  972. RoadEdge *nextEdge = NULL;
  973. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  974. {
  975. edge = &mEdges[i];
  976. nextEdge = &mEdges[i+1];
  977. edge->fvec = nextEdge->p1 - edge->p1;
  978. edge->fvec.normalize();
  979. edge->rvec = mCross( edge->fvec, edge->uvec );
  980. edge->rvec.normalize();
  981. }
  982. // Must do the last edge outside the loop
  983. RoadEdge *lastEdge = &mEdges[mEdges.size()-1];
  984. RoadEdge *prevEdge = &mEdges[mEdges.size()-2];
  985. lastEdge->fvec = prevEdge->fvec;
  986. lastEdge->rvec = prevEdge->rvec;
  987. //
  988. // Calculate p0/p2 for all edges
  989. //
  990. for ( U32 i = 0; i < mEdges.size(); i++ )
  991. {
  992. edge = &mEdges[i];
  993. edge->p0 = edge->p1 - edge->rvec * edge->width * 0.5f;
  994. edge->p2 = edge->p1 + edge->rvec * edge->width * 0.5f;
  995. _getTerrainHeight( edge->p0 );
  996. _getTerrainHeight( edge->p2 );
  997. }
  998. }
  999. void DecalRoad::_captureVerts()
  1000. {
  1001. PROFILE_SCOPE( DecalRoad_captureVerts );
  1002. //Con::warnf( "%s - captureVerts", isServerObject() ? "server" : "client" );
  1003. if ( isServerObject() )
  1004. {
  1005. //Con::errorf( "DecalRoad::_captureVerts - called on the server side!" );
  1006. return;
  1007. }
  1008. if ( mEdges.size() == 0 )
  1009. return;
  1010. //
  1011. // Construct ClippedPolyList objects for each pair
  1012. // of roadEdges.
  1013. // Use them to capture Terrain verts.
  1014. //
  1015. SphereF sphere;
  1016. RoadEdge *edge = NULL;
  1017. RoadEdge *nextEdge = NULL;
  1018. mTriangleCount = 0;
  1019. mVertCount = 0;
  1020. Vector<ClippedPolyList> clipperList;
  1021. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1022. {
  1023. Box3F box;
  1024. edge = &mEdges[i];
  1025. nextEdge = &mEdges[i+1];
  1026. box.minExtents = edge->p1;
  1027. box.maxExtents = edge->p1;
  1028. box.extend( edge->p0 );
  1029. box.extend( edge->p2 );
  1030. box.extend( nextEdge->p0 );
  1031. box.extend( nextEdge->p1 );
  1032. box.extend( nextEdge->p2 );
  1033. box.minExtents.z -= 5.0f;
  1034. box.maxExtents.z += 5.0f;
  1035. sphere.center = ( nextEdge->p1 + edge->p1 ) * 0.5f;
  1036. sphere.radius = 100.0f; // NOTE: no idea how to calculate this
  1037. ClippedPolyList clipper;
  1038. clipper.mNormal.set(0.0f, 0.0f, 0.0f);
  1039. VectorF n;
  1040. PlaneF plane0, plane1;
  1041. // Construct Back Plane
  1042. n = edge->p2 - edge->p0;
  1043. n.normalize();
  1044. n = mCross( n, edge->uvec );
  1045. plane0.set( edge->p0, n );
  1046. clipper.mPlaneList.push_back( plane0 );
  1047. // Construct Front Plane
  1048. n = nextEdge->p2 - nextEdge->p0;
  1049. n.normalize();
  1050. n = -mCross( edge->uvec, n );
  1051. plane1.set( nextEdge->p0, -n );
  1052. //clipper.mPlaneList.push_back( plane1 );
  1053. // Test if / where the planes intersect.
  1054. bool discardLeft = false;
  1055. bool discardRight = false;
  1056. Point3F iPos;
  1057. VectorF iDir;
  1058. if ( plane0.intersect( plane1, iPos, iDir ) )
  1059. {
  1060. Point2F iPos2F( iPos.x, iPos.y );
  1061. Point2F cPos2F( edge->p1.x, edge->p1.y );
  1062. Point2F rVec2F( edge->rvec.x, edge->rvec.y );
  1063. Point2F iVec2F = iPos2F - cPos2F;
  1064. F32 iLen = iVec2F.len();
  1065. iVec2F.normalize();
  1066. if ( iLen < edge->width * 0.5f )
  1067. {
  1068. F32 dot = mDot( rVec2F, iVec2F );
  1069. // The clipping planes intersected on the right side,
  1070. // discard the right side clipping plane.
  1071. if ( dot > 0.0f )
  1072. discardRight = true;
  1073. // The clipping planes intersected on the left side,
  1074. // discard the left side clipping plane.
  1075. else
  1076. discardLeft = true;
  1077. }
  1078. }
  1079. // Left Plane
  1080. if ( !discardLeft )
  1081. {
  1082. n = ( nextEdge->p0 - edge->p0 );
  1083. n.normalize();
  1084. n = mCross( edge->uvec, n );
  1085. clipper.mPlaneList.push_back( PlaneF(edge->p0, n) );
  1086. }
  1087. else
  1088. {
  1089. nextEdge->p0 = edge->p0;
  1090. }
  1091. // Right Plane
  1092. if ( !discardRight )
  1093. {
  1094. n = ( nextEdge->p2 - edge->p2 );
  1095. n.normalize();
  1096. n = -mCross( n, edge->uvec );
  1097. clipper.mPlaneList.push_back( PlaneF(edge->p2, -n) );
  1098. }
  1099. else
  1100. {
  1101. nextEdge->p2 = edge->p2;
  1102. }
  1103. n = nextEdge->p2 - nextEdge->p0;
  1104. n.normalize();
  1105. n = -mCross( edge->uvec, n );
  1106. plane1.set( nextEdge->p0, -n );
  1107. clipper.mPlaneList.push_back( plane1 );
  1108. // We have constructed the clipping planes,
  1109. // now grab/clip the terrain geometry
  1110. getContainer()->buildPolyList( PLC_Decal, box, TerrainObjectType, &clipper );
  1111. clipper.cullUnusedVerts();
  1112. clipper.triangulate();
  1113. clipper.generateNormals();
  1114. // If we got something, add it to the ClippedPolyList Vector
  1115. if ( !clipper.isEmpty() && !( smDiscardAll && ( discardRight || discardLeft ) ) )
  1116. {
  1117. clipperList.push_back( clipper );
  1118. mVertCount += clipper.mVertexList.size();
  1119. mTriangleCount += clipper.mPolyList.size();
  1120. }
  1121. }
  1122. //
  1123. // Set the roadEdge height to be flush with terrain
  1124. // This is not really necessary but makes the debug spline rendering better.
  1125. //
  1126. for ( U32 i = 0; i < mEdges.size() - 1; i++ )
  1127. {
  1128. edge = &mEdges[i];
  1129. _getTerrainHeight( edge->p0.x, edge->p0.y, edge->p0.z );
  1130. _getTerrainHeight( edge->p2.x, edge->p2.y, edge->p2.z );
  1131. }
  1132. //
  1133. // Allocate the RoadBatch(s)
  1134. //
  1135. // If we captured no verts, then we can return here without
  1136. // allocating any RoadBatches or the Vert/Index Buffers.
  1137. // PreprenderImage will not allocate a render instance while
  1138. // mBatches.size() is zero.
  1139. U32 numClippers = clipperList.size();
  1140. if ( numClippers == 0 )
  1141. return;
  1142. mBatches.clear();
  1143. // Allocate the VertexBuffer and PrimitiveBuffer
  1144. mVB.set( GFX, mVertCount, GFXBufferTypeStatic );
  1145. mPB.set( GFX, mTriangleCount * 3, 0, GFXBufferTypeStatic );
  1146. // Lock the VertexBuffer
  1147. GFXVertexPNTBT *vertPtr = mVB.lock();
  1148. if(!vertPtr) return;
  1149. U32 vertIdx = 0;
  1150. //
  1151. // Fill the VertexBuffer and vertex data for the RoadBatches
  1152. // Loop through the ClippedPolyList Vector
  1153. //
  1154. RoadBatch *batch = NULL;
  1155. F32 texStart = 0.0f;
  1156. F32 texEnd;
  1157. for ( U32 i = 0; i < clipperList.size(); i++ )
  1158. {
  1159. ClippedPolyList *clipper = &clipperList[i];
  1160. edge = &mEdges[i];
  1161. nextEdge = &mEdges[i+1];
  1162. VectorF segFvec = nextEdge->p1 - edge->p1;
  1163. F32 segLen = segFvec.len();
  1164. segFvec.normalize();
  1165. F32 texLen = segLen / mTextureLength;
  1166. texEnd = texStart + texLen;
  1167. BiQuadToSqr quadToSquare( Point2F( edge->p0.x, edge->p0.y ),
  1168. Point2F( edge->p2.x, edge->p2.y ),
  1169. Point2F( nextEdge->p2.x, nextEdge->p2.y ),
  1170. Point2F( nextEdge->p0.x, nextEdge->p0.y ) );
  1171. //
  1172. if ( i % mSegmentsPerBatch == 0 )
  1173. {
  1174. mBatches.increment();
  1175. batch = &mBatches.last();
  1176. batch->bounds.minExtents = clipper->mVertexList[0].point;
  1177. batch->bounds.maxExtents = clipper->mVertexList[0].point;
  1178. batch->startVert = vertIdx;
  1179. }
  1180. // Loop through each ClippedPolyList
  1181. for ( U32 j = 0; j < clipper->mVertexList.size(); j++ )
  1182. {
  1183. // Add each vert to the VertexBuffer
  1184. Point3F pos = clipper->mVertexList[j].point;
  1185. vertPtr[vertIdx].point = pos;
  1186. vertPtr[vertIdx].normal = clipper->mNormalList[j];
  1187. Point2F uv = quadToSquare.transform( Point2F(pos.x,pos.y) );
  1188. vertPtr[vertIdx].texCoord.x = uv.x;
  1189. vertPtr[vertIdx].texCoord.y = -(( texEnd - texStart ) * uv.y + texStart);
  1190. vertPtr[vertIdx].tangent = mCross( segFvec, clipper->mNormalList[j] );
  1191. vertPtr[vertIdx].binormal = segFvec;
  1192. vertIdx++;
  1193. // Expand the RoadBatch bounds to contain this vertex
  1194. batch->bounds.extend( pos );
  1195. }
  1196. batch->endVert = vertIdx - 1;
  1197. texStart = texEnd;
  1198. }
  1199. // Unlock the VertexBuffer, we are done filling it.
  1200. mVB.unlock();
  1201. // Lock the PrimitiveBuffer
  1202. U16 *idxBuff;
  1203. mPB.lock(&idxBuff);
  1204. U32 curIdx = 0;
  1205. U16 vertOffset = 0;
  1206. batch = NULL;
  1207. S32 batchIdx = -1;
  1208. // Fill the PrimitiveBuffer
  1209. // Loop through each ClippedPolyList in the Vector
  1210. for ( U32 i = 0; i < clipperList.size(); i++ )
  1211. {
  1212. ClippedPolyList *clipper = &clipperList[i];
  1213. if ( i % mSegmentsPerBatch == 0 )
  1214. {
  1215. batchIdx++;
  1216. batch = &mBatches[batchIdx];
  1217. batch->startIndex = curIdx;
  1218. }
  1219. for ( U32 j = 0; j < clipper->mPolyList.size(); j++ )
  1220. {
  1221. // Write indices for each Poly
  1222. ClippedPolyList::Poly *poly = &clipper->mPolyList[j];
  1223. AssertFatal( poly->vertexCount == 3, "Got non-triangle poly!" );
  1224. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart] + vertOffset;
  1225. curIdx++;
  1226. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 1] + vertOffset;
  1227. curIdx++;
  1228. idxBuff[curIdx] = clipper->mIndexList[poly->vertexStart + 2] + vertOffset;
  1229. curIdx++;
  1230. }
  1231. batch->endIndex = curIdx - 1;
  1232. vertOffset += clipper->mVertexList.size();
  1233. }
  1234. // Unlock the PrimitiveBuffer, we are done filling it.
  1235. mPB.unlock();
  1236. // Generate the object/world bounds
  1237. // Is the union of all batch bounding boxes.
  1238. Box3F box;
  1239. for ( U32 i = 0; i < mBatches.size(); i++ )
  1240. {
  1241. batch = &mBatches[i];
  1242. if ( i == 0 )
  1243. box = batch->bounds;
  1244. else
  1245. box.intersect( batch->bounds );
  1246. }
  1247. mWorldBox = box;
  1248. resetObjectBox();
  1249. // Make sure we are in the correct bins given our world box.
  1250. if( getSceneManager() != NULL )
  1251. getSceneManager()->notifyObjectDirty( this );
  1252. }
  1253. U32 DecalRoad::_addNode( const Point3F &pos, F32 width )
  1254. {
  1255. mNodes.increment();
  1256. RoadNode &node = mNodes.last();
  1257. node.point = pos;
  1258. node.width = width;
  1259. return mNodes.size() - 1;
  1260. }
  1261. U32 DecalRoad::_insertNode( const Point3F &pos, const F32 &width, const U32 &idx )
  1262. {
  1263. U32 ret;
  1264. RoadNode *node;
  1265. if ( idx == U32_MAX )
  1266. {
  1267. mNodes.increment();
  1268. node = &mNodes.last();
  1269. ret = mNodes.size() - 1;
  1270. }
  1271. else
  1272. {
  1273. mNodes.insert( idx );
  1274. node = &mNodes[idx];
  1275. ret = idx;
  1276. }
  1277. node->point = pos;
  1278. //node->t = -1.0f;
  1279. //node->rot.identity();
  1280. node->width = width;
  1281. return ret;
  1282. }
  1283. bool DecalRoad::_getTerrainHeight( Point3F &pos )
  1284. {
  1285. return _getTerrainHeight( pos.x, pos.y, pos.z );
  1286. }
  1287. bool DecalRoad::_getTerrainHeight( const Point2F &pos, F32 &height )
  1288. {
  1289. return _getTerrainHeight( pos.x, pos.y, height );
  1290. }
  1291. bool DecalRoad::_getTerrainHeight( const F32 &x, const F32 &y, F32 &height )
  1292. {
  1293. Point3F startPnt( x, y, 10000.0f );
  1294. Point3F endPnt( x, y, -10000.0f );
  1295. RayInfo ri;
  1296. bool hit;
  1297. hit = getContainer()->castRay(startPnt, endPnt, TerrainObjectType, &ri);
  1298. if ( hit )
  1299. height = ri.point.z;
  1300. return hit;
  1301. }
  1302. void DecalRoad::_onTerrainChanged( U32 type, TerrainBlock* tblock, const Point2I &min, const Point2I &max )
  1303. {
  1304. // The client side object just stores the area that has changed
  1305. // and waits for the (delayed) update event from the server
  1306. // to actually perform the update.
  1307. if ( isClientObject() && tblock->isClientObject() )
  1308. {
  1309. // Convert the min and max into world space.
  1310. const F32 size = tblock->getSquareSize();
  1311. const Point3F pos = tblock->getPosition();
  1312. // TODO: I don't think this works right with tiling!
  1313. Box3F dirty( F32( min.x * size ) + pos.x, F32( min.y * size ) + pos.y, -F32_MAX,
  1314. F32( max.x * size ) + pos.x, F32( max.y * size ) + pos.y, F32_MAX );
  1315. if ( !mTerrainUpdateRect.isValidBox() )
  1316. mTerrainUpdateRect = dirty;
  1317. else
  1318. mTerrainUpdateRect.intersect( dirty );
  1319. }
  1320. // The server object only updates edges (doesn't clip to geometry)
  1321. // and schedules an update to be sent to the client.
  1322. else if ( isServerObject() && tblock->isServerObject() )
  1323. {
  1324. //_generateEdges();
  1325. scheduleUpdate( TerrainChangedMask );
  1326. }
  1327. }
  1328. // Static protected field set methods
  1329. bool DecalRoad::ptSetBreakAngle( void *object, const char *index, const char *data )
  1330. {
  1331. DecalRoad *road = static_cast<DecalRoad*>( object );
  1332. F32 val = dAtof( data );
  1333. road->setBreakAngle( val );
  1334. // we already set the field
  1335. return false;
  1336. }
  1337. bool DecalRoad::ptSetTextureLength( void *object, const char *index, const char *data )
  1338. {
  1339. DecalRoad *road = static_cast<DecalRoad*>( object );
  1340. F32 val = dAtof( data );
  1341. road->setTextureLength( val );
  1342. // we already set the field
  1343. return false;
  1344. }
  1345. // ConsoleMethods
  1346. DefineEngineMethod( DecalRoad, regenerate, void, (),,
  1347. "Intended as a helper to developers and editor scripts.\n"
  1348. "Force DecalRoad to update it's spline and reclip geometry."
  1349. )
  1350. {
  1351. object->regenerate();
  1352. }
  1353. DefineEngineMethod( DecalRoad, postApply, void, (),,
  1354. "Intended as a helper to developers and editor scripts.\n"
  1355. "Force trigger an inspectPostApply. This will transmit "
  1356. "the material and other fields ( not including nodes ) "
  1357. "to client objects."
  1358. )
  1359. {
  1360. object->inspectPostApply();
  1361. }