meshRoad.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "environment/meshRoad.h"
  28. #include "console/consoleTypes.h"
  29. #include "console/engineAPI.h"
  30. #include "util/catmullRom.h"
  31. #include "math/util/quadTransforms.h"
  32. #include "scene/simPath.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "scene/sceneManager.h"
  35. #include "scene/sgUtil.h"
  36. #include "renderInstance/renderPassManager.h"
  37. #include "T3D/gameBase/gameConnection.h"
  38. #include "core/stream/bitStream.h"
  39. #include "gfx/gfxDrawUtil.h"
  40. #include "gfx/gfxTransformSaver.h"
  41. #include "gfx/primBuilder.h"
  42. #include "gfx/gfxDebugEvent.h"
  43. #include "materials/materialManager.h"
  44. #include "math/mathIO.h"
  45. #include "math/mathUtils.h"
  46. #include "math/util/frustum.h"
  47. #include "gui/3d/guiTSControl.h"
  48. #include "materials/shaderData.h"
  49. #include "gfx/sim/gfxStateBlockData.h"
  50. #include "gfx/sim/debugDraw.h"
  51. #include "collision/concretePolyList.h"
  52. #include "T3D/physics/physicsPlugin.h"
  53. #include "T3D/physics/physicsBody.h"
  54. #include "T3D/physics/physicsCollision.h"
  55. #include "environment/nodeListManager.h"
  56. #ifdef TORQUE_AFX_ENABLED
  57. #include "afx/ce/afxZodiacMgr.h"
  58. #endif
  59. #define MIN_METERS_PER_SEGMENT 1.0f
  60. #define MIN_NODE_DEPTH 0.25f
  61. #define MAX_NODE_DEPTH 50.0f
  62. #define MIN_NODE_WIDTH 0.25f
  63. #define MAX_NODE_WIDTH 50.0f
  64. static U32 gIdxArray[6][2][3] = {
  65. { { 0, 4, 5 }, { 0, 5, 1 }, }, // Top Face
  66. { { 2, 6, 4 }, { 2, 4, 0 }, }, // Left Face
  67. { { 1, 5, 7 }, { 1, 7, 3 }, }, // Right Face
  68. { { 2, 3, 7 }, { 2, 7, 6 }, }, // Bottom Face
  69. { { 0, 1, 3 }, { 0, 3, 2 }, }, // Front Face
  70. { { 4, 6, 7 }, { 4, 7, 5 }, }, // Back Face
  71. };
  72. static S32 QSORT_CALLBACK compareHitSegments(const void* a,const void* b)
  73. {
  74. const MeshRoadHitSegment *fa = (MeshRoadHitSegment*)a;
  75. const MeshRoadHitSegment *fb = (MeshRoadHitSegment*)b;
  76. return mSign(fb->t - fa->t);
  77. }
  78. //-----------------------------------------------------------------------------
  79. // MeshRoadNodeList Struct
  80. //-----------------------------------------------------------------------------
  81. struct MeshRoadNodeList : public NodeListManager::NodeList
  82. {
  83. Vector<Point3F> mPositions;
  84. Vector<F32> mWidths;
  85. Vector<F32> mDepths;
  86. Vector<VectorF> mNormals;
  87. MeshRoadNodeList() { }
  88. virtual ~MeshRoadNodeList() { }
  89. };
  90. //-----------------------------------------------------------------------------
  91. // MeshRoadNodeEvent Class
  92. //-----------------------------------------------------------------------------
  93. class MeshRoadNodeEvent : public NodeListEvent
  94. {
  95. typedef NodeListEvent Parent;
  96. public:
  97. Vector<Point3F> mPositions;
  98. Vector<F32> mWidths;
  99. Vector<F32> mDepths;
  100. Vector<VectorF> mNormals;
  101. public:
  102. MeshRoadNodeEvent() { mNodeList = NULL; }
  103. virtual ~MeshRoadNodeEvent() { }
  104. virtual void pack(NetConnection*, BitStream*);
  105. virtual void unpack(NetConnection*, BitStream*);
  106. virtual void copyIntoList(NodeListManager::NodeList* copyInto);
  107. virtual void padListToSize();
  108. DECLARE_CONOBJECT(MeshRoadNodeEvent);
  109. };
  110. void MeshRoadNodeEvent::pack(NetConnection* conn, BitStream* stream)
  111. {
  112. Parent::pack( conn, stream );
  113. stream->writeInt( mPositions.size(), 16 );
  114. for (U32 i=0; i<mPositions.size(); ++i)
  115. {
  116. mathWrite( *stream, mPositions[i] );
  117. stream->write( mWidths[i] );
  118. stream->write( mDepths[i] );
  119. mathWrite( *stream, mNormals[i] );
  120. }
  121. }
  122. void MeshRoadNodeEvent::unpack(NetConnection* conn, BitStream* stream)
  123. {
  124. mNodeList = new MeshRoadNodeList();
  125. Parent::unpack( conn, stream );
  126. U32 count = stream->readInt( 16 );
  127. Point3F pos;
  128. F32 width, depth;
  129. VectorF normal;
  130. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  131. for (U32 i=0; i<count; ++i)
  132. {
  133. mathRead( *stream, &pos );
  134. stream->read( &width );
  135. stream->read( &depth );
  136. mathRead( *stream, &normal );
  137. list->mPositions.push_back( pos );
  138. list->mWidths.push_back( width );
  139. list->mDepths.push_back( depth );
  140. list->mNormals.push_back( normal );
  141. }
  142. list->mTotalValidNodes = count;
  143. // Do we have a complete list?
  144. if (list->mPositions.size() >= mTotalNodes)
  145. list->mListComplete = true;
  146. }
  147. void MeshRoadNodeEvent::copyIntoList(NodeListManager::NodeList* copyInto)
  148. {
  149. MeshRoadNodeList* prevList = dynamic_cast<MeshRoadNodeList*>(copyInto);
  150. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  151. // Merge our list with the old list.
  152. for (U32 i=mLocalListStart, index=0; i<mLocalListStart+list->mPositions.size(); ++i, ++index)
  153. {
  154. prevList->mPositions[i] = list->mPositions[index];
  155. prevList->mWidths[i] = list->mWidths[index];
  156. prevList->mDepths[i] = list->mDepths[index];
  157. prevList->mNormals[i] = list->mNormals[index];
  158. }
  159. }
  160. void MeshRoadNodeEvent::padListToSize()
  161. {
  162. MeshRoadNodeList* list = static_cast<MeshRoadNodeList*>(mNodeList);
  163. U32 totalValidNodes = list->mTotalValidNodes;
  164. // Pad our list front?
  165. if (mLocalListStart)
  166. {
  167. MeshRoadNodeList* newlist = new MeshRoadNodeList();
  168. newlist->mPositions.increment(mLocalListStart);
  169. newlist->mWidths.increment(mLocalListStart);
  170. newlist->mDepths.increment(mLocalListStart);
  171. newlist->mNormals.increment(mLocalListStart);
  172. newlist->mPositions.merge(list->mPositions);
  173. newlist->mWidths.merge(list->mWidths);
  174. newlist->mDepths.merge(list->mDepths);
  175. newlist->mNormals.merge(list->mNormals);
  176. delete list;
  177. mNodeList = list = newlist;
  178. }
  179. // Pad our list end?
  180. if (list->mPositions.size() < mTotalNodes)
  181. {
  182. U32 delta = mTotalNodes - list->mPositions.size();
  183. list->mPositions.increment(delta);
  184. list->mWidths.increment(delta);
  185. list->mDepths.increment(delta);
  186. list->mNormals.increment(delta);
  187. }
  188. list->mTotalValidNodes = totalValidNodes;
  189. }
  190. IMPLEMENT_CO_NETEVENT_V1(MeshRoadNodeEvent);
  191. ConsoleDocClass( MeshRoadNodeEvent,
  192. "@brief Sends messages to the Mesh Road Editor\n\n"
  193. "Editor use only.\n\n"
  194. "@internal"
  195. );
  196. //-----------------------------------------------------------------------------
  197. // MeshRoadNodeListNotify Class
  198. //-----------------------------------------------------------------------------
  199. class MeshRoadNodeListNotify : public NodeListNotify
  200. {
  201. typedef NodeListNotify Parent;
  202. protected:
  203. SimObjectPtr<MeshRoad> mRoad;
  204. public:
  205. MeshRoadNodeListNotify( MeshRoad* road, U32 listId ) { mRoad = road; mListId = listId; }
  206. virtual ~MeshRoadNodeListNotify() { mRoad = NULL; }
  207. virtual void sendNotification( NodeListManager::NodeList* list );
  208. };
  209. void MeshRoadNodeListNotify::sendNotification( NodeListManager::NodeList* list )
  210. {
  211. if (mRoad.isValid())
  212. {
  213. // Build the road's nodes
  214. MeshRoadNodeList* roadList = dynamic_cast<MeshRoadNodeList*>( list );
  215. if (roadList)
  216. mRoad->buildNodesFromList( roadList );
  217. }
  218. }
  219. //------------------------------------------------------------------------------
  220. // MeshRoadConvex Class
  221. //------------------------------------------------------------------------------
  222. const MatrixF& MeshRoadConvex::getTransform() const
  223. {
  224. return MatrixF::Identity; //mObject->getTransform();
  225. }
  226. Box3F MeshRoadConvex::getBoundingBox() const
  227. {
  228. return box;
  229. }
  230. Box3F MeshRoadConvex::getBoundingBox(const MatrixF& mat, const Point3F& scale) const
  231. {
  232. Box3F newBox = box;
  233. newBox.minExtents.convolve(scale);
  234. newBox.maxExtents.convolve(scale);
  235. mat.mul(newBox);
  236. return newBox;
  237. }
  238. Point3F MeshRoadConvex::support(const VectorF& vec) const
  239. {
  240. F32 bestDot = mDot( verts[0], vec );
  241. const Point3F *bestP = &verts[0];
  242. for(S32 i=1; i<4; i++)
  243. {
  244. F32 newD = mDot(verts[i], vec);
  245. if(newD > bestDot)
  246. {
  247. bestDot = newD;
  248. bestP = &verts[i];
  249. }
  250. }
  251. return *bestP;
  252. }
  253. void MeshRoadConvex::getFeatures(const MatrixF& mat, const VectorF& n, ConvexFeature* cf)
  254. {
  255. cf->material = 0;
  256. cf->mObject = mObject;
  257. // For a tetrahedron this is pretty easy... first
  258. // convert everything into world space.
  259. Point3F tverts[4];
  260. mat.mulP(verts[0], &tverts[0]);
  261. mat.mulP(verts[1], &tverts[1]);
  262. mat.mulP(verts[2], &tverts[2]);
  263. mat.mulP(verts[3], &tverts[3]);
  264. // Points...
  265. S32 firstVert = cf->mVertexList.size();
  266. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[0];
  267. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[1];
  268. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[2];
  269. cf->mVertexList.increment(); cf->mVertexList.last() = tverts[3];
  270. // Edges...
  271. cf->mEdgeList.increment();
  272. cf->mEdgeList.last().vertex[0] = firstVert+0;
  273. cf->mEdgeList.last().vertex[1] = firstVert+1;
  274. cf->mEdgeList.increment();
  275. cf->mEdgeList.last().vertex[0] = firstVert+1;
  276. cf->mEdgeList.last().vertex[1] = firstVert+2;
  277. cf->mEdgeList.increment();
  278. cf->mEdgeList.last().vertex[0] = firstVert+2;
  279. cf->mEdgeList.last().vertex[1] = firstVert+0;
  280. cf->mEdgeList.increment();
  281. cf->mEdgeList.last().vertex[0] = firstVert+3;
  282. cf->mEdgeList.last().vertex[1] = firstVert+0;
  283. cf->mEdgeList.increment();
  284. cf->mEdgeList.last().vertex[0] = firstVert+3;
  285. cf->mEdgeList.last().vertex[1] = firstVert+1;
  286. cf->mEdgeList.increment();
  287. cf->mEdgeList.last().vertex[0] = firstVert+3;
  288. cf->mEdgeList.last().vertex[1] = firstVert+2;
  289. // Triangles...
  290. cf->mFaceList.increment();
  291. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[0]);
  292. cf->mFaceList.last().vertex[0] = firstVert+2;
  293. cf->mFaceList.last().vertex[1] = firstVert+1;
  294. cf->mFaceList.last().vertex[2] = firstVert+0;
  295. cf->mFaceList.increment();
  296. cf->mFaceList.last().normal = PlaneF(tverts[1], tverts[0], tverts[3]);
  297. cf->mFaceList.last().vertex[0] = firstVert+1;
  298. cf->mFaceList.last().vertex[1] = firstVert+0;
  299. cf->mFaceList.last().vertex[2] = firstVert+3;
  300. cf->mFaceList.increment();
  301. cf->mFaceList.last().normal = PlaneF(tverts[2], tverts[1], tverts[3]);
  302. cf->mFaceList.last().vertex[0] = firstVert+2;
  303. cf->mFaceList.last().vertex[1] = firstVert+1;
  304. cf->mFaceList.last().vertex[2] = firstVert+3;
  305. cf->mFaceList.increment();
  306. cf->mFaceList.last().normal = PlaneF(tverts[0], tverts[2], tverts[3]);
  307. cf->mFaceList.last().vertex[0] = firstVert+0;
  308. cf->mFaceList.last().vertex[1] = firstVert+2;
  309. cf->mFaceList.last().vertex[2] = firstVert+3;
  310. }
  311. void MeshRoadConvex::getPolyList( AbstractPolyList* list )
  312. {
  313. // Transform the list into object space and set the pointer to the object
  314. //MatrixF i( mObject->getTransform() );
  315. //Point3F iS( mObject->getScale() );
  316. //list->setTransform(&i, iS);
  317. list->setTransform( &MatrixF::Identity, Point3F::One );
  318. list->setObject(mObject);
  319. // Points...
  320. S32 base = list->addPoint(verts[1]);
  321. list->addPoint(verts[2]);
  322. list->addPoint(verts[0]);
  323. list->addPoint(verts[3]);
  324. // Planes...
  325. list->begin(0,0);
  326. list->vertex(base + 2);
  327. list->vertex(base + 1);
  328. list->vertex(base + 0);
  329. list->plane(base + 2, base + 1, base + 0);
  330. list->end();
  331. list->begin(0,0);
  332. list->vertex(base + 2);
  333. list->vertex(base + 1);
  334. list->vertex(base + 3);
  335. list->plane(base + 2, base + 1, base + 3);
  336. list->end();
  337. list->begin(0,0);
  338. list->vertex(base + 3);
  339. list->vertex(base + 1);
  340. list->vertex(base + 0);
  341. list->plane(base + 3, base + 1, base + 0);
  342. list->end();
  343. list->begin(0,0);
  344. list->vertex(base + 2);
  345. list->vertex(base + 3);
  346. list->vertex(base + 0);
  347. list->plane(base + 2, base + 3, base + 0);
  348. list->end();
  349. }
  350. //------------------------------------------------------------------------------
  351. // MeshRoadSegment Class
  352. //------------------------------------------------------------------------------
  353. MeshRoadSegment::MeshRoadSegment()
  354. {
  355. mPlaneCount = 0;
  356. columns = 0;
  357. rows = 0;
  358. numVerts = 0;
  359. numTriangles = 0;
  360. startVert = 0;
  361. endVert = 0;
  362. startIndex = 0;
  363. endIndex = 0;
  364. slice0 = NULL;
  365. slice1 = NULL;
  366. }
  367. MeshRoadSegment::MeshRoadSegment( MeshRoadSlice *rs0, MeshRoadSlice *rs1, const MatrixF &roadMat )
  368. {
  369. columns = 0;
  370. rows = 0;
  371. numVerts = 0;
  372. numTriangles = 0;
  373. startVert = 0;
  374. endVert = 0;
  375. startIndex = 0;
  376. endIndex = 0;
  377. slice0 = rs0;
  378. slice1 = rs1;
  379. // Calculate the bounding box(s)
  380. worldbounds.minExtents = worldbounds.maxExtents = rs0->p0;
  381. worldbounds.extend( rs0->p2 );
  382. worldbounds.extend( rs0->pb0 );
  383. worldbounds.extend( rs0->pb2 );
  384. worldbounds.extend( rs1->p0 );
  385. worldbounds.extend( rs1->p2 );
  386. worldbounds.extend( rs1->pb0 );
  387. worldbounds.extend( rs1->pb2 );
  388. objectbounds = worldbounds;
  389. roadMat.mul( objectbounds );
  390. // Calculate the planes for this segment
  391. // Will be used for intersection/buoyancy tests
  392. mPlaneCount = 6;
  393. mPlanes[0].set( slice0->pb0, slice0->p0, slice1->p0 ); // left
  394. mPlanes[1].set( slice1->pb2, slice1->p2, slice0->p2 ); // right
  395. mPlanes[2].set( slice0->pb2, slice0->p2, slice0->p0 ); // near
  396. mPlanes[3].set( slice1->p0, slice1->p2, slice1->pb2 ); // far
  397. mPlanes[4].set( slice1->p2, slice1->p0, slice0->p0 ); // top
  398. mPlanes[5].set( slice0->pb0, slice1->pb0, slice1->pb2 ); // bottom
  399. }
  400. void MeshRoadSegment::set( MeshRoadSlice *rs0, MeshRoadSlice *rs1 )
  401. {
  402. columns = 0;
  403. rows = 0;
  404. numVerts = 0;
  405. numTriangles = 0;
  406. startVert = 0;
  407. endVert = 0;
  408. startIndex = 0;
  409. endIndex = 0;
  410. slice0 = rs0;
  411. slice1 = rs1;
  412. }
  413. bool MeshRoadSegment::intersectBox( const Box3F &bounds ) const
  414. {
  415. // This code copied from Frustum class.
  416. Point3F maxPoint;
  417. F32 maxDot;
  418. // Note the planes are ordered left, right, near,
  419. // far, top, bottom for getting early rejections
  420. // from the typical horizontal scene.
  421. for ( S32 i = 0; i < mPlaneCount; i++ )
  422. {
  423. // This is pretty much as optimal as you can
  424. // get for a plane vs AABB test...
  425. //
  426. // 4 comparisons
  427. // 3 multiplies
  428. // 2 adds
  429. // 1 negation
  430. //
  431. // It will early out as soon as it detects the
  432. // bounds is outside one of the planes.
  433. if ( mPlanes[i].x > 0 )
  434. maxPoint.x = bounds.maxExtents.x;
  435. else
  436. maxPoint.x = bounds.minExtents.x;
  437. if ( mPlanes[i].y > 0 )
  438. maxPoint.y = bounds.maxExtents.y;
  439. else
  440. maxPoint.y = bounds.minExtents.y;
  441. if ( mPlanes[i].z > 0 )
  442. maxPoint.z = bounds.maxExtents.z;
  443. else
  444. maxPoint.z = bounds.minExtents.z;
  445. maxDot = mDot( maxPoint, mPlanes[ i ] );
  446. if ( maxDot <= -mPlanes[ i ].d )
  447. return false;
  448. }
  449. return true;
  450. }
  451. bool MeshRoadSegment::containsPoint( const Point3F &pnt ) const
  452. {
  453. // This code from Frustum class.
  454. F32 maxDot;
  455. // Note the planes are ordered left, right, near,
  456. // far, top, bottom for getting early rejections
  457. // from the typical horizontal scene.
  458. for ( S32 i = 0; i < mPlaneCount; i++ )
  459. {
  460. const PlaneF &plane = mPlanes[ i ];
  461. // This is pretty much as optimal as you can
  462. // get for a plane vs point test...
  463. //
  464. // 1 comparison
  465. // 2 multiplies
  466. // 1 adds
  467. //
  468. // It will early out as soon as it detects the
  469. // point is outside one of the planes.
  470. maxDot = mDot( pnt, plane ) + plane.d;
  471. if ( maxDot < 0.0f )
  472. return false;
  473. }
  474. return true;
  475. }
  476. F32 MeshRoadSegment::distanceToSurface(const Point3F &pnt) const
  477. {
  478. return mPlanes[4].distToPlane( pnt );
  479. }
  480. //------------------------------------------------------------------------------
  481. // MeshRoad Class
  482. //------------------------------------------------------------------------------
  483. ConsoleDocClass( MeshRoad,
  484. "@brief A strip of rectangular mesh segments defined by a 3D spline "
  485. "for prototyping road-shaped objects in your scene.\n\n"
  486. "User may control width and depth per node, overall spline shape in three "
  487. "dimensions, and seperate Materials for rendering the top, bottom, and side surfaces.\n\n"
  488. "MeshRoad is not capable of handling intersections, branches, curbs, or other "
  489. "desirable features in a final 'road' asset and is therefore intended for "
  490. "prototyping and experimentation.\n\n"
  491. "Materials assigned to MeshRoad should tile vertically.\n\n"
  492. "@ingroup Terrain"
  493. );
  494. bool MeshRoad::smEditorOpen = false;
  495. bool MeshRoad::smShowBatches = false;
  496. bool MeshRoad::smShowSpline = true;
  497. bool MeshRoad::smShowRoad = true;
  498. bool MeshRoad::smWireframe = true;
  499. SimObjectPtr<SimSet> MeshRoad::smServerMeshRoadSet = NULL;
  500. GFXStateBlockRef MeshRoad::smWireframeSB;
  501. IMPLEMENT_CO_NETOBJECT_V1(MeshRoad);
  502. MeshRoad::MeshRoad()
  503. : mTextureLength( 5.0f ),
  504. mBreakAngle( 3.0f ),
  505. mWidthSubdivisions( 0 ),
  506. mPhysicsRep( NULL )
  507. {
  508. mConvexList = new Convex;
  509. // Setup NetObject.
  510. mTypeMask |= StaticObjectType | StaticShapeObjectType;
  511. mNetFlags.set(Ghostable);
  512. mMatInst[Top] = NULL;
  513. mMatInst[Bottom] = NULL;
  514. mMatInst[Side] = NULL;
  515. mTypeMask |= TerrainLikeObjectType;
  516. for (U32 i = 0; i < SurfaceCount; i++)
  517. {
  518. mVertCount[i] = 0;
  519. mTriangleCount[i] = 0;
  520. }
  521. }
  522. MeshRoad::~MeshRoad()
  523. {
  524. delete mConvexList;
  525. mConvexList = NULL;
  526. }
  527. void MeshRoad::initPersistFields()
  528. {
  529. addGroup( "MeshRoad" );
  530. addField( "topMaterial", TypeMaterialName, Offset( mMaterialName[Top], MeshRoad ),
  531. "Material for the upper surface of the road." );
  532. addField( "bottomMaterial", TypeMaterialName, Offset( mMaterialName[Bottom], MeshRoad ),
  533. "Material for the bottom surface of the road." );
  534. addField( "sideMaterial", TypeMaterialName, Offset( mMaterialName[Side], MeshRoad ),
  535. "Material for the left, right, front, and back surfaces of the road." );
  536. addField( "textureLength", TypeF32, Offset( mTextureLength, MeshRoad ),
  537. "The length in meters of textures mapped to the MeshRoad." );
  538. addField( "breakAngle", TypeF32, Offset( mBreakAngle, MeshRoad ),
  539. "Angle in degrees - MeshRoad will subdivide the spline if its curve is greater than this threshold." );
  540. addField( "widthSubdivisions", TypeS32, Offset( mWidthSubdivisions, MeshRoad ),
  541. "Subdivide segments widthwise this many times when generating vertices." );
  542. endGroup( "MeshRoad" );
  543. addGroup( "Internal" );
  544. addProtectedField( "Node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn,
  545. "Do not modify, for internal use." );
  546. endGroup( "Internal" );
  547. Parent::initPersistFields();
  548. }
  549. void MeshRoad::consoleInit()
  550. {
  551. Parent::consoleInit();
  552. Con::addVariable( "$MeshRoad::EditorOpen", TypeBool, &MeshRoad::smEditorOpen, "True if the MeshRoad editor is open, otherwise false.\n"
  553. "@ingroup Editors\n");
  554. Con::addVariable( "$MeshRoad::wireframe", TypeBool, &MeshRoad::smWireframe, "If true, will render the wireframe of the road.\n"
  555. "@ingroup Editors\n");
  556. Con::addVariable( "$MeshRoad::showBatches", TypeBool, &MeshRoad::smShowBatches, "Determines if the debug rendering of the batches cubes is displayed or not.\n"
  557. "@ingroup Editors\n");
  558. Con::addVariable( "$MeshRoad::showSpline", TypeBool, &MeshRoad::smShowSpline, "If true, the spline on which the curvature of this road is based will be rendered.\n"
  559. "@ingroup Editors\n");
  560. Con::addVariable( "$MeshRoad::showRoad", TypeBool, &MeshRoad::smShowRoad, "If true, the road will be rendered. When in the editor, roads are always rendered regardless of this flag.\n"
  561. "@ingroup Editors\n");
  562. }
  563. bool MeshRoad::addNodeFromField( void *object, const char *index, const char *data )
  564. {
  565. MeshRoad *pObj = static_cast<MeshRoad*>(object);
  566. //if ( !pObj->isProperlyAdded() )
  567. //{
  568. F32 width, depth;
  569. Point3F pos, normal;
  570. U32 result = dSscanf( data, "%g %g %g %g %g %g %g %g", &pos.x, &pos.y, &pos.z, &width, &depth, &normal.x, &normal.y, &normal.z );
  571. if ( result == 8 )
  572. pObj->_addNode( pos, width, depth, normal );
  573. //}
  574. return false;
  575. }
  576. bool MeshRoad::onAdd()
  577. {
  578. if ( !Parent::onAdd() )
  579. return false;
  580. // Reset the World Box.
  581. //setGlobalBounds();
  582. resetWorldBox();
  583. // Set the Render Transform.
  584. setRenderTransform(mObjToWorld);
  585. // Add to ServerMeshRoadSet
  586. if ( isServerObject() )
  587. {
  588. getServerSet()->addObject( this );
  589. }
  590. if ( isClientObject() )
  591. _initMaterial();
  592. // Generate the Vert/Index buffers and everything else.
  593. _regenerate();
  594. // Add to Scene.
  595. addToScene();
  596. return true;
  597. }
  598. void MeshRoad::onRemove()
  599. {
  600. SAFE_DELETE( mPhysicsRep );
  601. mConvexList->nukeList();
  602. for ( U32 i = 0; i < SurfaceCount; i++ )
  603. {
  604. SAFE_DELETE( mMatInst[i] );
  605. }
  606. removeFromScene();
  607. Parent::onRemove();
  608. }
  609. void MeshRoad::inspectPostApply()
  610. {
  611. // Set Parent.
  612. Parent::inspectPostApply();
  613. //if ( mMetersPerSegment < MIN_METERS_PER_SEGMENT )
  614. // mMetersPerSegment = MIN_METERS_PER_SEGMENT;
  615. setMaskBits(MeshRoadMask);
  616. }
  617. void MeshRoad::onStaticModified( const char* slotName, const char*newValue )
  618. {
  619. Parent::onStaticModified( slotName, newValue );
  620. if ( dStricmp( slotName, "breakAngle" ) == 0 )
  621. {
  622. setMaskBits( RegenMask );
  623. }
  624. }
  625. void MeshRoad::writeFields( Stream &stream, U32 tabStop )
  626. {
  627. Parent::writeFields( stream, tabStop );
  628. // Now write all nodes
  629. stream.write(2, "\r\n");
  630. for ( U32 i = 0; i < mNodes.size(); i++ )
  631. {
  632. const MeshRoadNode &node = mNodes[i];
  633. stream.writeTabs(tabStop);
  634. char buffer[1024];
  635. dMemset( buffer, 0, 1024 );
  636. dSprintf( buffer, 1024, "Node = \"%g %g %g %g %g %g %g %g\";", node.point.x, node.point.y, node.point.z, node.width, node.depth, node.normal.x, node.normal.y, node.normal.z );
  637. stream.writeLine( (const U8*)buffer );
  638. }
  639. }
  640. bool MeshRoad::writeField( StringTableEntry fieldname, const char *value )
  641. {
  642. if ( fieldname == StringTable->insert("Node") )
  643. return false;
  644. return Parent::writeField( fieldname, value );
  645. }
  646. void MeshRoad::onEditorEnable()
  647. {
  648. }
  649. void MeshRoad::onEditorDisable()
  650. {
  651. }
  652. SimSet* MeshRoad::getServerSet()
  653. {
  654. if ( !smServerMeshRoadSet )
  655. {
  656. smServerMeshRoadSet = new SimSet();
  657. smServerMeshRoadSet->registerObject( "ServerMeshRoadSet" );
  658. Sim::getRootGroup()->addObject( smServerMeshRoadSet );
  659. }
  660. return smServerMeshRoadSet;
  661. }
  662. void MeshRoad::prepRenderImage( SceneRenderState* state )
  663. {
  664. if ( mNodes.size() <= 1 )
  665. return;
  666. RenderPassManager *renderPass = state->getRenderPass();
  667. // Normal Road RenderInstance
  668. // Always rendered when the editor is not open
  669. // otherwise obey the smShowRoad flag
  670. if ( smShowRoad || !smEditorOpen )
  671. {
  672. #ifdef TORQUE_AFX_ENABLED
  673. afxZodiacMgr::renderMeshRoadZodiacs(state, this);
  674. #endif
  675. MeshRenderInst coreRI;
  676. coreRI.clear();
  677. coreRI.objectToWorld = &MatrixF::Identity;
  678. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  679. coreRI.projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  680. coreRI.type = RenderPassManager::RIT_Mesh;
  681. BaseMatInstance *matInst;
  682. for ( U32 i = 0; i < SurfaceCount; i++ )
  683. {
  684. matInst = state->getOverrideMaterial( mMatInst[i] );
  685. if ( !matInst )
  686. continue;
  687. // Get the lights if we haven't already.
  688. if ( matInst->isForwardLit() && !coreRI.lights[0] )
  689. {
  690. LightQuery query;
  691. query.init( getWorldSphere() );
  692. query.getLights( coreRI.lights, 8 );
  693. }
  694. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  695. *ri = coreRI;
  696. // Currently rendering whole road, fix to cull and batch
  697. // per segment.
  698. // Set the correct material for rendering.
  699. ri->matInst = matInst;
  700. ri->vertBuff = &mVB[i];
  701. ri->primBuff = &mPB[i];
  702. ri->prim = renderPass->allocPrim();
  703. ri->prim->type = GFXTriangleList;
  704. ri->prim->minIndex = 0;
  705. ri->prim->startIndex = 0;
  706. ri->prim->numPrimitives = mTriangleCount[i];
  707. ri->prim->startVertex = 0;
  708. ri->prim->numVertices = mVertCount[i];
  709. // We sort by the material then vertex buffer.
  710. ri->defaultKey = matInst->getStateHint();
  711. ri->defaultKey2 = (uintptr_t)ri->vertBuff; // Not 64bit safe!
  712. renderPass->addInst( ri );
  713. }
  714. }
  715. // Debug RenderInstance
  716. // Only when editor is open.
  717. if ( smEditorOpen )
  718. {
  719. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  720. ri->renderDelegate.bind( this, &MeshRoad::_debugRender );
  721. ri->type = RenderPassManager::RIT_Editor;
  722. state->getRenderPass()->addInst( ri );
  723. }
  724. }
  725. void MeshRoad::_initMaterial()
  726. {
  727. for ( U32 i = 0; i < SurfaceCount; i++ )
  728. {
  729. if ( mMatInst[i] )
  730. SAFE_DELETE( mMatInst[i] );
  731. if ( mMaterial[i] )
  732. mMatInst[i] = mMaterial[i]->createMatInstance();
  733. else
  734. mMatInst[i] = MATMGR->createMatInstance( "WarningMaterial" );
  735. mMatInst[i]->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTT>() );
  736. }
  737. }
  738. void MeshRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  739. {
  740. //MeshRoadConvex convex;
  741. //buildConvex( Box3F(true), convex );
  742. //convex.render();
  743. //GFXDrawUtil *drawer = GFX->getDrawUtil();
  744. //GFX->setStateBlock( smStateBlock );
  745. return;
  746. /*
  747. U32 convexCount = mDebugConvex.size();
  748. PrimBuild::begin( GFXTriangleList, convexCount * 12 );
  749. PrimBuild::color4i( 0, 0, 255, 155 );
  750. for ( U32 i = 0; i < convexCount; i++ )
  751. {
  752. MeshRoadConvex *convex = mDebugConvex[i];
  753. Point3F a = convex->verts[0];
  754. Point3F b = convex->verts[1];
  755. Point3F c = convex->verts[2];
  756. Point3F p = convex->verts[3];
  757. //mObjToWorld.mulP(a);
  758. //mObjToWorld.mulP(b);
  759. //mObjToWorld.mulP(c);
  760. //mObjToWorld.mulP(p);
  761. PrimBuild::vertex3fv( c );
  762. PrimBuild::vertex3fv( b );
  763. PrimBuild::vertex3fv( a );
  764. PrimBuild::vertex3fv( b );
  765. PrimBuild::vertex3fv( a );
  766. PrimBuild::vertex3fv( p );
  767. PrimBuild::vertex3fv( c );
  768. PrimBuild::vertex3fv( b );
  769. PrimBuild::vertex3fv( p );
  770. PrimBuild::vertex3fv( a );
  771. PrimBuild::vertex3fv( c );
  772. PrimBuild::vertex3fv( p );
  773. }
  774. PrimBuild::end();
  775. for ( U32 i = 0; i < mSegments.size(); i++ )
  776. {
  777. ///GFX->getDrawUtil()->drawWireBox( mSegments[i].worldbounds, ColorI(255,0,0,255) );
  778. }
  779. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  780. GFXTransformSaver saver;
  781. GFX->setStateBlock( smStateBlock );
  782. Point3F size(1,1,1);
  783. ColorI color( 255, 0, 0, 255 );
  784. if ( smShowBatches )
  785. {
  786. for ( U32 i = 0; i < mBatches.size(); i++ )
  787. {
  788. const Box3F &box = mBatches[i].bounds;
  789. Point3F center;
  790. box.getCenter( &center );
  791. GFX->getDrawUtil()->drawWireCube( ( box.maxExtents - box.minExtents ) * 0.5f, center, ColorI(255,100,100,255) );
  792. }
  793. }
  794. GFX->leaveDebugEvent();
  795. */
  796. }
  797. U32 MeshRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  798. {
  799. U32 retMask = Parent::packUpdate(con, mask, stream);
  800. if ( stream->writeFlag( mask & MeshRoadMask ) )
  801. {
  802. // Write Object Transform.
  803. stream->writeAffineTransform( mObjToWorld );
  804. // Write Materials
  805. stream->write( mMaterialName[0] );
  806. stream->write( mMaterialName[1] );
  807. stream->write( mMaterialName[2] );
  808. stream->write( mTextureLength );
  809. stream->write( mBreakAngle );
  810. stream->write( mWidthSubdivisions );
  811. }
  812. if ( stream->writeFlag( mask & NodeMask ) )
  813. {
  814. const U32 nodeByteSize = 32; // Based on sending all of a node's parameters
  815. // Test if we can fit all of our nodes within the current stream.
  816. // We make sure we leave 100 bytes still free in the stream for whatever
  817. // may follow us.
  818. S32 allowedBytes = stream->getWriteByteSize() - 100;
  819. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  820. {
  821. // All nodes should fit, so send them out now.
  822. stream->writeInt( mNodes.size(), 16 );
  823. for ( U32 i = 0; i < mNodes.size(); i++ )
  824. {
  825. mathWrite( *stream, mNodes[i].point );
  826. stream->write( mNodes[i].width );
  827. stream->write( mNodes[i].depth );
  828. mathWrite( *stream, mNodes[i].normal );
  829. }
  830. }
  831. else
  832. {
  833. // There isn't enough space left in the stream for all of the
  834. // nodes. Batch them up into NetEvents.
  835. U32 id = gServerNodeListManager->nextListId();
  836. U32 count = 0;
  837. U32 index = 0;
  838. while (count < mNodes.size())
  839. {
  840. count += NodeListManager::smMaximumNodesPerEvent;
  841. if (count > mNodes.size())
  842. {
  843. count = mNodes.size();
  844. }
  845. MeshRoadNodeEvent* event = new MeshRoadNodeEvent();
  846. event->mId = id;
  847. event->mTotalNodes = mNodes.size();
  848. event->mLocalListStart = index;
  849. for (; index<count; ++index)
  850. {
  851. event->mPositions.push_back( mNodes[index].point );
  852. event->mWidths.push_back( mNodes[index].width );
  853. event->mDepths.push_back( mNodes[index].depth );
  854. event->mNormals.push_back( mNodes[index].normal );
  855. }
  856. con->postNetEvent( event );
  857. }
  858. stream->write( id );
  859. }
  860. }
  861. stream->writeFlag( mask & RegenMask );
  862. // Were done ...
  863. return retMask;
  864. }
  865. void MeshRoad::unpackUpdate(NetConnection * con, BitStream * stream)
  866. {
  867. // Unpack Parent.
  868. Parent::unpackUpdate(con, stream);
  869. // MeshRoadMask
  870. if(stream->readFlag())
  871. {
  872. MatrixF ObjectMatrix;
  873. stream->readAffineTransform(&ObjectMatrix);
  874. Parent::setTransform(ObjectMatrix);
  875. // Read Materials...
  876. Material *pMat = NULL;
  877. for ( U32 i = 0; i < SurfaceCount; i++ )
  878. {
  879. stream->read( &mMaterialName[i] );
  880. if ( !Sim::findObject( mMaterialName[i], pMat ) )
  881. Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name %s", mMaterialName[i].c_str() );
  882. else
  883. mMaterial[i] = pMat;
  884. }
  885. if ( isProperlyAdded() )
  886. _initMaterial();
  887. stream->read( &mTextureLength );
  888. stream->read( &mBreakAngle );
  889. stream->read( &mWidthSubdivisions );
  890. }
  891. // NodeMask
  892. if ( stream->readFlag() )
  893. {
  894. if (stream->readFlag())
  895. {
  896. // Nodes have been passed in this update
  897. U32 count = stream->readInt( 16 );
  898. mNodes.clear();
  899. Point3F pos, normal;
  900. F32 width, depth;
  901. for ( U32 i = 0; i < count; i++ )
  902. {
  903. mathRead( *stream, &pos );
  904. stream->read( &width );
  905. stream->read( &depth );
  906. mathRead( *stream, &normal );
  907. _addNode( pos, width, depth, normal );
  908. }
  909. }
  910. else
  911. {
  912. // Nodes will arrive as events
  913. U32 id;
  914. stream->read( &id );
  915. // Check if the road's nodes made it here before we did.
  916. NodeListManager::NodeList* list = NULL;
  917. if ( gClientNodeListManager->findListById( id, &list, true) )
  918. {
  919. // Work with the completed list
  920. MeshRoadNodeList* roadList = dynamic_cast<MeshRoadNodeList*>( list );
  921. if (roadList)
  922. buildNodesFromList( roadList );
  923. delete list;
  924. }
  925. else
  926. {
  927. // Nodes have not yet arrived, so register our interest in the list
  928. MeshRoadNodeListNotify* notify = new MeshRoadNodeListNotify( this, id );
  929. gClientNodeListManager->registerNotification( notify );
  930. }
  931. }
  932. }
  933. if ( stream->readFlag() && isProperlyAdded() )
  934. _regenerate();
  935. }
  936. void MeshRoad::setTransform( const MatrixF &mat )
  937. {
  938. for ( U32 i = 0; i < mNodes.size(); i++ )
  939. {
  940. mWorldToObj.mulP( mNodes[i].point );
  941. mat.mulP( mNodes[i].point );
  942. }
  943. Parent::setTransform( mat );
  944. if ( mPhysicsRep )
  945. mPhysicsRep->setTransform( mat );
  946. // Regenerate and update the client
  947. _regenerate();
  948. setMaskBits( NodeMask | RegenMask );
  949. }
  950. void MeshRoad::setScale( const VectorF &scale )
  951. {
  952. // We ignore scale requests from the editor
  953. // right now.
  954. //Parent::setScale( scale );
  955. }
  956. void MeshRoad::buildConvex(const Box3F& box, Convex* convex)
  957. {
  958. if ( mSlices.size() < 2 )
  959. return;
  960. mConvexList->collectGarbage();
  961. mDebugConvex.clear();
  962. Box3F realBox = box;
  963. mWorldToObj.mul(realBox);
  964. realBox.minExtents.convolveInverse(mObjScale);
  965. realBox.maxExtents.convolveInverse(mObjScale);
  966. if (realBox.isOverlapped(getObjBox()) == false)
  967. return;
  968. U32 segmentCount = mSegments.size();
  969. // Create convex(s) for each segment
  970. for ( U32 i = 0; i < segmentCount; i++ )
  971. {
  972. const MeshRoadSegment &segment = mSegments[i];
  973. // Is this segment overlapped?
  974. if ( !segment.getWorldBounds().isOverlapped( box ) )
  975. continue;
  976. // Each segment has 6 faces
  977. for ( U32 j = 0; j < 6; j++ )
  978. {
  979. // Only first segment has front face
  980. if ( j == 4 && i != 0 )
  981. continue;
  982. // Only last segment has back face
  983. if ( j == 5 && i != segmentCount-1 )
  984. continue;
  985. // Each face has 2 convex(s)
  986. for ( U32 k = 0; k < 2; k++ )
  987. {
  988. // See if this convex exists in the working set already...
  989. Convex* cc = 0;
  990. CollisionWorkingList& wl = convex->getWorkingList();
  991. for ( CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext )
  992. {
  993. if ( itr->mConvex->getType() == MeshRoadConvexType )
  994. {
  995. MeshRoadConvex *pConvex = static_cast<MeshRoadConvex*>(itr->mConvex);
  996. if ( pConvex->pRoad == this &&
  997. pConvex->segmentId == i &&
  998. pConvex->faceId == j &&
  999. pConvex->triangleId == k )
  1000. {
  1001. cc = itr->mConvex;
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. if (cc)
  1007. continue;
  1008. // Get the triangle...
  1009. U32 idx0 = gIdxArray[j][k][0];
  1010. U32 idx1 = gIdxArray[j][k][1];
  1011. U32 idx2 = gIdxArray[j][k][2];
  1012. Point3F a = segment[idx0];
  1013. Point3F b = segment[idx1];
  1014. Point3F c = segment[idx2];
  1015. // Transform the result into object space!
  1016. //mWorldToObj.mulP( a );
  1017. //mWorldToObj.mulP( b );
  1018. //mWorldToObj.mulP( c );
  1019. PlaneF p( c, b, a );
  1020. Point3F peak = ((a + b + c) / 3.0f) + (p * 0.15f);
  1021. // Set up the convex...
  1022. MeshRoadConvex *cp = new MeshRoadConvex();
  1023. mConvexList->registerObject( cp );
  1024. convex->addToWorkingList( cp );
  1025. cp->mObject = this;
  1026. cp->pRoad = this;
  1027. cp->segmentId = i;
  1028. cp->faceId = j;
  1029. cp->triangleId = k;
  1030. cp->normal = p;
  1031. cp->verts[0] = c;
  1032. cp->verts[1] = b;
  1033. cp->verts[2] = a;
  1034. cp->verts[3] = peak;
  1035. // Update the bounding box.
  1036. Box3F &bounds = cp->box;
  1037. bounds.minExtents.set( F32_MAX, F32_MAX, F32_MAX );
  1038. bounds.maxExtents.set( -F32_MAX, -F32_MAX, -F32_MAX );
  1039. bounds.minExtents.setMin( a );
  1040. bounds.minExtents.setMin( b );
  1041. bounds.minExtents.setMin( c );
  1042. bounds.minExtents.setMin( peak );
  1043. bounds.maxExtents.setMax( a );
  1044. bounds.maxExtents.setMax( b );
  1045. bounds.maxExtents.setMax( c );
  1046. bounds.maxExtents.setMax( peak );
  1047. mDebugConvex.push_back(cp);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. bool MeshRoad::buildPolyList( PolyListContext, AbstractPolyList* polyList, const Box3F &box, const SphereF & )
  1053. {
  1054. if ( mSlices.size() < 2 )
  1055. return false;
  1056. polyList->setTransform( &MatrixF::Identity, Point3F::One );
  1057. polyList->setObject(this);
  1058. // JCF: optimize this to not always add everything.
  1059. return buildSegmentPolyList( polyList, 0, mSegments.size() - 1, true, true );
  1060. }
  1061. bool MeshRoad::buildSegmentPolyList( AbstractPolyList* polyList, U32 startSegIdx, U32 endSegIdx, bool capFront, bool capEnd )
  1062. {
  1063. if ( mSlices.size() < 2 )
  1064. return false;
  1065. // Add verts
  1066. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1067. {
  1068. const MeshRoadSegment &seg = mSegments[i];
  1069. if ( i == startSegIdx )
  1070. {
  1071. polyList->addPoint( seg.slice0->p0 );
  1072. polyList->addPoint( seg.slice0->p2 );
  1073. polyList->addPoint( seg.slice0->pb0 );
  1074. polyList->addPoint( seg.slice0->pb2 );
  1075. }
  1076. polyList->addPoint( seg.slice1->p0 );
  1077. polyList->addPoint( seg.slice1->p2 );
  1078. polyList->addPoint( seg.slice1->pb0 );
  1079. polyList->addPoint( seg.slice1->pb2 );
  1080. }
  1081. // Temporaries to hold indices for the corner points of a quad.
  1082. S32 p00, p01, p11, p10;
  1083. S32 pb00, pb01, pb11, pb10;
  1084. U32 offset = 0;
  1085. DebugDrawer *ddraw = NULL;//DebugDrawer::get();
  1086. ClippedPolyList *cpolyList = dynamic_cast<ClippedPolyList*>(polyList);
  1087. MatrixF mat;
  1088. Point3F scale;
  1089. if ( cpolyList )
  1090. cpolyList->getTransform( &mat, &scale );
  1091. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1092. {
  1093. p00 = offset;
  1094. p10 = offset + 1;
  1095. pb00 = offset + 2;
  1096. pb10 = offset + 3;
  1097. p01 = offset + 4;
  1098. p11 = offset + 5;
  1099. pb01 = offset + 6;
  1100. pb11 = offset + 7;
  1101. // Top Face
  1102. polyList->begin( 0,0 );
  1103. polyList->vertex( p00 );
  1104. polyList->vertex( p01 );
  1105. polyList->vertex( p11 );
  1106. polyList->plane( p00, p01, p11 );
  1107. polyList->end();
  1108. if ( ddraw && cpolyList )
  1109. {
  1110. Point3F v0 = cpolyList->mVertexList[p00].point;
  1111. mat.mulP( v0 );
  1112. Point3F v1 = cpolyList->mVertexList[p01].point;
  1113. mat.mulP( v1 );
  1114. Point3F v2 = cpolyList->mVertexList[p11].point;
  1115. mat.mulP( v2 );
  1116. ddraw->drawTri( v0, v1, v2 );
  1117. ddraw->setLastZTest( false );
  1118. ddraw->setLastTTL( 0 );
  1119. }
  1120. polyList->begin( 0,0 );
  1121. polyList->vertex( p00 );
  1122. polyList->vertex( p11 );
  1123. polyList->vertex( p10 );
  1124. polyList->plane( p00, p11, p10 );
  1125. polyList->end();
  1126. if ( ddraw && cpolyList )
  1127. {
  1128. ddraw->drawTri( cpolyList->mVertexList[p00].point, cpolyList->mVertexList[p11].point, cpolyList->mVertexList[p10].point );
  1129. ddraw->setLastTTL( 0 );
  1130. }
  1131. if (buildPolyList_TopSurfaceOnly)
  1132. {
  1133. offset += 4;
  1134. continue;
  1135. }
  1136. // Left Face
  1137. polyList->begin( 0,0 );
  1138. polyList->vertex( pb00 );
  1139. polyList->vertex( pb01 );
  1140. polyList->vertex( p01 );
  1141. polyList->plane( pb00, pb01, p01 );
  1142. polyList->end();
  1143. polyList->begin( 0,0 );
  1144. polyList->vertex( pb00 );
  1145. polyList->vertex( p01 );
  1146. polyList->vertex( p00 );
  1147. polyList->plane( pb00, p01, p00 );
  1148. polyList->end();
  1149. // Right Face
  1150. polyList->begin( 0,0 );
  1151. polyList->vertex( p10 );
  1152. polyList->vertex( p11 );
  1153. polyList->vertex( pb11 );
  1154. polyList->plane( p10, p11, pb11 );
  1155. polyList->end();
  1156. polyList->begin( 0,0 );
  1157. polyList->vertex( p10 );
  1158. polyList->vertex( pb11 );
  1159. polyList->vertex( pb10 );
  1160. polyList->plane( p10, pb11, pb10 );
  1161. polyList->end();
  1162. // Bottom Face
  1163. polyList->begin( 0,0 );
  1164. polyList->vertex( pb00 );
  1165. polyList->vertex( pb10 );
  1166. polyList->vertex( pb11 );
  1167. polyList->plane( pb00, pb10, pb11 );
  1168. polyList->end();
  1169. polyList->begin( 0,0 );
  1170. polyList->vertex( pb00 );
  1171. polyList->vertex( pb11 );
  1172. polyList->vertex( pb01 );
  1173. polyList->plane( pb00, pb11, pb01 );
  1174. polyList->end();
  1175. // Front Face
  1176. if ( i == startSegIdx && capFront )
  1177. {
  1178. polyList->begin( 0,0 );
  1179. polyList->vertex( p00 );
  1180. polyList->vertex( p10 );
  1181. polyList->vertex( pb10 );
  1182. polyList->plane( p00, p10, pb10 );
  1183. polyList->end();
  1184. polyList->begin( 0,0 );
  1185. polyList->vertex( p00 );
  1186. polyList->vertex( pb10 );
  1187. polyList->vertex( pb00 );
  1188. polyList->plane( p00, pb10, pb00 );
  1189. polyList->end();
  1190. }
  1191. // Back Face
  1192. if ( i == endSegIdx && capEnd )
  1193. {
  1194. polyList->begin( 0,0 );
  1195. polyList->vertex( p01 );
  1196. polyList->vertex( pb01 );
  1197. polyList->vertex( pb11 );
  1198. polyList->plane( p01, pb01, pb11 );
  1199. polyList->end();
  1200. polyList->begin( 0,0 );
  1201. polyList->vertex( p01 );
  1202. polyList->vertex( pb11 );
  1203. polyList->vertex( p11 );
  1204. polyList->plane( p01, pb11, p11 );
  1205. polyList->end();
  1206. }
  1207. offset += 4;
  1208. }
  1209. return true;
  1210. }
  1211. bool MeshRoad::castRay( const Point3F &s, const Point3F &e, RayInfo *info )
  1212. {
  1213. Point3F start = s;
  1214. Point3F end = e;
  1215. mObjToWorld.mulP(start);
  1216. mObjToWorld.mulP(end);
  1217. F32 out = 1.0f; // The output fraction/percentage along the line defined by s and e
  1218. VectorF norm(0.0f, 0.0f, 0.0f); // The normal of the face intersected
  1219. Vector<MeshRoadHitSegment> hitSegments;
  1220. for ( U32 i = 0; i < mSegments.size(); i++ )
  1221. {
  1222. const MeshRoadSegment &segment = mSegments[i];
  1223. F32 t;
  1224. VectorF n;
  1225. if ( segment.getWorldBounds().collideLine( start, end, &t, &n ) )
  1226. {
  1227. hitSegments.increment();
  1228. hitSegments.last().t = t;
  1229. hitSegments.last().idx = i;
  1230. }
  1231. }
  1232. dQsort( hitSegments.address(), hitSegments.size(), sizeof(MeshRoadHitSegment), compareHitSegments );
  1233. U32 idx0, idx1, idx2;
  1234. F32 t;
  1235. for ( U32 i = 0; i < hitSegments.size(); i++ )
  1236. {
  1237. U32 segIdx = hitSegments[i].idx;
  1238. const MeshRoadSegment &segment = mSegments[segIdx];
  1239. // Each segment has 6 faces
  1240. for ( U32 j = 0; j < 6; j++ )
  1241. {
  1242. if ( j == 4 && segIdx != 0 )
  1243. continue;
  1244. if ( j == 5 && segIdx != mSegments.size() - 1 )
  1245. continue;
  1246. // Each face has 2 triangles
  1247. for ( U32 k = 0; k < 2; k++ )
  1248. {
  1249. idx0 = gIdxArray[j][k][0];
  1250. idx1 = gIdxArray[j][k][1];
  1251. idx2 = gIdxArray[j][k][2];
  1252. const Point3F &v0 = segment[idx0];
  1253. const Point3F &v1 = segment[idx1];
  1254. const Point3F &v2 = segment[idx2];
  1255. if ( !MathUtils::mLineTriangleCollide( start, end,
  1256. v2, v1, v0,
  1257. NULL,
  1258. &t ) )
  1259. continue;
  1260. if ( t >= 0.0f && t < 1.0f && t < out )
  1261. {
  1262. out = t;
  1263. norm = PlaneF( v0, v1, v2 );
  1264. }
  1265. }
  1266. }
  1267. if (out >= 0.0f && out < 1.0f)
  1268. break;
  1269. }
  1270. if (out >= 0.0f && out < 1.0f)
  1271. {
  1272. info->t = out;
  1273. info->normal = norm;
  1274. info->point.interpolate(start, end, out);
  1275. info->face = -1;
  1276. info->object = this;
  1277. info->material = this->mMatInst[0];
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. bool MeshRoad::collideBox(const Point3F &start, const Point3F &end, RayInfo* info)
  1283. {
  1284. Con::warnf( "MeshRoad::collideBox() - not yet implemented!" );
  1285. return Parent::collideBox( start, end, info );
  1286. }
  1287. void MeshRoad::_regenerate()
  1288. {
  1289. if ( mNodes.size() == 0 )
  1290. return;
  1291. const Point3F &nodePt = mNodes.first().point;
  1292. MatrixF mat( true );
  1293. mat.setPosition( nodePt );
  1294. Parent::setTransform( mat );
  1295. _generateSlices();
  1296. // Make sure we are in the correct bins given our world box.
  1297. if( getSceneManager() != NULL )
  1298. getSceneManager()->notifyObjectDirty( this );
  1299. }
  1300. void MeshRoad::_generateSlices()
  1301. {
  1302. if ( mNodes.size() < 2 )
  1303. return;
  1304. // Create the spline, initialized with the MeshRoadNode(s)
  1305. U32 nodeCount = mNodes.size();
  1306. MeshRoadSplineNode *splineNodes = new MeshRoadSplineNode[nodeCount];
  1307. for ( U32 i = 0; i < nodeCount; i++ )
  1308. {
  1309. MeshRoadSplineNode &splineNode = splineNodes[i];
  1310. const MeshRoadNode &node = mNodes[i];
  1311. splineNode.x = node.point.x;
  1312. splineNode.y = node.point.y;
  1313. splineNode.z = node.point.z;
  1314. splineNode.width = node.width;
  1315. splineNode.depth = node.depth;
  1316. splineNode.normal = node.normal;
  1317. }
  1318. CatmullRom<MeshRoadSplineNode> spline;
  1319. spline.initialize( nodeCount, splineNodes );
  1320. delete [] splineNodes;
  1321. mSlices.clear();
  1322. VectorF lastBreakVector(0,0,0);
  1323. MeshRoadSlice slice;
  1324. MeshRoadSplineNode lastBreakNode;
  1325. lastBreakNode = spline.evaluate(0.0f);
  1326. for ( U32 i = 1; i < mNodes.size(); i++ )
  1327. {
  1328. F32 t1 = spline.getTime(i);
  1329. F32 t0 = spline.getTime(i-1);
  1330. F32 segLength = spline.arcLength( t0, t1 );
  1331. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  1332. numSegments = getMax( numSegments, (U32)1 );
  1333. F32 tstep = ( t1 - t0 ) / numSegments;
  1334. U32 startIdx = 0;
  1335. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  1336. for ( U32 j = startIdx; j < endIdx; j++ )
  1337. {
  1338. F32 t = t0 + tstep * j;
  1339. MeshRoadSplineNode splineNode = spline.evaluate(t);
  1340. VectorF toNodeVec = splineNode.getPosition() - lastBreakNode.getPosition();
  1341. toNodeVec.normalizeSafe();
  1342. if ( lastBreakVector.isZero() )
  1343. lastBreakVector = toNodeVec;
  1344. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  1345. if ( j == startIdx ||
  1346. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  1347. angle > mBreakAngle )
  1348. {
  1349. // Push back a spline node
  1350. slice.p1.set( splineNode.x, splineNode.y, splineNode.z );
  1351. slice.width = splineNode.width;
  1352. slice.depth = splineNode.depth;
  1353. slice.normal = splineNode.normal;
  1354. slice.normal.normalize();
  1355. slice.parentNodeIdx = i-1;
  1356. slice.t = t;
  1357. mSlices.push_back( slice );
  1358. lastBreakVector = splineNode.getPosition() - lastBreakNode.getPosition();
  1359. lastBreakVector.normalizeSafe();
  1360. lastBreakNode = splineNode;
  1361. }
  1362. }
  1363. }
  1364. MatrixF mat(true);
  1365. Box3F box;
  1366. for ( U32 i = 0; i < mSlices.size(); i++ )
  1367. {
  1368. // Calculate uvec, fvec, and rvec for all slices
  1369. calcSliceTransform( i, mat );
  1370. MeshRoadSlice *slicePtr = &mSlices[i];
  1371. mat.getColumn( 0, &slicePtr->rvec );
  1372. mat.getColumn( 1, &slicePtr->fvec );
  1373. mat.getColumn( 2, &slicePtr->uvec );
  1374. // Calculate p0/p2/pb0/pb2 for all slices
  1375. slicePtr->p0 = slicePtr->p1 - slicePtr->rvec * slicePtr->width * 0.5f;
  1376. slicePtr->p2 = slicePtr->p1 + slicePtr->rvec * slicePtr->width * 0.5f;
  1377. slicePtr->pb0 = slicePtr->p0 - slicePtr->uvec * slicePtr->depth;
  1378. slicePtr->pb2 = slicePtr->p2 - slicePtr->uvec * slicePtr->depth;
  1379. // Generate or extend the object/world bounds
  1380. if ( i == 0 )
  1381. {
  1382. box.minExtents = slicePtr->p0;
  1383. box.maxExtents = slicePtr->p2;
  1384. box.extend(slicePtr->pb0 );
  1385. box.extend(slicePtr->pb2 );
  1386. }
  1387. else
  1388. {
  1389. box.extend(slicePtr->p0 );
  1390. box.extend(slicePtr->p2 );
  1391. box.extend(slicePtr->pb0 );
  1392. box.extend(slicePtr->pb2 );
  1393. }
  1394. }
  1395. mWorldBox = box;
  1396. resetObjectBox();
  1397. _generateSegments();
  1398. }
  1399. void MeshRoad::_generateSegments()
  1400. {
  1401. SAFE_DELETE( mPhysicsRep );
  1402. mSegments.clear();
  1403. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1404. {
  1405. MeshRoadSegment seg( &mSlices[i], &mSlices[i+1], getWorldTransform() );
  1406. mSegments.push_back( seg );
  1407. }
  1408. if ( isClientObject() )
  1409. _generateVerts();
  1410. if ( PHYSICSMGR )
  1411. {
  1412. ConcretePolyList polylist;
  1413. if ( buildPolyList( PLC_Collision, &polylist, getWorldBox(), getWorldSphere() ) )
  1414. {
  1415. polylist.triangulate();
  1416. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  1417. colShape->addTriangleMesh( polylist.mVertexList.address(),
  1418. polylist.mVertexList.size(),
  1419. polylist.mIndexList.address(),
  1420. polylist.mIndexList.size() / 3,
  1421. MatrixF::Identity );
  1422. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  1423. mPhysicsRep = PHYSICSMGR->createBody();
  1424. mPhysicsRep->init( colShape, 0, 0, this, world );
  1425. }
  1426. }
  1427. }
  1428. void MeshRoad::_generateVerts()
  1429. {
  1430. const U32 widthDivisions = getMax( 0, mWidthSubdivisions );
  1431. const F32 divisionStep = 1.0f / (F32)( widthDivisions + 1 );
  1432. const U32 sliceCount = mSlices.size();
  1433. const U32 segmentCount = mSegments.size();
  1434. mVertCount[Top] = ( 2 + widthDivisions ) * sliceCount;
  1435. mTriangleCount[Top] = segmentCount * 2 * ( widthDivisions + 1 );
  1436. mVertCount[Bottom] = sliceCount * 2;
  1437. mTriangleCount[Bottom] = segmentCount * 2;
  1438. mVertCount[Side] = sliceCount * 4;
  1439. mTriangleCount[Side] = segmentCount * 4 + 4;
  1440. // Calculate TexCoords for Slices
  1441. F32 texCoordV = 0.0f;
  1442. mSlices[0].texCoordV = 0.0f;
  1443. for ( U32 i = 1; i < sliceCount; i++ )
  1444. {
  1445. MeshRoadSlice &slice = mSlices[i];
  1446. MeshRoadSlice &prevSlice = mSlices[i-1];
  1447. // Increment the textCoordV for the next slice.
  1448. F32 len = ( slice.p1 - prevSlice.p1 ).len();
  1449. texCoordV += len / mTextureLength;
  1450. slice.texCoordV = texCoordV;
  1451. }
  1452. // Make Vertex Buffers
  1453. GFXVertexPNTT *pVert = NULL;
  1454. U32 vertCounter = 0;
  1455. // Top Buffers...
  1456. mVB[Top].set( GFX, mVertCount[Top], GFXBufferTypeStatic );
  1457. pVert = mVB[Top].lock();
  1458. vertCounter = 0;
  1459. for ( U32 i = 0; i < sliceCount; i++ )
  1460. {
  1461. MeshRoadSlice &slice = mSlices[i];
  1462. pVert->point = slice.p0;
  1463. pVert->normal = slice.uvec;
  1464. pVert->tangent = slice.fvec;
  1465. pVert->texCoord.set(1,slice.texCoordV);
  1466. pVert++;
  1467. vertCounter++;
  1468. for ( U32 j = 0; j < widthDivisions; j++ )
  1469. {
  1470. const F32 t = divisionStep * (F32)( j + 1 );
  1471. pVert->point.interpolate( slice.p0, slice.p2, t );
  1472. pVert->normal = slice.uvec;
  1473. pVert->tangent = slice.fvec;
  1474. pVert->texCoord.set( 1.0f - t, slice.texCoordV );
  1475. pVert++;
  1476. vertCounter++;
  1477. }
  1478. pVert->point = slice.p2;
  1479. pVert->normal = slice.uvec;
  1480. pVert->tangent = slice.fvec;
  1481. pVert->texCoord.set( 0, slice.texCoordV );
  1482. pVert++;
  1483. vertCounter++;
  1484. }
  1485. AssertFatal( vertCounter == mVertCount[Top], "MeshRoad, wrote incorrect number of verts in mVB[Top]!" );
  1486. mVB[Top].unlock();
  1487. // Bottom Buffer...
  1488. mVB[Bottom].set( GFX, mVertCount[Bottom], GFXBufferTypeStatic );
  1489. pVert = mVB[Bottom].lock();
  1490. vertCounter = 0;
  1491. for ( U32 i = 0; i < sliceCount; i++ )
  1492. {
  1493. MeshRoadSlice &slice = mSlices[i];
  1494. pVert->point = slice.pb2;
  1495. pVert->normal = -slice.uvec;
  1496. pVert->tangent = slice.fvec;
  1497. pVert->texCoord.set(0,slice.texCoordV);
  1498. pVert++;
  1499. vertCounter++;
  1500. pVert->point = slice.pb0;
  1501. pVert->normal = -slice.uvec;
  1502. pVert->tangent = slice.fvec;
  1503. pVert->texCoord.set(1,slice.texCoordV);
  1504. pVert++;
  1505. vertCounter++;
  1506. }
  1507. AssertFatal( vertCounter == mVertCount[Bottom], "MeshRoad, wrote incorrect number of verts in mVB[Bottom]!" );
  1508. mVB[Bottom].unlock();
  1509. // Side Buffers...
  1510. mVB[Side].set( GFX, mVertCount[Side], GFXBufferTypeStatic );
  1511. pVert = mVB[Side].lock();
  1512. vertCounter = 0;
  1513. for ( U32 i = 0; i < sliceCount; i++ )
  1514. {
  1515. MeshRoadSlice &slice = mSlices[i];
  1516. pVert->point = slice.p0;
  1517. pVert->normal = -slice.rvec;
  1518. pVert->tangent = slice.fvec;
  1519. pVert->texCoord.set(1,slice.texCoordV);
  1520. pVert++;
  1521. vertCounter++;
  1522. pVert->point = slice.p2;
  1523. pVert->normal = slice.rvec;
  1524. pVert->tangent = slice.fvec;
  1525. pVert->texCoord.set(1,slice.texCoordV);
  1526. pVert++;
  1527. vertCounter++;
  1528. pVert->point = slice.pb0;
  1529. pVert->normal = -slice.rvec;
  1530. pVert->tangent = slice.fvec;
  1531. pVert->texCoord.set(0,slice.texCoordV);
  1532. pVert++;
  1533. vertCounter++;
  1534. pVert->point = slice.pb2;
  1535. pVert->normal = slice.rvec;
  1536. pVert->tangent = slice.fvec;
  1537. pVert->texCoord.set(0,slice.texCoordV);
  1538. pVert++;
  1539. vertCounter++;
  1540. }
  1541. AssertFatal( vertCounter == mVertCount[Side], "MeshRoad, wrote incorrect number of verts in mVB[Side]!" );
  1542. mVB[Side].unlock();
  1543. // Make Primitive Buffers
  1544. U32 p00, p01, p11, p10;
  1545. U32 pb00, pb01, pb11, pb10;
  1546. U32 offset = 0;
  1547. U16 *pIdx = NULL;
  1548. U32 curIdx = 0;
  1549. // Top Primitive Buffer
  1550. mPB[Top].set( GFX, mTriangleCount[Top] * 3, mTriangleCount[Top], GFXBufferTypeStatic );
  1551. mPB[Top].lock(&pIdx);
  1552. curIdx = 0;
  1553. offset = 0;
  1554. const U32 rowStride = 2 + widthDivisions;
  1555. for ( U32 i = 0; i < mSegments.size(); i++ )
  1556. {
  1557. for ( U32 j = 0; j < widthDivisions + 1; j++ )
  1558. {
  1559. p00 = offset;
  1560. p10 = offset + 1;
  1561. p01 = offset + rowStride;
  1562. p11 = offset + rowStride + 1;
  1563. pIdx[curIdx] = p00;
  1564. curIdx++;
  1565. pIdx[curIdx] = p01;
  1566. curIdx++;
  1567. pIdx[curIdx] = p11;
  1568. curIdx++;
  1569. pIdx[curIdx] = p00;
  1570. curIdx++;
  1571. pIdx[curIdx] = p11;
  1572. curIdx++;
  1573. pIdx[curIdx] = p10;
  1574. curIdx++;
  1575. offset += 1;
  1576. }
  1577. offset += 1;
  1578. }
  1579. AssertFatal( curIdx == mTriangleCount[Top] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Top]!" );
  1580. mPB[Top].unlock();
  1581. // Bottom Primitive Buffer
  1582. mPB[Bottom].set( GFX, mTriangleCount[Bottom] * 3, mTriangleCount[Bottom], GFXBufferTypeStatic );
  1583. mPB[Bottom].lock(&pIdx);
  1584. curIdx = 0;
  1585. offset = 0;
  1586. for ( U32 i = 0; i < mSegments.size(); i++ )
  1587. {
  1588. p00 = offset;
  1589. p10 = offset + 1;
  1590. p01 = offset + 2;
  1591. p11 = offset + 3;
  1592. pIdx[curIdx] = p00;
  1593. curIdx++;
  1594. pIdx[curIdx] = p01;
  1595. curIdx++;
  1596. pIdx[curIdx] = p11;
  1597. curIdx++;
  1598. pIdx[curIdx] = p00;
  1599. curIdx++;
  1600. pIdx[curIdx] = p11;
  1601. curIdx++;
  1602. pIdx[curIdx] = p10;
  1603. curIdx++;
  1604. offset += 2;
  1605. }
  1606. AssertFatal( curIdx == mTriangleCount[Bottom] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Bottom]!" );
  1607. mPB[Bottom].unlock();
  1608. // Side Primitive Buffer
  1609. mPB[Side].set( GFX, mTriangleCount[Side] * 3, mTriangleCount[Side], GFXBufferTypeStatic );
  1610. mPB[Side].lock(&pIdx);
  1611. curIdx = 0;
  1612. offset = 0;
  1613. for ( U32 i = 0; i < mSegments.size(); i++ )
  1614. {
  1615. p00 = offset;
  1616. p10 = offset + 1;
  1617. pb00 = offset + 2;
  1618. pb10 = offset + 3;
  1619. p01 = offset + 4;
  1620. p11 = offset + 5;
  1621. pb01 = offset + 6;
  1622. pb11 = offset + 7;
  1623. // Left Side
  1624. pIdx[curIdx] = pb00;
  1625. curIdx++;
  1626. pIdx[curIdx] = pb01;
  1627. curIdx++;
  1628. pIdx[curIdx] = p01;
  1629. curIdx++;
  1630. pIdx[curIdx] = pb00;
  1631. curIdx++;
  1632. pIdx[curIdx] = p01;
  1633. curIdx++;
  1634. pIdx[curIdx] = p00;
  1635. curIdx++;
  1636. // Right Side
  1637. pIdx[curIdx] = p10;
  1638. curIdx++;
  1639. pIdx[curIdx] = p11;
  1640. curIdx++;
  1641. pIdx[curIdx] = pb11;
  1642. curIdx++;
  1643. pIdx[curIdx] = p10;
  1644. curIdx++;
  1645. pIdx[curIdx] = pb11;
  1646. curIdx++;
  1647. pIdx[curIdx] = pb10;
  1648. curIdx++;
  1649. offset += 4;
  1650. }
  1651. // Cap the front and back ends
  1652. pIdx[curIdx++] = 0;
  1653. pIdx[curIdx++] = 1;
  1654. pIdx[curIdx++] = 3;
  1655. pIdx[curIdx++] = 0;
  1656. pIdx[curIdx++] = 3;
  1657. pIdx[curIdx++] = 2;
  1658. pIdx[curIdx++] = offset + 0;
  1659. pIdx[curIdx++] = offset + 3;
  1660. pIdx[curIdx++] = offset + 1;
  1661. pIdx[curIdx++] = offset + 0;
  1662. pIdx[curIdx++] = offset + 2;
  1663. pIdx[curIdx++] = offset + 3;
  1664. AssertFatal( curIdx == mTriangleCount[Side] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Side]!" );
  1665. mPB[Side].unlock();
  1666. }
  1667. const MeshRoadNode& MeshRoad::getNode( U32 idx )
  1668. {
  1669. return mNodes[idx];
  1670. }
  1671. VectorF MeshRoad::getNodeNormal( U32 idx )
  1672. {
  1673. if ( mNodes.size() - 1 < idx )
  1674. return VectorF::Zero;
  1675. return mNodes[idx].normal;
  1676. }
  1677. void MeshRoad::setNodeNormal( U32 idx, const VectorF &normal )
  1678. {
  1679. if ( mNodes.size() - 1 < idx )
  1680. return;
  1681. mNodes[idx].normal = normal;
  1682. regenerate();
  1683. setMaskBits( NodeMask | RegenMask );
  1684. }
  1685. Point3F MeshRoad::getNodePosition( U32 idx )
  1686. {
  1687. if ( mNodes.size() - 1 < idx )
  1688. return Point3F::Zero;
  1689. return mNodes[idx].point;
  1690. }
  1691. void MeshRoad::setNodePosition( U32 idx, const Point3F &pos )
  1692. {
  1693. if ( mNodes.size() - 1 < idx )
  1694. return;
  1695. mNodes[idx].point = pos;
  1696. regenerate();
  1697. setMaskBits( NodeMask | RegenMask );
  1698. }
  1699. U32 MeshRoad::addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1700. {
  1701. U32 idx = _addNode( pos, width, depth, normal );
  1702. regenerate();
  1703. setMaskBits( NodeMask | RegenMask );
  1704. return idx;
  1705. }
  1706. void MeshRoad::buildNodesFromList( MeshRoadNodeList* list )
  1707. {
  1708. mNodes.clear();
  1709. for (U32 i=0; i<list->mPositions.size(); ++i)
  1710. {
  1711. _addNode( list->mPositions[i], list->mWidths[i], list->mDepths[i], list->mNormals[i] );
  1712. }
  1713. _regenerate();
  1714. }
  1715. U32 MeshRoad::insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1716. {
  1717. U32 ret = _insertNode( pos, width, depth, normal, idx );
  1718. regenerate();
  1719. setMaskBits( NodeMask | RegenMask );
  1720. return ret;
  1721. }
  1722. void MeshRoad::setNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1723. {
  1724. if ( mNodes.size() - 1 < idx )
  1725. return;
  1726. MeshRoadNode &node = mNodes[idx];
  1727. node.point = pos;
  1728. node.width = width;
  1729. node.depth = depth;
  1730. node.normal = normal;
  1731. regenerate();
  1732. setMaskBits( NodeMask | RegenMask );
  1733. }
  1734. void MeshRoad::setNodeWidth( U32 idx, F32 meters )
  1735. {
  1736. meters = mClampF( meters, MIN_NODE_WIDTH, MAX_NODE_WIDTH );
  1737. if ( mNodes.size() - 1 < idx )
  1738. return;
  1739. mNodes[idx].width = meters;
  1740. _regenerate();
  1741. setMaskBits( RegenMask | NodeMask );
  1742. }
  1743. F32 MeshRoad::getNodeWidth( U32 idx )
  1744. {
  1745. if ( mNodes.size() - 1 < idx )
  1746. return -1.0f;
  1747. return mNodes[idx].width;
  1748. }
  1749. void MeshRoad::setNodeDepth( U32 idx, F32 meters )
  1750. {
  1751. meters = mClampF( meters, MIN_NODE_DEPTH, MAX_NODE_DEPTH );
  1752. if ( mNodes.size() - 1 < idx )
  1753. return;
  1754. mNodes[idx].depth = meters;
  1755. _regenerate();
  1756. setMaskBits( MeshRoadMask | RegenMask | NodeMask );
  1757. }
  1758. F32 MeshRoad::getNodeDepth( U32 idx )
  1759. {
  1760. if ( mNodes.size() - 1 < idx )
  1761. return -1.0f;
  1762. return mNodes[idx].depth;
  1763. }
  1764. MatrixF MeshRoad::getNodeTransform( U32 idx )
  1765. {
  1766. MatrixF mat(true);
  1767. if ( mNodes.size() - 1 < idx )
  1768. return mat;
  1769. bool hasNext = idx + 1 < mNodes.size();
  1770. bool hasPrev = (S32)idx - 1 > 0;
  1771. const MeshRoadNode &node = mNodes[idx];
  1772. VectorF fvec( 0, 1, 0 );
  1773. if ( hasNext )
  1774. {
  1775. fvec = mNodes[idx+1].point - node.point;
  1776. fvec.normalizeSafe();
  1777. }
  1778. else if ( hasPrev )
  1779. {
  1780. fvec = node.point - mNodes[idx-1].point;
  1781. fvec.normalizeSafe();
  1782. }
  1783. else
  1784. fvec = mPerp( node.normal );
  1785. if ( fvec.isZero() )
  1786. fvec = mPerp( node.normal );
  1787. F32 dot = mDot( fvec, node.normal );
  1788. if ( dot < -0.9f || dot > 0.9f )
  1789. fvec = mPerp( node.normal );
  1790. VectorF rvec = mCross( fvec, node.normal );
  1791. if ( rvec.isZero() )
  1792. rvec = mPerp( fvec );
  1793. rvec.normalize();
  1794. fvec = mCross( node.normal, rvec );
  1795. fvec.normalize();
  1796. mat.setColumn( 0, rvec );
  1797. mat.setColumn( 1, fvec );
  1798. mat.setColumn( 2, node.normal );
  1799. mat.setColumn( 3, node.point );
  1800. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1801. return mat;
  1802. }
  1803. void MeshRoad::calcSliceTransform( U32 idx, MatrixF &mat )
  1804. {
  1805. if ( mSlices.size() - 1 < idx )
  1806. return;
  1807. bool hasNext = idx + 1 < mSlices.size();
  1808. bool hasPrev = (S32)idx - 1 >= 0;
  1809. const MeshRoadSlice &slice = mSlices[idx];
  1810. VectorF fvec( 0, 1, 0 );
  1811. if ( hasNext )
  1812. {
  1813. fvec = mSlices[idx+1].p1 - slice.p1;
  1814. fvec.normalizeSafe();
  1815. }
  1816. else if ( hasPrev )
  1817. {
  1818. fvec = slice.p1 - mSlices[idx-1].p1;
  1819. fvec.normalizeSafe();
  1820. }
  1821. else
  1822. fvec = mPerp( slice.normal );
  1823. if ( fvec.isZero() )
  1824. fvec = mPerp( slice.normal );
  1825. F32 dot = mDot( fvec, slice.normal );
  1826. if ( dot < -0.9f || dot > 0.9f )
  1827. fvec = mPerp( slice.normal );
  1828. VectorF rvec = mCross( fvec, slice.normal );
  1829. if ( rvec.isZero() )
  1830. rvec = mPerp( fvec );
  1831. rvec.normalize();
  1832. fvec = mCross( slice.normal, rvec );
  1833. fvec.normalize();
  1834. mat.setColumn( 0, rvec );
  1835. mat.setColumn( 1, fvec );
  1836. mat.setColumn( 2, slice.normal );
  1837. mat.setColumn( 3, slice.p1 );
  1838. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1839. }
  1840. F32 MeshRoad::getRoadLength() const
  1841. {
  1842. F32 length = 0.0f;
  1843. for ( U32 i = 0; i < mSegments.size(); i++ )
  1844. {
  1845. length += mSegments[i].length();
  1846. }
  1847. return length;
  1848. }
  1849. void MeshRoad::deleteNode( U32 idx )
  1850. {
  1851. if ( mNodes.size() - 1 < idx )
  1852. return;
  1853. mNodes.erase(idx);
  1854. _regenerate();
  1855. setMaskBits( RegenMask | NodeMask );
  1856. }
  1857. U32 MeshRoad::_addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1858. {
  1859. mNodes.increment();
  1860. MeshRoadNode &node = mNodes.last();
  1861. node.point = pos;
  1862. node.width = width;
  1863. node.depth = depth;
  1864. node.normal = normal;
  1865. setMaskBits( NodeMask | RegenMask );
  1866. return mNodes.size() - 1;
  1867. }
  1868. U32 MeshRoad::_insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1869. {
  1870. U32 ret;
  1871. MeshRoadNode *node;
  1872. if ( idx == U32_MAX )
  1873. {
  1874. mNodes.increment();
  1875. node = &mNodes.last();
  1876. ret = mNodes.size() - 1;
  1877. }
  1878. else
  1879. {
  1880. mNodes.insert( idx );
  1881. node = &mNodes[idx];
  1882. ret = idx;
  1883. }
  1884. node->point = pos;
  1885. node->depth = depth;
  1886. node->width = width;
  1887. node->normal = normal;
  1888. return ret;
  1889. }
  1890. bool MeshRoad::collideRay( const Point3F &origin, const Point3F &direction, U32 *nodeIdx, Point3F *collisionPnt )
  1891. {
  1892. Point3F p0 = origin;
  1893. Point3F p1 = origin + direction * 2000.0f;
  1894. // If the line segment does not collide with the MeshRoad's world box,
  1895. // it definitely does not collide with any part of the river.
  1896. if ( !getWorldBox().collideLine( p0, p1 ) )
  1897. return false;
  1898. if ( mSlices.size() < 2 )
  1899. return false;
  1900. MathUtils::Quad quad;
  1901. MathUtils::Ray ray;
  1902. F32 t;
  1903. // Check each road segment (formed by a pair of slices) for collision
  1904. // with the line segment.
  1905. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1906. {
  1907. const MeshRoadSlice &slice0 = mSlices[i];
  1908. const MeshRoadSlice &slice1 = mSlices[i+1];
  1909. // For simplicities sake we will only test for collision between the
  1910. // line segment and the Top face of the river segment.
  1911. // Clockwise starting with the leftmost/closest point.
  1912. quad.p00 = slice0.p0;
  1913. quad.p01 = slice1.p0;
  1914. quad.p11 = slice1.p2;
  1915. quad.p10 = slice0.p2;
  1916. ray.origin = origin;
  1917. ray.direction = direction;
  1918. if ( MathUtils::mRayQuadCollide( quad, ray, NULL, &t ) )
  1919. {
  1920. if ( nodeIdx )
  1921. *nodeIdx = slice0.parentNodeIdx;
  1922. if ( collisionPnt )
  1923. *collisionPnt = ray.origin + ray.direction * t;
  1924. return true;
  1925. }
  1926. }
  1927. return false;
  1928. }
  1929. void MeshRoad::regenerate()
  1930. {
  1931. _regenerate();
  1932. setMaskBits( RegenMask );
  1933. }
  1934. //-------------------------------------------------------------------------
  1935. // Console Methods
  1936. //-------------------------------------------------------------------------
  1937. DefineEngineMethod( MeshRoad, setNodeDepth, void, ( S32 idx, F32 meters ),,
  1938. "Intended as a helper to developers and editor scripts.\n"
  1939. "Sets the depth in meters of a particular node."
  1940. )
  1941. {
  1942. object->setNodeDepth( idx, meters );
  1943. }
  1944. DefineEngineMethod( MeshRoad, regenerate, void, (),,
  1945. "Intended as a helper to developers and editor scripts.\n"
  1946. "Force MeshRoad to recreate its geometry."
  1947. )
  1948. {
  1949. object->regenerate();
  1950. }
  1951. DefineEngineMethod( MeshRoad, postApply, void, (),,
  1952. "Intended as a helper to developers and editor scripts.\n"
  1953. "Force trigger an inspectPostApply. This will transmit "
  1954. "material and other fields ( not including nodes ) to client objects."
  1955. )
  1956. {
  1957. object->inspectPostApply();
  1958. }
  1959. bool MeshRoad::buildPolyList_TopSurfaceOnly = false;
  1960. bool MeshRoad::buildTopPolyList(PolyListContext plc, AbstractPolyList* polyList)
  1961. {
  1962. static Box3F box_prox; static SphereF ball_prox;
  1963. buildPolyList_TopSurfaceOnly = true;
  1964. bool result = buildPolyList(plc, polyList, box_prox, ball_prox);
  1965. buildPolyList_TopSurfaceOnly = false;
  1966. return result;
  1967. }