mathUtils.cpp 53 KB

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