decalRoad.cpp 47 KB

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