river.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "environment/river.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "util/catmullRom.h"
  27. #include "math/util/quadTransforms.h"
  28. #include "scene/simPath.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "scene/sceneManager.h"
  31. #include "materials/sceneData.h"
  32. #include "materials/baseMatInstance.h"
  33. #include "scene/sgUtil.h"
  34. #include "T3D/gameBase/gameConnection.h"
  35. #include "core/stream/bitStream.h"
  36. #include "gfx/gfxDrawUtil.h"
  37. #include "gfx/gfxTransformSaver.h"
  38. #include "gfx/primBuilder.h"
  39. #include "gfx/gfxDebugEvent.h"
  40. #include "gfx/gfxOcclusionQuery.h"
  41. #include "math/mathIO.h"
  42. #include "math/mathUtils.h"
  43. #include "math/util/frustum.h"
  44. #include "math/util/quadTransforms.h"
  45. #include "gui/3d/guiTSControl.h"
  46. #include "gfx/sim/debugDraw.h"
  47. #include "T3D/fx/particleEmitter.h"
  48. #include "scene/reflectionManager.h"
  49. #include "ts/tsShapeInstance.h"
  50. #include "postFx/postEffect.h"
  51. #include "math/util/matrixSet.h"
  52. #include "environment/nodeListManager.h"
  53. ConsoleDocClass( River,
  54. "@brief A water volume defined by a 3D spline.\n\n"
  55. "User may control width and depth per node and overall spline shape in three "
  56. "dimensions.\n\n"
  57. "%River supports dynamic planar reflections (fullReflect) like all WaterObject "
  58. "classes, but keep in mind it is not necessarily a planar surface. For best "
  59. "visual quality a %River should be less reflective the more it twists and "
  60. "bends. This caution only applies to %Rivers with fullReflect on.\n\n"
  61. "@see WaterObject for inherited functionality.\n\n"
  62. "@ingroup Water"
  63. );
  64. #define MIN_METERS_PER_SEGMENT 1.0f
  65. #define MIN_NODE_DEPTH 0.25f
  66. #define MAX_NODE_DEPTH 500.0f
  67. #define MIN_NODE_WIDTH 0.25f
  68. #define MAX_NODE_WIDTH 1000.0f
  69. #define NODE_RADIUS 15.0f
  70. static U32 gIdxArray[6][2][3] = {
  71. { { 0, 4, 5 }, { 0, 5, 1 }, }, // Top Face
  72. { { 2, 6, 4 }, { 2, 4, 0 }, }, // Left Face
  73. { { 1, 5, 7 }, { 1, 7, 3 }, }, // Right Face
  74. { { 2, 3, 7 }, { 2, 7, 6 }, }, // Bottom Face
  75. { { 0, 1, 3 }, { 0, 3, 2 }, }, // Front Face
  76. { { 4, 6, 7 }, { 4, 7, 5 }, }, // Back Face
  77. };
  78. struct RiverHitSegment
  79. {
  80. U32 idx;
  81. F32 t;
  82. };
  83. static S32 QSORT_CALLBACK compareHitSegments(const void* a,const void* b)
  84. {
  85. const RiverHitSegment *fa = (RiverHitSegment*)a;
  86. const RiverHitSegment *fb = (RiverHitSegment*)b;
  87. return mSign(fb->t - fa->t);
  88. }
  89. static Point3F sSegmentPointComparePoints[4];
  90. //-----------------------------------------------------------------------------
  91. // DecalRoadNodeList Struct
  92. //-----------------------------------------------------------------------------
  93. struct RiverNodeList : public NodeListManager::NodeList
  94. {
  95. Vector<Point3F> mPositions;
  96. Vector<F32> mWidths;
  97. Vector<F32> mDepths;
  98. Vector<VectorF> mNormals;
  99. RiverNodeList() { }
  100. virtual ~RiverNodeList() { }
  101. };
  102. //-----------------------------------------------------------------------------
  103. // RiverNodeEvent Class
  104. //-----------------------------------------------------------------------------
  105. class RiverNodeEvent : public NodeListEvent
  106. {
  107. typedef NodeListEvent Parent;
  108. public:
  109. Vector<Point3F> mPositions;
  110. Vector<F32> mWidths;
  111. Vector<F32> mDepths;
  112. Vector<VectorF> mNormals;
  113. public:
  114. RiverNodeEvent() { mNodeList = NULL; }
  115. virtual ~RiverNodeEvent() { }
  116. virtual void pack(NetConnection*, BitStream*);
  117. virtual void unpack(NetConnection*, BitStream*);
  118. virtual void copyIntoList(NodeListManager::NodeList* copyInto);
  119. virtual void padListToSize();
  120. DECLARE_CONOBJECT(RiverNodeEvent);
  121. };
  122. void RiverNodeEvent::pack(NetConnection* conn, BitStream* stream)
  123. {
  124. Parent::pack( conn, stream );
  125. stream->writeInt( mPositions.size(), 16 );
  126. for (U32 i=0; i<mPositions.size(); ++i)
  127. {
  128. mathWrite( *stream, mPositions[i] );
  129. stream->write( mWidths[i] );
  130. stream->write( mDepths[i] );
  131. mathWrite( *stream, mNormals[i] );
  132. }
  133. }
  134. void RiverNodeEvent::unpack(NetConnection* conn, BitStream* stream)
  135. {
  136. mNodeList = new RiverNodeList();
  137. Parent::unpack( conn, stream );
  138. U32 count = stream->readInt( 16 );
  139. Point3F pos;
  140. F32 width, depth;
  141. VectorF normal;
  142. RiverNodeList* list = static_cast<RiverNodeList*>(mNodeList);
  143. for (U32 i=0; i<count; ++i)
  144. {
  145. mathRead( *stream, &pos );
  146. stream->read( &width );
  147. stream->read( &depth );
  148. mathRead( *stream, &normal );
  149. list->mPositions.push_back( pos );
  150. list->mWidths.push_back( width );
  151. list->mDepths.push_back( depth );
  152. list->mNormals.push_back( normal );
  153. }
  154. list->mTotalValidNodes = count;
  155. // Do we have a complete list?
  156. if (list->mPositions.size() >= mTotalNodes)
  157. list->mListComplete = true;
  158. }
  159. void RiverNodeEvent::copyIntoList(NodeListManager::NodeList* copyInto)
  160. {
  161. RiverNodeList* prevList = dynamic_cast<RiverNodeList*>(copyInto);
  162. RiverNodeList* list = static_cast<RiverNodeList*>(mNodeList);
  163. // Merge our list with the old list.
  164. for (U32 i=mLocalListStart, index=0; i<mLocalListStart+list->mPositions.size(); ++i, ++index)
  165. {
  166. prevList->mPositions[i] = list->mPositions[index];
  167. prevList->mWidths[i] = list->mWidths[index];
  168. prevList->mDepths[i] = list->mDepths[index];
  169. prevList->mNormals[i] = list->mNormals[index];
  170. }
  171. }
  172. void RiverNodeEvent::padListToSize()
  173. {
  174. RiverNodeList* list = static_cast<RiverNodeList*>(mNodeList);
  175. U32 totalValidNodes = list->mTotalValidNodes;
  176. // Pad our list front?
  177. if (mLocalListStart)
  178. {
  179. RiverNodeList* newlist = new RiverNodeList();
  180. newlist->mPositions.increment(mLocalListStart);
  181. newlist->mWidths.increment(mLocalListStart);
  182. newlist->mDepths.increment(mLocalListStart);
  183. newlist->mNormals.increment(mLocalListStart);
  184. newlist->mPositions.merge(list->mPositions);
  185. newlist->mWidths.merge(list->mWidths);
  186. newlist->mDepths.merge(list->mDepths);
  187. newlist->mNormals.merge(list->mNormals);
  188. delete list;
  189. mNodeList = list = newlist;
  190. }
  191. // Pad our list end?
  192. if (list->mPositions.size() < mTotalNodes)
  193. {
  194. U32 delta = mTotalNodes - list->mPositions.size();
  195. list->mPositions.increment(delta);
  196. list->mWidths.increment(delta);
  197. list->mDepths.increment(delta);
  198. list->mNormals.increment(delta);
  199. }
  200. list->mTotalValidNodes = totalValidNodes;
  201. }
  202. IMPLEMENT_CO_NETEVENT_V1(RiverNodeEvent);
  203. ConsoleDocClass( RiverNodeEvent,
  204. "@brief Sends messages to the River Editor\n\n"
  205. "Editor use only.\n\n"
  206. "@internal"
  207. );
  208. //-----------------------------------------------------------------------------
  209. // RiverNodeListNotify Class
  210. //-----------------------------------------------------------------------------
  211. class RiverNodeListNotify : public NodeListNotify
  212. {
  213. typedef NodeListNotify Parent;
  214. protected:
  215. SimObjectPtr<River> mRiver;
  216. public:
  217. RiverNodeListNotify( River* river, U32 listId ) { mRiver = river; mListId = listId; }
  218. virtual ~RiverNodeListNotify() { mRiver = NULL; }
  219. virtual void sendNotification( NodeListManager::NodeList* list );
  220. };
  221. void RiverNodeListNotify::sendNotification( NodeListManager::NodeList* list )
  222. {
  223. if (mRiver.isValid())
  224. {
  225. // Build the road's nodes
  226. RiverNodeList* riverList = dynamic_cast<RiverNodeList*>( list );
  227. if (riverList)
  228. mRiver->buildNodesFromList( riverList );
  229. }
  230. }
  231. //------------------------------------------------------------------------------
  232. // Class: RiverSegment
  233. //------------------------------------------------------------------------------
  234. RiverSegment::RiverSegment()
  235. {
  236. mPlaneCount = 0;
  237. columns = 0;
  238. rows = 0;
  239. numVerts = 0;
  240. numTriangles = 0;
  241. startVert = 0;
  242. endVert = 0;
  243. startIndex = 0;
  244. endIndex = 0;
  245. slice0 = NULL;
  246. slice1 = NULL;
  247. }
  248. RiverSegment::RiverSegment( RiverSlice *rs0, RiverSlice *rs1 )
  249. {
  250. columns = 0;
  251. rows = 0;
  252. numVerts = 0;
  253. numTriangles = 0;
  254. startVert = 0;
  255. endVert = 0;
  256. startIndex = 0;
  257. endIndex = 0;
  258. slice0 = rs0;
  259. slice1 = rs1;
  260. // Calculate the planes for this segment
  261. // Will be used for intersection/buoyancy tests
  262. VectorF normal;
  263. mPlaneCount = 6;
  264. sSegmentPointCompareReference = getFaceCenter(6);
  265. // left
  266. mPlanes[0] = _getBestPlane( &slice1->p0, &slice1->pb0, &slice0->pb0, &slice0->p0 );
  267. // right
  268. mPlanes[1] = _getBestPlane( &slice0->pb2, &slice1->pb2, &slice1->p2, &slice0->p2 );
  269. // near
  270. mPlanes[2] = _getBestPlane( &slice0->pb0, &slice0->pb2, &slice0->p2, &slice0->p0 );
  271. // far
  272. mPlanes[3] = _getBestPlane( &slice1->pb2, &slice1->pb0, &slice1->p0, &slice1->p2 );
  273. // top
  274. mPlanes[4] = _getBestPlane( &slice0->p2, &slice1->p2, &slice1->p0, &slice0->p0 );
  275. // bottom
  276. mPlanes[5] = _getBestPlane( &slice0->pb2, &slice0->pb0, &slice1->pb0, &slice1->pb2 );
  277. // Calculate the bounding box(s)
  278. worldbounds.minExtents = worldbounds.maxExtents = rs0->p0;
  279. worldbounds.extend( rs0->p2 );
  280. worldbounds.extend( rs0->pb0 );
  281. worldbounds.extend( rs0->pb2 );
  282. worldbounds.extend( rs1->p0 );
  283. worldbounds.extend( rs1->p2 );
  284. worldbounds.extend( rs1->pb0 );
  285. worldbounds.extend( rs1->pb2 );
  286. /*
  287. // Calculate tetrahedrons (for collision and buoyancy testing)
  288. // This is 0 in the diagram.
  289. mCubePoints[0] = cornerPoint;
  290. mCubePoints[1] = cornerPoint + (VectorF( 1.0f, 0.0f, 0.0f ) * size );
  291. mCubePoints[2] = cornerPoint + (VectorF( 0.0f, 1.0f, 0.0f ) * size );
  292. mCubePoints[3] = cornerPoint + (VectorF( 1.0f, 1.0f, 0.0f ) * size );
  293. mCubePoints[4] = cornerPoint + (VectorF( 0.0f, 0.0f, 1.0f );
  294. mCubePoints[5] = cornerPoint + (VectorF( 1.0f, 0.0f, 1.0f );
  295. mCubePoints[6] = cornerPoint + (VectorF( 0.0f, 1.0f, 1.0f );
  296. mCubePoints[7] = cornerPoint + (VectorF( 1.0f, 1.0f, 1.0f );
  297. // Center tetra.
  298. mTetras[0].p0 = &mCubePoints[1];
  299. mTetras[0].p1 = &mCubePoints[2];
  300. mTetras[0].p2 = &mCubePoints[4];
  301. mTetras[0].p3 = &mCubePoints[7];
  302. mTetras[1].p0 = &mCubePoints[0]; // this is the tip
  303. mTetras[1].p1 = &mCubePoints[1];
  304. mTetras[1].p2 = &mCubePoints[2];
  305. mTetras[1].p3 = &mCubePoints[4];
  306. mTetras[2].p0 = &mCubePoints[3]; // tip
  307. mTetras[2].p1 = &mCubePoints[2];
  308. mTetras[2].p2 = &mCubePoints[1];
  309. mTetras[2].p3 = &mCubePoints[7];
  310. mTetras[3].p0 = &mCubePoints[6]; // tip
  311. mTetras[3].p1 = &mCubePoints[7];
  312. mTetras[3].p2 = &mCubePoints[4];
  313. mTetras[3].p3 = &mCubePoints[2];
  314. mTetras[4].p0 = &mCubePoints[5]; // tip
  315. mTetras[4].p1 = &mCubePoints[7];
  316. mTetras[4].p2 = &mCubePoints[4];
  317. mTetras[4].p3 = &mCubePoints[3];*/
  318. }
  319. void RiverSegment::set( RiverSlice *rs0, RiverSlice *rs1 )
  320. {
  321. columns = 0;
  322. rows = 0;
  323. numVerts = 0;
  324. numTriangles = 0;
  325. startVert = 0;
  326. endVert = 0;
  327. startIndex = 0;
  328. endIndex = 0;
  329. slice0 = rs0;
  330. slice1 = rs1;
  331. }
  332. static S32 QSORT_CALLBACK SegmentPointCompare(const void *aptr, const void *bptr)
  333. {
  334. const U32 a = *(const U32*)aptr;
  335. const U32 b = *(const U32*)bptr;
  336. F32 lenA = ( sSegmentPointCompareReference - sSegmentPointComparePoints[a] ).lenSquared();
  337. F32 lenB = ( sSegmentPointCompareReference - sSegmentPointComparePoints[b] ).lenSquared();
  338. return ( lenB - lenA );
  339. }
  340. PlaneF RiverSegment::_getBestPlane( const Point3F *p0, const Point3F *p1, const Point3F *p2, const Point3F *p3 )
  341. {
  342. sSegmentPointComparePoints[0] = *p0;
  343. sSegmentPointComparePoints[1] = *p1;
  344. sSegmentPointComparePoints[2] = *p2;
  345. sSegmentPointComparePoints[3] = *p3;
  346. Point3F points[4] = {
  347. *p0, *p1, *p2, *p3
  348. };
  349. U32 indices[4] = {
  350. 0,1,2,3
  351. };
  352. dQsort(indices, 4, sizeof(U32), SegmentPointCompare);
  353. // Collect the best three points (in correct winding order)
  354. // To generate the plane's normal
  355. Vector<Point3F> normalPnts;
  356. for ( U32 i = 0; i < 4; i++ )
  357. {
  358. if ( i == indices[3] )
  359. continue;
  360. normalPnts.push_back(points[i]);
  361. }
  362. PlaneF plane( normalPnts[0], normalPnts[1], normalPnts[2] );
  363. return plane;
  364. }
  365. Point3F RiverSegment::getFaceCenter( U32 faceIdx ) const
  366. {
  367. Point3F center(0,0,0);
  368. switch ( faceIdx )
  369. {
  370. case 0: // left
  371. center = slice1->p0 + slice0->p0 + slice0->pb0 + slice1->pb0;
  372. center *= 0.25f;
  373. break;
  374. case 1: // right
  375. center = slice0->p2 + slice1->p2 + slice1->pb2 + slice0->pb2;
  376. center *= 0.25f;
  377. break;
  378. case 2: // near
  379. center = slice0->p0 + slice0->p2 + slice0->pb2 + slice0->pb0;
  380. center *= 0.25f;
  381. break;
  382. case 3: // far
  383. center = slice1->pb0 + slice1->p0 + slice1->pb0 + slice1->pb2;
  384. center *= 0.25f;
  385. break;
  386. case 4: // top
  387. center = slice0->p0 + slice1->p0 + slice1->p2 + slice0->p2;
  388. center *= 0.25f;
  389. break;
  390. case 5: // bottom
  391. center = slice1->pb2 + slice1->pb0 + slice0->pb0 + slice0->pb2;
  392. center *= 0.25f;
  393. break;
  394. case 6: // segment center
  395. center = slice0->p0 + slice0->p2 + slice1->p0 + slice1->p2 + slice0->pb0 + slice0->pb2 + slice1->pb0 + slice1->pb2;
  396. center /= 8;
  397. break;
  398. }
  399. return center;
  400. }
  401. bool RiverSegment::intersectBox( const Box3F &bounds ) const
  402. {
  403. // This code copied from Frustum class.
  404. Point3F maxPoint;
  405. F32 maxDot;
  406. // Note the planes are ordered left, right, near,
  407. // far, top, bottom for getting early rejections
  408. // from the typical horizontal scene.
  409. for ( S32 i = 0; i < mPlaneCount; i++ )
  410. {
  411. // This is pretty much as optimal as you can
  412. // get for a plane vs AABB test...
  413. //
  414. // 4 comparisons
  415. // 3 multiplies
  416. // 2 adds
  417. // 1 negation
  418. //
  419. // It will early out as soon as it detects the
  420. // bounds is outside one of the planes.
  421. if ( mPlanes[i].x > 0 )
  422. maxPoint.x = bounds.maxExtents.x;
  423. else
  424. maxPoint.x = bounds.minExtents.x;
  425. if ( mPlanes[i].y > 0 )
  426. maxPoint.y = bounds.maxExtents.y;
  427. else
  428. maxPoint.y = bounds.minExtents.y;
  429. if ( mPlanes[i].z > 0 )
  430. maxPoint.z = bounds.maxExtents.z;
  431. else
  432. maxPoint.z = bounds.minExtents.z;
  433. maxDot = mDot( maxPoint, mPlanes[ i ] );
  434. if ( maxDot <= -mPlanes[ i ].d )
  435. return false;
  436. }
  437. return true;
  438. }
  439. bool RiverSegment::containsPoint( const Point3F &pnt ) const
  440. {
  441. // NOTE: this code from Frustum class.
  442. F32 maxDot;
  443. // Note the planes are ordered left, right, near,
  444. // far, top, bottom for getting early rejections
  445. // from the typical horizontal scene.
  446. for ( S32 i = 0; i < mPlaneCount; i++ )
  447. {
  448. const PlaneF &plane = mPlanes[ i ];
  449. // This is pretty much as optimal as you can
  450. // get for a plane vs point test...
  451. //
  452. // 1 comparison
  453. // 2 multiplies
  454. // 1 adds
  455. //
  456. // It will early out as soon as it detects the
  457. // point is outside one of the planes.
  458. maxDot = mDot( pnt, plane ) + plane.d;
  459. if ( maxDot < -0.1f )
  460. return false;
  461. }
  462. return true;
  463. }
  464. F32 RiverSegment::distanceToSurface(const Point3F &pnt) const
  465. {
  466. return mPlanes[4].distToPlane( pnt );
  467. }
  468. bool River::smEditorOpen = false;
  469. bool River::smWireframe = false;
  470. bool River::smShowWalls = false;
  471. bool River::smShowNodes = false;
  472. bool River::smShowSpline = true;
  473. bool River::smShowRiver = true;
  474. SimObjectPtr<SimSet> River::smServerRiverSet = NULL;
  475. IMPLEMENT_CO_NETOBJECT_V1(River);
  476. River::River()
  477. : mSegmentsPerBatch(10),
  478. mMetersPerSegment(10.0f),
  479. mDepthScale(1.0f),
  480. mFlowMagnitude(1.0f),
  481. mLodDistance( 50.0f ),
  482. mMaxDivisionSize(2.5f),
  483. mMinDivisionSize(0.25f),
  484. mColumnCount(5)
  485. {
  486. mNetFlags.set( Ghostable | ScopeAlways );
  487. mObjScale.set( 1, 1, 1 );
  488. mObjBox.minExtents.set( -0.5, -0.5, -0.5 );
  489. mObjBox.maxExtents.set( 0.5, 0.5, 0.5 );
  490. mReflectNormalUp = false;
  491. // We use the shader const miscParams.w to signify
  492. // that this object is a River.
  493. mMiscParamW = 1.0f;
  494. }
  495. River::~River()
  496. {
  497. }
  498. void River::initPersistFields()
  499. {
  500. addGroup( "River" );
  501. addField( "SegmentLength", TypeF32, Offset( mMetersPerSegment, River ),
  502. "Divide the River lengthwise into segments of this length in meters. "
  503. "These geometric volumes are used for spacial queries like determining containment." );
  504. addField( "SubdivideLength", TypeF32, Offset( mMaxDivisionSize, River ),
  505. "For purposes of generating the renderable geometry River segments are further subdivided "
  506. "such that no quad is of greater width or length than this distance in meters." );
  507. addField( "FlowMagnitude", TypeF32, Offset( mFlowMagnitude, River ),
  508. "Magnitude of the force vector applied to dynamic objects within the River." );
  509. addField( "LowLODDistance", TypeF32, Offset( mLodDistance, River ),
  510. "Segments of the river at this distance in meters or greater will "
  511. "render as a single unsubdivided without undulation effects." );
  512. endGroup( "River" );
  513. addGroup( "Internal" );
  514. addProtectedField( "Node", TypeString, NULL, &addNodeFromField, &emptyStringProtectedGetFn, "For internal use, do not modify." );
  515. endGroup( "Internal" );
  516. Parent::initPersistFields();
  517. }
  518. void River::consoleInit()
  519. {
  520. Parent::consoleInit();
  521. Con::addVariable( "$River::EditorOpen", TypeBool, &River::smEditorOpen, "For editor use.\n"
  522. "@ingroup Editors\n" );
  523. Con::addVariable( "$River::showWalls", TypeBool, &River::smShowWalls, "For editor use.\n"
  524. "@ingroup Editors\n" );
  525. Con::addVariable( "$River::showNodes", TypeBool, &River::smShowNodes, "For editor use.\n"
  526. "@ingroup Editors\n");
  527. Con::addVariable( "$River::showSpline", TypeBool, &River::smShowSpline, "For editor use.\n"
  528. "@ingroup Editors\n" );
  529. Con::addVariable( "$River::showRiver", TypeBool, &River::smShowRiver, "For editor use.\n"
  530. "@ingroup Editors\n" );
  531. Con::addVariable( "$River::showWireframe", TypeBool, &River::smWireframe, "For editor use.\n"
  532. "@ingroup Editors\n");
  533. }
  534. bool River::addNodeFromField( void *object, const char *index, const char *data )
  535. {
  536. River *pObj = static_cast<River*>(object);
  537. //if ( !pObj->isProperlyAdded() )
  538. //{
  539. F32 x,y,z,width,depth;
  540. VectorF normal;
  541. U32 result = dSscanf( data, "%f %f %f %f %f %f %f %f", &x, &y, &z, &width, &depth, &normal.x, &normal.y, &normal.z );
  542. if ( result == 8 )
  543. pObj->_addNode( Point3F(x,y,z), width, depth, normal );
  544. //}
  545. return false;
  546. }
  547. bool River::onAdd()
  548. {
  549. if ( !Parent::onAdd() )
  550. return false;
  551. // Reset the World Box.
  552. //setGlobalBounds();
  553. resetWorldBox();
  554. // Set the Render Transform.
  555. setRenderTransform(mObjToWorld);
  556. // Add to Scene.
  557. addToScene();
  558. if ( isServerObject() )
  559. getServerSet()->addObject( this );
  560. _regenerate();
  561. return true;
  562. }
  563. void River::onRemove()
  564. {
  565. removeFromScene();
  566. Parent::onRemove();
  567. }
  568. void River::inspectPostApply()
  569. {
  570. // Set Parent.
  571. Parent::inspectPostApply();
  572. if ( mMetersPerSegment < MIN_METERS_PER_SEGMENT )
  573. mMetersPerSegment = MIN_METERS_PER_SEGMENT;
  574. mMaxDivisionSize = getMax( mMaxDivisionSize, mMinDivisionSize );
  575. // Set fxPortal Mask.
  576. setMaskBits(RiverMask|RegenMask);
  577. }
  578. void River::onStaticModified( const char* slotName, const char*newValue )
  579. {
  580. Parent::onStaticModified( slotName, newValue );
  581. if ( dStricmp( slotName, "surfMaterial" ) == 0 )
  582. setMaskBits( MaterialMask );
  583. }
  584. SimSet* River::getServerSet()
  585. {
  586. if ( !smServerRiverSet )
  587. {
  588. smServerRiverSet = new SimSet();
  589. smServerRiverSet->registerObject( "ServerRiverSet" );
  590. Sim::getRootGroup()->addObject( smServerRiverSet );
  591. }
  592. return smServerRiverSet;
  593. }
  594. void River::writeFields( Stream &stream, U32 tabStop )
  595. {
  596. Parent::writeFields( stream, tabStop );
  597. // Now write all nodes
  598. stream.write(2, "\r\n");
  599. for ( U32 i = 0; i < mNodes.size(); i++ )
  600. {
  601. const RiverNode &node = mNodes[i];
  602. stream.writeTabs(tabStop);
  603. char buffer[1024];
  604. dMemset( buffer, 0, 1024 );
  605. dSprintf( buffer, 1024, "Node = \"%f %f %f %f %f %f %f %f\";", node.point.x, node.point.y, node.point.z,
  606. node.width,
  607. node.depth,
  608. node.normal.x, node.normal.y, node.normal.z );
  609. stream.writeLine( (const U8*)buffer );
  610. }
  611. }
  612. bool River::writeField( StringTableEntry fieldname, const char *value )
  613. {
  614. if ( fieldname == StringTable->insert("node") )
  615. return false;
  616. return Parent::writeField( fieldname, value );
  617. }
  618. void River::innerRender( SceneRenderState *state )
  619. {
  620. GFXDEBUGEVENT_SCOPE( River_innerRender, ColorI( 255, 0, 0 ) );
  621. PROFILE_SCOPE( River_innerRender );
  622. // Setup SceneData
  623. SceneData sgData;
  624. sgData.init( state );
  625. sgData.lights[0] = LIGHTMGR->getSpecialLight( LightManager::slSunLightType );
  626. sgData.backBuffTex = REFLECTMGR->getRefractTex();
  627. sgData.reflectTex = mPlaneReflector.reflectTex;
  628. sgData.wireframe |= smWireframe;
  629. const Point3F &camPosition = state->getCameraPosition();
  630. // set the material
  631. S32 matIdx = getMaterialIndex( camPosition );
  632. if ( !initMaterial( matIdx ) )
  633. return;
  634. BaseMatInstance *mat = mMatInstances[matIdx];
  635. WaterMatParams matParams = mMatParamHandles[matIdx];
  636. if ( !mat )
  637. return;
  638. // setup proj/world transform
  639. GFXTransformSaver saver;
  640. setShaderParams( state, mat, matParams );
  641. _makeRenderBatches( camPosition );
  642. if ( !River::smShowRiver )
  643. return;
  644. // If no material... we're done.
  645. if ( mLowLODBatches.empty() && mHighLODBatches.empty() )
  646. return;
  647. if ( !mHighLODBatches.empty() )
  648. _makeHighLODBuffers();
  649. mMatrixSet->restoreSceneViewProjection();
  650. mMatrixSet->setWorld( MatrixF::Identity );
  651. while( mat->setupPass( state, sgData ) )
  652. {
  653. mat->setSceneInfo(state, sgData);
  654. mat->setTransforms(*mMatrixSet, state);
  655. setCustomTextures( matIdx, mat->getCurPass(), matParams );
  656. GFX->setVertexBuffer( mVB_low );
  657. GFX->setPrimitiveBuffer( mPB_low );
  658. for ( U32 i = 0; i < mLowLODBatches.size(); i++ )
  659. {
  660. const RiverRenderBatch &batch = mLowLODBatches[i];
  661. U32 startVert = batch.startSegmentIdx * 2;
  662. U32 endVert = ( batch.endSegmentIdx + 1 ) * 2 + 1;
  663. U32 startIdx = batch.startSegmentIdx * 6;
  664. U32 endIdx = batch.endSegmentIdx * 6 + 5;
  665. U32 vertCount = ( endVert - startVert ) + 1;
  666. U32 idxCount = ( endIdx - startIdx ) + 1;
  667. U32 triangleCount = idxCount / 3;
  668. AssertFatal( startVert < mLowVertCount, "River, bad draw call!" );
  669. AssertFatal( startVert + vertCount <= mLowVertCount, "River, bad draw call!" );
  670. AssertFatal( triangleCount <= mLowTriangleCount, "River, bad draw call!" );
  671. GFX->drawIndexedPrimitive( GFXTriangleList, 0, startVert, vertCount, startIdx, triangleCount );
  672. }
  673. // Render all high detail batches.
  674. //
  675. // It is possible that the buffers could not be allocated because
  676. // the max number of verts/indices was exceeded. We don't want to
  677. // crash because that would be unhelpful for working in the editor.
  678. if ( mVB_high.isValid() && mPB_high.isValid() )
  679. {
  680. GFX->setVertexBuffer( mVB_high );
  681. GFX->setPrimitiveBuffer( mPB_high );
  682. for ( U32 i = 0; i < mHighLODBatches.size(); i++ )
  683. {
  684. const RiverRenderBatch &batch = mHighLODBatches[i];
  685. AssertFatal( batch.startVert < mHighVertCount, "River, bad draw call!" );
  686. AssertFatal( batch.startVert + batch.vertCount <= mHighVertCount, "River, bad draw call!" );
  687. AssertFatal( batch.triangleCount <= mHighTriangleCount, "River, bad draw call!" );
  688. AssertFatal( batch.startIndex < mHighTriangleCount * 3, "River, bad draw call!" );
  689. AssertFatal( batch.startIndex + batch.triangleCount * 3 <= mHighTriangleCount * 3, "River, bad draw call!" );
  690. GFX->drawIndexedPrimitive( GFXTriangleList,
  691. 0,
  692. 0,
  693. batch.vertCount,
  694. batch.startIndex,
  695. batch.triangleCount );
  696. }
  697. }
  698. } // while( mat->setupPass( sgData ) )
  699. }
  700. void River::updateUnderwaterEffect( SceneRenderState *state )
  701. {
  702. // Calculate mWaterPlane before calling updateUnderwaterEffect.
  703. Point3F dummy;
  704. _getWaterPlane( state->getCameraPosition(), mWaterFogData.plane, dummy );
  705. Parent::updateUnderwaterEffect( state );
  706. }
  707. void River::setShaderParams( SceneRenderState *state, BaseMatInstance* mat, const WaterMatParams& paramHandles )
  708. {
  709. // Set variables that will be assigned to shader consts within WaterCommon
  710. // before calling Parent::setShaderParams
  711. mUndulateMaxDist = mLodDistance;
  712. Parent::setShaderParams( state, mat, paramHandles );
  713. // Now set the rest of the shader consts that are either unique to this
  714. // class or that WaterObject leaves to us to handle...
  715. MaterialParameters* matParams = mat->getMaterialParameters();
  716. // set vertex shader constants
  717. //-----------------------------------
  718. matParams->setSafe(paramHandles.mGridElementSizeSC, 1.0f);
  719. if ( paramHandles.mModelMatSC->isValid() )
  720. matParams->set(paramHandles.mModelMatSC, MatrixF::Identity, GFXSCT_Float4x4);
  721. // set pixel shader constants
  722. //-----------------------------------
  723. ColorF c( mWaterFogData.color );
  724. matParams->setSafe(paramHandles.mBaseColorSC, c);
  725. // By default we need to show a true reflection is fullReflect is enabled and
  726. // we are above water.
  727. F32 reflect = mPlaneReflector.isEnabled() && !isUnderwater( state->getCameraPosition() );
  728. // If we were occluded the last frame a query was fetched ( not necessarily last frame )
  729. // and we weren't updated last frame... we don't have a valid texture to show
  730. // so use the cubemap / fake reflection color this frame.
  731. if ( mPlaneReflector.lastUpdateMs != REFLECTMGR->getLastUpdateMs() && mPlaneReflector.isOccluded() )
  732. reflect = false;
  733. Point4F reflectParams( mWaterPos.z, 0.0f, 1000.0f, !reflect );
  734. matParams->setSafe(paramHandles.mReflectParamsSC, reflectParams );
  735. matParams->setSafe(paramHandles.mReflectNormalSC, mPlaneReflector.refplane );
  736. }
  737. bool River::isUnderwater( const Point3F &pnt ) const
  738. {
  739. return containsPoint( pnt, NULL );
  740. }
  741. U32 River::packUpdate(NetConnection * con, U32 mask, BitStream * stream)
  742. {
  743. // Pack Parent.
  744. U32 retMask = Parent::packUpdate(con, mask, stream);
  745. if ( stream->writeFlag( mask & RiverMask ) )
  746. {
  747. // Write Object Transform.
  748. stream->writeAffineTransform(mObjToWorld);
  749. stream->write( mMetersPerSegment );
  750. stream->write( mSegmentsPerBatch );
  751. stream->write( mDepthScale );
  752. stream->write( mMaxDivisionSize );
  753. stream->write( mColumnCount );
  754. stream->write( mFlowMagnitude );
  755. stream->write( mLodDistance );
  756. }
  757. if ( stream->writeFlag( mask & NodeMask ) )
  758. {
  759. const U32 nodeByteSize = 32; // Based on sending all of a node's parameters
  760. // Test if we can fit all of our nodes within the current stream.
  761. // We make sure we leave 100 bytes still free in the stream for whatever
  762. // may follow us.
  763. S32 allowedBytes = stream->getWriteByteSize() - 100;
  764. if ( stream->writeFlag( (nodeByteSize * mNodes.size()) < allowedBytes ) )
  765. {
  766. // All nodes should fit, so send them out now.
  767. stream->writeInt( mNodes.size(), 16 );
  768. for ( U32 i = 0; i < mNodes.size(); i++ )
  769. {
  770. mathWrite( *stream, mNodes[i].point );
  771. stream->write( mNodes[i].width );
  772. stream->write( mNodes[i].depth );
  773. mathWrite( *stream, mNodes[i].normal );
  774. }
  775. }
  776. else
  777. {
  778. // There isn't enough space left in the stream for all of the
  779. // nodes. Batch them up into NetEvents.
  780. U32 id = gServerNodeListManager->nextListId();
  781. U32 count = 0;
  782. U32 index = 0;
  783. while (count < mNodes.size())
  784. {
  785. count += NodeListManager::smMaximumNodesPerEvent;
  786. if (count > mNodes.size())
  787. {
  788. count = mNodes.size();
  789. }
  790. RiverNodeEvent* event = new RiverNodeEvent();
  791. event->mId = id;
  792. event->mTotalNodes = mNodes.size();
  793. event->mLocalListStart = index;
  794. for (; index<count; ++index)
  795. {
  796. event->mPositions.push_back( mNodes[index].point );
  797. event->mWidths.push_back( mNodes[index].width );
  798. event->mDepths.push_back( mNodes[index].depth );
  799. event->mNormals.push_back( mNodes[index].normal );
  800. }
  801. con->postNetEvent( event );
  802. }
  803. stream->write( id );
  804. }
  805. }
  806. if( stream->writeFlag( mask & ( RiverMask | InitialUpdateMask ) ) )
  807. {
  808. // This is set to allow the user to modify the size of the water dynamically
  809. // in the editor
  810. mathWrite( *stream, mObjScale );
  811. stream->writeAffineTransform( mObjToWorld );
  812. }
  813. stream->writeFlag( mask & RegenMask );
  814. return retMask;
  815. }
  816. void River::unpackUpdate(NetConnection * con, BitStream * stream)
  817. {
  818. // Unpack Parent.
  819. Parent::unpackUpdate(con, stream);
  820. // RiverMask
  821. if(stream->readFlag())
  822. {
  823. MatrixF ObjectMatrix;
  824. stream->readAffineTransform(&ObjectMatrix);
  825. Parent::setTransform(ObjectMatrix);
  826. stream->read( &mMetersPerSegment );
  827. stream->read( &mSegmentsPerBatch );
  828. stream->read( &mDepthScale );
  829. stream->read( &mMaxDivisionSize );
  830. stream->read( &mColumnCount );
  831. stream->read( &mFlowMagnitude );
  832. stream->read( &mLodDistance );
  833. }
  834. // NodeMask
  835. if ( stream->readFlag() )
  836. {
  837. if (stream->readFlag())
  838. {
  839. // Nodes have been passed in this update
  840. U32 count = stream->readInt( 16 );
  841. mNodes.clear();
  842. Point3F pos;
  843. VectorF normal;
  844. F32 width,depth;
  845. for ( U32 i = 0; i < count; i++ )
  846. {
  847. mathRead( *stream, &pos );
  848. stream->read( &width );
  849. stream->read( &depth );
  850. mathRead( *stream, &normal );
  851. _addNode( pos, width, depth, normal );
  852. }
  853. }
  854. else
  855. {
  856. // Nodes will arrive as events
  857. U32 id;
  858. stream->read( &id );
  859. // Check if the road's nodes made it here before we did.
  860. NodeListManager::NodeList* list = NULL;
  861. if ( gClientNodeListManager->findListById( id, &list, true) )
  862. {
  863. // Work with the completed list
  864. RiverNodeList* riverList = dynamic_cast<RiverNodeList*>( list );
  865. if (riverList)
  866. buildNodesFromList( riverList );
  867. delete list;
  868. }
  869. else
  870. {
  871. // Nodes have not yet arrived, so register our interest in the list
  872. RiverNodeListNotify* notify = new RiverNodeListNotify( this, id );
  873. gClientNodeListManager->registerNotification( notify );
  874. }
  875. }
  876. }
  877. // RiverMask | InitialUpdateMask
  878. if( stream->readFlag() )
  879. {
  880. mathRead( *stream, &mObjScale );
  881. stream->readAffineTransform( &mObjToWorld );
  882. }
  883. // RegenMask
  884. if ( stream->readFlag() && isProperlyAdded() )
  885. regenerate();
  886. }
  887. void River::_getWaterPlane( const Point3F &camPos, PlaneF &outPlane, Point3F &outPos )
  888. {
  889. // Find the RiverSegment closest to the camera.
  890. F32 closestDist = F32_MAX;
  891. S32 closestSegment = 0;
  892. Point3F projPnt(0.0f, 0.0f, 0.0f);
  893. VectorF normal(0,0,0);
  894. for ( U32 i = 0; i < mSegments.size(); i++ )
  895. {
  896. const RiverSegment &segment = mSegments[i];
  897. const Point3F pos = MathUtils::mClosestPointOnSegment( segment.slice0->p1, segment.slice1->p1, camPos );
  898. F32 dist = ( camPos - pos ).len();
  899. if ( dist < closestDist )
  900. {
  901. closestDist = dist;
  902. closestSegment = i;
  903. projPnt = pos;
  904. }
  905. normal += segment.getSurfaceNormal();
  906. }
  907. if ( mReflectNormalUp )
  908. normal.set(0,0,1);
  909. else
  910. normal.normalizeSafe();
  911. outPos = projPnt;
  912. outPlane.set( projPnt, normal );
  913. }
  914. void River::setTransform( const MatrixF &mat )
  915. {
  916. for ( U32 i = 0; i < mNodes.size(); i++ )
  917. {
  918. mWorldToObj.mulP( mNodes[i].point );
  919. mat.mulP( mNodes[i].point );
  920. }
  921. /*
  922. // Get the amount of change in position.
  923. MatrixF oldMat = getTransform();
  924. Point3F oldPos = oldMat.getPosition();
  925. Point3F newPos = mat.getPosition();
  926. Point3F delta = newPos - oldPos;
  927. // Offset all nodes by that amount
  928. for ( U32 i = 0; i < mNodes.size(); i++ )
  929. {
  930. mNodes[i].point += delta;
  931. }
  932. // Assign the new position ( we ignore rotation )
  933. MatrixF newMat( oldMat );
  934. newMat.setPosition( newPos );
  935. */
  936. Parent::setTransform( mat );
  937. // Regenerate and update the client
  938. _regenerate();
  939. setMaskBits( NodeMask | RegenMask );
  940. }
  941. void River::setScale( const VectorF &scale )
  942. {
  943. // We ignore scale requests from the editor
  944. // right now.
  945. }
  946. bool River::castRay(const Point3F &s, const Point3F &e, RayInfo* info)
  947. {
  948. Point3F start = s;
  949. Point3F end = e;
  950. mObjToWorld.mulP(start);
  951. mObjToWorld.mulP(end);
  952. F32 out = 1.0f; // The output fraction/percentage along the line defined by s and e
  953. VectorF norm(0.0f, 0.0f, 0.0f); // The normal of the face intersected
  954. Vector<RiverHitSegment> hitSegments;
  955. for ( U32 i = 0; i < mSegments.size(); i++ )
  956. {
  957. const RiverSegment &segment = mSegments[i];
  958. F32 t;
  959. VectorF n;
  960. if ( segment.worldbounds.collideLine( start, end, &t, &n ) )
  961. {
  962. hitSegments.increment();
  963. hitSegments.last().t = t;
  964. hitSegments.last().idx = i;
  965. }
  966. }
  967. dQsort( hitSegments.address(), hitSegments.size(), sizeof(RiverHitSegment), compareHitSegments );
  968. U32 idx0, idx1, idx2;
  969. F32 t;
  970. for ( U32 i = 0; i < hitSegments.size(); i++ )
  971. {
  972. U32 segIdx = hitSegments[i].idx;
  973. const RiverSegment &segment = mSegments[segIdx];
  974. // Each segment has 6 faces
  975. for ( U32 j = 0; j < 6; j++ )
  976. {
  977. if ( j == 4 && segIdx != 0 )
  978. continue;
  979. if ( j == 5 && segIdx != mSegments.size() - 1 )
  980. continue;
  981. // Each face has 2 triangles
  982. for ( U32 k = 0; k < 2; k++ )
  983. {
  984. idx0 = gIdxArray[j][k][0];
  985. idx1 = gIdxArray[j][k][1];
  986. idx2 = gIdxArray[j][k][2];
  987. const Point3F &v0 = segment[idx0];
  988. const Point3F &v1 = segment[idx1];
  989. const Point3F &v2 = segment[idx2];
  990. if ( !MathUtils::mLineTriangleCollide( start, end,
  991. v2, v1, v0,
  992. NULL,
  993. &t ) )
  994. continue;
  995. if ( t >= 0.0f && t < 1.0f && t < out )
  996. {
  997. out = t;
  998. // optimize this, can be calculated easily within
  999. // the collision test
  1000. norm = PlaneF( v0, v1, v2 );
  1001. }
  1002. }
  1003. }
  1004. if (out >= 0.0f && out < 1.0f)
  1005. break;
  1006. }
  1007. if (out >= 0.0f && out < 1.0f)
  1008. {
  1009. info->t = out;
  1010. info->normal = norm;
  1011. info->point.interpolate(start, end, out);
  1012. info->face = -1;
  1013. info->object = this;
  1014. return true;
  1015. }
  1016. return false;
  1017. }
  1018. bool River::collideBox(const Point3F &start, const Point3F &end, RayInfo* info)
  1019. {
  1020. return false;
  1021. }
  1022. bool River::buildPolyList( PolyListContext context, AbstractPolyList* polyList, const Box3F& box, const SphereF& sphere )
  1023. {
  1024. Vector<const RiverSegment*> hitSegments;
  1025. for ( U32 i = 0; i < mSegments.size(); i++ )
  1026. {
  1027. const RiverSegment &segment = mSegments[i];
  1028. if ( segment.worldbounds.isOverlapped( box ) )
  1029. {
  1030. hitSegments.push_back( &segment );
  1031. }
  1032. }
  1033. if ( !hitSegments.size() )
  1034. return false;
  1035. polyList->setObject( this );
  1036. polyList->setTransform( &MatrixF::Identity, Point3F( 1.0f, 1.0f, 1.0f ) );
  1037. for ( U32 i = 0; i < hitSegments.size(); i++ )
  1038. {
  1039. const RiverSegment* segment = hitSegments[i];
  1040. for ( U32 k = 0; k < 2; k++ )
  1041. {
  1042. // gIdxArray[0] gives us the top plane (see table definition).
  1043. U32 idx0 = gIdxArray[0][k][0];
  1044. U32 idx1 = gIdxArray[0][k][1];
  1045. U32 idx2 = gIdxArray[0][k][2];
  1046. const Point3F &v0 = (*segment)[idx0];
  1047. const Point3F &v1 = (*segment)[idx1];
  1048. const Point3F &v2 = (*segment)[idx2];
  1049. // Add vertices to poly list.
  1050. U32 i0 = polyList->addPoint(v0);
  1051. polyList->addPoint(v1);
  1052. polyList->addPoint(v2);
  1053. // Add plane between them.
  1054. polyList->begin(0, 0);
  1055. polyList->vertex(i0);
  1056. polyList->vertex(i0+1);
  1057. polyList->vertex(i0+2);
  1058. polyList->plane(i0, i0+1, i0+2);
  1059. polyList->end();
  1060. }
  1061. }
  1062. return true;
  1063. }
  1064. F32 River::getWaterCoverage( const Box3F &worldBox ) const
  1065. {
  1066. PROFILE_SCOPE( River_GetWaterCoverage );
  1067. if ( !mWorldBox.isOverlapped(worldBox) )
  1068. return 0.0f;
  1069. Point3F bottomPnt = worldBox.getCenter();
  1070. bottomPnt.z = worldBox.minExtents.z;
  1071. F32 farthest = 0.0f;
  1072. for ( U32 i = 0; i < mSegments.size(); i++ )
  1073. {
  1074. const RiverSegment &segment = mSegments[i];
  1075. if ( !segment.worldbounds.isOverlapped(worldBox) )
  1076. continue;
  1077. if ( !segment.intersectBox( worldBox ) )
  1078. continue;
  1079. F32 distance = segment.distanceToSurface( bottomPnt );
  1080. if ( distance > farthest )
  1081. farthest = distance;
  1082. }
  1083. F32 height = worldBox.maxExtents.z - worldBox.minExtents.z;
  1084. F32 distance = mClampF( farthest, 0.0f, height );
  1085. F32 coverage = distance / height;
  1086. return coverage;
  1087. }
  1088. F32 River::getSurfaceHeight( const Point2F &pos ) const
  1089. {
  1090. PROFILE_SCOPE( River_GetSurfaceHeight );
  1091. Point3F origin( pos.x, pos.y, mWorldBox.maxExtents.z );
  1092. Point3F direction(0,0,-1);
  1093. U32 nodeIdx;
  1094. Point3F collisionPnt;
  1095. if ( !collideRay( origin, direction, &nodeIdx, &collisionPnt ) )
  1096. return -1.0f;
  1097. return collisionPnt.z;
  1098. }
  1099. VectorF River::getFlow( const Point3F &pos ) const
  1100. {
  1101. PROFILE_SCOPE( River_GetFlow );
  1102. for ( U32 i = 0; i < mSegments.size(); i++ )
  1103. {
  1104. const RiverSegment &segment = mSegments[i];
  1105. if ( !segment.containsPoint(pos) )
  1106. continue;
  1107. VectorF flow = segment.slice0->p1 - segment.slice1->p1;
  1108. flow.normalize();
  1109. flow *= mFlowMagnitude;
  1110. return flow;
  1111. }
  1112. return VectorF::Zero;
  1113. }
  1114. void River::onReflectionInfoChanged()
  1115. {
  1116. /*
  1117. if ( isClientObject() && GFX->getPixelShaderVersion() >= 1.4 )
  1118. {
  1119. if ( mFullReflect )
  1120. REFLECTMGR->registerObject( this, ReflectDelegate( this, &River::updateReflection ), mReflectPriority, mReflectMaxRateMs, mReflectMaxDist );
  1121. else
  1122. {
  1123. REFLECTMGR->unregisterObject( this );
  1124. mReflectTex = NULL;
  1125. }
  1126. }
  1127. */
  1128. }
  1129. void River::_regenerate()
  1130. {
  1131. if ( mNodes.size() == 0 )
  1132. return;
  1133. const Point3F &nodePt = mNodes.first().point;
  1134. MatrixF mat( true );
  1135. mat.setPosition( nodePt );
  1136. Parent::setTransform( mat );
  1137. _generateSlices();
  1138. }
  1139. void River::_generateSlices()
  1140. {
  1141. if ( mNodes.size() < 2 )
  1142. return;
  1143. U32 nodeCount = mNodes.size();
  1144. RiverSplineNode *splineNodes = new RiverSplineNode[nodeCount];
  1145. for ( U32 i = 0; i < nodeCount; i++ )
  1146. {
  1147. const RiverNode &node = mNodes[i];
  1148. splineNodes[i].x = node.point.x;
  1149. splineNodes[i].y = node.point.y;
  1150. splineNodes[i].z = node.point.z;
  1151. splineNodes[i].width = node.width;
  1152. splineNodes[i].depth = node.depth;
  1153. splineNodes[i].normal = node.normal;
  1154. }
  1155. CatmullRom<RiverSplineNode> spline;
  1156. spline.initialize( nodeCount, splineNodes );
  1157. delete [] splineNodes;
  1158. mSlices.clear();
  1159. for ( U32 i = 1; i < nodeCount; i++ )
  1160. {
  1161. F32 t0 = spline.getTime( i-1 );
  1162. F32 t1 = spline.getTime( i );
  1163. F32 segLength = spline.arcLength( t0, t1 );
  1164. U32 numSegments = mCeil( segLength / mMetersPerSegment );
  1165. numSegments = getMax( numSegments, (U32)1 );
  1166. F32 tstep = ( t1 - t0 ) / numSegments;
  1167. //AssertFatal( numSegments > 0, "River::_generateSlices, got zero segments!" );
  1168. U32 startIdx = 0;
  1169. U32 endIdx = ( i == nodeCount - 1 ) ? numSegments + 1 : numSegments;
  1170. for ( U32 j = startIdx; j < endIdx; j++ )
  1171. {
  1172. F32 t = t0 + tstep * j; //spline.findParameterByDistance( 0.0f, i * segLen );
  1173. RiverSplineNode val = spline.evaluate(t);
  1174. RiverSlice slice;
  1175. slice.p1.set( val.x, val.y, val.z );
  1176. slice.uvec.set( 0,0,1 );
  1177. slice.width = val.width;
  1178. slice.depth = val.depth;
  1179. slice.parentNodeIdx = i-1;
  1180. slice.normal = val.normal;
  1181. slice.normal.normalize();
  1182. mSlices.push_back( slice );
  1183. }
  1184. }
  1185. //
  1186. // Calculate fvec and rvec for all slices
  1187. //
  1188. RiverSlice *pSlice = NULL;
  1189. RiverSlice *pNextSlice = NULL;
  1190. // Must do the first slice outside the loop
  1191. {
  1192. pSlice = &mSlices[0];
  1193. pNextSlice = &mSlices[1];
  1194. pSlice->fvec = pNextSlice->p1 - pSlice->p1;
  1195. pSlice->fvec.normalize();
  1196. pSlice->rvec = mCross( pSlice->fvec, pSlice->normal );
  1197. pSlice->rvec.normalize();
  1198. pSlice->uvec = mCross( pSlice->rvec, pSlice->fvec );
  1199. pSlice->uvec.normalize();
  1200. pSlice->rvec = mCross( pSlice->fvec, pSlice->uvec );
  1201. pSlice->rvec.normalize();
  1202. }
  1203. for ( U32 i = 1; i < mSlices.size() - 1; i++ )
  1204. {
  1205. pSlice = &mSlices[i];
  1206. pNextSlice = &mSlices[i+1];
  1207. pSlice->fvec = pNextSlice->p1 - pSlice->p1;
  1208. pSlice->fvec.normalize();
  1209. pSlice->rvec = mCross( pSlice->fvec, pSlice->normal );
  1210. pSlice->rvec.normalize();
  1211. pSlice->uvec = mCross( pSlice->rvec, pSlice->fvec );
  1212. pSlice->uvec.normalize();
  1213. pSlice->rvec = mCross( pSlice->fvec, pSlice->uvec );
  1214. pSlice->rvec.normalize();
  1215. }
  1216. // Must do the last slice outside the loop
  1217. {
  1218. RiverSlice *lastSlice = &mSlices[mSlices.size()-1];
  1219. RiverSlice *prevSlice = &mSlices[mSlices.size()-2];
  1220. lastSlice->fvec = prevSlice->fvec;
  1221. lastSlice->rvec = mCross( lastSlice->fvec, lastSlice->normal );
  1222. lastSlice->rvec.normalize();
  1223. lastSlice->uvec = mCross( lastSlice->rvec, lastSlice->fvec );
  1224. lastSlice->uvec.normalize();
  1225. lastSlice->rvec = mCross( lastSlice->fvec, lastSlice->uvec );
  1226. lastSlice->rvec.normalize();
  1227. }
  1228. //
  1229. // Calculate p0/p2/pb0/pb2 for all slices
  1230. //
  1231. for ( U32 i = 0; i < mSlices.size(); i++ )
  1232. {
  1233. RiverSlice *slice = &mSlices[i];
  1234. slice->p0 = slice->p1 - slice->rvec * slice->width * 0.5f;
  1235. slice->p2 = slice->p1 + slice->rvec * slice->width * 0.5f;
  1236. slice->pb0 = slice->p0 - slice->uvec * slice->depth;
  1237. slice->pb2 = slice->p2 - slice->uvec * slice->depth;
  1238. }
  1239. // Generate the object/world bounds
  1240. Box3F box;
  1241. for ( U32 i = 0; i < mSlices.size(); i++ )
  1242. {
  1243. const RiverSlice &slice = mSlices[i];
  1244. if ( i == 0 )
  1245. {
  1246. box.minExtents = slice.p0;
  1247. box.maxExtents = slice.p2;
  1248. box.extend( slice.pb0 );
  1249. box.extend( slice.pb2 );
  1250. }
  1251. else
  1252. {
  1253. box.extend( slice.p0 );
  1254. box.extend( slice.p2 );
  1255. box.extend( slice.pb0 );
  1256. box.extend( slice.pb2 );
  1257. }
  1258. }
  1259. mWorldBox = box;
  1260. //mObjBox.minExtents -= pos;
  1261. //mObjBox.maxExtents -= pos;
  1262. resetObjectBox();
  1263. // Make sure we are in the correct bins given our world box.
  1264. if( getSceneManager() != NULL )
  1265. getSceneManager()->notifyObjectDirty( this );
  1266. _generateSegments();
  1267. }
  1268. void River::_generateSegments()
  1269. {
  1270. mSegments.clear();
  1271. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1272. {
  1273. RiverSegment seg( &mSlices[i], &mSlices[i+1] );
  1274. mSegments.push_back( seg );
  1275. }
  1276. /*
  1277. #ifdef TORQUE_DEBUG
  1278. for ( U32 i = 0; i < mSegments.size(); i++ )
  1279. {
  1280. const RiverSegment &segment = mSegments[i];
  1281. PlaneF normal0 = MathUtils::mTriangleNormal( segment.slice0->p0, segment.slice1->p0, segment.slice1->p2 );
  1282. PlaneF normal1 = MathUtils::mTriangleNormal( segment.slice0->p0, segment.slice1->p2, segment.slice0->p2 );
  1283. AssertFatal( true || normal0 != normal1, "River::generateSegments, segment is not coplanar!" );
  1284. }
  1285. #endif // TORQUE_DEBUG
  1286. */
  1287. // We have to go back and generate normals for each slice
  1288. // to be used in calculation of the reflect plane.
  1289. // The slice-normal we calculate are relative to the surface normal
  1290. // of the segments adjacent to the slice.
  1291. /*
  1292. if ( mSlices.size() >= 2 )
  1293. {
  1294. mSlices[0].normal = mSegments[0].getSurfaceNormal();
  1295. for ( U32 i = 1; i < mSlices.size() - 1; i++ )
  1296. {
  1297. mSlices[i].normal = ( mSegments[i-1].getSurfaceNormal() + mSegments[i].getSurfaceNormal() ) / 2;
  1298. }
  1299. mSlices.last().normal = mSegments.last().getSurfaceNormal();
  1300. }
  1301. */
  1302. _generateVerts();
  1303. }
  1304. void River::_generateVerts()
  1305. {
  1306. if ( isServerObject() )
  1307. return;
  1308. // These will depend on the level of subdivision per segment
  1309. // calculated below.
  1310. mHighVertCount = 0;
  1311. mHighTriangleCount = 0;
  1312. // Calculate the number of row/column subdivisions per each
  1313. // RiverSegment.
  1314. F32 greatestWidth = 0.1f;
  1315. for ( U32 i = 0; i < mNodes.size(); i++ )
  1316. {
  1317. RiverNode &node = mNodes[i];
  1318. if ( node.width > greatestWidth )
  1319. greatestWidth = node.width;
  1320. }
  1321. mColumnCount = mCeil( greatestWidth / mMaxDivisionSize );
  1322. for ( U32 i = 0; i < mSegments.size(); i++ )
  1323. {
  1324. RiverSegment &segment = mSegments[i];
  1325. const RiverSlice *slice = segment.slice0;
  1326. const RiverSlice *nextSlice = segment.slice1;
  1327. // Calculate the size of divisions in the forward direction ( p00 -> p01 )
  1328. F32 segLength = (nextSlice->p1 - slice->p1).len();
  1329. // A division count of one is actually NO subdivision,
  1330. // the segment corners are the only verts in this segment.
  1331. U32 numRows = 1;
  1332. if ( segLength > 0.0f )
  1333. numRows = mCeil( segLength / mMaxDivisionSize );
  1334. // The problem with calculating num columns per segment is
  1335. // two adjacent - high lod segments of different width can have
  1336. // verts that don't line up! So even though RiverSegment HAS a
  1337. // column data member we initialize all segments in the river to
  1338. // the same (River::mColumnCount)
  1339. // Calculate the size of divisions in the right direction ( p00 -> p10 )
  1340. // F32 segWidth = ( ( p11 - p01 ).len() + ( p10 - p00 ).len() ) * 0.5f;
  1341. // U32 numColumns = 5;
  1342. //F32 columnSize = segWidth / numColumns;
  1343. //while ( columnSize > mMaxDivisionSize )
  1344. //{
  1345. // numColumns++;
  1346. // columnSize = segWidth / numColumns;
  1347. //}
  1348. // Save the calculated numb of columns / rows for this segment.
  1349. segment.columns = mColumnCount;
  1350. segment.rows = numRows;
  1351. // Save the corresponding number of verts/prims
  1352. segment.numVerts = ( 1 + mColumnCount ) * ( 1 + numRows );
  1353. segment.numTriangles = mColumnCount * numRows * 2;
  1354. mHighVertCount += segment.numVerts;
  1355. mHighTriangleCount += segment.numTriangles;
  1356. }
  1357. // Number of low detail verts/prims.
  1358. mLowVertCount = mSlices.size() * 2;
  1359. mLowTriangleCount = mSegments.size() * 2;
  1360. // Allocate the low detail VertexBuffer,
  1361. // this will stay in memory and will never need to change.
  1362. mVB_low.set( GFX, mLowVertCount, GFXBufferTypeStatic );
  1363. GFXWaterVertex *lowVertPtr = mVB_low.lock();
  1364. U32 vertCounter = 0;
  1365. // The texCoord.y value start/end for a segment
  1366. // as we loop through them.
  1367. F32 textCoordV = 0;
  1368. //
  1369. // Fill the low-detail VertexBuffer
  1370. //
  1371. for ( U32 i = 0; i < mSlices.size(); i++ )
  1372. {
  1373. RiverSlice &slice = mSlices[i];
  1374. lowVertPtr->point = slice.p0;
  1375. lowVertPtr->normal = slice.normal;
  1376. lowVertPtr->undulateData.set( -slice.width*0.5f, textCoordV );
  1377. lowVertPtr->horizonFactor.set( 0, 0, 0, 0 );
  1378. lowVertPtr++;
  1379. vertCounter++;
  1380. lowVertPtr->point = slice.p2;
  1381. lowVertPtr->normal = slice.normal;
  1382. lowVertPtr->undulateData.set( slice.width*0.5f, textCoordV );
  1383. lowVertPtr->horizonFactor.set( 0, 0, 0, 0 );
  1384. lowVertPtr++;
  1385. vertCounter++;
  1386. // Save this so we can get it later.
  1387. slice.texCoordV = textCoordV;
  1388. if ( i < mSlices.size() - 1 )
  1389. {
  1390. // Increment the textCoordV for the next slice.
  1391. F32 segLen = ( mSlices[i+1].p1 - slice.p1 ).len();
  1392. textCoordV += segLen;
  1393. }
  1394. }
  1395. AssertFatal( vertCounter == mLowVertCount, "River, wrote incorrect number of verts in mBV_low!" );
  1396. // Unlock the low-detail VertexBuffer, we are done filling it.
  1397. mVB_low.unlock();
  1398. //
  1399. // Create the low-detail prim buffer(s)
  1400. //
  1401. mPB_low.set( GFX, mLowTriangleCount * 3, mLowTriangleCount, GFXBufferTypeStatic );
  1402. U16 *lowIdxBuff;
  1403. mPB_low.lock(&lowIdxBuff);
  1404. U32 curLowIdx = 0;
  1405. // Temporaries to hold indices for the corner points of a quad.
  1406. U32 p00, p01, p11, p10;
  1407. U32 offset = 0;
  1408. // Fill the low-detail PrimitiveBuffer
  1409. for ( U32 i = 0; i < mSegments.size(); i++ )
  1410. {
  1411. //const RiverSegment &segment = mSegments[i];
  1412. // Two triangles formed by the corner points of this segment
  1413. // into the the low detail primitive buffer.
  1414. p00 = offset;
  1415. p01 = p00 + 2;
  1416. p11 = p01 + 1;
  1417. p10 = p00 + 1;
  1418. // Upper-Left triangle
  1419. lowIdxBuff[curLowIdx] = p00;
  1420. curLowIdx++;
  1421. lowIdxBuff[curLowIdx] = p01;
  1422. curLowIdx++;
  1423. lowIdxBuff[curLowIdx] = p11;
  1424. curLowIdx++;
  1425. // Lower-Right Triangle
  1426. lowIdxBuff[curLowIdx] = p00;
  1427. curLowIdx++;
  1428. lowIdxBuff[curLowIdx] = p11;
  1429. curLowIdx++;
  1430. lowIdxBuff[curLowIdx] = p10;
  1431. curLowIdx++;
  1432. offset += 2;
  1433. }
  1434. AssertFatal( curLowIdx == mLowTriangleCount * 3, "River, wrote incorrect number of indices in mPB_low!" );
  1435. // Unlock the low-detail PrimitiveBuffer, we are done filling it.
  1436. mPB_low.unlock();
  1437. }
  1438. bool River::getClosestNode( const Point3F &pos, U32 &idx ) const
  1439. {
  1440. F32 closestDist = F32_MAX;
  1441. for ( U32 i = 0; i < mNodes.size(); i++ )
  1442. {
  1443. F32 dist = ( mNodes[i].point - pos ).len();
  1444. if ( dist < closestDist )
  1445. {
  1446. closestDist = dist;
  1447. idx = i;
  1448. }
  1449. }
  1450. return closestDist != F32_MAX;
  1451. }
  1452. bool River::containsPoint( const Point3F &worldPos, U32 *nodeIdx ) const
  1453. {
  1454. // If point isn't in the world box,
  1455. // it's definitely not in the River.
  1456. //if ( !getWorldBox().isContained( worldPos ) )
  1457. // return false;
  1458. // Look through all edges, does the polygon
  1459. // formed from adjacent edge's contain the worldPos?
  1460. for ( U32 i = 0; i < mSegments.size(); i++ )
  1461. {
  1462. const RiverSegment &segment = mSegments[i];
  1463. if ( segment.containsPoint( worldPos ) )
  1464. {
  1465. if ( nodeIdx )
  1466. *nodeIdx = i;
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }
  1472. F32 River::distanceToSurface( const Point3F &pnt, U32 segmentIdx )
  1473. {
  1474. return mSegments[segmentIdx].distanceToSurface( pnt );
  1475. }
  1476. bool River::collideRay( const Point3F &origin, const Point3F &direction, U32 *nodeIdx, Point3F *collisionPnt ) const
  1477. {
  1478. Point3F p0 = origin;
  1479. Point3F p1 = origin + direction * 2000.0f;
  1480. // If the line segment does not collide with the river's world box,
  1481. // it definitely does not collide with any part of the river.
  1482. if ( !getWorldBox().collideLine( p0, p1 ) )
  1483. return false;
  1484. if ( mSlices.size() < 2 )
  1485. return false;
  1486. MathUtils::Quad quad;
  1487. MathUtils::Ray ray;
  1488. F32 t;
  1489. // Check each river segment (formed by a pair of slices) for collision
  1490. // with the line segment.
  1491. for ( U32 i = 0; i < mSlices.size() - 1; i++ )
  1492. {
  1493. const RiverSlice &slice0 = mSlices[i];
  1494. const RiverSlice &slice1 = mSlices[i+1];
  1495. // For simplicities sake we will only test for collision between the
  1496. // line segment and the Top face of the river segment.
  1497. // Clockwise starting with the leftmost/closest point.
  1498. quad.p00 = slice0.p0;
  1499. quad.p01 = slice1.p0;
  1500. quad.p11 = slice1.p2;
  1501. quad.p10 = slice0.p2;
  1502. ray.origin = origin;
  1503. ray.direction = direction;
  1504. // NOTE:
  1505. // mRayQuadCollide is designed for a "real" quad in which all four points
  1506. // are coplanar which is actually not the case here. The more twist
  1507. // and turn in-between two neighboring river slices the more incorrect
  1508. // this calculation will be.
  1509. if ( MathUtils::mRayQuadCollide( quad, ray, NULL, &t ) )
  1510. {
  1511. if ( nodeIdx )
  1512. *nodeIdx = slice0.parentNodeIdx;
  1513. if ( collisionPnt )
  1514. *collisionPnt = ray.origin + ray.direction * t;
  1515. return true;
  1516. }
  1517. }
  1518. return false;
  1519. }
  1520. Point3F River::getNodePosition( U32 idx ) const
  1521. {
  1522. if ( mNodes.size() - 1 < idx )
  1523. return Point3F();
  1524. return mNodes[idx].point;
  1525. }
  1526. void River::setNodePosition( U32 idx, const Point3F &pos )
  1527. {
  1528. if ( mNodes.size() - 1 < idx )
  1529. return;
  1530. mNodes[idx].point = pos;
  1531. regenerate();
  1532. setMaskBits( NodeMask | RegenMask );
  1533. }
  1534. U32 River::addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1535. {
  1536. U32 idx = _addNode( pos, width, depth, normal );
  1537. regenerate();
  1538. setMaskBits( NodeMask | RegenMask );
  1539. return idx;
  1540. }
  1541. U32 River::insertNode(const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx)
  1542. {
  1543. U32 ret = _insertNode( pos, width, depth, normal, idx );
  1544. regenerate();
  1545. setMaskBits( NodeMask | RegenMask );
  1546. return ret;
  1547. }
  1548. void River::setNode(const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx)
  1549. {
  1550. if ( mNodes.size() - 1 < idx )
  1551. return;
  1552. RiverNode &node = mNodes[idx];
  1553. node.point = pos;
  1554. node.width = width;
  1555. node.depth = depth;
  1556. node.normal = normal;
  1557. regenerate();
  1558. setMaskBits( NodeMask | RegenMask );
  1559. }
  1560. void River::setNodeWidth( U32 idx, F32 meters )
  1561. {
  1562. meters = mClampF( meters, MIN_NODE_WIDTH, MAX_NODE_WIDTH );
  1563. if ( mNodes.size() - 1 < idx )
  1564. return;
  1565. mNodes[idx].width = meters;
  1566. _regenerate();
  1567. setMaskBits( RegenMask | NodeMask );
  1568. }
  1569. void River::setNodeHeight( U32 idx, F32 height )
  1570. {
  1571. if ( mNodes.size() - 1 < idx )
  1572. return;
  1573. mNodes[idx].point.z = height;
  1574. _regenerate();
  1575. setMaskBits( RegenMask | NodeMask );
  1576. }
  1577. F32 River::getNodeWidth( U32 idx ) const
  1578. {
  1579. if ( mNodes.size() - 1 < idx )
  1580. return -1.0f;
  1581. return mNodes[idx].width;
  1582. }
  1583. void River::setNodeDepth( U32 idx, F32 meters )
  1584. {
  1585. meters = mClampF( meters, MIN_NODE_DEPTH, MAX_NODE_DEPTH );
  1586. if ( mNodes.size() - 1 < idx )
  1587. return;
  1588. mNodes[idx].depth = meters;
  1589. _regenerate();
  1590. setMaskBits( RiverMask | RegenMask | NodeMask );
  1591. }
  1592. void River::setNodeNormal( U32 idx, const VectorF &normal )
  1593. {
  1594. if ( mNodes.size() - 1 < idx )
  1595. return;
  1596. mNodes[idx].normal = normal;
  1597. regenerate();
  1598. setMaskBits( NodeMask | RegenMask );
  1599. }
  1600. F32 River::getNodeDepth( U32 idx ) const
  1601. {
  1602. if ( mNodes.size() - 1 < idx )
  1603. return -1.0f;
  1604. return mNodes[idx].depth;
  1605. }
  1606. VectorF River::getNodeNormal( U32 idx ) const
  1607. {
  1608. if ( mNodes.size() - 1 < idx )
  1609. return VectorF::Zero;
  1610. return mNodes[idx].normal;
  1611. }
  1612. MatrixF River::getNodeTransform( U32 idx ) const
  1613. {
  1614. MatrixF mat(true);
  1615. if ( mNodes.size() - 1 < idx )
  1616. return mat;
  1617. bool hasNext = idx + 1 < mNodes.size();
  1618. bool hasPrev = (S32)idx - 1 >= 0;
  1619. const RiverNode &node = mNodes[idx];
  1620. VectorF fvec( 0, 1, 0 );
  1621. if ( hasNext )
  1622. {
  1623. fvec = mNodes[idx+1].point - node.point;
  1624. fvec.normalizeSafe();
  1625. }
  1626. else if ( hasPrev )
  1627. {
  1628. fvec = node.point - mNodes[idx-1].point;
  1629. fvec.normalizeSafe();
  1630. }
  1631. else
  1632. fvec = mPerp( node.normal );
  1633. if ( fvec.isZero() )
  1634. fvec = mPerp( node.normal );
  1635. F32 dot = mDot( fvec, node.normal );
  1636. if ( dot < -0.9f || dot > 0.9f )
  1637. fvec = mPerp( node.normal );
  1638. VectorF rvec = mCross( fvec, node.normal );
  1639. if ( rvec.isZero() )
  1640. rvec = mPerp( fvec );
  1641. rvec.normalize();
  1642. fvec = mCross( node.normal, rvec );
  1643. fvec.normalize();
  1644. mat.setColumn( 0, rvec );
  1645. mat.setColumn( 1, fvec );
  1646. mat.setColumn( 2, node.normal );
  1647. mat.setColumn( 3, node.point );
  1648. AssertFatal( m_matF_determinant( mat ) != 0.0f, "no inverse!");
  1649. return mat;
  1650. }
  1651. void River::deleteNode( U32 idx )
  1652. {
  1653. if ( mNodes.size() - 1 < idx )
  1654. return;
  1655. mNodes.erase(idx);
  1656. _regenerate();
  1657. setMaskBits( RegenMask | NodeMask );
  1658. }
  1659. void River::buildNodesFromList( RiverNodeList* list )
  1660. {
  1661. mNodes.clear();
  1662. for (U32 i=0; i<list->mPositions.size(); ++i)
  1663. {
  1664. _addNode( list->mPositions[i], list->mWidths[i], list->mDepths[i], list->mNormals[i] );
  1665. }
  1666. _regenerate();
  1667. }
  1668. void River::_makeRenderBatches( const Point3F &cameraPos )
  1669. {
  1670. // Loop through each segment to determine if it is either 1 [not visible], 2 [high LOD], 3 [low LOD]
  1671. mHighLODBatches.clear();
  1672. mLowLODBatches.clear();
  1673. // Keeps track of what we batch type we are currently collecting.
  1674. // -1 is uninitialized, 0 is low detail, 1 is high detail
  1675. S32 lastDetail = -1;
  1676. bool highDetail;
  1677. U32 startSegmentIdx = -1;
  1678. U32 endSegmentIdx = 0;
  1679. F32 lodDistSquared = mLodDistance * mLodDistance;
  1680. for ( U32 i = 0; i < mSegments.size(); i++ )
  1681. {
  1682. const RiverSegment &segment = mSegments[i];
  1683. const RiverSlice *slice = segment.slice0;
  1684. const RiverSlice *nextSlice = segment.slice1;
  1685. // TODO: add bounds BoxF to RiverSegment
  1686. const bool isVisible = true; //frustum.intersects( segment.bounds );
  1687. if ( isVisible )
  1688. {
  1689. F32 dist0 = MathUtils::mTriangleDistance( slice->p0, nextSlice->p0, nextSlice->p2, cameraPos );
  1690. F32 dist1 = MathUtils::mTriangleDistance( slice->p0, nextSlice->p2, slice->p2, cameraPos );
  1691. F32 dist = getMin( dist0, dist1 );
  1692. highDetail = ( dist < lodDistSquared );
  1693. if ( (highDetail && lastDetail == 0) ||
  1694. (!highDetail && lastDetail == 1) )
  1695. {
  1696. // We hit a segment with a different lod than the previous.
  1697. // Save what we have so far...
  1698. RiverRenderBatch batch;
  1699. batch.startSegmentIdx = startSegmentIdx;
  1700. batch.endSegmentIdx = endSegmentIdx;
  1701. if ( lastDetail == 0 )
  1702. {
  1703. mLowLODBatches.push_back( batch );
  1704. }
  1705. else
  1706. {
  1707. mHighLODBatches.push_back( batch );
  1708. }
  1709. // Reset the batching
  1710. startSegmentIdx = -1;
  1711. lastDetail = -1;
  1712. i--;
  1713. continue;
  1714. }
  1715. // If this is the start of a set of batches.
  1716. if ( startSegmentIdx == -1 )
  1717. {
  1718. endSegmentIdx = startSegmentIdx = i;
  1719. lastDetail = ( highDetail ) ? 1 : 0;
  1720. }
  1721. // Else we're extending the end batch index.
  1722. else
  1723. ++endSegmentIdx;
  1724. // If this isn't the last batch then continue.
  1725. if ( i < mSegments.size()-1 )
  1726. continue;
  1727. }
  1728. // If we still don't have a start batch skip.
  1729. if ( startSegmentIdx == -1 )
  1730. continue;
  1731. // Save what we have so far...
  1732. RiverRenderBatch batch;
  1733. batch.startSegmentIdx = startSegmentIdx;
  1734. batch.endSegmentIdx = endSegmentIdx;
  1735. if ( lastDetail == 0 )
  1736. {
  1737. mLowLODBatches.push_back( batch );
  1738. }
  1739. else
  1740. {
  1741. mHighLODBatches.push_back( batch );
  1742. }
  1743. // Reset the batching.
  1744. startSegmentIdx = -1;
  1745. lastDetail = -1;
  1746. }
  1747. }
  1748. void River::_makeHighLODBuffers()
  1749. {
  1750. PROFILE_SCOPE( River_makeHighLODBuffers );
  1751. // This is the number of verts/triangles for ALL high lod batches combined.
  1752. // eg. the size for the buffers.
  1753. U32 numVerts = 0;
  1754. U32 numTriangles = 0;
  1755. for ( U32 i = 0; i < mHighLODBatches.size(); i++ )
  1756. {
  1757. RiverRenderBatch &batch = mHighLODBatches[i];
  1758. for ( U32 j = batch.startSegmentIdx; j <= batch.endSegmentIdx; j++ )
  1759. {
  1760. const RiverSegment &segment = mSegments[j];
  1761. numTriangles += segment.numTriangles;
  1762. numVerts += segment.numVerts;
  1763. }
  1764. }
  1765. if ( numVerts > MAX_DYNAMIC_VERTS || numTriangles * 3 > MAX_DYNAMIC_INDICES )
  1766. {
  1767. mVB_high = NULL;
  1768. mPB_high = NULL;
  1769. return;
  1770. }
  1771. mHighTriangleCount = numTriangles;
  1772. mHighVertCount = numVerts;
  1773. mVB_high.set( GFX, numVerts, GFXBufferTypeVolatile );
  1774. GFXWaterVertex *vertPtr = mVB_high.lock();
  1775. U32 vertCounter = 0;
  1776. // NOTE: this will break if different segments have different number
  1777. // of columns, but that will also cause T-junction triangles so just don't
  1778. // do that.
  1779. // For each batch, loop through the segments contained by
  1780. // that batch, and add their verts to the buffer.
  1781. for ( U32 i = 0; i < mHighLODBatches.size(); i++ )
  1782. {
  1783. RiverRenderBatch &batch = mHighLODBatches[i];
  1784. batch.startVert = vertCounter;
  1785. batch.vertCount = 0;
  1786. VectorF lastNormal(0,0,1);
  1787. for ( U32 j = batch.startSegmentIdx; j <= batch.endSegmentIdx; j++ )
  1788. {
  1789. // Add the verts for this segment to the buffer.
  1790. RiverSegment &segment = mSegments[j];
  1791. BiSqrToQuad3D squareToQuad( segment.getP00(),
  1792. segment.getP10(),
  1793. segment.getP11(),
  1794. segment.getP01() );
  1795. // We are duplicating the last row of verts in a segment on
  1796. // the first row of the next segment. This could be optimized but
  1797. // shouldn't cause any problems.
  1798. VectorF normal = segment.getSurfaceNormal();
  1799. for ( U32 k = 0; k <= segment.rows; k++ )
  1800. {
  1801. VectorF vertNormal = ( k == 0 && j != batch.startSegmentIdx ) ? lastNormal : normal;
  1802. F32 rowLen = mLerp( segment.slice0->width, segment.slice1->width, (F32)k / (F32)segment.rows );
  1803. for ( U32 l = 0; l <= segment.columns; l++ )
  1804. {
  1805. // We are generating a "row" of verts along the forwardDivision
  1806. // Each l iteration is a step to the right along with row.
  1807. Point2F uv( (F32)l / (F32)segment.columns, (F32)k / (F32)segment.rows );
  1808. Point3F pnt = squareToQuad.transform( uv );
  1809. // Assign the Vert
  1810. vertPtr->point = pnt;
  1811. vertPtr->normal = vertNormal;
  1812. vertPtr->undulateData.x = ( uv.x - 0.5f ) * rowLen;
  1813. vertPtr->undulateData.y = ( segment.TexCoordEnd() - segment.TexCoordStart() ) * uv.y + segment.TexCoordStart();
  1814. vertPtr->horizonFactor.set( 0, 0, 0, 0 );
  1815. vertPtr++;
  1816. vertCounter++;
  1817. batch.vertCount++;
  1818. }
  1819. }
  1820. lastNormal = normal;
  1821. }
  1822. }
  1823. AssertFatal( vertCounter == mHighVertCount, "River, wrote incorrect number of verts in mVB_high" );
  1824. mVB_high.unlock();
  1825. //
  1826. // Do the high lod primitive buffer.
  1827. //
  1828. mPB_high.set( GFX, numTriangles * 3, numTriangles, GFXBufferTypeVolatile );
  1829. U16 *idxBuff;
  1830. mPB_high.lock(&idxBuff);
  1831. U32 curIdx = 0;
  1832. U32 batchOffset = 0;
  1833. // For each high lod batch, we must add indices to the buffer
  1834. // for each segment it contains ( and the count will depend on
  1835. // the division level columns/rows for each segment ).
  1836. // Temporaries for holding the indices of a quad
  1837. U32 p00, p01, p11, p10;
  1838. for ( U32 i = 0; i < mHighLODBatches.size(); i++ )
  1839. {
  1840. RiverRenderBatch &batch = mHighLODBatches[i];
  1841. batch.indexCount = 0;
  1842. batch.triangleCount = 0;
  1843. batch.startIndex = curIdx;
  1844. U32 temp = 0;
  1845. U32 segmentOffset = 0;
  1846. for ( U32 j = batch.startSegmentIdx; j <= batch.endSegmentIdx; j++ )
  1847. {
  1848. const RiverSegment &segment = mSegments[j];
  1849. // Loop through all divisions adding the indices to the
  1850. // high detail primitive buffer.
  1851. for ( U32 k = 0; k < segment.rows; k++ )
  1852. {
  1853. for ( U32 l = 0; l < segment.columns; l++ )
  1854. {
  1855. // The indices for this quad.
  1856. p00 = batchOffset + segmentOffset + l + k * ( segment.columns + 1 );
  1857. p01 = p00 + segment.columns + 1;
  1858. p11 = p01 + 1;
  1859. p10 = p00 + 1;
  1860. AssertFatal( p00 <= mHighTriangleCount * 3, "River, bad draw call!" );
  1861. AssertFatal( p01 <= mHighTriangleCount * 3, "River, bad draw call!" );
  1862. AssertFatal( p11 <= mHighTriangleCount * 3, "River, bad draw call!" );
  1863. AssertFatal( p10 <= mHighTriangleCount * 3, "River, bad draw call!" );
  1864. // Upper-Left triangle
  1865. idxBuff[curIdx] = p00;
  1866. curIdx++;
  1867. idxBuff[curIdx] = p01;
  1868. curIdx++;
  1869. idxBuff[curIdx] = p11;
  1870. curIdx++;
  1871. // Lower-Right Triangle
  1872. idxBuff[curIdx] = p00;
  1873. curIdx++;
  1874. idxBuff[curIdx] = p11;
  1875. curIdx++;
  1876. idxBuff[curIdx] = p10;
  1877. curIdx++;
  1878. batch.indexCount += 6;
  1879. batch.triangleCount += 2;
  1880. }
  1881. }
  1882. // Increment the sliceOffset by the number of verts
  1883. // used by this segment. So the next segment will index
  1884. // into new verts.
  1885. segmentOffset += ( segment.columns + 1 ) * ( segment.rows + 1 );
  1886. temp += ( segment.columns + 1 ) * ( segment.rows + 1 );
  1887. }
  1888. batchOffset += temp;
  1889. }
  1890. // Unlock the PrimitiveBuffer, we are done filling it.
  1891. mPB_high.unlock();
  1892. }
  1893. U32 River::_addNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal )
  1894. {
  1895. mNodes.increment();
  1896. RiverNode &node = mNodes.last();
  1897. node.point = pos;
  1898. node.width = width;
  1899. node.depth = depth;
  1900. node.normal = normal;
  1901. setMaskBits( NodeMask | RegenMask );
  1902. return mNodes.size() - 1;
  1903. }
  1904. U32 River::_insertNode( const Point3F &pos, const F32 &width, const F32 &depth, const VectorF &normal, const U32 &idx )
  1905. {
  1906. U32 ret;
  1907. RiverNode *node;
  1908. if ( idx == U32_MAX )
  1909. {
  1910. mNodes.increment();
  1911. node = &mNodes.last();
  1912. ret = mNodes.size() - 1;
  1913. }
  1914. else
  1915. {
  1916. mNodes.insert( idx );
  1917. node = &mNodes[idx];
  1918. ret = idx;
  1919. }
  1920. node->point = pos;
  1921. node->depth = depth;
  1922. node->width = width;
  1923. node->normal = normal;
  1924. return ret;
  1925. }
  1926. void River::setMetersPerSegment( F32 meters )
  1927. {
  1928. if ( meters < MIN_METERS_PER_SEGMENT )
  1929. {
  1930. Con::warnf( "River::setMetersPerSegment, specified meters (%g) is below the min meters (%g), NOT SET!", meters, MIN_METERS_PER_SEGMENT );
  1931. return;
  1932. }
  1933. mMetersPerSegment = meters;
  1934. _regenerate();
  1935. setMaskBits( RiverMask | RegenMask );
  1936. }
  1937. void River::setBatchSize( U32 size )
  1938. {
  1939. // Not functional
  1940. //mSegmentsPerBatch = size;
  1941. //_regenerate();
  1942. //setMaskBits( RiverMask | RegenMask );
  1943. }
  1944. void River::regenerate()
  1945. {
  1946. _regenerate();
  1947. setMaskBits( RegenMask );
  1948. }
  1949. void River::setMaxDivisionSize( F32 meters )
  1950. {
  1951. if ( meters < mMinDivisionSize )
  1952. mMaxDivisionSize = mMinDivisionSize;
  1953. else
  1954. mMaxDivisionSize = meters;
  1955. _regenerate();
  1956. setMaskBits( RiverMask | RegenMask );
  1957. }
  1958. //-------------------------------------------------------------------------
  1959. // Console Methods
  1960. //-------------------------------------------------------------------------
  1961. DefineEngineMethod( River, regenerate, void, (),,
  1962. "Intended as a helper to developers and editor scripts.\n"
  1963. "Force River to recreate its geometry."
  1964. )
  1965. {
  1966. object->regenerate();
  1967. }
  1968. DefineEngineMethod( River, setMetersPerSegment, void, ( F32 meters ),,
  1969. "Intended as a helper to developers and editor scripts.\n"
  1970. "@see SegmentLength field."
  1971. )
  1972. {
  1973. object->setMetersPerSegment( meters );
  1974. }
  1975. DefineEngineMethod( River, setBatchSize, void, ( F32 meters ),,
  1976. "Intended as a helper to developers and editor scripts.\n"
  1977. "BatchSize is not currently used."
  1978. )
  1979. {
  1980. object->setBatchSize( meters );
  1981. }
  1982. DefineEngineMethod( River, setNodeDepth, void, ( S32 idx, F32 meters ),,
  1983. "Intended as a helper to developers and editor scripts.\n"
  1984. "Sets the depth in meters of a particular node."
  1985. )
  1986. {
  1987. object->setNodeDepth( idx, meters );
  1988. }
  1989. DefineEngineMethod( River, setMaxDivisionSize, void, ( F32 meters ),,
  1990. "Intended as a helper to developers and editor scripts.\n"
  1991. "@see SubdivideLength field."
  1992. )
  1993. {
  1994. object->setMaxDivisionSize( meters );
  1995. }