mathUtils.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  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 "math/util/frustum.h"
  24. #include "math/mathUtils.h"
  25. #include "math/mMath.h"
  26. #include "math/mRandom.h"
  27. #include "math/util/frustum.h"
  28. #include "platform/profiler.h"
  29. #include "core/tAlgorithm.h"
  30. #include "gfx/gfxDevice.h"
  31. namespace MathUtils
  32. {
  33. MRandomLCG sgRandom(0xdeadbeef); ///< Our random number generator.
  34. //-----------------------------------------------------------------------------
  35. bool capsuleCapsuleOverlap(const Point3F & a1, const Point3F & b1, F32 rad1, const Point3F & a2, const Point3F & b2, F32 rad2)
  36. {
  37. F32 s,t;
  38. Point3F c1,c2;
  39. F32 dist = segmentSegmentNearest(a1,b1,a2,b2,s,t,c1,c2);
  40. return dist <= (rad1+rad2)*(rad1+rad2);
  41. }
  42. //-----------------------------------------------------------------------------
  43. F32 segmentSegmentNearest(const Point3F & p1, const Point3F & q1, const Point3F & p2, const Point3F & q2, F32 & s, F32 & t, Point3F & c1, Point3F & c2)
  44. {
  45. Point3F d1 = q1-p1;
  46. Point3F d2 = q2-p2;
  47. Point3F r = p1-p2;
  48. F32 a = mDot(d1,d1);
  49. F32 e = mDot(d2,d2);
  50. F32 f = mDot(d2,r);
  51. const F32 EPSILON = 0.001f;
  52. if (a <= EPSILON && e <= EPSILON)
  53. {
  54. s = t = 0.0f;
  55. c1 = p1;
  56. c2 = p2;
  57. return mDot(c1-c2,c1-c2);
  58. }
  59. if (a <= EPSILON)
  60. {
  61. s = 0.0f;
  62. t = mClampF(f/e,0.0f,1.0f);
  63. }
  64. else
  65. {
  66. F32 c = mDot(d1,r);
  67. if (e <= EPSILON)
  68. {
  69. t = 0.0f;
  70. s = mClampF(-c/a,0.0f,1.0f);
  71. }
  72. else
  73. {
  74. F32 b = mDot(d1,d2);
  75. F32 denom = a*e-b*b;
  76. if (denom != 0.0f)
  77. s = mClampF((b*f-c*e)/denom,0.0f,1.0f);
  78. else
  79. s = 0.0f;
  80. F32 tnom = b*s+f;
  81. if (tnom < 0.0f)
  82. {
  83. t = 0.0f;
  84. s = mClampF(-c/a,0.0f,1.0f);
  85. }
  86. else if (tnom>e)
  87. {
  88. t = 1.0f;
  89. s = mClampF((b-c)/a,0.0f,1.0f);
  90. }
  91. else
  92. t = tnom/e;
  93. }
  94. }
  95. c1 = p1 + d1*s;
  96. c2 = p2 + d2*t;
  97. return mDot(c1-c2,c1-c2);
  98. }
  99. //-----------------------------------------------------------------------------
  100. bool capsuleSphereNearestOverlap(const Point3F & A0, const Point3F A1, F32 radA, const Point3F & B, F32 radB, F32 & t)
  101. {
  102. Point3F V = A1-A0;
  103. Point3F A0B = A0-B;
  104. F32 d1 = mDot(A0B,V);
  105. F32 d2 = mDot(A0B,A0B);
  106. F32 d3 = mDot(V,V);
  107. F32 R2 = (radA+radB)*(radA+radB);
  108. if (d2<R2)
  109. {
  110. // starting in collision state
  111. t=0;
  112. return true;
  113. }
  114. if (d3<0.01f)
  115. // no movement, and don't start in collision state, so no collision
  116. return false;
  117. F32 b24ac = mSqrt(d1*d1-d2*d3+d3*R2);
  118. F32 t1 = (-d1-b24ac)/d3;
  119. if (t1>0 && t1<1.0f)
  120. {
  121. t=t1;
  122. return true;
  123. }
  124. F32 t2 = (-d1+b24ac)/d3;
  125. if (t2>0 && t2<1.0f)
  126. {
  127. t=t2;
  128. return true;
  129. }
  130. if (t1<0 && t2>0)
  131. {
  132. t=0;
  133. return true;
  134. }
  135. return false;
  136. }
  137. //-----------------------------------------------------------------------------
  138. void vectorRotateZAxis( Point3F &vector, F32 radians )
  139. {
  140. F32 sin, cos;
  141. mSinCos(radians, sin, cos);
  142. F32 x = cos * vector.x - sin * vector.y;
  143. F32 y = sin * vector.x + cos * vector.y;
  144. vector.x = x;
  145. vector.y = y;
  146. }
  147. void vectorRotateZAxis( F32 radians, Point3F *vectors, U32 count )
  148. {
  149. F32 sin, cos;
  150. mSinCos(radians, sin, cos);
  151. F32 x, y;
  152. const Point3F *end = vectors + count;
  153. for ( ; vectors != end; vectors++ )
  154. {
  155. x = cos * vectors->x - sin * vectors->y;
  156. y = sin * vectors->x + cos * vectors->y;
  157. vectors->x = x;
  158. vectors->y = y;
  159. }
  160. }
  161. //-----------------------------------------------------------------------------
  162. void getZBiasProjectionMatrix( F32 bias, const Frustum &frustum, MatrixF *outMat, bool rotate )
  163. {
  164. Frustum temp(frustum);
  165. temp.setNearDist(frustum.getNearDist() + bias);
  166. temp.getProjectionMatrix(outMat, rotate);
  167. }
  168. //-----------------------------------------------------------------------------
  169. MatrixF createOrientFromDir( const Point3F &direction )
  170. {
  171. Point3F j = direction;
  172. Point3F k(0.0f, 0.0f, 1.0f);
  173. Point3F i;
  174. mCross( j, k, &i );
  175. if( i.magnitudeSafe() == 0.0f )
  176. {
  177. i.set( 0.0f, -1.0f, 0.0f );
  178. }
  179. i.normalizeSafe();
  180. mCross( i, j, &k );
  181. MatrixF mat( true );
  182. mat.setColumn( 0, i );
  183. mat.setColumn( 1, j );
  184. mat.setColumn( 2, k );
  185. return mat;
  186. }
  187. //-----------------------------------------------------------------------------
  188. void getMatrixFromUpVector( const VectorF &up, MatrixF *outMat )
  189. {
  190. AssertFatal( up.isUnitLength(), "MathUtils::getMatrixFromUpVector() - Up vector was not normalized!" );
  191. AssertFatal( outMat, "MathUtils::getMatrixFromUpVector() - Got null output matrix!" );
  192. AssertFatal( outMat->isAffine(), "MathUtils::getMatrixFromUpVector() - Got uninitialized matrix!" );
  193. VectorF forward = mPerp( up );
  194. VectorF right = mCross( forward, up );
  195. right.normalize();
  196. forward = mCross( up, right );
  197. forward.normalize();
  198. outMat->setColumn( 0, right );
  199. outMat->setColumn( 1, forward );
  200. outMat->setColumn( 2, up );
  201. }
  202. //-----------------------------------------------------------------------------
  203. void getMatrixFromForwardVector( const VectorF &forward, MatrixF *outMat )
  204. {
  205. AssertFatal( forward.isUnitLength(), "MathUtils::getMatrixFromForwardVector() - Forward vector was not normalized!" );
  206. AssertFatal( outMat, "MathUtils::getMatrixFromForwardVector() - Got null output matrix!" );
  207. AssertFatal( outMat->isAffine(), "MathUtils::getMatrixFromForwardVector() - Got uninitialized matrix!" );
  208. VectorF up = mPerp( forward );
  209. VectorF right = mCross( forward, up );
  210. right.normalize();
  211. up = mCross( right, forward );
  212. up.normalize();
  213. outMat->setColumn( 0, right );
  214. outMat->setColumn( 1, forward );
  215. outMat->setColumn( 2, up );
  216. }
  217. //-----------------------------------------------------------------------------
  218. Point3F randomDir( const Point3F &axis, F32 thetaAngleMin, F32 thetaAngleMax,
  219. F32 phiAngleMin, F32 phiAngleMax )
  220. {
  221. MatrixF orient = createOrientFromDir( axis );
  222. Point3F axisx;
  223. orient.getColumn( 0, &axisx );
  224. F32 theta = (thetaAngleMax - thetaAngleMin) * sgRandom.randF() + thetaAngleMin;
  225. F32 phi = (phiAngleMax - phiAngleMin) * sgRandom.randF() + phiAngleMin;
  226. // Both phi and theta are in degs. Create axis angles out of them, and create the
  227. // appropriate rotation matrix...
  228. AngAxisF thetaRot(axisx, theta * (M_PI_F / 180.0f));
  229. AngAxisF phiRot(axis, phi * (M_PI_F / 180.0f));
  230. Point3F ejectionAxis = axis;
  231. MatrixF temp(true);
  232. thetaRot.setMatrix(&temp);
  233. temp.mulP(ejectionAxis);
  234. phiRot.setMatrix(&temp);
  235. temp.mulP(ejectionAxis);
  236. return ejectionAxis;
  237. }
  238. //-----------------------------------------------------------------------------
  239. Point3F randomPointInSphere( F32 radius )
  240. {
  241. AssertFatal( radius > 0.0f, "MathUtils::randomPointInRadius - radius must be positive" );
  242. #define MAX_TRIES 20
  243. Point3F out;
  244. F32 radiusSq = radius * radius;
  245. for ( S32 i = 0; i < MAX_TRIES; i++ )
  246. {
  247. out.x = sgRandom.randF(-radius,radius);
  248. out.y = sgRandom.randF(-radius,radius);
  249. out.z = sgRandom.randF(-radius,radius);
  250. if ( out.lenSquared() < radiusSq )
  251. return out;
  252. }
  253. AssertFatal( false, "MathUtils::randomPointInRadius - something is wrong, should not fail this many times." );
  254. return Point3F::Zero;
  255. }
  256. //-----------------------------------------------------------------------------
  257. Point2F randomPointInCircle( F32 radius )
  258. {
  259. AssertFatal( radius > 0.0f, "MathUtils::randomPointInRadius - radius must be positive" );
  260. #define MAX_TRIES 20
  261. Point2F out;
  262. F32 radiusSq = radius * radius;
  263. for ( S32 i = 0; i < MAX_TRIES; i++ )
  264. {
  265. out.x = sgRandom.randF(-radius,radius);
  266. out.y = sgRandom.randF(-radius,radius);
  267. if ( out.lenSquared() < radiusSq )
  268. return out;
  269. }
  270. AssertFatal( false, "MathUtils::randomPointInRadius - something is wrong, should not fail this many times." );
  271. return Point2F::Zero;
  272. }
  273. //-----------------------------------------------------------------------------
  274. void getAnglesFromVector( const VectorF &vec, F32 &yawAng, F32 &pitchAng )
  275. {
  276. yawAng = mAtan2( vec.x, vec.y );
  277. if( yawAng < 0.0f )
  278. yawAng += M_2PI_F;
  279. if( mFabs(vec.x) > mFabs(vec.y) )
  280. pitchAng = mAtan2( mFabs(vec.z), mFabs(vec.x) );
  281. else
  282. pitchAng = mAtan2( mFabs(vec.z), mFabs(vec.y) );
  283. if( vec.z < 0.0f )
  284. pitchAng = -pitchAng;
  285. }
  286. //-----------------------------------------------------------------------------
  287. void getVectorFromAngles( VectorF &vec, F32 yawAng, F32 pitchAng )
  288. {
  289. VectorF pnt( 0.0f, 1.0f, 0.0f );
  290. EulerF rot( -pitchAng, 0.0f, 0.0f );
  291. MatrixF mat( rot );
  292. rot.set( 0.0f, 0.0f, yawAng );
  293. MatrixF mat2( rot );
  294. mat.mulV( pnt );
  295. mat2.mulV( pnt );
  296. vec = pnt;
  297. }
  298. F32 getAngleBetweenVectors(VectorF vecA, VectorF vecB)
  299. {
  300. F32 dot = mDot(vecA, vecB);
  301. F32 lenSq1 = vecA.lenSquared();
  302. F32 lenSq2 = vecB.lenSquared();
  303. F32 angle = mAcos(dot / mSqrt(lenSq1 * lenSq2));
  304. return angle;
  305. }
  306. F32 getSignedAngleBetweenVectors(VectorF vecA, VectorF vecB, VectorF norm)
  307. {
  308. // angle in 0-180
  309. F32 angle = getAngleBetweenVectors(vecA, vecB);
  310. F32 sign = mSign(mDot(norm, mCross(vecA, vecB)));
  311. // angle in -179-180
  312. F32 signed_angle = angle * sign;
  313. return signed_angle;
  314. }
  315. //-----------------------------------------------------------------------------
  316. void transformBoundingBox(const Box3F &sbox, const MatrixF &mat, const Point3F scale, Box3F &dbox)
  317. {
  318. Point3F center;
  319. // set transformed center...
  320. sbox.getCenter(&center);
  321. center.convolve(scale);
  322. mat.mulP(center);
  323. dbox.minExtents = center;
  324. dbox.maxExtents = center;
  325. Point3F val;
  326. for(U32 ix=0; ix<2; ix++)
  327. {
  328. if(ix & 0x1)
  329. val.x = sbox.minExtents.x;
  330. else
  331. val.x = sbox.maxExtents.x;
  332. for(U32 iy=0; iy<2; iy++)
  333. {
  334. if(iy & 0x1)
  335. val.y = sbox.minExtents.y;
  336. else
  337. val.y = sbox.maxExtents.y;
  338. for(U32 iz=0; iz<2; iz++)
  339. {
  340. if(iz & 0x1)
  341. val.z = sbox.minExtents.z;
  342. else
  343. val.z = sbox.maxExtents.z;
  344. Point3F v1, v2;
  345. v1 = val;
  346. v1.convolve(scale);
  347. mat.mulP(v1, &v2);
  348. dbox.minExtents.setMin(v2);
  349. dbox.maxExtents.setMax(v2);
  350. }
  351. }
  352. }
  353. }
  354. //-----------------------------------------------------------------------------
  355. bool mProjectWorldToScreen( const Point3F &in,
  356. Point3F *out,
  357. const RectI &view,
  358. const MatrixF &world,
  359. const MatrixF &projection )
  360. {
  361. MatrixF worldProjection = projection;
  362. worldProjection.mul(world);
  363. return mProjectWorldToScreen( in, out, view, worldProjection );
  364. }
  365. //-----------------------------------------------------------------------------
  366. bool mProjectWorldToScreen( const Point3F &in,
  367. Point3F *out,
  368. const RectI &view,
  369. const MatrixF &worldProjection )
  370. {
  371. Point4F temp(in.x,in.y,in.z,1.0f);
  372. worldProjection.mul(temp);
  373. // Perform the perspective division. For orthographic
  374. // projections, temp.w will be 1.
  375. temp.x /= temp.w;
  376. temp.y /= temp.w;
  377. temp.z /= temp.w;
  378. // Take the normalized device coordinates (NDC) and transform them
  379. // into device coordinates.
  380. out->x = (temp.x + 1.0f) / 2.0f * view.extent.x + view.point.x;
  381. out->y = (1.0f - temp.y) / 2.0f * view.extent.y + view.point.y;
  382. out->z = temp.z;
  383. if ( out->z < 0.0f || out->z > 1.0f ||
  384. out->x < (F32)view.point.x || out->x > (F32)view.point.x + (F32)view.extent.x ||
  385. out->y < (F32)view.point.y || out->y > (F32)view.point.y + (F32)view.extent.y )
  386. return false;
  387. return true;
  388. }
  389. //-----------------------------------------------------------------------------
  390. void mProjectScreenToWorld( const Point3F &in,
  391. Point3F *out,
  392. const RectI &view,
  393. const MatrixF &world,
  394. const MatrixF &projection,
  395. F32 zfar,
  396. F32 znear )
  397. {
  398. MatrixF invWorldProjection = projection;
  399. invWorldProjection.mul(world);
  400. invWorldProjection.inverse();
  401. Point3F vec;
  402. vec.x = (in.x - view.point.x) * 2.0f / view.extent.x - 1.0f;
  403. vec.y = -(in.y - view.point.y) * 2.0f / view.extent.y + 1.0f;
  404. vec.z = (znear + in.z * (zfar - znear))/zfar;
  405. invWorldProjection.mulV(vec);
  406. vec *= 1.0f + in.z * zfar;
  407. invWorldProjection.getColumn(3, out);
  408. (*out) += vec;
  409. }
  410. //-----------------------------------------------------------------------------
  411. bool pointInPolygon( const Point2F *verts, U32 vertCount, const Point2F &testPt )
  412. {
  413. U32 i, j, c = 0;
  414. for ( i = 0, j = vertCount-1; i < vertCount; j = i++ )
  415. {
  416. if ( ( ( verts[i].y > testPt.y ) != ( verts[j].y > testPt.y ) ) &&
  417. ( testPt.x < ( verts[j].x - verts[i].x ) *
  418. ( testPt.y - verts[i].y ) /
  419. ( verts[j].y - verts[i].y ) + verts[i].x ) )
  420. c = !c;
  421. }
  422. return c != 0;
  423. }
  424. //-----------------------------------------------------------------------------
  425. F32 mTriangleDistance( const Point3F &A, const Point3F &B, const Point3F &C, const Point3F &P, IntersectInfo* info )
  426. {
  427. Point3F diff = A - P;
  428. Point3F edge0 = B - A;
  429. Point3F edge1 = C - A;
  430. F32 a00 = edge0.lenSquared();
  431. F32 a01 = mDot( edge0, edge1 );
  432. F32 a11 = edge1.lenSquared();
  433. F32 b0 = mDot( diff, edge0 );
  434. F32 b1 = mDot( diff, edge1 );
  435. F32 c = diff.lenSquared();
  436. F32 det = mFabs(a00*a11-a01*a01);
  437. F32 s = a01*b1-a11*b0;
  438. F32 t = a01*b0-a00*b1;
  439. F32 sqrDistance;
  440. if (s + t <= det)
  441. {
  442. if (s < 0.0f)
  443. {
  444. if (t < 0.0f) // region 4
  445. {
  446. if (b0 < 0.0f)
  447. {
  448. t = 0.0f;
  449. if (-b0 >= a00)
  450. {
  451. s = 1.0f;
  452. sqrDistance = a00 + (2.0f)*b0 + c;
  453. }
  454. else
  455. {
  456. s = -b0/a00;
  457. sqrDistance = b0*s + c;
  458. }
  459. }
  460. else
  461. {
  462. s = 0.0f;
  463. if (b1 >= 0.0f)
  464. {
  465. t = 0.0f;
  466. sqrDistance = c;
  467. }
  468. else if (-b1 >= a11)
  469. {
  470. t = 1.0f;
  471. sqrDistance = a11 + 2.0f*b1 + c;
  472. }
  473. else
  474. {
  475. t = -b1/a11;
  476. sqrDistance = b1*t + c;
  477. }
  478. }
  479. }
  480. else // region 3
  481. {
  482. s = 0.0f;
  483. if (b1 >= 0.0f)
  484. {
  485. t = 0.0f;
  486. sqrDistance = c;
  487. }
  488. else if (-b1 >= a11)
  489. {
  490. t = 1.0f;
  491. sqrDistance = a11 + 2.0f*b1 + c;
  492. }
  493. else
  494. {
  495. t = -b1/a11;
  496. sqrDistance = b1*t + c;
  497. }
  498. }
  499. }
  500. else if (t < 0.0f) // region 5
  501. {
  502. t = 0.0f;
  503. if (b0 >= 0.0f)
  504. {
  505. s = 0.0f;
  506. sqrDistance = c;
  507. }
  508. else if (-b0 >= a00)
  509. {
  510. s = 1.0f;
  511. sqrDistance = a00 + 2.0f*b0 + c;
  512. }
  513. else
  514. {
  515. s = -b0/a00;
  516. sqrDistance = b0*s + c;
  517. }
  518. }
  519. else // region 0
  520. {
  521. // minimum at interior point
  522. F32 invDet = 1.0f / det;
  523. s *= invDet;
  524. t *= invDet;
  525. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  526. t * (a01*s + a11*t + 2.0f*b1) + c;
  527. }
  528. }
  529. else
  530. {
  531. F32 tmp0, tmp1, numer, denom;
  532. if (s < 0.0f) // region 2
  533. {
  534. tmp0 = a01 + b0;
  535. tmp1 = a11 + b1;
  536. if (tmp1 > tmp0)
  537. {
  538. numer = tmp1 - tmp0;
  539. denom = a00 - 2.0f*a01 + a11;
  540. if (numer >= denom)
  541. {
  542. s = 1.0f;
  543. t = 0.0f;
  544. sqrDistance = a00 + 2.0f*b0 + c;
  545. }
  546. else
  547. {
  548. s = numer/denom;
  549. t = 1.0f - s;
  550. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  551. t * (a01*s + a11*t + 2.0f*b1) + c;
  552. }
  553. }
  554. else
  555. {
  556. s = 0.0f;
  557. if (tmp1 <= 0.0f)
  558. {
  559. t = 1.0f;
  560. sqrDistance = a11 + 2.0f*b1 + c;
  561. }
  562. else if (b1 >= 0.0f)
  563. {
  564. t = 0.0f;
  565. sqrDistance = c;
  566. }
  567. else
  568. {
  569. t = -b1/a11;
  570. sqrDistance = b1*t + c;
  571. }
  572. }
  573. }
  574. else if (t < 0.0f) // region 6
  575. {
  576. tmp0 = a01 + b1;
  577. tmp1 = a00 + b0;
  578. if (tmp1 > tmp0)
  579. {
  580. numer = tmp1 - tmp0;
  581. denom = a00 - 2.0f*a01 + a11;
  582. if (numer >= denom)
  583. {
  584. t = 1.0f;
  585. s = 0.0f;
  586. sqrDistance = a11 + 2.0f*b1 + c;
  587. }
  588. else
  589. {
  590. t = numer/denom;
  591. s = 1.0f - t;
  592. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  593. t * (a01*s + a11*t + 2.0f*b1) + c;
  594. }
  595. }
  596. else
  597. {
  598. t = 0.0f;
  599. if (tmp1 <= 0.0f)
  600. {
  601. s = 1.0f;
  602. sqrDistance = a00 + 2.0f*b0 + c;
  603. }
  604. else if (b0 >= 0.0f)
  605. {
  606. s = 0.0f;
  607. sqrDistance = c;
  608. }
  609. else
  610. {
  611. s = -b0/a00;
  612. sqrDistance = b0*s + c;
  613. }
  614. }
  615. }
  616. else // region 1
  617. {
  618. numer = a11 + b1 - a01 - b0;
  619. if (numer <= 0.0f)
  620. {
  621. s = 0.0f;
  622. t = 1.0f;
  623. sqrDistance = a11 + 2.0f*b1 + c;
  624. }
  625. else
  626. {
  627. denom = a00 - 2.0f*a01 + a11;
  628. if (numer >= denom)
  629. {
  630. s = 1.0f;
  631. t = 0.0f;
  632. sqrDistance = a00 + 2.0f*b0 + c;
  633. }
  634. else
  635. {
  636. s = numer/denom;
  637. t = 1.0f - s;
  638. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  639. t * (a01*s + a11*t + 2.0f*b1) + c;
  640. }
  641. }
  642. }
  643. }
  644. // account for numerical round-off error
  645. if (sqrDistance < 0.0f)
  646. sqrDistance = 0.0f;
  647. // This also calculates the barycentric coordinates and the closest point!
  648. //m_kClosestPoint0 = P;
  649. //m_kClosestPoint1 = A + s*edge0 + t*edge1;
  650. //m_afTriangleBary[1] = s;
  651. //m_afTriangleBary[2] = t;
  652. //m_afTriangleBary[0] = (Real)1.0 - fS - fT;
  653. if(info)
  654. {
  655. info->segment.p0 = P;
  656. info->segment.p1 = A + s*edge0 + t*edge1;
  657. info->bary.x = s;
  658. info->bary.y = t;
  659. info->bary.z = 1.0f - s - t;
  660. }
  661. return sqrDistance;
  662. }
  663. //-----------------------------------------------------------------------------
  664. Point3F mTriangleNormal( const Point3F &a, const Point3F &b, const Point3F &c )
  665. {
  666. // Vector from b to a.
  667. const F32 ax = a.x-b.x;
  668. const F32 ay = a.y-b.y;
  669. const F32 az = a.z-b.z;
  670. // Vector from b to c.
  671. const F32 cx = c.x-b.x;
  672. const F32 cy = c.y-b.y;
  673. const F32 cz = c.z-b.z;
  674. Point3F n;
  675. // This is an in-line cross product.
  676. n.x = ay*cz - az*cy;
  677. n.y = az*cx - ax*cz;
  678. n.z = ax*cy - ay*cx;
  679. m_point3F_normalize( (F32*)(&n) );
  680. return n;
  681. }
  682. //-----------------------------------------------------------------------------
  683. Point3F mClosestPointOnSegment( const Point3F &a, const Point3F &b, const Point3F &p )
  684. {
  685. Point3F c = p - a; // Vector from a to Point
  686. Point3F v = (b - a);
  687. F32 d = v.len(); // Length of the line segment
  688. v.normalize(); // Unit Vector from a to b
  689. F32 t = mDot( v, c ); // Intersection point Distance from a
  690. // Check to see if the point is on the line
  691. // if not then return the endpoint
  692. if(t < 0) return a;
  693. if(t > d) return b;
  694. // get the distance to move from point a
  695. v *= t;
  696. // move from point a to the nearest point on the segment
  697. return a + v;
  698. }
  699. //-----------------------------------------------------------------------------
  700. void mShortestSegmentBetweenLines( const Line &line0, const Line &line1, LineSegment *outSegment )
  701. {
  702. // compute intermediate parameters
  703. Point3F w0 = line0.origin - line1.origin;
  704. F32 a = mDot( line0.direction, line0.direction );
  705. F32 b = mDot( line0.direction, line1.direction );
  706. F32 c = mDot( line1.direction, line1.direction );
  707. F32 d = mDot( line0.direction, w0 );
  708. F32 e = mDot( line1.direction, w0 );
  709. F32 denom = a*c - b*b;
  710. if ( denom > -0.001f && denom < 0.001f )
  711. {
  712. outSegment->p0 = line0.origin;
  713. outSegment->p1 = line1.origin + (e/c)*line1.direction;
  714. }
  715. else
  716. {
  717. outSegment->p0 = line0.origin + ((b*e - c*d)/denom)*line0.direction;
  718. outSegment->p1 = line1.origin + ((a*e - b*d)/denom)*line1.direction;
  719. }
  720. }
  721. //-----------------------------------------------------------------------------
  722. U32 greatestCommonDivisor( U32 u, U32 v )
  723. {
  724. // http://en.wikipedia.org/wiki/Binary_GCD_algorithm
  725. S32 shift;
  726. /* GCD(0,x) := x */
  727. if (u == 0 || v == 0)
  728. return u | v;
  729. /* Left shift := lg K, where K is the greatest power of 2
  730. dividing both u and v. */
  731. for (shift = 0; ((u | v) & 1) == 0; ++shift) {
  732. u >>= 1;
  733. v >>= 1;
  734. }
  735. while ((u & 1) == 0)
  736. u >>= 1;
  737. /* From here on, u is always odd. */
  738. do {
  739. while ((v & 1) == 0) /* Loop X */
  740. v >>= 1;
  741. /* Now u and v are both odd, so diff(u, v) is even.
  742. Let u = min(u, v), v = diff(u, v)/2. */
  743. if (u < v) {
  744. v -= u;
  745. } else {
  746. U32 diff = u - v;
  747. u = v;
  748. v = diff;
  749. }
  750. v >>= 1;
  751. } while (v != 0);
  752. return u << shift;
  753. }
  754. //-----------------------------------------------------------------------------
  755. bool mLineTriangleCollide( const Point3F &p1, const Point3F &p2,
  756. const Point3F &t1, const Point3F &t2, const Point3F &t3,
  757. Point3F *outUVW, F32 *outT )
  758. {
  759. VectorF ab = t2 - t1;
  760. VectorF ac = t3 - t1;
  761. VectorF qp = p1 - p2;
  762. // Compute triangle normal. Can be precalculated or cached if
  763. // intersecting multiple segments against the same triangle
  764. VectorF n = mCross( ab, ac );
  765. // Compute denominator d. If d <= 0, segment is parallel to or points
  766. // away from triangle, so exit early
  767. F32 d = mDot( qp, n );
  768. if ( d <= 0.0f )
  769. return false;
  770. // Compute intersection t value of pq with plane of triangle. A ray
  771. // intersects if 0 <= t. Segment intersects iff 0 <= t <= 1. Delay
  772. // dividing by d until intersection has been found to pierce triangle
  773. VectorF ap = p1 - t1;
  774. F32 t = mDot( ap, n );
  775. if ( t < 0.0f )
  776. return false;
  777. if ( t > d )
  778. return false; // For segment; exclude this code line for a ray test
  779. // Compute barycentric coordinate components and test if within bounds
  780. VectorF e = mCross( qp, ap );
  781. F32 v = mDot( ac, e );
  782. if ( v < 0.0f || v > d )
  783. return false;
  784. F32 w = -mDot( ab, e );
  785. if ( w < 0.0f || v + w > d )
  786. return false;
  787. // Segment/ray intersects triangle. Perform delayed division and
  788. // compute the last barycentric coordinate component
  789. const F32 ood = 1.0f / d;
  790. if ( outT )
  791. *outT = t * ood;
  792. if ( outUVW )
  793. {
  794. v *= ood;
  795. w *= ood;
  796. outUVW->set( 1.0f - v - w, v, w );
  797. }
  798. return true;
  799. }
  800. //-----------------------------------------------------------------------------
  801. bool mRayQuadCollide( const Quad &quad,
  802. const Ray &ray,
  803. Point2F *outUV,
  804. F32 *outT )
  805. {
  806. static const F32 eps = F32(10e-6);
  807. // Rejects rays that are parallel to Q, and rays that intersect the plane of
  808. // Q either on the left of the line V00V01 or on the right of the line V00V10.
  809. // p01-----eXX-----p11
  810. // ^ . ^ |
  811. // | . |
  812. // e03 e02 eXX
  813. // | . |
  814. // | . |
  815. // p00-----e01---->p10
  816. VectorF e01 = quad.p10 - quad.p00;
  817. VectorF e03 = quad.p01 - quad.p00;
  818. // If the ray is perfectly perpendicular to e03, which
  819. // represents the entire planes tangent, then the
  820. // result of this cross product (P) will equal e01
  821. // If it is parallel it will result in a vector opposite e01.
  822. // If the ray is heading DOWN the cross product will point to the RIGHT
  823. // If the ray is heading UP the cross product will point to the LEFT
  824. // We do not reject based on this though...
  825. //
  826. // In either case cross product will be more parallel to e01 the more
  827. // perpendicular the ray is to e03, and it will be more perpendicular to
  828. // e01 the more parallel it is to e03.
  829. VectorF P = mCross(ray.direction, e03);
  830. // det can be seen as 'the amount of vector e01 in the direction P'
  831. F32 det = mDot(e01, P);
  832. // Take a Abs of the dot because we do not care if the ray is heading up or down,
  833. // but if it is perfectly parallel to the quad we want to reject it.
  834. if ( mFabs(det) < eps )
  835. return false;
  836. F32 inv_det = 1.0f / det;
  837. VectorF T = ray.origin - quad.p00;
  838. // alpha can be seen as 'the amount of vector T in the direction P'
  839. // T is a vector up from the quads corner point 00 to the ray's origin.
  840. // P is the cross product of the ray and e01, which should be "roughly"
  841. // parallel with e03 but might be of either positive or negative magnitude.
  842. F32 alpha = mDot(T, P) * inv_det;
  843. if ( alpha < 0.0f )
  844. return false;
  845. // if (alpha > real(1.0)) return false; // Uncomment if VR is used.
  846. // The cross product of T and e01 should be roughly parallel to e03
  847. // and of either positive or negative magnitude.
  848. VectorF Q = mCross(T, e01);
  849. F32 beta = mDot(ray.direction, Q) * inv_det;
  850. if ( beta < 0.0f )
  851. return false;
  852. // if (beta > real(1.0)) return false; // Uncomment if VR is used.
  853. if ( alpha + beta > 1.0f )
  854. //if ( false )
  855. {
  856. // Rejects rays that intersect the plane of Q either on the
  857. // left of the line V11V10 or on the right of the line V11V01.
  858. VectorF e23 = quad.p01 - quad.p11;
  859. VectorF e21 = quad.p10 - quad.p11;
  860. VectorF P_prime = mCross(ray.direction, e21);
  861. F32 det_prime = mDot(e23, P_prime);
  862. if ( mFabs(det_prime) < eps)
  863. return false;
  864. F32 inv_det_prime = 1.0f / det_prime;
  865. VectorF T_prime = ray.origin - quad.p11;
  866. F32 alpha_prime = mDot(T_prime, P_prime) * inv_det_prime;
  867. if (alpha_prime < 0.0f)
  868. return false;
  869. VectorF Q_prime = mCross(T_prime, e23);
  870. F32 beta_prime = mDot(ray.direction, Q_prime) * inv_det_prime;
  871. if (beta_prime < 0.0f)
  872. return false;
  873. }
  874. // Compute the ray parameter of the intersection point, and
  875. // reject the ray if it does not hit Q.
  876. F32 t = mDot(e03, Q) * inv_det;
  877. if ( t < 0.0f )
  878. return false;
  879. // Compute the barycentric coordinates of the fourth vertex.
  880. // These do not depend on the ray, and can be precomputed
  881. // and stored with the quadrilateral.
  882. F32 alpha_11, beta_11;
  883. VectorF e02 = quad.p11 - quad.p00;
  884. VectorF n = mCross(e01, e03);
  885. if ( mFabs(n.x) >= mFabs(n.y) &&
  886. mFabs(n.x) >= mFabs(n.z) )
  887. {
  888. alpha_11 = ( e02.y * e03.z - e02.z * e03.y ) / n.x;
  889. beta_11 = ( e01.y * e02.z - e01.z * e02.y ) / n.x;
  890. }
  891. else if ( mFabs(n.y) >= mFabs(n.x) &&
  892. mFabs(n.y) >= mFabs(n.z) )
  893. {
  894. alpha_11 = ((e02.z * e03.x) - (e02.x * e03.z)) / n.y;
  895. beta_11 = ((e01.z * e02.x) - (e01.x * e02.z)) / n.y;
  896. }
  897. else
  898. {
  899. alpha_11 = ((e02.x * e03.y) - (e02.y * e03.x)) / n.z;
  900. beta_11 = ((e01.x * e02.y) - (e01.y * e02.x)) / n.z;
  901. }
  902. // Compute the bilinear coordinates of the intersection point.
  903. F32 u,v;
  904. if ( mFabs(alpha_11 - 1.0f) < eps)
  905. {
  906. // Q is a trapezium.
  907. u = alpha;
  908. if ( mFabs(beta_11 - 1.0f) < eps)
  909. v = beta; // Q is a parallelogram.
  910. else
  911. v = beta / ((u * (beta_11 - 1.0f)) + 1.0f); // Q is a trapezium.
  912. }
  913. else if ( mFabs(beta_11 - 1.0f) < eps)
  914. {
  915. // Q is a trapezium.
  916. v = beta;
  917. u = alpha / ((v * (alpha_11 - 1.0f)) + 1.0f);
  918. }
  919. else
  920. {
  921. F32 A = 1.0f - beta_11;
  922. F32 B = (alpha * (beta_11 - 1.0f))
  923. - (beta * (alpha_11 - 1.0f)) - 1.0f;
  924. F32 C = alpha;
  925. F32 D = (B * B) - (4.0f * A * C);
  926. F32 F = -0.5f * (B + (B < 0.0f ? -1.0f : 1.0f) ) * mSqrt(D);
  927. u = F / A;
  928. if ((u < 0.0f) || (u > 1.0f)) u = C / F;
  929. v = beta / ((u * (beta_11 - 1.0f)) + 1.0f);
  930. }
  931. if ( outUV )
  932. outUV->set( u, v );
  933. if ( outT )
  934. *outT = t;
  935. return true;
  936. }
  937. //-----------------------------------------------------------------------------
  938. // Used by sortQuadWindingOrder.
  939. struct QuadSortPoint
  940. {
  941. U32 id;
  942. F32 theta;
  943. };
  944. // Used by sortQuadWindingOrder.
  945. S32 QSORT_CALLBACK cmpAngleAscending( const void *a, const void *b )
  946. {
  947. const QuadSortPoint *p0 = (const QuadSortPoint*)a;
  948. const QuadSortPoint *p1 = (const QuadSortPoint*)b;
  949. F32 diff = p1->theta - p0->theta;
  950. if ( diff > 0.0f )
  951. return -1;
  952. else if ( diff < 0.0f )
  953. return 1;
  954. else
  955. return 0;
  956. }
  957. // Used by sortQuadWindingOrder.
  958. S32 QSORT_CALLBACK cmpAngleDescending( const void *a, const void *b )
  959. {
  960. const QuadSortPoint *p0 = (const QuadSortPoint*)a;
  961. const QuadSortPoint *p1 = (const QuadSortPoint*)b;
  962. F32 diff = p1->theta - p0->theta;
  963. if ( diff > 0.0f )
  964. return 1;
  965. else if ( diff < 0.0f )
  966. return -1;
  967. else
  968. return 0;
  969. }
  970. void sortQuadWindingOrder( const MatrixF &quadMat, bool clockwise, const Point3F *verts, U32 *vertMap, U32 count )
  971. {
  972. PROFILE_SCOPE( MathUtils_sortQuadWindingOrder );
  973. if ( count == 0 )
  974. return;
  975. Point3F *quadPoints = new Point3F[count];
  976. for ( S32 i = 0; i < count; i++ )
  977. {
  978. quadMat.mulP( verts[i], &quadPoints[i] );
  979. quadPoints[i].normalizeSafe();
  980. }
  981. sortQuadWindingOrder( clockwise, quadPoints, vertMap, count );
  982. delete [] quadPoints;
  983. }
  984. void sortQuadWindingOrder( bool clockwise, const Point3F *verts, U32 *vertMap, U32 count )
  985. {
  986. QuadSortPoint *sortPoints = new QuadSortPoint[count];
  987. for ( S32 i = 0; i < count; i++ )
  988. {
  989. QuadSortPoint &sortPnt = sortPoints[i];
  990. const Point3F &vec = verts[i];
  991. sortPnt.id = i;
  992. F32 theta = mAtan2( vec.y, vec.x );
  993. if ( vec.y < 0.0f )
  994. theta = M_2PI_F + theta;
  995. sortPnt.theta = theta;
  996. }
  997. dQsort( sortPoints, count, sizeof( QuadSortPoint ), clockwise ? cmpAngleDescending : cmpAngleAscending );
  998. for ( S32 i = 0; i < count; i++ )
  999. vertMap[i] = sortPoints[i].id;
  1000. delete [] sortPoints;
  1001. }
  1002. //-----------------------------------------------------------------------------
  1003. void buildMatrix( const VectorF *rvec, const VectorF *fvec, const VectorF *uvec, const VectorF *pos, MatrixF *outMat )
  1004. {
  1005. /// Work in Progress
  1006. /*
  1007. AssertFatal( !rvec || rvec->isUnitLength(), "MathUtils::buildMatrix() - Right vector was not normalized!" );
  1008. AssertFatal( !fvec || fvec->isUnitLength(), "MathUtils::buildMatrix() - Forward vector was not normalized!" );
  1009. AssertFatal( !uvec || uvec->isUnitLength(), "MathUtils::buildMatrix() - Up vector was not normalized!" );
  1010. // Note this relationship:
  1011. //
  1012. // Column0 Column1 Column2
  1013. // Axis X Axis Y Axis Z
  1014. // Rvec Fvec Uvec
  1015. //
  1016. enum
  1017. {
  1018. RVEC = 1,
  1019. FVEC = 1 << 1,
  1020. UVEC = 1 << 2,
  1021. ALL = RVEC | FVEC | UVEC
  1022. };
  1023. U8 mask = 0;
  1024. U8 count = 0;
  1025. U8 axis0, axis1;
  1026. if ( rvec )
  1027. {
  1028. mask |= RVEC;
  1029. axis0 == 0;
  1030. count++;
  1031. }
  1032. if ( fvec )
  1033. {
  1034. mask |= FVEC;
  1035. if ( count == 0 )
  1036. axis0 = 1;
  1037. else
  1038. axis1 = 1;
  1039. count++;
  1040. }
  1041. if ( uvec )
  1042. {
  1043. mask |= UVEC;
  1044. count++;
  1045. }
  1046. U8 bR = 1;
  1047. U8 bF = 1 << 1;
  1048. U8 bU = 1 << 2;
  1049. U8 bRF = bR | bF;
  1050. U8 bRU = bR | bU;
  1051. U8 bFU = bF | bU;
  1052. U8 bRFU = bR | bF | bU;
  1053. // Cross product map.
  1054. U8 cpdMap[3][2] =
  1055. {
  1056. { 1, 2 },
  1057. { 2, 0 },
  1058. { 0, 1 },
  1059. }
  1060. if ( count == 1 )
  1061. {
  1062. if ( mask == bR )
  1063. {
  1064. }
  1065. else if ( mask == bF )
  1066. {
  1067. }
  1068. else if ( mask == bU )
  1069. {
  1070. }
  1071. }
  1072. else if ( count == 2 )
  1073. {
  1074. if ( mask == bRF )
  1075. {
  1076. }
  1077. else if ( mask == bRU )
  1078. {
  1079. }
  1080. else if ( mask == bFU )
  1081. {
  1082. }
  1083. }
  1084. else // bRFU
  1085. {
  1086. }
  1087. if ( rvec )
  1088. {
  1089. outMat->setColumn( 0, *rvec );
  1090. if ( fvec )
  1091. {
  1092. outMat->setColumn( 1, *fvec );
  1093. if ( uvec )
  1094. outMat->setColumn( 2, *uvec );
  1095. else
  1096. {
  1097. // Set uvec from rvec/fvec
  1098. tmp = mCross( rvec, fvec );
  1099. tmp.normalizeSafe();
  1100. outMat->setColumn( 2, tmp );
  1101. }
  1102. }
  1103. else if ( uvec )
  1104. {
  1105. // Set fvec from uvec/rvec
  1106. tmp = mCross( uvec, rvec );
  1107. tmp.normalizeSafe();
  1108. outMat->setColumn( 1, tmp );
  1109. }
  1110. else
  1111. {
  1112. // Set fvec and uvec from rvec
  1113. Point3F tempFvec = mPerp( rvec );
  1114. Point3F tempUvec = mCross( )
  1115. }
  1116. }
  1117. AssertFatal( rvec->isUnitLength(), "MathUtils::buildMatrix() - Right vector was not normalized!" );
  1118. AssertFatal( fvec->isUnitLength(), "MathUtils::buildMatrix() - Forward vector was not normalized!" );
  1119. AssertFatal( uvec->isUnitLength(), "MathUtils::buildMatrix() - UpVector vector was not normalized!" );
  1120. AssertFatal( outMat, "MathUtils::buildMatrix() - Got null output matrix!" );
  1121. AssertFatal( outMat->isAffine(), "MathUtils::buildMatrix() - Got uninitialized matrix!" );
  1122. */
  1123. }
  1124. //-----------------------------------------------------------------------------
  1125. bool reduceFrustum( const Frustum& frustum, const RectI& viewport, const RectF& area, Frustum& outFrustum )
  1126. {
  1127. // Just to be safe, clamp the area to the viewport.
  1128. Point2F clampedMin;
  1129. Point2F clampedMax;
  1130. clampedMin.x = mClampF( area.extent.x, ( F32 ) viewport.point.x, ( F32 ) viewport.point.x + viewport.extent.x );
  1131. clampedMin.y = mClampF( area.extent.y, ( F32 ) viewport.point.y, ( F32 ) viewport.point.y + viewport.extent.y );
  1132. clampedMax.x = mClampF( area.extent.x, ( F32 ) viewport.point.x, ( F32 ) viewport.point.x + viewport.extent.x );
  1133. clampedMax.y = mClampF( area.extent.y, ( F32 ) viewport.point.y, ( F32 ) viewport.point.y + viewport.extent.y );
  1134. // If we have ended up without a visible region on the screen,
  1135. // terminate now.
  1136. if( mFloor( clampedMin.x ) == mFloor( clampedMax.x ) ||
  1137. mFloor( clampedMin.y ) == mFloor( clampedMax.y ) )
  1138. return false;
  1139. // Get the extents of the frustum.
  1140. const F32 frustumXExtent = mFabs( frustum.getNearRight() - frustum.getNearLeft() );
  1141. const F32 frustumYExtent = mFabs( frustum.getNearTop() - frustum.getNearBottom() );
  1142. // Now, normalize the screen-space pixel coordinates to lie within the screen-centered
  1143. // -1 to 1 coordinate space that is used for the frustum planes.
  1144. Point2F normalizedMin;
  1145. Point2F normalizedMax;
  1146. normalizedMin.x = ( ( clampedMin.x / viewport.extent.x ) * frustumXExtent ) - ( frustumXExtent / 2.f );
  1147. normalizedMin.y = ( ( clampedMin.y / viewport.extent.y ) * frustumYExtent ) - ( frustumYExtent / 2.f );
  1148. normalizedMax.x = ( ( clampedMax.x / viewport.extent.x ) * frustumXExtent ) - ( frustumXExtent / 2.f );
  1149. normalizedMax.y = ( ( clampedMax.y / viewport.extent.y ) * frustumYExtent ) - ( frustumYExtent / 2.f );
  1150. // Make sure the generated frustum metrics are somewhat sane.
  1151. if( normalizedMax.x - normalizedMin.x < 0.001f ||
  1152. normalizedMax.y - normalizedMin.y < 0.001f )
  1153. return false;
  1154. // Finally, create the new frustum using the original's frustum
  1155. // information except its left/right/top/bottom planes.
  1156. //
  1157. // Note that screen-space coordinates go upside down on Y whereas
  1158. // camera-space frustum coordinates go downside up on Y which is
  1159. // why we are inverting Y here.
  1160. outFrustum.set(
  1161. frustum.isOrtho(),
  1162. normalizedMin.x,
  1163. normalizedMax.x,
  1164. - normalizedMin.y,
  1165. - normalizedMax.y,
  1166. frustum.getNearDist(),
  1167. frustum.getFarDist(),
  1168. frustum.getTransform()
  1169. );
  1170. return true;
  1171. }
  1172. //-----------------------------------------------------------------------------
  1173. void makeFrustum( F32 *outLeft,
  1174. F32 *outRight,
  1175. F32 *outTop,
  1176. F32 *outBottom,
  1177. F32 fovYInRadians,
  1178. F32 aspectRatio,
  1179. F32 nearPlane )
  1180. {
  1181. F32 top = nearPlane * mTan( fovYInRadians / 2.0 );
  1182. if ( outTop ) *outTop = top;
  1183. if ( outBottom ) *outBottom = -top;
  1184. F32 left = top * aspectRatio;
  1185. if ( outLeft ) *outLeft = -left;
  1186. if ( outRight ) *outRight = left;
  1187. }
  1188. //-----------------------------------------------------------------------------
  1189. void makeProjection( MatrixF *outMatrix,
  1190. F32 fovYInRadians,
  1191. F32 aspectRatio,
  1192. F32 nearPlane,
  1193. F32 farPlane,
  1194. bool gfxRotate )
  1195. {
  1196. F32 left, right, top, bottom;
  1197. makeFrustum( &left, &right, &top, &bottom, fovYInRadians, aspectRatio, nearPlane );
  1198. makeProjection( outMatrix, left, right, top, bottom, nearPlane, farPlane, gfxRotate );
  1199. }
  1200. //-----------------------------------------------------------------------------
  1201. void makeFovPortFrustum(
  1202. Frustum *outFrustum,
  1203. bool isOrtho,
  1204. F32 nearDist,
  1205. F32 farDist,
  1206. const FovPort &inPort,
  1207. const MatrixF &transform)
  1208. {
  1209. F32 leftSize = nearDist * inPort.leftTan;
  1210. F32 rightSize = nearDist * inPort.rightTan;
  1211. F32 upSize = nearDist * inPort.upTan;
  1212. F32 downSize = nearDist * inPort.downTan;
  1213. F32 left = -leftSize;
  1214. F32 right = rightSize;
  1215. F32 top = upSize;
  1216. F32 bottom = -downSize;
  1217. outFrustum->set(isOrtho, left, right, top, bottom, nearDist, farDist, transform);
  1218. }
  1219. //-----------------------------------------------------------------------------
  1220. /// This is the special rotation matrix applied to
  1221. /// projection matricies for GFX.
  1222. ///
  1223. /// It is a wart of the OGL to DX change over.
  1224. ///
  1225. static const MatrixF sGFXProjRotMatrix( EulerF( (M_PI_F / 2.0f), 0.0f, 0.0f ) );
  1226. void makeProjection( MatrixF *outMatrix,
  1227. F32 left,
  1228. F32 right,
  1229. F32 top,
  1230. F32 bottom,
  1231. F32 nearPlane,
  1232. F32 farPlane,
  1233. bool gfxRotate)
  1234. {
  1235. const bool isGL = GFX->getAdapterType() == OpenGL;
  1236. Point4F row;
  1237. row.x = 2.0f * nearPlane / (right - left);
  1238. row.y = 0.0f;
  1239. row.z = 0.0f;
  1240. row.w = 0.0f;
  1241. outMatrix->setRow(0, row);
  1242. row.x = 0.0f;
  1243. row.y = 2.0f * nearPlane / (top - bottom);
  1244. row.z = 0.0f;
  1245. row.w = 0.0f;
  1246. outMatrix->setRow(1, row);
  1247. row.x = (left + right) / (right - left);
  1248. row.y = (top + bottom) / (top - bottom);
  1249. row.z = isGL ? (nearPlane + farPlane) / (nearPlane - farPlane) : farPlane / (nearPlane - farPlane);
  1250. row.w = -1.0f;
  1251. outMatrix->setRow(2, row);
  1252. row.x = 0.0f;
  1253. row.y = 0.0f;
  1254. row.z = isGL ? 2.0f * nearPlane * farPlane / (nearPlane - farPlane) : farPlane * nearPlane / (nearPlane - farPlane);
  1255. row.w = 0.0f;
  1256. outMatrix->setRow(3, row);
  1257. outMatrix->transpose();
  1258. if (gfxRotate)
  1259. outMatrix->mul(sGFXProjRotMatrix);
  1260. }
  1261. //-----------------------------------------------------------------------------
  1262. void makeOrthoProjection( MatrixF *outMatrix,
  1263. F32 left,
  1264. F32 right,
  1265. F32 top,
  1266. F32 bottom,
  1267. F32 nearPlane,
  1268. F32 farPlane,
  1269. bool gfxRotate )
  1270. {
  1271. Point4F row;
  1272. row.x = 2.0f / (right - left);
  1273. row.y = 0.0f;
  1274. row.z = 0.0f;
  1275. row.w = 0.0f;
  1276. outMatrix->setRow( 0, row );
  1277. row.x = 0.0f;
  1278. row.y = 2.0f / (top - bottom);
  1279. row.z = 0.0f;
  1280. row.w = 0.0f;
  1281. outMatrix->setRow( 1, row );
  1282. row.x = 0.0f;
  1283. row.y = 0.0f;
  1284. row.z = 1.0f / (nearPlane - farPlane);
  1285. row.w = 0.0f;
  1286. outMatrix->setRow( 2, row );
  1287. row.x = (left + right) / (left - right);
  1288. row.y = (top + bottom) / (bottom - top);
  1289. row.z = nearPlane / (nearPlane - farPlane);
  1290. row.w = 1.0f;
  1291. outMatrix->setRow( 3, row );
  1292. outMatrix->transpose();
  1293. if ( gfxRotate )
  1294. outMatrix->mul( sGFXProjRotMatrix );
  1295. }
  1296. //-----------------------------------------------------------------------------
  1297. bool edgeFaceIntersect( const Point3F &edgeA, const Point3F &edgeB,
  1298. const Point3F &faceA, const Point3F &faceB, const Point3F &faceC, const Point3F &faceD, Point3F *intersection )
  1299. {
  1300. VectorF edgeAB = edgeB - edgeA;
  1301. VectorF edgeAFaceA = faceA - edgeA;
  1302. VectorF edgeAFaceB = faceB - edgeA;
  1303. VectorF edgeAFaceC = faceC - edgeA;
  1304. VectorF m = mCross( edgeAFaceC, edgeAB );
  1305. F32 v = mDot( edgeAFaceA, m );
  1306. if ( v >= 0.0f )
  1307. {
  1308. F32 u = -mDot( edgeAFaceB, m );
  1309. if ( u < 0.0f )
  1310. return false;
  1311. VectorF tmp = mCross( edgeAFaceB, edgeAB );
  1312. F32 w = mDot( edgeAFaceA, tmp );
  1313. if ( w < 0.0f )
  1314. return false;
  1315. F32 denom = 1.0f / (u + v + w );
  1316. u *= denom;
  1317. v *= denom;
  1318. w *= denom;
  1319. (*intersection) = u * faceA + v * faceB + w * faceC;
  1320. }
  1321. else
  1322. {
  1323. VectorF edgeAFaceD = faceD - edgeA;
  1324. F32 u = mDot( edgeAFaceD, m );
  1325. if ( u < 0.0f )
  1326. return false;
  1327. VectorF tmp = mCross( edgeAFaceA, edgeAB );
  1328. F32 w = mDot( edgeAFaceD, tmp );
  1329. if ( w < 0.0f )
  1330. return false;
  1331. v = -v;
  1332. F32 denom = 1.0f / ( u + v + w );
  1333. u *= denom;
  1334. v *= denom;
  1335. w *= denom;
  1336. (*intersection) = u * faceA + v * faceD + w * faceC;
  1337. }
  1338. return true;
  1339. }
  1340. //-----------------------------------------------------------------------------
  1341. bool isPlanarPolygon( const Point3F* vertices, U32 numVertices )
  1342. {
  1343. AssertFatal( vertices != NULL, "MathUtils::isPlanarPolygon - Received NULL pointer" );
  1344. AssertFatal( numVertices >= 3, "MathUtils::isPlanarPolygon - Must have at least three vertices" );
  1345. // Triangles are always planar. Letting smaller numVertices
  1346. // slip through provides robustness for errors in release builds.
  1347. if( numVertices <= 3 )
  1348. return true;
  1349. // Compute the normal of the first triangle in the polygon.
  1350. Point3F triangle1Normal = mTriangleNormal( vertices[ 0 ], vertices[ 1 ], vertices[ 2 ] );
  1351. // Now go through all the remaining vertices and build triangles
  1352. // with the first two vertices. Then the normals of all these triangles
  1353. // must be the same (minus some variance due to floating-point inaccuracies)
  1354. // as the normal of the first triangle.
  1355. for( U32 i = 3; i < numVertices; ++ i )
  1356. {
  1357. Point3F triangle2Normal = mTriangleNormal( vertices[ 0 ], vertices[ 1 ], vertices[ i ] );
  1358. if( !triangle1Normal.equal( triangle2Normal ) )
  1359. return false;
  1360. }
  1361. return true;
  1362. }
  1363. //-----------------------------------------------------------------------------
  1364. bool isConvexPolygon( const Point3F* vertices, U32 numVertices )
  1365. {
  1366. AssertFatal( vertices != NULL, "MathUtils::isConvexPolygon - Received NULL pointer" );
  1367. AssertFatal( numVertices >= 3, "MathUtils::isConvexPolygon - Must have at least three vertices" );
  1368. // Triangles are always convex. Letting smaller numVertices
  1369. // slip through provides robustness for errors in release builds.
  1370. if( numVertices <= 3 )
  1371. return true;
  1372. U32 numPositive = 0;
  1373. U32 numNegative = 0;
  1374. for( U32 i = 0; i < numVertices; ++ i )
  1375. {
  1376. const Point3F& a = vertices[ i ];
  1377. const Point3F& b = vertices[ ( i + 1 ) % numVertices ];
  1378. const Point3F& c = vertices[ ( i + 2 ) % numVertices ];
  1379. const F32 crossProductLength = mCross( b - a, c - b ).len();
  1380. if( crossProductLength < 0.f )
  1381. numNegative ++;
  1382. else if( crossProductLength > 0.f )
  1383. numPositive ++;
  1384. if( numNegative && numPositive )
  1385. return false;
  1386. }
  1387. return true;
  1388. }
  1389. //-----------------------------------------------------------------------------
  1390. bool clipFrustumByPolygon( const Point3F* points, U32 numPoints, const RectI& viewport, const MatrixF& world,
  1391. const MatrixF& projection, const Frustum& inFrustum, const Frustum& rootFrustum, Frustum& outFrustum )
  1392. {
  1393. enum
  1394. {
  1395. MAX_RESULT_VERTICES = 64,
  1396. MAX_INPUT_VERTICES = MAX_RESULT_VERTICES - Frustum::PlaneCount // Clipping against each plane may add a vertex.
  1397. };
  1398. AssertFatal( numPoints <= MAX_INPUT_VERTICES, "MathUtils::clipFrustumByPolygon - Too many vertices!" );
  1399. if( numPoints > MAX_INPUT_VERTICES )
  1400. return false;
  1401. // First, we need to clip the polygon against inFrustum.
  1402. //
  1403. // Use two buffers here in interchanging roles as sources and targets
  1404. // in clipping against the frustum planes.
  1405. Point3F polygonBuffer1[ MAX_RESULT_VERTICES ];
  1406. Point3F polygonBuffer2[ MAX_RESULT_VERTICES ];
  1407. Point3F* tempPolygon = polygonBuffer1;
  1408. Point3F* clippedPolygon = polygonBuffer2;
  1409. dMemcpy( clippedPolygon, points, numPoints * sizeof( points[ 0 ] ) );
  1410. U32 numClippedPolygonVertices = numPoints;
  1411. U32 numTempPolygonVertices = 0;
  1412. for( U32 nplane = 0; nplane < Frustum::PlaneCount; ++ nplane )
  1413. {
  1414. // Make the output of the last iteration the
  1415. // input of this iteration.
  1416. T3D::swap( tempPolygon, clippedPolygon );
  1417. numTempPolygonVertices = numClippedPolygonVertices;
  1418. // Clip our current remainder of the original polygon
  1419. // against the current plane.
  1420. const PlaneF& plane = inFrustum.getPlanes()[ nplane ];
  1421. numClippedPolygonVertices = plane.clipPolygon( tempPolygon, numTempPolygonVertices, clippedPolygon );
  1422. // If the polygon was completely on the backside of the plane,
  1423. // then polygon is outside the frustum. In this case, return false
  1424. // to indicate we haven't clipped anything.
  1425. if( !numClippedPolygonVertices )
  1426. return false;
  1427. }
  1428. // Project the clipped polygon into screen space.
  1429. MatrixF worldProjection = projection;
  1430. worldProjection.mul( world ); // Premultiply world*projection so we don't have to do this over and over for each point.
  1431. Point3F projectedPolygon[ 10 ];
  1432. for( U32 i = 0; i < numClippedPolygonVertices; ++ i )
  1433. mProjectWorldToScreen(
  1434. clippedPolygon[ i ],
  1435. &projectedPolygon[ i ],
  1436. viewport,
  1437. worldProjection
  1438. );
  1439. // Put an axis-aligned rectangle around our polygon.
  1440. Point2F minPoint( projectedPolygon[ 0 ].x, projectedPolygon[ 0 ].y );
  1441. Point2F maxPoint( projectedPolygon[ 0 ].x, projectedPolygon[ 0 ].y );
  1442. for( U32 i = 1; i < numClippedPolygonVertices; ++ i )
  1443. {
  1444. minPoint.setMin( Point2F( projectedPolygon[ i ].x, projectedPolygon[ i ].y ) );
  1445. maxPoint.setMax( Point2F( projectedPolygon[ i ].x, projectedPolygon[ i ].y ) );
  1446. }
  1447. RectF area( minPoint, maxPoint - minPoint );
  1448. // Finally, reduce the input frustum to the given area. Note that we
  1449. // use rootFrustum here instead of inFrustum as the latter does not necessarily
  1450. // represent the full viewport we are using here which thus would skew the mapping.
  1451. return reduceFrustum( rootFrustum, viewport, area, outFrustum );
  1452. }
  1453. //-----------------------------------------------------------------------------
  1454. U32 extrudePolygonEdges( const Point3F* vertices, U32 numVertices, const Point3F& direction, PlaneF* outPlanes )
  1455. {
  1456. U32 numPlanes = 0;
  1457. U32 lastVertex = numVertices - 1;
  1458. bool invert = false;
  1459. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  1460. {
  1461. const Point3F& v1 = vertices[ i ];
  1462. const Point3F& v2 = vertices[ lastVertex ];
  1463. // Skip the edge if it's length is really short.
  1464. const Point3F edgeVector = v2 - v1;
  1465. if( edgeVector.len() < 0.05 )
  1466. continue;
  1467. // Compute the plane normal. The direction and the edge vector
  1468. // basically define the orientation of the plane so their cross
  1469. // product is the plane normal.
  1470. Point3F normal;
  1471. if( !invert )
  1472. normal = mCross( edgeVector, direction );
  1473. else
  1474. normal = mCross( direction, edgeVector );
  1475. // Create a plane for the edge.
  1476. outPlanes[ numPlanes ] = PlaneF( v1, normal );
  1477. numPlanes ++;
  1478. // If this is the first plane that we have created, find out whether
  1479. // the vertex ordering is giving us the plane orientations that we want
  1480. // (facing inside). If not, invert vertex order from now on.
  1481. if( i == 0 )
  1482. {
  1483. const PlaneF& plane = outPlanes[ numPlanes - 1 ];
  1484. for( U32 n = i + 1; n < numVertices; ++ n )
  1485. {
  1486. const PlaneF::Side side = plane.whichSide( vertices[ n ] );
  1487. if( side == PlaneF::On )
  1488. continue;
  1489. if( side != PlaneF::Front )
  1490. invert = true;
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. return numPlanes;
  1496. }
  1497. //-----------------------------------------------------------------------------
  1498. U32 extrudePolygonEdgesFromPoint( const Point3F* vertices, U32 numVertices, const Point3F& fromPoint, PlaneF* outPlanes )
  1499. {
  1500. U32 numPlanes = 0;
  1501. U32 lastVertex = numVertices - 1;
  1502. bool invert = false;
  1503. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  1504. {
  1505. const Point3F& v1 = vertices[ i ];
  1506. const Point3F& v2 = vertices[ lastVertex ];
  1507. // Skip the edge if it's length is really short.
  1508. const Point3F edgeVector = v2 - v1;
  1509. if( edgeVector.len() < 0.05 )
  1510. continue;
  1511. // Create a plane for the edge.
  1512. if( !invert )
  1513. outPlanes[ numPlanes ] = PlaneF( v1, fromPoint, v2 );
  1514. else
  1515. outPlanes[ numPlanes ] = PlaneF( v2, fromPoint, v1 );
  1516. numPlanes ++;
  1517. // If this is the first plane that we have created, find out whether
  1518. // the vertex ordering is giving us the plane orientations that we want
  1519. // (facing inside). If not, invert vertex order from now on.
  1520. if( i == 0 )
  1521. {
  1522. const PlaneF& plane = outPlanes[ numPlanes - 1 ];
  1523. for( U32 n = i + 1; n < numVertices; ++ n )
  1524. {
  1525. const PlaneF::Side side = plane.whichSide( vertices[ n ] );
  1526. if( side == PlaneF::On )
  1527. continue;
  1528. if( side != PlaneF::Front )
  1529. invert = true;
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. return numPlanes;
  1535. }
  1536. //-----------------------------------------------------------------------------
  1537. void mBuildHull2D(const Vector<Point2F> _inPoints, Vector<Point2F> &hullPoints)
  1538. {
  1539. /// Andrew's monotone chain convex hull algorithm implementation
  1540. struct Util
  1541. {
  1542. //compare by x and then by y
  1543. static int CompareLexicographic( const Point2F *a, const Point2F *b)
  1544. {
  1545. return a->x < b->x || (a->x == b->x && a->y < b->y);
  1546. }
  1547. };
  1548. hullPoints.clear();
  1549. hullPoints.setSize( _inPoints.size()*2 );
  1550. // sort in points by x and then by y
  1551. Vector<Point2F> inSortedPoints = _inPoints;
  1552. inSortedPoints.sort( &Util::CompareLexicographic );
  1553. Point2F* lowerHullPtr = hullPoints.address();
  1554. U32 lowerHullIdx = 0;
  1555. //lower part of hull
  1556. for( int i = 0; i < inSortedPoints.size(); ++i )
  1557. {
  1558. while( lowerHullIdx >= 2 && mCross( lowerHullPtr[ lowerHullIdx - 2], lowerHullPtr[lowerHullIdx - 1], inSortedPoints[i] ) <= 0 )
  1559. --lowerHullIdx;
  1560. lowerHullPtr[lowerHullIdx++] = inSortedPoints[i];
  1561. }
  1562. --lowerHullIdx; // last point are the same as first in upperHullPtr
  1563. Point2F* upperHullPtr = hullPoints.address() + lowerHullIdx;
  1564. U32 upperHullIdx = 0;
  1565. //upper part of hull
  1566. for( int i = inSortedPoints.size()-1; i >= 0; --i )
  1567. {
  1568. while( upperHullIdx >= 2 && mCross( upperHullPtr[ upperHullIdx - 2], upperHullPtr[upperHullIdx - 1], inSortedPoints[i] ) <= 0 )
  1569. --upperHullIdx;
  1570. upperHullPtr[upperHullIdx++] = inSortedPoints[i];
  1571. }
  1572. hullPoints.setSize( lowerHullIdx + upperHullIdx );
  1573. }
  1574. } // namespace MathUtils