meshRoad.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  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->object = 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. }
  517. MeshRoad::~MeshRoad()
  518. {
  519. delete mConvexList;
  520. mConvexList = NULL;
  521. }
  522. void MeshRoad::initPersistFields()
  523. {
  524. addGroup( "MeshRoad" );
  525. addField( "topMaterial", TypeMaterialName, Offset( mMaterialName[Top], MeshRoad ),
  526. "Material for the upper surface of the road." );
  527. addField( "bottomMaterial", TypeMaterialName, Offset( mMaterialName[Bottom], MeshRoad ),
  528. "Material for the bottom surface of the road." );
  529. addField( "sideMaterial", TypeMaterialName, Offset( mMaterialName[Side], MeshRoad ),
  530. "Material for the left, right, front, and back surfaces of the road." );
  531. addField( "textureLength", TypeF32, Offset( mTextureLength, MeshRoad ),
  532. "The length in meters of textures mapped to the MeshRoad." );
  533. addField( "breakAngle", TypeF32, Offset( mBreakAngle, MeshRoad ),
  534. "Angle in degrees - MeshRoad will subdivide the spline if its curve is greater than this threshold." );
  535. addField( "widthSubdivisions", TypeS32, Offset( mWidthSubdivisions, MeshRoad ),
  536. "Subdivide segments widthwise this many times when generating vertices." );
  537. endGroup( "MeshRoad" );
  538. addGroup( "Internal" );
  539. addProtectedField( "Node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn,
  540. "Do not modify, for internal use." );
  541. endGroup( "Internal" );
  542. Parent::initPersistFields();
  543. }
  544. void MeshRoad::consoleInit()
  545. {
  546. Parent::consoleInit();
  547. Con::addVariable( "$MeshRoad::EditorOpen", TypeBool, &MeshRoad::smEditorOpen, "True if the MeshRoad editor is open, otherwise false.\n"
  548. "@ingroup Editors\n");
  549. Con::addVariable( "$MeshRoad::wireframe", TypeBool, &MeshRoad::smWireframe, "If true, will render the wireframe of the road.\n"
  550. "@ingroup Editors\n");
  551. Con::addVariable( "$MeshRoad::showBatches", TypeBool, &MeshRoad::smShowBatches, "Determines if the debug rendering of the batches cubes is displayed or not.\n"
  552. "@ingroup Editors\n");
  553. Con::addVariable( "$MeshRoad::showSpline", TypeBool, &MeshRoad::smShowSpline, "If true, the spline on which the curvature of this road is based will be rendered.\n"
  554. "@ingroup Editors\n");
  555. 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"
  556. "@ingroup Editors\n");
  557. }
  558. bool MeshRoad::addNodeFromField( void *object, const char *index, const char *data )
  559. {
  560. MeshRoad *pObj = static_cast<MeshRoad*>(object);
  561. //if ( !pObj->isProperlyAdded() )
  562. //{
  563. F32 width, depth;
  564. Point3F pos, normal;
  565. 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 );
  566. if ( result == 8 )
  567. pObj->_addNode( pos, width, depth, normal );
  568. //}
  569. return false;
  570. }
  571. bool MeshRoad::onAdd()
  572. {
  573. if ( !Parent::onAdd() )
  574. return false;
  575. // Reset the World Box.
  576. //setGlobalBounds();
  577. resetWorldBox();
  578. // Set the Render Transform.
  579. setRenderTransform(mObjToWorld);
  580. // Add to ServerMeshRoadSet
  581. if ( isServerObject() )
  582. {
  583. getServerSet()->addObject( this );
  584. }
  585. if ( isClientObject() )
  586. _initMaterial();
  587. // Generate the Vert/Index buffers and everything else.
  588. _regenerate();
  589. // Add to Scene.
  590. addToScene();
  591. return true;
  592. }
  593. void MeshRoad::onRemove()
  594. {
  595. SAFE_DELETE( mPhysicsRep );
  596. mConvexList->nukeList();
  597. for ( U32 i = 0; i < SurfaceCount; i++ )
  598. {
  599. SAFE_DELETE( mMatInst[i] );
  600. }
  601. removeFromScene();
  602. Parent::onRemove();
  603. }
  604. void MeshRoad::inspectPostApply()
  605. {
  606. // Set Parent.
  607. Parent::inspectPostApply();
  608. //if ( mMetersPerSegment < MIN_METERS_PER_SEGMENT )
  609. // mMetersPerSegment = MIN_METERS_PER_SEGMENT;
  610. setMaskBits(MeshRoadMask);
  611. }
  612. void MeshRoad::onStaticModified( const char* slotName, const char*newValue )
  613. {
  614. Parent::onStaticModified( slotName, newValue );
  615. if ( dStricmp( slotName, "breakAngle" ) == 0 )
  616. {
  617. setMaskBits( RegenMask );
  618. }
  619. }
  620. void MeshRoad::writeFields( Stream &stream, U32 tabStop )
  621. {
  622. Parent::writeFields( stream, tabStop );
  623. // Now write all nodes
  624. stream.write(2, "\r\n");
  625. for ( U32 i = 0; i < mNodes.size(); i++ )
  626. {
  627. const MeshRoadNode &node = mNodes[i];
  628. stream.writeTabs(tabStop);
  629. char buffer[1024];
  630. dMemset( buffer, 0, 1024 );
  631. 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 );
  632. stream.writeLine( (const U8*)buffer );
  633. }
  634. }
  635. bool MeshRoad::writeField( StringTableEntry fieldname, const char *value )
  636. {
  637. if ( fieldname == StringTable->insert("Node") )
  638. return false;
  639. return Parent::writeField( fieldname, value );
  640. }
  641. void MeshRoad::onEditorEnable()
  642. {
  643. }
  644. void MeshRoad::onEditorDisable()
  645. {
  646. }
  647. SimSet* MeshRoad::getServerSet()
  648. {
  649. if ( !smServerMeshRoadSet )
  650. {
  651. smServerMeshRoadSet = new SimSet();
  652. smServerMeshRoadSet->registerObject( "ServerMeshRoadSet" );
  653. Sim::getRootGroup()->addObject( smServerMeshRoadSet );
  654. }
  655. return smServerMeshRoadSet;
  656. }
  657. void MeshRoad::prepRenderImage( SceneRenderState* state )
  658. {
  659. if ( mNodes.size() <= 1 )
  660. return;
  661. RenderPassManager *renderPass = state->getRenderPass();
  662. // Normal Road RenderInstance
  663. // Always rendered when the editor is not open
  664. // otherwise obey the smShowRoad flag
  665. if ( smShowRoad || !smEditorOpen )
  666. {
  667. #ifdef TORQUE_AFX_ENABLED
  668. afxZodiacMgr::renderMeshRoadZodiacs(state, this);
  669. #endif
  670. MeshRenderInst coreRI;
  671. coreRI.clear();
  672. coreRI.objectToWorld = &MatrixF::Identity;
  673. coreRI.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  674. coreRI.projection = renderPass->allocSharedXform(RenderPassManager::Projection);
  675. coreRI.type = RenderPassManager::RIT_Mesh;
  676. BaseMatInstance *matInst;
  677. for ( U32 i = 0; i < SurfaceCount; i++ )
  678. {
  679. matInst = state->getOverrideMaterial( mMatInst[i] );
  680. if ( !matInst )
  681. continue;
  682. // Get the lights if we haven't already.
  683. if ( matInst->isForwardLit() && !coreRI.lights[0] )
  684. {
  685. LightQuery query;
  686. query.init( getWorldSphere() );
  687. query.getLights( coreRI.lights, 8 );
  688. }
  689. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  690. *ri = coreRI;
  691. // Currently rendering whole road, fix to cull and batch
  692. // per segment.
  693. // Set the correct material for rendering.
  694. ri->matInst = matInst;
  695. ri->vertBuff = &mVB[i];
  696. ri->primBuff = &mPB[i];
  697. ri->prim = renderPass->allocPrim();
  698. ri->prim->type = GFXTriangleList;
  699. ri->prim->minIndex = 0;
  700. ri->prim->startIndex = 0;
  701. ri->prim->numPrimitives = mTriangleCount[i];
  702. ri->prim->startVertex = 0;
  703. ri->prim->numVertices = mVertCount[i];
  704. // We sort by the material then vertex buffer.
  705. ri->defaultKey = matInst->getStateHint();
  706. ri->defaultKey2 = (uintptr_t)ri->vertBuff; // Not 64bit safe!
  707. renderPass->addInst( ri );
  708. }
  709. }
  710. // Debug RenderInstance
  711. // Only when editor is open.
  712. if ( smEditorOpen )
  713. {
  714. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  715. ri->renderDelegate.bind( this, &MeshRoad::_debugRender );
  716. ri->type = RenderPassManager::RIT_Editor;
  717. state->getRenderPass()->addInst( ri );
  718. }
  719. }
  720. void MeshRoad::_initMaterial()
  721. {
  722. for ( U32 i = 0; i < SurfaceCount; i++ )
  723. {
  724. if ( mMatInst[i] )
  725. SAFE_DELETE( mMatInst[i] );
  726. if ( mMaterial[i] )
  727. mMatInst[i] = mMaterial[i]->createMatInstance();
  728. else
  729. mMatInst[i] = MATMGR->createMatInstance( "WarningMaterial" );
  730. mMatInst[i]->init( MATMGR->getDefaultFeatures(), getGFXVertexFormat<GFXVertexPNTT>() );
  731. }
  732. }
  733. void MeshRoad::_debugRender( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* )
  734. {
  735. //MeshRoadConvex convex;
  736. //buildConvex( Box3F(true), convex );
  737. //convex.render();
  738. //GFXDrawUtil *drawer = GFX->getDrawUtil();
  739. //GFX->setStateBlock( smStateBlock );
  740. return;
  741. /*
  742. U32 convexCount = mDebugConvex.size();
  743. PrimBuild::begin( GFXTriangleList, convexCount * 12 );
  744. PrimBuild::color4i( 0, 0, 255, 155 );
  745. for ( U32 i = 0; i < convexCount; i++ )
  746. {
  747. MeshRoadConvex *convex = mDebugConvex[i];
  748. Point3F a = convex->verts[0];
  749. Point3F b = convex->verts[1];
  750. Point3F c = convex->verts[2];
  751. Point3F p = convex->verts[3];
  752. //mObjToWorld.mulP(a);
  753. //mObjToWorld.mulP(b);
  754. //mObjToWorld.mulP(c);
  755. //mObjToWorld.mulP(p);
  756. PrimBuild::vertex3fv( c );
  757. PrimBuild::vertex3fv( b );
  758. PrimBuild::vertex3fv( a );
  759. PrimBuild::vertex3fv( b );
  760. PrimBuild::vertex3fv( a );
  761. PrimBuild::vertex3fv( p );
  762. PrimBuild::vertex3fv( c );
  763. PrimBuild::vertex3fv( b );
  764. PrimBuild::vertex3fv( p );
  765. PrimBuild::vertex3fv( a );
  766. PrimBuild::vertex3fv( c );
  767. PrimBuild::vertex3fv( p );
  768. }
  769. PrimBuild::end();
  770. for ( U32 i = 0; i < mSegments.size(); i++ )
  771. {
  772. ///GFX->getDrawUtil()->drawWireBox( mSegments[i].worldbounds, ColorI(255,0,0,255) );
  773. }
  774. GFX->enterDebugEvent( ColorI( 255, 0, 0 ), "DecalRoad_debugRender" );
  775. GFXTransformSaver saver;
  776. GFX->setStateBlock( smStateBlock );
  777. Point3F size(1,1,1);
  778. ColorI color( 255, 0, 0, 255 );
  779. if ( smShowBatches )
  780. {
  781. for ( U32 i = 0; i < mBatches.size(); i++ )
  782. {
  783. const Box3F &box = mBatches[i].bounds;
  784. Point3F center;
  785. box.getCenter( &center );
  786. GFX->getDrawUtil()->drawWireCube( ( box.maxExtents - box.minExtents ) * 0.5f, center, ColorI(255,100,100,255) );
  787. }
  788. }
  789. GFX->leaveDebugEvent();
  790. */
  791. }
  792. U32 MeshRoad::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  793. {
  794. U32 retMask = Parent::packUpdate(con, mask, stream);
  795. if ( stream->writeFlag( mask & MeshRoadMask ) )
  796. {
  797. // Write Object Transform.
  798. stream->writeAffineTransform( mObjToWorld );
  799. // Write Materials
  800. stream->write( mMaterialName[0] );
  801. stream->write( mMaterialName[1] );
  802. stream->write( mMaterialName[2] );
  803. stream->write( mTextureLength );
  804. stream->write( mBreakAngle );
  805. stream->write( mWidthSubdivisions );
  806. }
  807. if ( stream->writeFlag( mask & NodeMask ) )
  808. {
  809. const U32 nodeByteSize = 32; // Based on sending all of a node's parameters
  810. // Test if we can fit all of our nodes within the current stream.
  811. // We make sure we leave 100 bytes still free in the stream for whatever
  812. // may follow us.
  813. S32 allowedBytes = stream->getWriteByteSize() - 100;
  814. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  815. {
  816. // All nodes should fit, so send them out now.
  817. stream->writeInt( mNodes.size(), 16 );
  818. for ( U32 i = 0; i < mNodes.size(); i++ )
  819. {
  820. mathWrite( *stream, mNodes[i].point );
  821. stream->write( mNodes[i].width );
  822. stream->write( mNodes[i].depth );
  823. mathWrite( *stream, mNodes[i].normal );
  824. }
  825. }
  826. else
  827. {
  828. // There isn't enough space left in the stream for all of the
  829. // nodes. Batch them up into NetEvents.
  830. U32 id = gServerNodeListManager->nextListId();
  831. U32 count = 0;
  832. U32 index = 0;
  833. while (count < mNodes.size())
  834. {
  835. count += NodeListManager::smMaximumNodesPerEvent;
  836. if (count > mNodes.size())
  837. {
  838. count = mNodes.size();
  839. }
  840. MeshRoadNodeEvent* event = new MeshRoadNodeEvent();
  841. event->mId = id;
  842. event->mTotalNodes = mNodes.size();
  843. event->mLocalListStart = index;
  844. for (; index<count; ++index)
  845. {
  846. event->mPositions.push_back( mNodes[index].point );
  847. event->mWidths.push_back( mNodes[index].width );
  848. event->mDepths.push_back( mNodes[index].depth );
  849. event->mNormals.push_back( mNodes[index].normal );
  850. }
  851. con->postNetEvent( event );
  852. }
  853. stream->write( id );
  854. }
  855. }
  856. stream->writeFlag( mask & RegenMask );
  857. // Were done ...
  858. return retMask;
  859. }
  860. void MeshRoad::unpackUpdate(NetConnection * con, BitStream * stream)
  861. {
  862. // Unpack Parent.
  863. Parent::unpackUpdate(con, stream);
  864. // MeshRoadMask
  865. if(stream->readFlag())
  866. {
  867. MatrixF ObjectMatrix;
  868. stream->readAffineTransform(&ObjectMatrix);
  869. Parent::setTransform(ObjectMatrix);
  870. // Read Materials...
  871. Material *pMat = NULL;
  872. for ( U32 i = 0; i < SurfaceCount; i++ )
  873. {
  874. stream->read( &mMaterialName[i] );
  875. if ( !Sim::findObject( mMaterialName[i], pMat ) )
  876. Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name %s", mMaterialName[i].c_str() );
  877. else
  878. mMaterial[i] = pMat;
  879. }
  880. if ( isProperlyAdded() )
  881. _initMaterial();
  882. stream->read( &mTextureLength );
  883. stream->read( &mBreakAngle );
  884. stream->read( &mWidthSubdivisions );
  885. }
  886. // NodeMask
  887. if ( stream->readFlag() )
  888. {
  889. if (stream->readFlag())
  890. {
  891. // Nodes have been passed in this update
  892. U32 count = stream->readInt( 16 );
  893. mNodes.clear();
  894. Point3F pos, normal;
  895. F32 width, depth;
  896. for ( U32 i = 0; i < count; i++ )
  897. {
  898. mathRead( *stream, &pos );
  899. stream->read( &width );
  900. stream->read( &depth );
  901. mathRead( *stream, &normal );
  902. _addNode( pos, width, depth, normal );
  903. }
  904. }
  905. else
  906. {
  907. // Nodes will arrive as events
  908. U32 id;
  909. stream->read( &id );
  910. // Check if the road's nodes made it here before we did.
  911. NodeListManager::NodeList* list = NULL;
  912. if ( gClientNodeListManager->findListById( id, &list, true) )
  913. {
  914. // Work with the completed list
  915. MeshRoadNodeList* roadList = dynamic_cast<MeshRoadNodeList*>( list );
  916. if (roadList)
  917. buildNodesFromList( roadList );
  918. delete list;
  919. }
  920. else
  921. {
  922. // Nodes have not yet arrived, so register our interest in the list
  923. MeshRoadNodeListNotify* notify = new MeshRoadNodeListNotify( this, id );
  924. gClientNodeListManager->registerNotification( notify );
  925. }
  926. }
  927. }
  928. if ( stream->readFlag() && isProperlyAdded() )
  929. _regenerate();
  930. }
  931. void MeshRoad::setTransform( const MatrixF &mat )
  932. {
  933. for ( U32 i = 0; i < mNodes.size(); i++ )
  934. {
  935. mWorldToObj.mulP( mNodes[i].point );
  936. mat.mulP( mNodes[i].point );
  937. }
  938. Parent::setTransform( mat );
  939. if ( mPhysicsRep )
  940. mPhysicsRep->setTransform( mat );
  941. // Regenerate and update the client
  942. _regenerate();
  943. setMaskBits( NodeMask | RegenMask );
  944. }
  945. void MeshRoad::setScale( const VectorF &scale )
  946. {
  947. // We ignore scale requests from the editor
  948. // right now.
  949. //Parent::setScale( scale );
  950. }
  951. void MeshRoad::buildConvex(const Box3F& box, Convex* convex)
  952. {
  953. if ( mSlices.size() < 2 )
  954. return;
  955. mConvexList->collectGarbage();
  956. mDebugConvex.clear();
  957. Box3F realBox = box;
  958. mWorldToObj.mul(realBox);
  959. realBox.minExtents.convolveInverse(mObjScale);
  960. realBox.maxExtents.convolveInverse(mObjScale);
  961. if (realBox.isOverlapped(getObjBox()) == false)
  962. return;
  963. U32 segmentCount = mSegments.size();
  964. // Create convex(s) for each segment
  965. for ( U32 i = 0; i < segmentCount; i++ )
  966. {
  967. const MeshRoadSegment &segment = mSegments[i];
  968. // Is this segment overlapped?
  969. if ( !segment.getWorldBounds().isOverlapped( box ) )
  970. continue;
  971. // Each segment has 6 faces
  972. for ( U32 j = 0; j < 6; j++ )
  973. {
  974. // Only first segment has front face
  975. if ( j == 4 && i != 0 )
  976. continue;
  977. // Only last segment has back face
  978. if ( j == 5 && i != segmentCount-1 )
  979. continue;
  980. // Each face has 2 convex(s)
  981. for ( U32 k = 0; k < 2; k++ )
  982. {
  983. // See if this convex exists in the working set already...
  984. Convex* cc = 0;
  985. CollisionWorkingList& wl = convex->getWorkingList();
  986. for ( CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext )
  987. {
  988. if ( itr->mConvex->getType() == MeshRoadConvexType )
  989. {
  990. MeshRoadConvex *pConvex = static_cast<MeshRoadConvex*>(itr->mConvex);
  991. if ( pConvex->pRoad == this &&
  992. pConvex->segmentId == i &&
  993. pConvex->faceId == j &&
  994. pConvex->triangleId == k )
  995. {
  996. cc = itr->mConvex;
  997. break;
  998. }
  999. }
  1000. }
  1001. if (cc)
  1002. continue;
  1003. // Get the triangle...
  1004. U32 idx0 = gIdxArray[j][k][0];
  1005. U32 idx1 = gIdxArray[j][k][1];
  1006. U32 idx2 = gIdxArray[j][k][2];
  1007. Point3F a = segment[idx0];
  1008. Point3F b = segment[idx1];
  1009. Point3F c = segment[idx2];
  1010. // Transform the result into object space!
  1011. //mWorldToObj.mulP( a );
  1012. //mWorldToObj.mulP( b );
  1013. //mWorldToObj.mulP( c );
  1014. PlaneF p( c, b, a );
  1015. Point3F peak = ((a + b + c) / 3.0f) + (p * 0.15f);
  1016. // Set up the convex...
  1017. MeshRoadConvex *cp = new MeshRoadConvex();
  1018. mConvexList->registerObject( cp );
  1019. convex->addToWorkingList( cp );
  1020. cp->mObject = this;
  1021. cp->pRoad = this;
  1022. cp->segmentId = i;
  1023. cp->faceId = j;
  1024. cp->triangleId = k;
  1025. cp->normal = p;
  1026. cp->verts[0] = c;
  1027. cp->verts[1] = b;
  1028. cp->verts[2] = a;
  1029. cp->verts[3] = peak;
  1030. // Update the bounding box.
  1031. Box3F &bounds = cp->box;
  1032. bounds.minExtents.set( F32_MAX, F32_MAX, F32_MAX );
  1033. bounds.maxExtents.set( -F32_MAX, -F32_MAX, -F32_MAX );
  1034. bounds.minExtents.setMin( a );
  1035. bounds.minExtents.setMin( b );
  1036. bounds.minExtents.setMin( c );
  1037. bounds.minExtents.setMin( peak );
  1038. bounds.maxExtents.setMax( a );
  1039. bounds.maxExtents.setMax( b );
  1040. bounds.maxExtents.setMax( c );
  1041. bounds.maxExtents.setMax( peak );
  1042. mDebugConvex.push_back(cp);
  1043. }
  1044. }
  1045. }
  1046. }
  1047. bool MeshRoad::buildPolyList( PolyListContext, AbstractPolyList* polyList, const Box3F &box, const SphereF & )
  1048. {
  1049. if ( mSlices.size() < 2 )
  1050. return false;
  1051. polyList->setTransform( &MatrixF::Identity, Point3F::One );
  1052. polyList->setObject(this);
  1053. // JCF: optimize this to not always add everything.
  1054. return buildSegmentPolyList( polyList, 0, mSegments.size() - 1, true, true );
  1055. }
  1056. bool MeshRoad::buildSegmentPolyList( AbstractPolyList* polyList, U32 startSegIdx, U32 endSegIdx, bool capFront, bool capEnd )
  1057. {
  1058. if ( mSlices.size() < 2 )
  1059. return false;
  1060. // Add verts
  1061. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1062. {
  1063. const MeshRoadSegment &seg = mSegments[i];
  1064. if ( i == startSegIdx )
  1065. {
  1066. polyList->addPoint( seg.slice0->p0 );
  1067. polyList->addPoint( seg.slice0->p2 );
  1068. polyList->addPoint( seg.slice0->pb0 );
  1069. polyList->addPoint( seg.slice0->pb2 );
  1070. }
  1071. polyList->addPoint( seg.slice1->p0 );
  1072. polyList->addPoint( seg.slice1->p2 );
  1073. polyList->addPoint( seg.slice1->pb0 );
  1074. polyList->addPoint( seg.slice1->pb2 );
  1075. }
  1076. // Temporaries to hold indices for the corner points of a quad.
  1077. S32 p00, p01, p11, p10;
  1078. S32 pb00, pb01, pb11, pb10;
  1079. U32 offset = 0;
  1080. DebugDrawer *ddraw = NULL;//DebugDrawer::get();
  1081. ClippedPolyList *cpolyList = dynamic_cast<ClippedPolyList*>(polyList);
  1082. MatrixF mat;
  1083. Point3F scale;
  1084. if ( cpolyList )
  1085. cpolyList->getTransform( &mat, &scale );
  1086. for ( U32 i = startSegIdx; i <= endSegIdx; i++ )
  1087. {
  1088. p00 = offset;
  1089. p10 = offset + 1;
  1090. pb00 = offset + 2;
  1091. pb10 = offset + 3;
  1092. p01 = offset + 4;
  1093. p11 = offset + 5;
  1094. pb01 = offset + 6;
  1095. pb11 = offset + 7;
  1096. // Top Face
  1097. polyList->begin( 0,0 );
  1098. polyList->vertex( p00 );
  1099. polyList->vertex( p01 );
  1100. polyList->vertex( p11 );
  1101. polyList->plane( p00, p01, p11 );
  1102. polyList->end();
  1103. if ( ddraw && cpolyList )
  1104. {
  1105. Point3F v0 = cpolyList->mVertexList[p00].point;
  1106. mat.mulP( v0 );
  1107. Point3F v1 = cpolyList->mVertexList[p01].point;
  1108. mat.mulP( v1 );
  1109. Point3F v2 = cpolyList->mVertexList[p11].point;
  1110. mat.mulP( v2 );
  1111. ddraw->drawTri( v0, v1, v2 );
  1112. ddraw->setLastZTest( false );
  1113. ddraw->setLastTTL( 0 );
  1114. }
  1115. polyList->begin( 0,0 );
  1116. polyList->vertex( p00 );
  1117. polyList->vertex( p11 );
  1118. polyList->vertex( p10 );
  1119. polyList->plane( p00, p11, p10 );
  1120. polyList->end();
  1121. if ( ddraw && cpolyList )
  1122. {
  1123. ddraw->drawTri( cpolyList->mVertexList[p00].point, cpolyList->mVertexList[p11].point, cpolyList->mVertexList[p10].point );
  1124. ddraw->setLastTTL( 0 );
  1125. }
  1126. if (buildPolyList_TopSurfaceOnly)
  1127. {
  1128. offset += 4;
  1129. continue;
  1130. }
  1131. // Left Face
  1132. polyList->begin( 0,0 );
  1133. polyList->vertex( pb00 );
  1134. polyList->vertex( pb01 );
  1135. polyList->vertex( p01 );
  1136. polyList->plane( pb00, pb01, p01 );
  1137. polyList->end();
  1138. polyList->begin( 0,0 );
  1139. polyList->vertex( pb00 );
  1140. polyList->vertex( p01 );
  1141. polyList->vertex( p00 );
  1142. polyList->plane( pb00, p01, p00 );
  1143. polyList->end();
  1144. // Right Face
  1145. polyList->begin( 0,0 );
  1146. polyList->vertex( p10 );
  1147. polyList->vertex( p11 );
  1148. polyList->vertex( pb11 );
  1149. polyList->plane( p10, p11, pb11 );
  1150. polyList->end();
  1151. polyList->begin( 0,0 );
  1152. polyList->vertex( p10 );
  1153. polyList->vertex( pb11 );
  1154. polyList->vertex( pb10 );
  1155. polyList->plane( p10, pb11, pb10 );
  1156. polyList->end();
  1157. // Bottom Face
  1158. polyList->begin( 0,0 );
  1159. polyList->vertex( pb00 );
  1160. polyList->vertex( pb10 );
  1161. polyList->vertex( pb11 );
  1162. polyList->plane( pb00, pb10, pb11 );
  1163. polyList->end();
  1164. polyList->begin( 0,0 );
  1165. polyList->vertex( pb00 );
  1166. polyList->vertex( pb11 );
  1167. polyList->vertex( pb01 );
  1168. polyList->plane( pb00, pb11, pb01 );
  1169. polyList->end();
  1170. // Front Face
  1171. if ( i == startSegIdx && capFront )
  1172. {
  1173. polyList->begin( 0,0 );
  1174. polyList->vertex( p00 );
  1175. polyList->vertex( p10 );
  1176. polyList->vertex( pb10 );
  1177. polyList->plane( p00, p10, pb10 );
  1178. polyList->end();
  1179. polyList->begin( 0,0 );
  1180. polyList->vertex( p00 );
  1181. polyList->vertex( pb10 );
  1182. polyList->vertex( pb00 );
  1183. polyList->plane( p00, pb10, pb00 );
  1184. polyList->end();
  1185. }
  1186. // Back Face
  1187. if ( i == endSegIdx && capEnd )
  1188. {
  1189. polyList->begin( 0,0 );
  1190. polyList->vertex( p01 );
  1191. polyList->vertex( pb01 );
  1192. polyList->vertex( pb11 );
  1193. polyList->plane( p01, pb01, pb11 );
  1194. polyList->end();
  1195. polyList->begin( 0,0 );
  1196. polyList->vertex( p01 );
  1197. polyList->vertex( pb11 );
  1198. polyList->vertex( p11 );
  1199. polyList->plane( p01, pb11, p11 );
  1200. polyList->end();
  1201. }
  1202. offset += 4;
  1203. }
  1204. return true;
  1205. }
  1206. bool MeshRoad::castRay( const Point3F &s, const Point3F &e, RayInfo *info )
  1207. {
  1208. Point3F start = s;
  1209. Point3F end = e;
  1210. mObjToWorld.mulP(start);
  1211. mObjToWorld.mulP(end);
  1212. F32 out = 1.0f; // The output fraction/percentage along the line defined by s and e
  1213. VectorF norm(0.0f, 0.0f, 0.0f); // The normal of the face intersected
  1214. Vector<MeshRoadHitSegment> hitSegments;
  1215. for ( U32 i = 0; i < mSegments.size(); i++ )
  1216. {
  1217. const MeshRoadSegment &segment = mSegments[i];
  1218. F32 t;
  1219. VectorF n;
  1220. if ( segment.getWorldBounds().collideLine( start, end, &t, &n ) )
  1221. {
  1222. hitSegments.increment();
  1223. hitSegments.last().t = t;
  1224. hitSegments.last().idx = i;
  1225. }
  1226. }
  1227. dQsort( hitSegments.address(), hitSegments.size(), sizeof(MeshRoadHitSegment), compareHitSegments );
  1228. U32 idx0, idx1, idx2;
  1229. F32 t;
  1230. for ( U32 i = 0; i < hitSegments.size(); i++ )
  1231. {
  1232. U32 segIdx = hitSegments[i].idx;
  1233. const MeshRoadSegment &segment = mSegments[segIdx];
  1234. // Each segment has 6 faces
  1235. for ( U32 j = 0; j < 6; j++ )
  1236. {
  1237. if ( j == 4 && segIdx != 0 )
  1238. continue;
  1239. if ( j == 5 && segIdx != mSegments.size() - 1 )
  1240. continue;
  1241. // Each face has 2 triangles
  1242. for ( U32 k = 0; k < 2; k++ )
  1243. {
  1244. idx0 = gIdxArray[j][k][0];
  1245. idx1 = gIdxArray[j][k][1];
  1246. idx2 = gIdxArray[j][k][2];
  1247. const Point3F &v0 = segment[idx0];
  1248. const Point3F &v1 = segment[idx1];
  1249. const Point3F &v2 = segment[idx2];
  1250. if ( !MathUtils::mLineTriangleCollide( start, end,
  1251. v2, v1, v0,
  1252. NULL,
  1253. &t ) )
  1254. continue;
  1255. if ( t >= 0.0f && t < 1.0f && t < out )
  1256. {
  1257. out = t;
  1258. norm = PlaneF( v0, v1, v2 );
  1259. }
  1260. }
  1261. }
  1262. if (out >= 0.0f && out < 1.0f)
  1263. break;
  1264. }
  1265. if (out >= 0.0f && out < 1.0f)
  1266. {
  1267. info->t = out;
  1268. info->normal = norm;
  1269. info->point.interpolate(start, end, out);
  1270. info->face = -1;
  1271. info->object = this;
  1272. info->material = this->mMatInst[0];
  1273. return true;
  1274. }
  1275. return false;
  1276. }
  1277. bool MeshRoad::collideBox(const Point3F &start, const Point3F &end, RayInfo* info)
  1278. {
  1279. Con::warnf( "MeshRoad::collideBox() - not yet implemented!" );
  1280. return Parent::collideBox( start, end, info );
  1281. }
  1282. void MeshRoad::_regenerate()
  1283. {
  1284. if ( mNodes.size() == 0 )
  1285. return;
  1286. const Point3F &nodePt = mNodes.first().point;
  1287. MatrixF mat( true );
  1288. mat.setPosition( nodePt );
  1289. Parent::setTransform( mat );
  1290. _generateSlices();
  1291. // Make sure we are in the correct bins given our world box.
  1292. if( getSceneManager() != NULL )
  1293. getSceneManager()->notifyObjectDirty( this );
  1294. }
  1295. void MeshRoad::_generateSlices()
  1296. {
  1297. if ( mNodes.size() < 2 )
  1298. return;
  1299. // Create the spline, initialized with the MeshRoadNode(s)
  1300. U32 nodeCount = mNodes.size();
  1301. MeshRoadSplineNode *splineNodes = new MeshRoadSplineNode[nodeCount];
  1302. for ( U32 i = 0; i < nodeCount; i++ )
  1303. {
  1304. MeshRoadSplineNode &splineNode = splineNodes[i];
  1305. const MeshRoadNode &node = mNodes[i];
  1306. splineNode.x = node.point.x;
  1307. splineNode.y = node.point.y;
  1308. splineNode.z = node.point.z;
  1309. splineNode.width = node.width;
  1310. splineNode.depth = node.depth;
  1311. splineNode.normal = node.normal;
  1312. }
  1313. CatmullRom<MeshRoadSplineNode> spline;
  1314. spline.initialize( nodeCount, splineNodes );
  1315. delete [] splineNodes;
  1316. mSlices.clear();
  1317. VectorF lastBreakVector(0,0,0);
  1318. MeshRoadSlice slice;
  1319. MeshRoadSplineNode lastBreakNode;
  1320. lastBreakNode = spline.evaluate(0.0f);
  1321. for ( U32 i = 1; i < mNodes.size(); i++ )
  1322. {
  1323. F32 t1 = spline.getTime(i);
  1324. F32 t0 = spline.getTime(i-1);
  1325. F32 segLength = spline.arcLength( t0, t1 );
  1326. U32 numSegments = mCeil( segLength / MIN_METERS_PER_SEGMENT );
  1327. numSegments = getMax( numSegments, (U32)1 );
  1328. F32 tstep = ( t1 - t0 ) / numSegments;
  1329. U32 startIdx = 0;
  1330. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  1331. for ( U32 j = startIdx; j < endIdx; j++ )
  1332. {
  1333. F32 t = t0 + tstep * j;
  1334. MeshRoadSplineNode splineNode = spline.evaluate(t);
  1335. VectorF toNodeVec = splineNode.getPosition() - lastBreakNode.getPosition();
  1336. toNodeVec.normalizeSafe();
  1337. if ( lastBreakVector.isZero() )
  1338. lastBreakVector = toNodeVec;
  1339. F32 angle = mRadToDeg( mAcos( mDot( toNodeVec, lastBreakVector ) ) );
  1340. if ( j == startIdx ||
  1341. ( j == endIdx - 1 && i == mNodes.size() - 1 ) ||
  1342. angle > mBreakAngle )
  1343. {
  1344. // Push back a spline node
  1345. slice.p1.set( splineNode.x, splineNode.y, splineNode.z );
  1346. slice.width = splineNode.width;
  1347. slice.depth = splineNode.depth;
  1348. slice.normal = splineNode.normal;
  1349. slice.normal.normalize();
  1350. slice.parentNodeIdx = i-1;
  1351. slice.t = t;
  1352. mSlices.push_back( slice );
  1353. lastBreakVector = splineNode.getPosition() - lastBreakNode.getPosition();
  1354. lastBreakVector.normalizeSafe();
  1355. lastBreakNode = splineNode;
  1356. }
  1357. }
  1358. }
  1359. MatrixF mat(true);
  1360. Box3F box;
  1361. for ( U32 i = 0; i < mSlices.size(); i++ )
  1362. {
  1363. // Calculate uvec, fvec, and rvec for all slices
  1364. calcSliceTransform( i, mat );
  1365. MeshRoadSlice *slicePtr = &mSlices[i];
  1366. mat.getColumn( 0, &slicePtr->rvec );
  1367. mat.getColumn( 1, &slicePtr->fvec );
  1368. mat.getColumn( 2, &slicePtr->uvec );
  1369. // Calculate p0/p2/pb0/pb2 for all slices
  1370. slicePtr->p0 = slicePtr->p1 - slicePtr->rvec * slicePtr->width * 0.5f;
  1371. slicePtr->p2 = slicePtr->p1 + slicePtr->rvec * slicePtr->width * 0.5f;
  1372. slicePtr->pb0 = slicePtr->p0 - slicePtr->uvec * slicePtr->depth;
  1373. slicePtr->pb2 = slicePtr->p2 - slicePtr->uvec * slicePtr->depth;
  1374. // Generate or extend the object/world bounds
  1375. if ( i == 0 )
  1376. {
  1377. box.minExtents = slicePtr->p0;
  1378. box.maxExtents = slicePtr->p2;
  1379. box.extend(slicePtr->pb0 );
  1380. box.extend(slicePtr->pb2 );
  1381. }
  1382. else
  1383. {
  1384. box.extend(slicePtr->p0 );
  1385. box.extend(slicePtr->p2 );
  1386. box.extend(slicePtr->pb0 );
  1387. box.extend(slicePtr->pb2 );
  1388. }
  1389. }
  1390. mWorldBox = box;
  1391. resetObjectBox();
  1392. _generateSegments();
  1393. }
  1394. void MeshRoad::_generateSegments()
  1395. {
  1396. SAFE_DELETE( mPhysicsRep );
  1397. mSegments.clear();
  1398. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1399. {
  1400. MeshRoadSegment seg( &mSlices[i], &mSlices[i+1], getWorldTransform() );
  1401. mSegments.push_back( seg );
  1402. }
  1403. if ( isClientObject() )
  1404. _generateVerts();
  1405. if ( PHYSICSMGR )
  1406. {
  1407. ConcretePolyList polylist;
  1408. if ( buildPolyList( PLC_Collision, &polylist, getWorldBox(), getWorldSphere() ) )
  1409. {
  1410. polylist.triangulate();
  1411. PhysicsCollision *colShape = PHYSICSMGR->createCollision();
  1412. colShape->addTriangleMesh( polylist.mVertexList.address(),
  1413. polylist.mVertexList.size(),
  1414. polylist.mIndexList.address(),
  1415. polylist.mIndexList.size() / 3,
  1416. MatrixF::Identity );
  1417. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  1418. mPhysicsRep = PHYSICSMGR->createBody();
  1419. mPhysicsRep->init( colShape, 0, 0, this, world );
  1420. }
  1421. }
  1422. }
  1423. void MeshRoad::_generateVerts()
  1424. {
  1425. const U32 widthDivisions = getMax( 0, mWidthSubdivisions );
  1426. const F32 divisionStep = 1.0f / (F32)( widthDivisions + 1 );
  1427. const U32 sliceCount = mSlices.size();
  1428. const U32 segmentCount = mSegments.size();
  1429. mVertCount[Top] = ( 2 + widthDivisions ) * sliceCount;
  1430. mTriangleCount[Top] = segmentCount * 2 * ( widthDivisions + 1 );
  1431. mVertCount[Bottom] = sliceCount * 2;
  1432. mTriangleCount[Bottom] = segmentCount * 2;
  1433. mVertCount[Side] = sliceCount * 4;
  1434. mTriangleCount[Side] = segmentCount * 4 + 4;
  1435. // Calculate TexCoords for Slices
  1436. F32 texCoordV = 0.0f;
  1437. mSlices[0].texCoordV = 0.0f;
  1438. for ( U32 i = 1; i < sliceCount; i++ )
  1439. {
  1440. MeshRoadSlice &slice = mSlices[i];
  1441. MeshRoadSlice &prevSlice = mSlices[i-1];
  1442. // Increment the textCoordV for the next slice.
  1443. F32 len = ( slice.p1 - prevSlice.p1 ).len();
  1444. texCoordV += len / mTextureLength;
  1445. slice.texCoordV = texCoordV;
  1446. }
  1447. // Make Vertex Buffers
  1448. GFXVertexPNTT *pVert = NULL;
  1449. U32 vertCounter = 0;
  1450. // Top Buffers...
  1451. mVB[Top].set( GFX, mVertCount[Top], GFXBufferTypeStatic );
  1452. pVert = mVB[Top].lock();
  1453. vertCounter = 0;
  1454. for ( U32 i = 0; i < sliceCount; i++ )
  1455. {
  1456. MeshRoadSlice &slice = mSlices[i];
  1457. pVert->point = slice.p0;
  1458. pVert->normal = slice.uvec;
  1459. pVert->tangent = slice.fvec;
  1460. pVert->texCoord.set(1,slice.texCoordV);
  1461. pVert++;
  1462. vertCounter++;
  1463. for ( U32 j = 0; j < widthDivisions; j++ )
  1464. {
  1465. const F32 t = divisionStep * (F32)( j + 1 );
  1466. pVert->point.interpolate( slice.p0, slice.p2, t );
  1467. pVert->normal = slice.uvec;
  1468. pVert->tangent = slice.fvec;
  1469. pVert->texCoord.set( 1.0f - t, slice.texCoordV );
  1470. pVert++;
  1471. vertCounter++;
  1472. }
  1473. pVert->point = slice.p2;
  1474. pVert->normal = slice.uvec;
  1475. pVert->tangent = slice.fvec;
  1476. pVert->texCoord.set( 0, slice.texCoordV );
  1477. pVert++;
  1478. vertCounter++;
  1479. }
  1480. AssertFatal( vertCounter == mVertCount[Top], "MeshRoad, wrote incorrect number of verts in mVB[Top]!" );
  1481. mVB[Top].unlock();
  1482. // Bottom Buffer...
  1483. mVB[Bottom].set( GFX, mVertCount[Bottom], GFXBufferTypeStatic );
  1484. pVert = mVB[Bottom].lock();
  1485. vertCounter = 0;
  1486. for ( U32 i = 0; i < sliceCount; i++ )
  1487. {
  1488. MeshRoadSlice &slice = mSlices[i];
  1489. pVert->point = slice.pb2;
  1490. pVert->normal = -slice.uvec;
  1491. pVert->tangent = slice.fvec;
  1492. pVert->texCoord.set(0,slice.texCoordV);
  1493. pVert++;
  1494. vertCounter++;
  1495. pVert->point = slice.pb0;
  1496. pVert->normal = -slice.uvec;
  1497. pVert->tangent = slice.fvec;
  1498. pVert->texCoord.set(1,slice.texCoordV);
  1499. pVert++;
  1500. vertCounter++;
  1501. }
  1502. AssertFatal( vertCounter == mVertCount[Bottom], "MeshRoad, wrote incorrect number of verts in mVB[Bottom]!" );
  1503. mVB[Bottom].unlock();
  1504. // Side Buffers...
  1505. mVB[Side].set( GFX, mVertCount[Side], GFXBufferTypeStatic );
  1506. pVert = mVB[Side].lock();
  1507. vertCounter = 0;
  1508. for ( U32 i = 0; i < sliceCount; i++ )
  1509. {
  1510. MeshRoadSlice &slice = mSlices[i];
  1511. pVert->point = slice.p0;
  1512. pVert->normal = -slice.rvec;
  1513. pVert->tangent = slice.fvec;
  1514. pVert->texCoord.set(1,slice.texCoordV);
  1515. pVert++;
  1516. vertCounter++;
  1517. pVert->point = slice.p2;
  1518. pVert->normal = slice.rvec;
  1519. pVert->tangent = slice.fvec;
  1520. pVert->texCoord.set(1,slice.texCoordV);
  1521. pVert++;
  1522. vertCounter++;
  1523. pVert->point = slice.pb0;
  1524. pVert->normal = -slice.rvec;
  1525. pVert->tangent = slice.fvec;
  1526. pVert->texCoord.set(0,slice.texCoordV);
  1527. pVert++;
  1528. vertCounter++;
  1529. pVert->point = slice.pb2;
  1530. pVert->normal = slice.rvec;
  1531. pVert->tangent = slice.fvec;
  1532. pVert->texCoord.set(0,slice.texCoordV);
  1533. pVert++;
  1534. vertCounter++;
  1535. }
  1536. AssertFatal( vertCounter == mVertCount[Side], "MeshRoad, wrote incorrect number of verts in mVB[Side]!" );
  1537. mVB[Side].unlock();
  1538. // Make Primitive Buffers
  1539. U32 p00, p01, p11, p10;
  1540. U32 pb00, pb01, pb11, pb10;
  1541. U32 offset = 0;
  1542. U16 *pIdx = NULL;
  1543. U32 curIdx = 0;
  1544. // Top Primitive Buffer
  1545. mPB[Top].set( GFX, mTriangleCount[Top] * 3, mTriangleCount[Top], GFXBufferTypeStatic );
  1546. mPB[Top].lock(&pIdx);
  1547. curIdx = 0;
  1548. offset = 0;
  1549. const U32 rowStride = 2 + widthDivisions;
  1550. for ( U32 i = 0; i < mSegments.size(); i++ )
  1551. {
  1552. for ( U32 j = 0; j < widthDivisions + 1; j++ )
  1553. {
  1554. p00 = offset;
  1555. p10 = offset + 1;
  1556. p01 = offset + rowStride;
  1557. p11 = offset + rowStride + 1;
  1558. pIdx[curIdx] = p00;
  1559. curIdx++;
  1560. pIdx[curIdx] = p01;
  1561. curIdx++;
  1562. pIdx[curIdx] = p11;
  1563. curIdx++;
  1564. pIdx[curIdx] = p00;
  1565. curIdx++;
  1566. pIdx[curIdx] = p11;
  1567. curIdx++;
  1568. pIdx[curIdx] = p10;
  1569. curIdx++;
  1570. offset += 1;
  1571. }
  1572. offset += 1;
  1573. }
  1574. AssertFatal( curIdx == mTriangleCount[Top] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Top]!" );
  1575. mPB[Top].unlock();
  1576. // Bottom Primitive Buffer
  1577. mPB[Bottom].set( GFX, mTriangleCount[Bottom] * 3, mTriangleCount[Bottom], GFXBufferTypeStatic );
  1578. mPB[Bottom].lock(&pIdx);
  1579. curIdx = 0;
  1580. offset = 0;
  1581. for ( U32 i = 0; i < mSegments.size(); i++ )
  1582. {
  1583. p00 = offset;
  1584. p10 = offset + 1;
  1585. p01 = offset + 2;
  1586. p11 = offset + 3;
  1587. pIdx[curIdx] = p00;
  1588. curIdx++;
  1589. pIdx[curIdx] = p01;
  1590. curIdx++;
  1591. pIdx[curIdx] = p11;
  1592. curIdx++;
  1593. pIdx[curIdx] = p00;
  1594. curIdx++;
  1595. pIdx[curIdx] = p11;
  1596. curIdx++;
  1597. pIdx[curIdx] = p10;
  1598. curIdx++;
  1599. offset += 2;
  1600. }
  1601. AssertFatal( curIdx == mTriangleCount[Bottom] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Bottom]!" );
  1602. mPB[Bottom].unlock();
  1603. // Side Primitive Buffer
  1604. mPB[Side].set( GFX, mTriangleCount[Side] * 3, mTriangleCount[Side], GFXBufferTypeStatic );
  1605. mPB[Side].lock(&pIdx);
  1606. curIdx = 0;
  1607. offset = 0;
  1608. for ( U32 i = 0; i < mSegments.size(); i++ )
  1609. {
  1610. p00 = offset;
  1611. p10 = offset + 1;
  1612. pb00 = offset + 2;
  1613. pb10 = offset + 3;
  1614. p01 = offset + 4;
  1615. p11 = offset + 5;
  1616. pb01 = offset + 6;
  1617. pb11 = offset + 7;
  1618. // Left Side
  1619. pIdx[curIdx] = pb00;
  1620. curIdx++;
  1621. pIdx[curIdx] = pb01;
  1622. curIdx++;
  1623. pIdx[curIdx] = p01;
  1624. curIdx++;
  1625. pIdx[curIdx] = pb00;
  1626. curIdx++;
  1627. pIdx[curIdx] = p01;
  1628. curIdx++;
  1629. pIdx[curIdx] = p00;
  1630. curIdx++;
  1631. // Right Side
  1632. pIdx[curIdx] = p10;
  1633. curIdx++;
  1634. pIdx[curIdx] = p11;
  1635. curIdx++;
  1636. pIdx[curIdx] = pb11;
  1637. curIdx++;
  1638. pIdx[curIdx] = p10;
  1639. curIdx++;
  1640. pIdx[curIdx] = pb11;
  1641. curIdx++;
  1642. pIdx[curIdx] = pb10;
  1643. curIdx++;
  1644. offset += 4;
  1645. }
  1646. // Cap the front and back ends
  1647. pIdx[curIdx++] = 0;
  1648. pIdx[curIdx++] = 1;
  1649. pIdx[curIdx++] = 3;
  1650. pIdx[curIdx++] = 0;
  1651. pIdx[curIdx++] = 3;
  1652. pIdx[curIdx++] = 2;
  1653. pIdx[curIdx++] = offset + 0;
  1654. pIdx[curIdx++] = offset + 3;
  1655. pIdx[curIdx++] = offset + 1;
  1656. pIdx[curIdx++] = offset + 0;
  1657. pIdx[curIdx++] = offset + 2;
  1658. pIdx[curIdx++] = offset + 3;
  1659. AssertFatal( curIdx == mTriangleCount[Side] * 3, "MeshRoad, wrote incorrect number of indices in mPB[Side]!" );
  1660. mPB[Side].unlock();
  1661. }
  1662. const MeshRoadNode& MeshRoad::getNode( U32 idx )
  1663. {
  1664. return mNodes[idx];
  1665. }
  1666. VectorF MeshRoad::getNodeNormal( U32 idx )
  1667. {
  1668. if ( mNodes.size() - 1 < idx )
  1669. return VectorF::Zero;
  1670. return mNodes[idx].normal;
  1671. }
  1672. void MeshRoad::setNodeNormal( U32 idx, const VectorF &normal )
  1673. {
  1674. if ( mNodes.size() - 1 < idx )
  1675. return;
  1676. mNodes[idx].normal = normal;
  1677. regenerate();
  1678. setMaskBits( NodeMask | RegenMask );
  1679. }
  1680. Point3F MeshRoad::getNodePosition( U32 idx )
  1681. {
  1682. if ( mNodes.size() - 1 < idx )
  1683. return Point3F::Zero;
  1684. return mNodes[idx].point;
  1685. }
  1686. void MeshRoad::setNodePosition( U32 idx, const Point3F &pos )
  1687. {
  1688. if ( mNodes.size() - 1 < idx )
  1689. return;
  1690. mNodes[idx].point = pos;
  1691. regenerate();
  1692. setMaskBits( NodeMask | RegenMask );
  1693. }
  1694. U32 MeshRoad::addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1695. {
  1696. U32 idx = _addNode( pos, width, depth, normal );
  1697. regenerate();
  1698. setMaskBits( NodeMask | RegenMask );
  1699. return idx;
  1700. }
  1701. void MeshRoad::buildNodesFromList( MeshRoadNodeList* list )
  1702. {
  1703. mNodes.clear();
  1704. for (U32 i=0; i<list->mPositions.size(); ++i)
  1705. {
  1706. _addNode( list->mPositions[i], list->mWidths[i], list->mDepths[i], list->mNormals[i] );
  1707. }
  1708. _regenerate();
  1709. }
  1710. U32 MeshRoad::insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1711. {
  1712. U32 ret = _insertNode( pos, width, depth, normal, idx );
  1713. regenerate();
  1714. setMaskBits( NodeMask | RegenMask );
  1715. return ret;
  1716. }
  1717. void MeshRoad::setNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1718. {
  1719. if ( mNodes.size() - 1 < idx )
  1720. return;
  1721. MeshRoadNode &node = mNodes[idx];
  1722. node.point = pos;
  1723. node.width = width;
  1724. node.depth = depth;
  1725. node.normal = normal;
  1726. regenerate();
  1727. setMaskBits( NodeMask | RegenMask );
  1728. }
  1729. void MeshRoad::setNodeWidth( U32 idx, F32 meters )
  1730. {
  1731. meters = mClampF( meters, MIN_NODE_WIDTH, MAX_NODE_WIDTH );
  1732. if ( mNodes.size() - 1 < idx )
  1733. return;
  1734. mNodes[idx].width = meters;
  1735. _regenerate();
  1736. setMaskBits( RegenMask | NodeMask );
  1737. }
  1738. F32 MeshRoad::getNodeWidth( U32 idx )
  1739. {
  1740. if ( mNodes.size() - 1 < idx )
  1741. return -1.0f;
  1742. return mNodes[idx].width;
  1743. }
  1744. void MeshRoad::setNodeDepth( U32 idx, F32 meters )
  1745. {
  1746. meters = mClampF( meters, MIN_NODE_DEPTH, MAX_NODE_DEPTH );
  1747. if ( mNodes.size() - 1 < idx )
  1748. return;
  1749. mNodes[idx].depth = meters;
  1750. _regenerate();
  1751. setMaskBits( MeshRoadMask | RegenMask | NodeMask );
  1752. }
  1753. F32 MeshRoad::getNodeDepth( U32 idx )
  1754. {
  1755. if ( mNodes.size() - 1 < idx )
  1756. return -1.0f;
  1757. return mNodes[idx].depth;
  1758. }
  1759. MatrixF MeshRoad::getNodeTransform( U32 idx )
  1760. {
  1761. MatrixF mat(true);
  1762. if ( mNodes.size() - 1 < idx )
  1763. return mat;
  1764. bool hasNext = idx + 1 < mNodes.size();
  1765. bool hasPrev = (S32)idx - 1 > 0;
  1766. const MeshRoadNode &node = mNodes[idx];
  1767. VectorF fvec( 0, 1, 0 );
  1768. if ( hasNext )
  1769. {
  1770. fvec = mNodes[idx+1].point - node.point;
  1771. fvec.normalizeSafe();
  1772. }
  1773. else if ( hasPrev )
  1774. {
  1775. fvec = node.point - mNodes[idx-1].point;
  1776. fvec.normalizeSafe();
  1777. }
  1778. else
  1779. fvec = mPerp( node.normal );
  1780. if ( fvec.isZero() )
  1781. fvec = mPerp( node.normal );
  1782. F32 dot = mDot( fvec, node.normal );
  1783. if ( dot < -0.9f || dot > 0.9f )
  1784. fvec = mPerp( node.normal );
  1785. VectorF rvec = mCross( fvec, node.normal );
  1786. if ( rvec.isZero() )
  1787. rvec = mPerp( fvec );
  1788. rvec.normalize();
  1789. fvec = mCross( node.normal, rvec );
  1790. fvec.normalize();
  1791. mat.setColumn( 0, rvec );
  1792. mat.setColumn( 1, fvec );
  1793. mat.setColumn( 2, node.normal );
  1794. mat.setColumn( 3, node.point );
  1795. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1796. return mat;
  1797. }
  1798. void MeshRoad::calcSliceTransform( U32 idx, MatrixF &mat )
  1799. {
  1800. if ( mSlices.size() - 1 < idx )
  1801. return;
  1802. bool hasNext = idx + 1 < mSlices.size();
  1803. bool hasPrev = (S32)idx - 1 >= 0;
  1804. const MeshRoadSlice &slice = mSlices[idx];
  1805. VectorF fvec( 0, 1, 0 );
  1806. if ( hasNext )
  1807. {
  1808. fvec = mSlices[idx+1].p1 - slice.p1;
  1809. fvec.normalizeSafe();
  1810. }
  1811. else if ( hasPrev )
  1812. {
  1813. fvec = slice.p1 - mSlices[idx-1].p1;
  1814. fvec.normalizeSafe();
  1815. }
  1816. else
  1817. fvec = mPerp( slice.normal );
  1818. if ( fvec.isZero() )
  1819. fvec = mPerp( slice.normal );
  1820. F32 dot = mDot( fvec, slice.normal );
  1821. if ( dot < -0.9f || dot > 0.9f )
  1822. fvec = mPerp( slice.normal );
  1823. VectorF rvec = mCross( fvec, slice.normal );
  1824. if ( rvec.isZero() )
  1825. rvec = mPerp( fvec );
  1826. rvec.normalize();
  1827. fvec = mCross( slice.normal, rvec );
  1828. fvec.normalize();
  1829. mat.setColumn( 0, rvec );
  1830. mat.setColumn( 1, fvec );
  1831. mat.setColumn( 2, slice.normal );
  1832. mat.setColumn( 3, slice.p1 );
  1833. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1834. }
  1835. F32 MeshRoad::getRoadLength() const
  1836. {
  1837. F32 length = 0.0f;
  1838. for ( U32 i = 0; i < mSegments.size(); i++ )
  1839. {
  1840. length += mSegments[i].length();
  1841. }
  1842. return length;
  1843. }
  1844. void MeshRoad::deleteNode( U32 idx )
  1845. {
  1846. if ( mNodes.size() - 1 < idx )
  1847. return;
  1848. mNodes.erase(idx);
  1849. _regenerate();
  1850. setMaskBits( RegenMask | NodeMask );
  1851. }
  1852. U32 MeshRoad::_addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1853. {
  1854. mNodes.increment();
  1855. MeshRoadNode &node = mNodes.last();
  1856. node.point = pos;
  1857. node.width = width;
  1858. node.depth = depth;
  1859. node.normal = normal;
  1860. setMaskBits( NodeMask | RegenMask );
  1861. return mNodes.size() - 1;
  1862. }
  1863. U32 MeshRoad::_insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1864. {
  1865. U32 ret;
  1866. MeshRoadNode *node;
  1867. if ( idx == U32_MAX )
  1868. {
  1869. mNodes.increment();
  1870. node = &mNodes.last();
  1871. ret = mNodes.size() - 1;
  1872. }
  1873. else
  1874. {
  1875. mNodes.insert( idx );
  1876. node = &mNodes[idx];
  1877. ret = idx;
  1878. }
  1879. node->point = pos;
  1880. node->depth = depth;
  1881. node->width = width;
  1882. node->normal = normal;
  1883. return ret;
  1884. }
  1885. bool MeshRoad::collideRay( const Point3F &origin, const Point3F &direction, U32 *nodeIdx, Point3F *collisionPnt )
  1886. {
  1887. Point3F p0 = origin;
  1888. Point3F p1 = origin + direction * 2000.0f;
  1889. // If the line segment does not collide with the MeshRoad's world box,
  1890. // it definitely does not collide with any part of the river.
  1891. if ( !getWorldBox().collideLine( p0, p1 ) )
  1892. return false;
  1893. if ( mSlices.size() < 2 )
  1894. return false;
  1895. MathUtils::Quad quad;
  1896. MathUtils::Ray ray;
  1897. F32 t;
  1898. // Check each road segment (formed by a pair of slices) for collision
  1899. // with the line segment.
  1900. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1901. {
  1902. const MeshRoadSlice &slice0 = mSlices[i];
  1903. const MeshRoadSlice &slice1 = mSlices[i+1];
  1904. // For simplicities sake we will only test for collision between the
  1905. // line segment and the Top face of the river segment.
  1906. // Clockwise starting with the leftmost/closest point.
  1907. quad.p00 = slice0.p0;
  1908. quad.p01 = slice1.p0;
  1909. quad.p11 = slice1.p2;
  1910. quad.p10 = slice0.p2;
  1911. ray.origin = origin;
  1912. ray.direction = direction;
  1913. if ( MathUtils::mRayQuadCollide( quad, ray, NULL, &t ) )
  1914. {
  1915. if ( nodeIdx )
  1916. *nodeIdx = slice0.parentNodeIdx;
  1917. if ( collisionPnt )
  1918. *collisionPnt = ray.origin + ray.direction * t;
  1919. return true;
  1920. }
  1921. }
  1922. return false;
  1923. }
  1924. void MeshRoad::regenerate()
  1925. {
  1926. _regenerate();
  1927. setMaskBits( RegenMask );
  1928. }
  1929. //-------------------------------------------------------------------------
  1930. // Console Methods
  1931. //-------------------------------------------------------------------------
  1932. DefineEngineMethod( MeshRoad, setNodeDepth, void, ( S32 idx, F32 meters ),,
  1933. "Intended as a helper to developers and editor scripts.\n"
  1934. "Sets the depth in meters of a particular node."
  1935. )
  1936. {
  1937. object->setNodeDepth( idx, meters );
  1938. }
  1939. DefineEngineMethod( MeshRoad, regenerate, void, (),,
  1940. "Intended as a helper to developers and editor scripts.\n"
  1941. "Force MeshRoad to recreate its geometry."
  1942. )
  1943. {
  1944. object->regenerate();
  1945. }
  1946. DefineEngineMethod( MeshRoad, postApply, void, (),,
  1947. "Intended as a helper to developers and editor scripts.\n"
  1948. "Force trigger an inspectPostApply. This will transmit "
  1949. "material and other fields ( not including nodes ) to client objects."
  1950. )
  1951. {
  1952. object->inspectPostApply();
  1953. }
  1954. bool MeshRoad::buildPolyList_TopSurfaceOnly = false;
  1955. bool MeshRoad::buildTopPolyList(PolyListContext plc, AbstractPolyList* polyList)
  1956. {
  1957. static Box3F box_prox; static SphereF ball_prox;
  1958. buildPolyList_TopSurfaceOnly = true;
  1959. bool result = buildPolyList(plc, polyList, box_prox, ball_prox);
  1960. buildPolyList_TopSurfaceOnly = false;
  1961. return result;
  1962. }