Debian Codegraph @

src/base/castlevectors_single.inc

raw
1 {%MainUnit castlevectors.pas}
2 {
3 Copyright 2003-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { CastleVectors routines (global functions, procedures)
18 for Single precision of vectors and matrices. }
19
20 {$ifdef read_interface}
21
22 type
23 TGetVertexFromIndexFunc = function (Index: integer): TVector3 of object;
24
25 { Cosinus of angle between two vectors.
26
27 CosAngleBetweenNormals is a little faster, but must receive
28 normalized (length 1) vectors. This avoids expensive Sqrt
29 inside CosAngleBetweenVectors.
30
31 @raises EVectorInvalidOp If V1 or V2 is zero.
32 @groupBegin }
33 function CosAngleBetweenVectors(const V1, V2: TVector3): Single; overload;
34 function CosAngleBetweenNormals(const V1, V2: TVector3): Single; overload;
35 { @groupEnd }
36
37 { Angle between two vectors, in radians.
38 Returns always positive angle, between 0 and Pi.
39
40 AngleRadBetweenNormals is a little faster, but must receive
41 normalized (length 1) vectors. This avoids expensive Sqrt.
42 See also CosAngleBetweenVectors and CosAngleBetweenNormals
43 to avoid expensive ArcCos.
44
45 @raises EVectorInvalidOp If V1 or V2 is zero.
46 @groupBegin }
47 function AngleRadBetweenVectors(const V1, V2: TVector3): Single; overload;
48 function AngleRadBetweenNormals(const V1, V2: TVector3): Single; overload;
49 { @groupEnd }
50
51 { Signed angle between two vectors, in radians.
52 As opposed to AngleRadBetweenNormals, this returns a signed angle,
53 between -Pi and Pi. This is guaranteed to be such angle that rotating
54 V1 around vector cross product (V1 x V2) will produce V2.
55 As you see, the order or arguments is important (just like it's important
56 for vector cross).
57
58 Overloaded versions with Cross argument assume the rotation is done around
59 given Cross vector, which @italic(must) be a cross product or it's negation
60 (in other words, it must be orthogonal to both vectors).
61
62 @raises EVectorInvalidOp If V1 or V2 is zero.
63 @groupBegin }
64 function RotationAngleRadBetweenVectors(const V1, V2: TVector3): Single; overload;
65 function RotationAngleRadBetweenVectors(const V1, V2, Cross: TVector3): Single; overload;
66 { @groupEnd }
67
68 { Rotate Point around the Axis by given Angle.
69 Axis does not have to be normalized (it will be normalized internally).
70
71 Axis can be an exact zero only if Angle is also an exact zero.
72 This special case is supported to make it easier to initialize stuff.
73 This way by default a vector and an angle can be left filled with zeros
74 (like @link(TCastleTransform.Rotation)), and this function will accept
75 them (in effect e.g. @link(TCastleTransform.Direction) will be valid).
76 In all other cases, axis must be a non-zero vector.
77
78 Note that this is equivalent to constructing a rotation matrix
79 and then using it, like
80
81 @longCode(#
82 M := RotationMatrixRad(Angle, Axis);
83 Result := M.MultPoint(Point);
84 #)
85
86 Except this will be a little faster.
87
88 Rotations are done in the same direction as RotationMatrixRad, and as OpenGL.
89
90 @groupBegin }
91 function RotatePointAroundAxisRad(const Angle: Single; const Point: TVector3; const Axis: TVector3): TVector3; overload;
92 function RotatePointAroundAxisDeg(const Angle: Single; const Point: TVector3; const Axis: TVector3): TVector3; overload;
93 deprecated 'use radians for everything throughout CGE';
94 { @groupEnd }
95
96 { Rotate Point around the Axis by 90 degrees.
97 This is specialized and optimized version of RotatePointAroundAxisRad. }
98 function RotatePointAroundAxis90(const Point: TVector3; const Axis: TVector3): TVector3;
99
100 { Rotate Point around the Axis by -90 degrees.
101 This is specialized and optimized version of RotatePointAroundAxisRad. }
102 function RotatePointAroundAxisMinus90(const Point: TVector3; const Axis: TVector3): TVector3;
103
104 { Rotate Point around the given axis by a given angle.
105 Axis is specified in the first 3 components of AxisAngle,
106 rotation angle (in radians) is specified in the last component of AxisAngle. }
107 function RotatePointAroundAxis(const AxisAngle: TVector4; const Point: TVector3): TVector3;
108
109 { Which coordinate (0, 1, 2, and eventually 3 for 4D versions) is the largest.
110 When the vector components are equal, the first one "wins", for example
111 if V[0] = V[1] (and are larger than other vector component) we return 0.
112 MaxAbsVectorCoord compares the absolute value of components.
113 @groupBegin }
114 function MaxVectorCoord(const V: TVector2): Integer; overload;
115 function MaxVectorCoord(const V: TVector3): T3DAxis; overload;
116 function MaxVectorCoord(const V: TVector4): Integer; overload;
117 function MaxAbsVectorCoord(const V: TVector2): Integer; overload;
118 function MaxAbsVectorCoord(const V: TVector3): T3DAxis; overload;
119 function MaxAbsVectorCoord(const V: TVector4): Integer; overload;
120 { @groupEnd }
121
122 function MinAbsVectorCoord(const V: TVector2): Integer; overload;
123 function MinAbsVectorCoord(const V: TVector3): T3DAxis; overload;
124 function MinAbsVectorCoord(const V: TVector4): Integer; overload;
125
126 function MinVectorCoord(const V: TVector3): T3DAxis; overload;
127
128 procedure SortAbsVectorCoord(const V: TVector3; out Max, Middle, Min: T3DAxis); overload;
129
130 { Vector orthogonal to plane and pointing in the given direction.
131
132 Given a plane equation (or just the first 3 components of this equation),
133 we have vector orthogonal to the plane (just the first 3 components of plane
134 equation). This returns either this vector, or it's negation.
135 It chooses the one that points in the same 3D half-space as given Direction.
136
137 When given Direction is paralell to Plane, returns original
138 plane direction, not it's negation.
139
140 This really simply returns the first 3 components of plane equation.
141 possibly negated. So e.g. if the plane direction was normalized, result
142 is normalized too.
143
144 PlaneDirNotInDirection chooses the direction opposite to given Direction
145 parameter. So it's like @code(PlaneDirInDirection(Plane, -Direction)).
146
147 @groupBegin }
148 function PlaneDirInDirection(const Plane: TVector4; const Direction: TVector3): TVector3; overload;
149 function PlaneDirInDirection(const PlaneDir, Direction: TVector3): TVector3; overload;
150 function PlaneDirNotInDirection(const Plane: TVector4; const Direction: TVector3): TVector3; overload;
151 function PlaneDirNotInDirection(const PlaneDir, Direction: TVector3): TVector3; overload;
152 { @groupEnd }
153
154 { Endianess swapping for vectors. }
155 function SwapEndian(const V: TVector2): TVector2; overload;
156 function SwapEndian(const V: TVector3): TVector3; overload;
157 function SwapEndian(const V: TVector4): TVector4; overload;
158
159 { Endianess conversion for vectors (little endian to native). }
160 function LEtoN(const V: TVector2): TVector2; overload;
161 function LEtoN(const V: TVector3): TVector3; overload;
162 function LEtoN(const V: TVector4): TVector4; overload;
163
164 { Endianess conversion for vectors (big endian to native). }
165 function BEtoN(const V: TVector2): TVector2; overload;
166 function BEtoN(const V: TVector3): TVector3; overload;
167 function BEtoN(const V: TVector4): TVector4; overload;
168
169 { Endianess conversion for vectors (native to little endian). }
170 function NtoLE(const V: TVector2): TVector2; overload;
171 function NtoLE(const V: TVector3): TVector3; overload;
172 function NtoLE(const V: TVector4): TVector4; overload;
173
174 { Endianess conversion for vectors (native to big endian). }
175 function NtoBE(const V: TVector2): TVector2; overload;
176 function NtoBE(const V: TVector3): TVector3; overload;
177 function NtoBE(const V: TVector4): TVector4; overload;
178
179 { Replace contents of 2 variables. }
180 procedure SwapValues(var V1, V2: TVector2); overload;
181 procedure SwapValues(var V1, V2: TVector3); overload;
182 procedure SwapValues(var V1, V2: TVector4); overload;
183
184 { This normalizes Plane by scaling all @italic(four) coordinates of Plane
185 so that length of plane vector (taken from 1st @italic(three) coordinates)
186 is one.
187
188 Also, contrary to normal NormalizeVar on 3-component vectors,
189 this will fail with some awful error (like floating point overflow)
190 in case length of plane vector is zero. That's because we know
191 that plane vector @italic(must) be always non-zero. }
192 procedure NormalizePlaneVar(var V: TVector4); overload;
193
194 { Intersection of two 3D planes.
195 @raises EPlanesParallel If planes are parallel.
196 @groupBegin }
197 procedure TwoPlanesIntersectionLine(const Plane0, Plane1: TVector4;
198 out Line0, LineVector: TVector3); overload;
199 { @groupEnd }
200
201 { Intersection of two 2D lines.
202 2D lines are expressed here as a vector of three values (A,B,C),
203 such that Ax+By+C=0 is true for points on the line.
204 @raises ELinesParallel if lines parallel
205 @groupBegin }
206 function Lines2DIntersection(const Line0, Line1: TVector3): TVector2; overload;
207 { @groupEnd }
208
209 { Intersection of three 3D planes, results in a single 3D point.
210 If the intersection is not a single 3D point, result is undefined,
211 so don't try to use this.
212 @groupBegin }
213 function ThreePlanesIntersectionPoint(
214 const Plane0, Plane1, Plane2: TVector4): TVector3; overload;
215 { @groupEnd }
216
217 { Move a plane by a specifed vector.
218 The first three plane numbers (plane normal vector) don't change
219 (so, in particular, if you used the plane to define the half-space,
220 the half-space gets moved as it should).
221
222 PlaneAntiMove work like PlaneMove, but they translate by negated Move
223 So it's like PlaneAntiMove(Plane, V) := PlaneMove(Plane, -V),
224 but (very slightly) faster.
225
226 This works Ok with invalid planes (1st three components = 0),
227 that is after the move the plane remains invalid (1st three components
228 remain = 0).
229
230 @groupBegin }
231 function PlaneMove(const Plane: TVector4;
232 const Move: TVector3): TVector4; overload;
233
234 procedure PlaneMoveVar(var Plane: TVector4; const Move: TVector3); overload;
235
236 function PlaneAntiMove(const Plane: TVector4;
237 const Move: TVector3): TVector4; overload;
238 { @groupEnd }
239
240 { Check if both directions indicate the same side of given 3D plane.
241 If one direction is parallel to the plane, also returns @true.
242 You can specify only the first 3 components of plane equation (PlaneDir),
243 since the 4th component would be ignored anyway.
244 @groupBegin }
245 function VectorsSamePlaneDirections(const V1, V2: TVector3; const Plane: TVector4): boolean; overload;
246 function VectorsSamePlaneDirections(const V1, V2: TVector3; const PlaneDir: TVector3): boolean; overload;
247 { @groupEnd }
248
249 { Check if both points are on the same side of given 3D plane.
250 If one of the points is exactly on the plane, also returns @true.
251 @groupBegin }
252 function PointsSamePlaneSides(const p1, p2: TVector3; const Plane: TVector4): boolean; overload;
253 { @groupEnd }
254
255 function PointsDistance(const V1, V2: TVector2): Single; overload;
256 function PointsDistance(const V1, V2: TVector3): Single; overload;
257 function PointsDistanceSqr(const V1, V2: TVector2): Single; overload;
258 function PointsDistanceSqr(const V1, V2: TVector3): Single; overload;
259
260 { Distance between points projected on the 2D plane.
261 Projection is done by rejecting IgnoreIndex coordinate (must be 0, 1 or 2).
262 @groupBegin }
263 function PointsDistance2DSqr(const V1, V2: TVector3; const IgnoreIndex: Integer): Single; overload;
264 { @groupEnd }
265
266 function VectorsPerp(const V1, V2: TVector3): boolean; overload;
267
268 { Are the two vectors parallel (one is a scaled version of another).
269 In particular, if one of the vectors is zero, then this is @true.
270 @groupBegin }
271 function VectorsParallel(const V1, V2: TVector3): boolean; overload;
272 { @groupEnd }
273
274 { Adjust the V1 vector to force given angle between V1 and V2.
275 Vector V1 will be adjusted, such that it has the same length
276 and the 3D plane defined by V1, V2 and (0, 0, 0) is the same.
277
278 When vectors are parallel (this includes the case when one of them is zero),
279 we set V1 to ResultWhenParallel.
280
281 We make it such that V1 rotated around axis TVector3.CrossProduct(V1, V2) by given
282 angle will result in V2. Note that this means that
283 @code(MakeVectorsAngleRadOnTheirPlane(V1, V2, Angle, ...))
284 results in the same (not reversed) relation between vectors as
285 @code(MakeVectorsAngleRadOnTheirPlane(V2, V1, Angle, ...)).
286 That's because you change the arguments order, but also TVector3.CrossProduct
287 sign changes.
288 @groupBegin }
289 procedure MakeVectorsAngleRadOnTheirPlane(var v1: TVector3;
290 const v2: TVector3; const AngleRad: Single;
291 const ResultWhenParallel: TVector3); overload;
292 { @groupEnd }
293
294 { Adjust the V1 vector to force V1 and V2 to be orthogonal,
295 but keep the 3D plane determined by V1 and V2 unchanged.
296 When vectors are parallel, we set V1 to be AnyOrthogonalVector(V2). }
297 procedure MakeVectorsOrthoOnTheirPlane(var v1: TVector3; const v2: TVector3); overload;
298
299 { Adjust and return the V1 vector to force V1 and V2 to be orthogonal,
300 but keep the 3D plane determined by V1 and V2 unchanged.
301 When vectors are parallel, we return AnyOrthogonalVector(V2).
302
303 This is a functional version of MakeVectorsOrthoOnTheirPlane. }
304 function MakeVectorOrthogonal(const V1, V2: TVector3): TVector3;
305
306 { Return, deterministically, some vector orthogonal to V.
307 When V is non-zero, then the result is non-zero.
308 @groupBegin }
309 function AnyOrthogonalVector(const V: TVector2): TVector2; overload;
310 function AnyOrthogonalVector(const V: TVector3): TVector3; overload;
311 { @groupEnd }
312
313 function IsLineParallelToPlane(const lineVector: TVector3; const plane: TVector4): boolean; overload;
314
315 function IsLineParallelToSimplePlane(const lineVector: TVector3;
316 const PlaneConstCoord: T3DAxis): boolean; overload;
317
318 { Assuming that Vector1 and Vector2 are parallel,
319 check do they point in the same direction.
320
321 This assumes that both vectors are non-zero.
322 If one of the vectors is zero, the result is undefined --- false or true.
323 (but the function will surely not raise some floating point error etc.) }
324 function AreParallelVectorsSameDirection(
325 const Vector1, Vector2: TVector3): boolean; overload;
326
327 { Orthogonally project a point on a plane, that is find a closest
328 point to Point lying on a Plane.
329 @groupBegin }
330 function PointOnPlaneClosestToPoint(const plane: TVector4; const point: TVector3): TVector3; overload;
331 { @groupEnd }
332
333 function PointToPlaneDistanceSqr(const Point: TVector3;
334 const Plane: TVector4): Single; overload;
335
336 { Distance from a point to a plane (with already normalized direction).
337
338 Note: distance of the plane from origin point (0,0,0) may be simply
339 obtained by Abs(Plane[3]) when Plane is Normalized.
340 @groupBegin }
341 function PointToNormalizedPlaneDistance(const Point: TVector3;
342 const Plane: TVector4): Single; overload;
343 { @groupEnd }
344
345 { Distance from a point to a plane.
346
347 Note that calculating this costs you one Sqrt
348 (contrary to PointToPlaneDistanceSqr or
349 PointToNormalizedPlaneDistance).
350
351 @groupBegin }
352 function PointToPlaneDistance(const Point: TVector3;
353 const Plane: TVector4): Single; overload;
354 { @groupEnd }
355
356 function PointToSimplePlaneDistance(const point: TVector3;
357 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single): Single; overload;
358
359 function PointOnLineClosestToPoint(const line0, lineVector, point: TVector2): TVector2; overload;
360 function PointOnLineClosestToPoint(const line0, lineVector, point: TVector3): TVector3; overload;
361
362 function PointToLineDistanceSqr(const point, line0, lineVector: TVector3): Single; overload;
363
364 { Plane and line intersection.
365
366 Returns @false and doesn't modify Intersection or T when
367 the line is parallel to the plane (this includes the case when
368 the line @italic(lies on a plane), so theoretically the whole
369 line is an intersection).
370
371 Otherwise, returns @true, and calculates 3D intersection point,
372 or calculates T such that @code(3D intersection = Line0 + LineVector * T).
373 T is always within [0,1] range.
374 @groupBegin }
375 function TryPlaneLineIntersection(out intersection: TVector3;
376 const plane: TVector4; const line0, lineVector: TVector3): boolean; overload;
377 function TryPlaneLineIntersection(out t: Single;
378 const plane: TVector4; const line0, lineVector: TVector3): boolean; overload;
379 { @groupEnd }
380
381 { Plane and ray intersection.
382
383 Returns @false and doesn't modify Intersection or T when
384 the ray is parallel to the plane (this includes the case when
385 the ray @italic(lies on a plane). Also returns @false when the ray would
386 have to point in the opposite direction to hit the plane.
387
388 Otherwise, returns @true, and calculates 3D intersection point,
389 or calculates T such that @code(3D intersection = RayOrigin + RayDirection * T).
390 T is always >= 0.
391 @groupBegin }
392 function TrySimplePlaneRayIntersection(out Intersection: TVector3;
393 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
394 const RayOrigin, RayDirection: TVector3): boolean; overload;
395 function TrySimplePlaneRayIntersection(out Intersection: TVector3; out T: Single;
396 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
397 const RayOrigin, RayDirection: TVector3): boolean; overload;
398 function TrySimplePlaneRayIntersection(out T: Single;
399 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
400 const RayOrigin, RayDirection: TVector3): boolean; overload;
401
402 function TryPlaneRayIntersection(out Intersection: TVector3;
403 const Plane: TVector4; const RayOrigin, RayDirection: TVector3): boolean; overload;
404 function TryPlaneRayIntersection(out Intersection: TVector3; out T: Single;
405 const Plane: TVector4; const RayOrigin, RayDirection: TVector3): boolean; overload;
406 { @groupEnd }
407
408 { Plane and line segment intersection.
409
410 Returns @false and doesn't modify Intersection or T when
411 the segment is parallel to the plane (this includes the case when
412 the segment @italic(lies on a plane). Also returns @false when the segment
413 would have to be longer to hit the plane.
414
415 Otherwise, returns @true, and calculates 3D intersection point,
416 or calculates T such that @code(3D intersection = Segment0 + SegmentVector * T).
417 T is always in range [0,1].
418 @groupBegin }
419 function TrySimplePlaneSegmentIntersection(
420 out Intersection: TVector3;
421 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
422 const Pos1, Pos2: TVector3): boolean; overload;
423 function TrySimplePlaneSegmentIntersection(
424 out Intersection: TVector3; out T: Single;
425 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
426 const Pos1, Pos2: TVector3): boolean; overload;
427 function TrySimplePlaneSegmentIntersection(
428 out T: Single;
429 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
430 const Pos1, Pos2: TVector3): boolean; overload;
431
432 function TryPlaneSegmentDirIntersection(out Intersection: TVector3;
433 const Plane: TVector4; const Segment0, SegmentVector: TVector3): boolean; overload;
434 function TryPlaneSegmentDirIntersection(out Intersection: TVector3; out T: Single;
435 const Plane: TVector4; const Segment0, SegmentVector: TVector3): boolean; overload;
436 { @groupEnd }
437
438 function IsPointOnSegmentLineWithinSegment(const intersection, pos1, pos2: TVector2): boolean; overload;
439 function IsPointOnSegmentLineWithinSegment(const intersection, pos1, pos2: TVector3): boolean; overload;
440
441 { Coefficients of the 2D line equation (Ax + By + C = 0),
442 given 2 @italic(different) points lying on the line.
443 When the points are equal, this is undefined. }
444 function Line2DFrom2Points(const P1, P2: TVector2): TVector3;
445 function LineOfTwoDifferentPoints2D(const P1, P2: TVector2): TVector3; deprecated 'use Line2DFrom2Points';
446
447 { Coefficients of the 2D line equation (Ax + By + C = 0),
448 given 1 point lying on the line, and non-zero line direction.
449 When LineVector is zero, this is undefined. }
450 function Line2DFromOriginVector(const Line0, LineVector: TVector2): TVector3;
451
452 function PointToSegmentDistanceSqr(const point, pos1, pos2: TVector3): Single; overload;
453
454 { Transform plane by a matrix.
455
456 @raises(ETransformedResultInvalid Raised when matrix
457 will transform some point to a direction, or direction to point,
458 in homogeneous coordinates.)
459
460 @groupBegin }
461 function PlaneTransform(const Plane: TVector4; const Matrix: TMatrix4): TVector4;
462 { @groupEnd }
463
464 function IsTunnelSphereCollision(const Tunnel1, Tunnel2: TVector3;
465 const TunnelRadius: Single; const SphereCenter: TVector3;
466 const SphereRadius: Single): boolean; overload;
467
468 function IsSpheresCollision(const Sphere1Center: TVector3; const Sphere1Radius: Single;
469 const Sphere2Center: TVector3; const Sphere2Radius: Single): boolean; overload;
470
471 function IsSegmentSphereCollision(const pos1, pos2, SphereCenter: TVector3;
472 const SphereRadius: Single): boolean; overload;
473
474 function TrySphereRayIntersection(out Intersection: TVector3;
475 const SphereCenter: TVector3; const SphereRadius: Single;
476 const RayOrigin, RayDirection: TVector3): boolean; overload;
477
478 { Intersection between an (infinitely tall) cylinder and a ray.
479 @groupBegin }
480 function TryCylinderRayIntersection(out Intersection: TVector3;
481 const CylinderAxisOrigin, CylinderAxis: TVector3;
482 const CylinderRadius: Single;
483 const RayOrigin, RayDirection: TVector3): boolean; overload;
484 { @groupEnd }
485
486 { Given two 3D lines (both given as an some point + direction in 3D),
487 calculate closest point on 1st line to the 2nd line.
488 Returns @false if lines are parallel, thus is not possible to determine any single
489 closest point. }
490 function PointOnLineClosestToLine(
491 out Intersection: TVector3;
492 const Line1Origin, Line1Vector, Line2Origin, Line2Vector: TVector3): Boolean;
493
494 { Matrix operations ---------------------------------------------------------- }
495
496 { Functions to create common 4x4 matrices used in 3D graphics.
497
498 These functions generate the same matrices as old OpenGL fixed-function was using.
499 They work in right-handed coordinate system, just like X3D, glTF and OpenGL.
500
501 Functions named Matrices below generate both normal and inverted matrices.
502 For example, function RotationMatrices returns two matrices that you
503 could calculate separately by
504
505 @longCode(#
506 Matrix: = RotationMatrix( Angle, Axis);
507 InvertedMatrix: = RotationMatrix(-Angle, Axis);
508 #)
509
510 This is useful sometimes, and generating them both at the same time
511 allows for some speedup (for example, calling RotationMatrix twice will
512 calculate sincos of Angle twice).
513
514 Note that inverse of scaling matrix will not exist if the
515 ScaleFactor has one of the components zero !
516 Depending on InvertedMatrixIdentityIfNotExists, this will
517 (if @false) raise division by zero exception or (if @true) cause
518 the matrix to be set to identity.
519
520 Note that rotation matrix (both normal and inverse) is always defined,
521 for Axis = zero both normal and inverse matrices are set to identity.
522
523 @groupBegin }
524 function TranslationMatrix(const X, Y, Z: Single): TMatrix4; overload;
525 function TranslationMatrix(const Transl: TVector3): TMatrix4; overload;
526
527 procedure TranslationMatrices(const X, Y, Z: Single; out Matrix, InvertedMatrix: TMatrix4); overload;
528 procedure TranslationMatrices(const Transl: TVector3; out Matrix, InvertedMatrix: TMatrix4); overload;
529
530 { Multiply matrix M by translation matrix.
531
532 This is equivalent to M := M * TranslationMatrix(Transl),
533 but it works much faster since TranslationMatrix is a very simple matrix
534 and multiplication by it may be much optimized.
535
536 An additional speedup comes from the fact that the result is placed
537 back in M (so on places where M doesn't change (and there's a lot
538 of them for multiplication with translation matrix) there's no useless
539 copying).
540
541 MultMatricesTranslation is analogous to calculating both
542 TranslationMatrix(Transl) and it's inverse, and then
543
544 @longCode(#
545 M := M * translation;
546 MInvert := inverted-translation * MInvert;
547 #)
548
549 The idea is that if M represented some translation, and MInvert it's
550 inverse, then after MultMatricesTranslation this will still hold.
551
552 @groupBegin }
553 procedure MultMatrixTranslation(var M: TMatrix4; const Transl: TVector3); overload;
554 procedure MultMatricesTranslation(var M, MInvert: TMatrix4; const Transl: TVector3); overload;
555 { @groupEnd }
556
557 { Transform coordinates to / from a coordinate system.
558 Stuff multiplied by this matrix is supplied in other coordinate system.
559
560 The "new" coordinate system (you specify it explicitly for
561 TransformToCoordsMatrix) is the coordinate system in which your 3D stuff
562 is defined. That is, when you supply the points (that will later be
563 multiplied by TransformToCoordsMatrix) you think in the "new" coordinate
564 system. The "old" coordinate system
565 (you specify it explicitly for TransformFromCoordsMatrix)
566 is the coordinate system of stuff @italic(after)
567 it's multiplied by this matrix.
568
569 This may get confusing, so to be more precise:
570
571 @unorderedList(
572
573 @item(
574 TransformToCoordsMatrix says how the new coords system looks
575 from the point of view of the old coords system.
576 A stuff lying at (0, 0, 0) in new coord system will be seen
577 at NewOrigin after the transformation (in the old coordinate system).
578 Similarly, direction (0, 1, 0) will be seen as NewY after
579 the transformation.)
580
581 @item(
582 TransformFromCoordsMatrix is the inverse: how the old system
583 is seen from the new one. If before the transformation you are
584 at OldOrigin, then after the transformation you are at (0, 0, 0).
585 This is natural way to implement LookAtMatrix, LookDirMatrix.)
586 )
587
588 The lengths of directions (New or Old X, Y, Z vectors) are meaningful.
589 These vectors correspond to unit vectors (1, 0, 0), (0, 1, 0) and (0, 0, 1)
590 in the other coordinate system. Supplying here non-normalized vectors
591 will result in scaling.
592
593 You can use the "NoScale" versions to have the vectors automatically
594 normalized, thus you waste a little time (on normalizing) but you
595 avoid the scaling.
596
597 Overloaded versions without OldOrigin / NewOrigin parameters
598 work like the old/new origin is zero. IOW, the origin of the coordinate
599 system doesn't change in this case.
600
601 @groupBegin }
602 function TransformToCoordsMatrix(const
603 NewX, NewY, NewZ: TVector3): TMatrix4; overload;
604 function TransformToCoordsMatrix(const NewOrigin,
605 NewX, NewY, NewZ: TVector3): TMatrix4; overload;
606 function TransformToCoordsNoScaleMatrix(const NewOrigin,
607 NewX, NewY, NewZ: TVector3): TMatrix4; overload;
608
609 function TransformFromCoordsMatrix(const
610 OldX, OldY, OldZ: TVector3): TMatrix4; overload;
611 function TransformFromCoordsMatrix(const OldOrigin,
612 OldX, OldY, OldZ: TVector3): TMatrix4; overload;
613 function TransformFromCoordsNoScaleMatrix(const OldOrigin,
614 OldX, OldY, OldZ: TVector3): TMatrix4; overload;
615 { @groupEnd }
616
617 { Calculate matrix to convert to given coordinate system
618 (like TransformToCoordsMatrix) and it's inverse
619 (like TransformFromCoordsMatrix).
620
621 @groupBegin }
622 procedure TransformCoordsMatrices(const NewX, NewY, NewZ: TVector3;
623 out ToCoords, FromCoords: TMatrix4); overload;
624 { @groupEnd }
625
626 { Transform vector into new coordinate space.
627
628 Equivalent to @code(TransformToCoordsMatrix(TVector3.Zero,
629 NewX, NewY, NewZ).MultPoint(V)). So the origin of new coordinate system is at the same
630 place. You should pass NewX, NewY, NewZ vectors normalized if you want to
631 preserve vector length.
632 @groupBegin }
633 function TransformToCoords(const V, NewX, NewY, NewZ: TVector3): TVector3;
634 { @groupEnd }
635
636 type
637 { Express a 3D transformation as position, direction and up 3D vectors.
638 Useful especially for cameras. }
639 TViewVectors = record
640 Translation, Direction, Up: TVector3;
641 function Matrix: TMatrix4;
642 function RotationMatrix: TMatrix4;
643 end;
644
645 { Camera matrix to look at the specified point (or along the specified direction).
646 Work according to right-handed coordinate system.
647
648 When applied to the scene, they transform it, such that a camera standing
649 at (0, 0, 0) (with dir (0, 0, -1) and up vector (0, 1, 0)),
650 was seeing the same view as if it was standing at Eye
651 (with given Dir and Up vectors).
652
653 For LookAtMatrix, looking direction is implicitly given as @code(Center - Eye).
654 Just like gluLookAt.
655
656 @unorderedList(
657 @item(For the overloaded LookDirMatrix version with Side parameter,
658 we assume that Dir, Side and Up are already normalized
659 and orthogonal to each other.)
660
661 @item(For the overloaded version without the Side parameter,
662 Dir and Up do not have to normalized.
663 We'll normalize them if needed, so their lengths do not affect the result
664 (just as the distance between Center and Eye points for LookAtMatrix).
665
666 Also, Dir and Up do not have to be perfectly orthogonal
667 (we will eventually adjust Up internally to make it orthogonal to Up).
668
669 You still must make sure that Dir and Up are not parallel.)
670 )
671
672 @groupBegin }
673 function LookAtMatrix(const Eye, Center, Up: TVector3): TMatrix4; overload;
674 function LookDirMatrix(const Eye, Dir, Up: TVector3): TMatrix4; overload;
675 function LookDirMatrix(const Eye, Dir, Side, Up: TVector3): TMatrix4; overload;
676 { @groupEnd }
677
678 { Calculate LookDirMatrix (or it's inverse), fast.
679
680 Has some assumptions that make it run fast:
681 @unorderedList(
682 @item(It assumes camera position is zero.)
683 @item(It assumes that Dir and Up are already normalized and orthogonal.)
684 )
685
686 @groupBegin
687 }
688 function FastLookDirMatrix(const Direction, Up: TVector3): TMatrix4;
689 function InverseFastLookDirMatrix(const Direction, Up: TVector3): TMatrix4;
690 { @groupEnd }
691
692 { Convert ModelView matrix to a Normal matrix, just like 3D graphic libraries do.
693 See e.g. http://www.lighthouse3d.com/tutorials/glsl-tutorial/the-normal-matrix/
694 for explanation why this is necessary, and how it's done. }
695 function ModelViewToNormalMatrix(const M: TMatrix4): TMatrix3;
696
697 { Multiply vector by a transposition of the same vector.
698 For 3d vectors, this results in a 3x3 matrix.
699 To put this inside a 4x4 matrix,
700 we fill the last row and column just like for an identity matrix.
701
702 This is useful for calculating rotation matrix. }
703 function VectorMultTransposedSameVector(const V: TVector3): TMatrix4;
704
705 function ScalingMatrix(const ScaleFactor: TVector3): TMatrix4;
706
707 procedure ScalingMatrices(const ScaleFactor: TVector3;
708 InvertedMatrixIdentityIfNotExists: boolean;
709 out Matrix, InvertedMatrix: TMatrix4);
710
711 function RotationMatrix(const AxisAngle: TVector4): TMatrix4; overload;
712
713 function RotationMatrixRad(const AngleRad: Single; const Axis: TVector3): TMatrix4; overload;
714 function RotationMatrixDeg(const AngleDeg: Single; const Axis: TVector3): TMatrix4; overload; deprecated 'use radians for everything throughout CGE';
715 function RotationMatrixRad(const AngleRad: Single; const AxisX, AxisY, AxisZ: Single): TMatrix4; overload;
716 function RotationMatrixDeg(const AngleDeg: Single; const AxisX, AxisY, AxisZ: Single): TMatrix4; overload; deprecated 'use radians for everything throughout CGE';
717
718 procedure RotationMatricesRad(const AngleRad: Single; const Axis: TVector3;
719 out Matrix, InvertedMatrix: TMatrix4); overload;
720 procedure RotationMatricesRad(const AxisAngle: TVector4;
721 out Matrix, InvertedMatrix: TMatrix4); overload;
722 { @groupEnd }
723
724 { Negate a rotation expressed as axis-angle (3 components for axis, 1 for angle).
725 This simply negates the 4th vector component. }
726 function RotationNegate(const Rotation: TVector4): TVector4;
727
728 { Rotate point in 2D, in a counter-clockwise fashion.
729 AngleRad is in radians. }
730 function RotatePoint2D(const Point: TVector2; const AngleRad: Single): TVector2;
731
732 { When you really, really must approximate a 3D or 2D scale by a single float.
733 E.g. if your algorithm cannot handle non-uniform 3D or 2D scale,
734 you have to approximate 3D or 2D scale by a single float.
735
736 This is similar to an average of X, Y (and Z, in 3D), but it additionally
737 secures in case some of X, Y, Z are negative and some are positive
738 (like scale (-1, 1), common in 2D to flip horizontally).
739
740 The overloaded version with matrix argument
741 extracts scale from matrix, just like MatrixDecompose.
742
743 @groupBegin }
744 function Approximate3DScale(const X, Y, Z: Single): Single; overload;
745 function Approximate3DScale(const V: TVector3): Single; overload;
746 function Approximate3DScale(const M: TMatrix4): Single; overload;
747
748 function Approximate2DScale(const X, Y: Single): Single; overload;
749 function Approximate2DScale(const V: TVector2): Single; overload;
750 { @groupEnd }
751
752 { Smoothly change Source to Target.
753
754 The speed decreases as Source is closer to Target,
755 so the animation ends smoothly.
756
757 Note: Initially the argument Speed was represented by 2 values:
758 MaxChangeSpeed, MaxDistance: Single
759 The intended meaning of MaxChangeSpeed was the speed
760 with which Source changes to Target,
761 so that MaxChangeSpeed = 1.0 means that it changes in 1 second,
762 MaxChangeSpeed = 0.5 means that it changes in 2 seconds,
763 MaxChangeSpeed = 2 means that it changes in 0.5 seconds.
764
765 Later: now it's just Speed.
766 You can just passs Speed = MaxChangeSpeed / MaxDistance to get the
767 same logic as above.
768 }
769 function SmoothTowards(const Source, Target, SecondsPassed,
770 Speed: Single): Single; overload;
771 function SmoothTowards(const Source, Target: TVector2;
772 const SecondsPassed, Speed: Single): TVector2; overload;
773 function SmoothTowards(const Source, Target: TVector3;
774 const SecondsPassed, Speed: Single): TVector3; overload;
775
776 const
777 NoScale: TVector3 = (X: 1; Y: 1; Z: 1);
778
779 {$endif read_interface}
780
781 {$ifdef read_implementation}
782
783 function SwapEndian(const V: TVector2): TVector2;
784 begin
785 Result.X := SwapEndian(V.X);
786 Result.Y := SwapEndian(V.Y);
787 end;
788
789 function SwapEndian(const V: TVector3): TVector3;
790 begin
791 Result.X := SwapEndian(V.X);
792 Result.Y := SwapEndian(V.Y);
793 Result.Z := SwapEndian(V.Z);
794 end;
795
796 function SwapEndian(const V: TVector4): TVector4;
797 begin
798 Result.X := SwapEndian(V.X);
799 Result.Y := SwapEndian(V.Y);
800 Result.Z := SwapEndian(V.Z);
801 Result.W := SwapEndian(V.W);
802 end;
803
804 function NtoLE(const V: TVector2): TVector2;
805 begin
806 {$ifdef ENDIAN_BIG}
807 Result := SwapEndian(V);
808 {$else ENDIAN_BIG}
809 Result := V;
810 {$endif ENDIAN_BIG}
811 end;
812
813 function NtoLE(const V: TVector3): TVector3;
814 begin
815 {$ifdef ENDIAN_BIG}
816 Result := SwapEndian(V);
817 {$else ENDIAN_BIG}
818 Result := V;
819 {$endif ENDIAN_BIG}
820 end;
821
822 function NtoLE(const V: TVector4): TVector4;
823 begin
824 {$ifdef ENDIAN_BIG}
825 Result := SwapEndian(V);
826 {$else ENDIAN_BIG}
827 Result := V;
828 {$endif ENDIAN_BIG}
829 end;
830
831 function NtoBE(const V: TVector2): TVector2;
832 begin
833 {$ifdef ENDIAN_BIG}
834 Result := V;
835 {$else ENDIAN_BIG}
836 Result := SwapEndian(V);
837 {$endif ENDIAN_BIG}
838 end;
839
840 function NtoBE(const V: TVector3): TVector3;
841 begin
842 {$ifdef ENDIAN_BIG}
843 Result := V;
844 {$else ENDIAN_BIG}
845 Result := SwapEndian(V);
846 {$endif ENDIAN_BIG}
847 end;
848
849 function NtoBE(const V: TVector4): TVector4;
850 begin
851 {$ifdef ENDIAN_BIG}
852 Result := V;
853 {$else ENDIAN_BIG}
854 Result := SwapEndian(V);
855 {$endif ENDIAN_BIG}
856 end;
857
858 function LEtoN(const V: TVector2): TVector2;
859 begin
860 {$ifdef ENDIAN_BIG}
861 Result := SwapEndian(V);
862 {$else ENDIAN_BIG}
863 Result := V;
864 {$endif ENDIAN_BIG}
865 end;
866
867 function LEtoN(const V: TVector3): TVector3;
868 begin
869 {$ifdef ENDIAN_BIG}
870 Result := SwapEndian(V);
871 {$else ENDIAN_BIG}
872 Result := V;
873 {$endif ENDIAN_BIG}
874 end;
875
876 function LEtoN(const V: TVector4): TVector4;
877 begin
878 {$ifdef ENDIAN_BIG}
879 Result := SwapEndian(V);
880 {$else ENDIAN_BIG}
881 Result := V;
882 {$endif ENDIAN_BIG}
883 end;
884
885 function BEtoN(const V: TVector2): TVector2;
886 begin
887 {$ifdef ENDIAN_BIG}
888 Result := V;
889 {$else ENDIAN_BIG}
890 Result := SwapEndian(V);
891 {$endif ENDIAN_BIG}
892 end;
893
894 function BEtoN(const V: TVector3): TVector3;
895 begin
896 {$ifdef ENDIAN_BIG}
897 Result := V;
898 {$else ENDIAN_BIG}
899 Result := SwapEndian(V);
900 {$endif ENDIAN_BIG}
901 end;
902
903 function BEtoN(const V: TVector4): TVector4;
904 begin
905 {$ifdef ENDIAN_BIG}
906 Result := V;
907 {$else ENDIAN_BIG}
908 Result := SwapEndian(V);
909 {$endif ENDIAN_BIG}
910 end;
911
912 procedure SwapValues(var V1, V2: TVector2);
913 var
914 Tmp: TVector2;
915 begin
916 Tmp := V1;
917 V1 := V2;
918 V2 := Tmp;
919 end;
920
921 procedure SwapValues(var V1, V2: TVector3);
922 var
923 Tmp: TVector3;
924 begin
925 Tmp := V1;
926 V1 := V2;
927 V2 := Tmp;
928 end;
929
930 procedure SwapValues(var V1, V2: TVector4);
931 var
932 Tmp: TVector4;
933 begin
934 Tmp := V1;
935 V1 := V2;
936 V2 := Tmp;
937 end;
938
939 procedure NormalizePlaneVar(var V: TVector4);
940 var
941 Len: Single;
942 begin
943 Len := Sqrt( Sqr(V.X) + Sqr(V.Y) + Sqr(V.Z) );
944 Len := 1 / Len;
945 V.X := V.X * Len;
946 V.Y := V.Y * Len;
947 V.Z := V.Z * Len;
948 V.W := V.W * Len;
949 end;
950
951 function CosAngleBetweenVectors(const V1, V2: TVector3): Single;
952 var
953 LensSquared: Single;
954 begin
955 { Optimization: We don't do 2x Sqrt (on V1 length and V2 length).
956 Instead, we can do 1x Sqrt on both of them,
957 simply they are multiplied for the final purpose. }
958 LensSquared := v1.LengthSqr * v2.LengthSqr;
959 if IsZero(LensSquared) then
960 raise EVectorInvalidOp.Create(
961 'Cannot calculate angle between vectors, at least one of the vectors is zero');
962
963 { We need to clamp to [-1...1] range, otherwise sometimes floating-point
964 errors make the result very slightly outside this range. And ArcCos
965 (used in AngleRadBetweenVectors) expects [-1...1] range (as the only valid
966 range of cosinus values, makes sense), otherwise it makes EInvalidArgument
967 exception. }
968 Result := Clamped(
969 TVector3.DotProduct(V1, V2) / Sqrt(LensSquared), -1.0, 1.0);
970 end;
971
972 function AngleRadBetweenVectors(const V1, V2: TVector3): Single;
973 begin
974 Result := ArcCos(CosAngleBetweenVectors(V1, V2));
975 end;
976
977 function CosAngleBetweenNormals(const V1, V2: TVector3): Single;
978 begin
979 Result := Clamped(TVector3.DotProduct(V1, V2), -1.0, 1.0);
980 end;
981
982 function AngleRadBetweenNormals(const V1, V2: TVector3): Single;
983 begin
984 Result := ArcCos(CosAngleBetweenNormals(V1, V2));
985 end;
986
987 function RotationAngleRadBetweenVectors(const V1, V2, Cross: TVector3): Single;
988 begin
989 Result := AngleRadBetweenVectors(V1, V2);
990 if PointsDistanceSqr(RotatePointAroundAxisRad( Result, V1, Cross), V2) >
991 PointsDistanceSqr(RotatePointAroundAxisRad(-Result, V1, Cross), V2) then
992 Result := -Result;
993
994 { Note that an assertion here that
995
996 PointsDistance(RotatePointAroundAxisRad(Result, V1, Cross), V2)
997
998 is zero would *not* be correct: V1 and V2 may have different
999 lengths, and then really neither Result nor -Result will get
1000 V1 to rotate exactly to V2. However, the algorithm is still correct:
1001 The valid Result (AngleRadBetweenVectors or -AngleRadBetweenVectors)
1002 will result in shorter distance (difference between V1 and V2 lengths),
1003 the invalid Result would for sure make longer distance. }
1004
1005 { Commented out by default because this assertion is costly.
1006 But it should be valid, you can uncomment it for test!
1007
1008 Assert(SameValue(
1009 PointsDistance(RotatePointAroundAxisRad(Result, V1, Cross), V2),
1010 Abs(V1.Length - V2.Length), 0.01));
1011 }
1012 end;
1013
1014 function RotationAngleRadBetweenVectors(const V1, V2: TVector3): Single;
1015 begin
1016 Result := RotationAngleRadBetweenVectors(V1, V2, TVector3.CrossProduct(V1, V2));
1017 end;
1018
1019 function RotatePointAroundAxisDeg(const Angle: Single; const Point: TVector3;
1020 const Axis: TVector3): TVector3;
1021 begin
1022 Result := RotatePointAroundAxisRad(DegToRad(Angle), Point, Axis);
1023 end;
1024
1025 procedure WarningZeroVectorNonZeroAngle(const Axis: TVector3; const Angle: Single);
1026 begin
1027 WritelnWarning('RotatePointAroundAxisRad called with rotation Axis = zero (%s) but non-zero rotation Angle (%g), this is invalid', [
1028 Axis.ToRawString,
1029 Angle
1030 ]);
1031 end;
1032
1033 procedure WarningZeroVectorNonZeroAngle90(const Axis: TVector3);
1034 begin
1035 WritelnWarning('RotatePointAroundAxis90 called with rotation Axis = zero (%s) but non-zero rotation Angle (90, implied by name), this is invalid', [
1036 Axis.ToRawString
1037 ]);
1038 end;
1039
1040 procedure WarningZeroVectorNonZeroAngleMinus90(const Axis: TVector3);
1041 begin
1042 WritelnWarning('RotatePointAroundAxisMinus90 called with rotation Axis = zero (%s) but non-zero rotation Angle (-90, implied by name), this is invalid', [
1043 Axis.ToRawString
1044 ]);
1045 end;
1046
1047 function RotatePointAroundAxisRad(const Angle: Single; const Point: TVector3;
1048 const Axis: TVector3): TVector3;
1049 var
1050 X, Y, Z, L: Single;
1051 SinAngle, CosAngle: Single;
1052 begin
1053 SinCos(Angle, SinAngle, CosAngle);
1054
1055 { normalize and decompose Axis vector }
1056 L := Axis.Length;
1057 if L <> 0 then
1058 begin
1059 L := 1 / L;
1060 X := Axis.X * L;
1061 Y := Axis.Y * L;
1062 Z := Axis.Z * L;
1063 end else
1064 begin
1065 { In case vector has zero length (so it's just zero),
1066 the Angle must be zero, and we can exit early. }
1067 if Angle <> 0 then
1068 WarningZeroVectorNonZeroAngle(Axis, Angle);
1069 Exit(Point);
1070 end;
1071
1072 Result.X := (CosAngle + (1 - CosAngle) * x * x) * Point.X
1073 + ((1 - CosAngle) * x * y - z * SinAngle) * Point.Y
1074 + ((1 - CosAngle) * x * z + y * SinAngle) * Point.Z;
1075
1076 Result.Y := ((1 - CosAngle) * x * y + z * SinAngle) * Point.X
1077 + (CosAngle + (1 - CosAngle) * y * y) * Point.Y
1078 + ((1 - CosAngle) * y * z - x * SinAngle) * Point.Z;
1079
1080 Result.Z := ((1 - CosAngle) * x * z - y * SinAngle) * Point.X
1081 + ((1 - CosAngle) * y * z + x * SinAngle) * Point.Y
1082 + (CosAngle + (1 - CosAngle) * z * z) * Point.Z;
1083 end;
1084
1085 function RotatePointAroundAxis90(const Point: TVector3; const Axis: TVector3): TVector3;
1086 var
1087 X, Y, Z, L: Single;
1088 begin
1089 { Optimized version of RotatePointAroundAxisRad for Angle = Pi / 2,
1090 so SinAngle = 1, CosAngle = 0. }
1091
1092 { normalize and decompose Axis vector }
1093 L := Axis.Length;
1094 if L <> 0 then
1095 begin
1096 L := 1 / L;
1097 X := Axis.X * L;
1098 Y := Axis.Y * L;
1099 Z := Axis.Z * L;
1100 end else
1101 begin
1102 WarningZeroVectorNonZeroAngle90(Axis);
1103 Exit(Point);
1104 end;
1105
1106 Result.X := ( x * x) * Point.X
1107 + (x * y - z) * Point.Y
1108 + (x * z + y) * Point.Z;
1109
1110 Result.Y := (x * y + z) * Point.X
1111 + ( y * y) * Point.Y
1112 + (y * z - x) * Point.Z;
1113
1114 Result.Z := (x * z - y) * Point.X
1115 + (y * z + x) * Point.Y
1116 + ( z * z) * Point.Z;
1117 end;
1118
1119 function RotatePointAroundAxisMinus90(const Point: TVector3; const Axis: TVector3): TVector3;
1120 var
1121 X, Y, Z, L: Single;
1122 begin
1123 { Optimized version of RotatePointAroundAxisRad for Angle = -Pi / 2,
1124 so SinAngle = -1, CosAngle = 0. }
1125
1126 { normalize and decompose Axis vector }
1127 L := Axis.Length;
1128 if L <> 0 then
1129 begin
1130 L := 1 / L;
1131 X := Axis.X * L;
1132 Y := Axis.Y * L;
1133 Z := Axis.Z * L;
1134 end else
1135 begin
1136 WarningZeroVectorNonZeroAngleMinus90(Axis);
1137 Exit(Point);
1138 end;
1139
1140 Result.X := ( x * x) * Point.X
1141 + (x * y + z) * Point.Y
1142 + (x * z - y) * Point.Z;
1143
1144 Result.Y := (x * y - z) * Point.X
1145 + ( y * y) * Point.Y
1146 + (y * z + x) * Point.Z;
1147
1148 Result.Z := (x * z + y) * Point.X
1149 + (y * z - x) * Point.Y
1150 + ( z * z) * Point.Z;
1151 end;
1152
1153 function RotatePointAroundAxis(const AxisAngle: TVector4; const Point: TVector3): TVector3;
1154 var
1155 Axis: TVector3 absolute AxisAngle;
1156 begin
1157 Result := RotatePointAroundAxisRad(AxisAngle.W, Point, Axis);
1158 end;
1159
1160 function MaxVectorCoord(const V: TVector2): Integer;
1161 begin
1162 Result := 0;
1163 if V.Y > V[Result] then Result := 1;
1164 end;
1165
1166 function MaxVectorCoord(const V: TVector3): T3DAxis;
1167 begin
1168 Result := 0;
1169 { order of comparisons is important. We start from 0, then 1 and 2,
1170 and change only when differ (>, not just >=). This way we
1171 guarantee that when values are equal, lower coordinate wins. }
1172 if V.Y > V[Result] then Result := 1;
1173 if V.Z > V[Result] then Result := 2;
1174 end;
1175
1176 function MinVectorCoord(const V: TVector3): T3DAxis;
1177 begin
1178 Result := 0;
1179 if V.Y < V[Result] then Result := 1;
1180 if V.Z < V[Result] then Result := 2;
1181 end;
1182
1183 function MaxVectorCoord(const V: TVector4): Integer;
1184 begin
1185 Result := 0;
1186 if V.Y > V[Result] then Result := 1;
1187 if V.Z > V[Result] then Result := 2;
1188 if V.W > V[Result] then Result := 3;
1189 end;
1190
1191 function MaxAbsVectorCoord(const V: TVector2): Integer;
1192 begin
1193 Result := 0;
1194 if Abs(V.Y) > Abs(V[Result]) then Result := 1;
1195 end;
1196
1197 function MaxAbsVectorCoord(const V: TVector3): T3DAxis;
1198 var
1199 Max, New: Single;
1200 begin
1201 Result := 0;
1202 Max := Abs(V.X);
1203 New := Abs(V.Y); if New > Max then begin Result := 1; Max := New; end;
1204 New := Abs(V.Z); if New > Max then begin Result := 2; { Max := New; not needed anymore } end;
1205 end;
1206
1207 function MaxAbsVectorCoord(const V: TVector4): Integer;
1208 var
1209 Max, New: Single;
1210 begin
1211 Result := 0;
1212 Max := Abs(V.X);
1213 New := Abs(V.Y); if New > Max then begin Result := 1; Max := New; end;
1214 New := Abs(V.Z); if New > Max then begin Result := 2; Max := New; end;
1215 New := Abs(V.W); if New > Max then begin Result := 3; { Max := New; not needed anymore } end;
1216 end;
1217
1218 function MinAbsVectorCoord(const V: TVector2): Integer;
1219 begin
1220 Result := 0;
1221 if Abs(V.Y) < Abs(V[Result]) then Result := 1;
1222 end;
1223
1224 function MinAbsVectorCoord(const V: TVector3): T3DAxis;
1225 var
1226 Min, New: Single;
1227 begin
1228 Result := 0;
1229 Min := Abs(V.X);
1230 New := Abs(V.Y); if New < Min then begin Result := 1; Min := New; end;
1231 New := Abs(V.Z); if New < Min then begin Result := 2; { Min := New; not needed anymore } end;
1232 end;
1233
1234 function MinAbsVectorCoord(const V: TVector4): Integer;
1235 var
1236 Min, New: Single;
1237 begin
1238 Result := 0;
1239 Min := Abs(V.X);
1240 New := Abs(V.Y); if New < Min then begin Result := 1; Min := New; end;
1241 New := Abs(V.Z); if New < Min then begin Result := 2; Min := New; end;
1242 New := Abs(V.W); if New < Min then begin Result := 3; { Min := New; not needed anymore } end;
1243 end;
1244
1245 procedure SortAbsVectorCoord(const V: TVector3;
1246 out Max, Middle, Min: T3DAxis);
1247 begin
1248 Max := MaxAbsVectorCoord(V);
1249 case Max of
1250 0: if Abs(V.Y) >= Abs(V.Z) then begin Middle := 1; Min := 2; end else begin Middle := 2; Min := 1; end;
1251 1: if Abs(V.X) >= Abs(V.Z) then begin Middle := 0; Min := 2; end else begin Middle := 2; Min := 0; end;
1252 else {2: }
1253 if Abs(V.X) >= Abs(V.Y) then begin Middle := 0; Min := 1; end else begin Middle := 1; Min := 0; end;
1254 end;
1255 end;
1256
1257 function PlaneDirInDirection(const Plane: TVector4; const Direction: TVector3): TVector3;
1258 var
1259 PlaneDir: TVector3 absolute Plane;
1260 begin
1261 Result := PlaneDirInDirection(PlaneDir, Direction);
1262 end;
1263
1264 function PlaneDirInDirection(const PlaneDir, Direction: TVector3): TVector3;
1265 begin
1266 (* "Normalny" sposob aby sprawdzic czy dwa wektory wskazuja z tej samej
1267 plaszczyzny to porownac
1268 TVector3.DotProduct(V1, PlaneDir) > 0
1269 TVector3.DotProduct(V2, PlaneDir) > 0
1270 czyli tak jakby obciac czwarta wspolrzedna plaszczyzny (zeby plaszczyzna
1271 przechodzila przez (0, 0,0)) i sprawdzic czy dwa punkty leza po tej samej
1272 stronie plaszczyzny
1273
1274 (jezeli jeden z wektorow V1 lub V2 jest rownolegly do plaszczyzny,
1275 tzn. TVector3.DotProduct(V*, PlaneDir) = 0 to przyjmujemy ze drugi
1276 moze byc w dowolna strone, wiec nawet sie
1277 nie przejmujemy co bedzie gdy zajdzie rownosc w ktorejs z powyzszych
1278 nierownosci).
1279
1280 Ale mozna to uproscic gdy V1 = PlaneDir. Wiemy ze
1281 TVector3.DotProduct(PlaneDir, PlaneDir) > 0
1282 bo to przeciez suma trzech kwadratow. Wiec wystarczy sprawdzic czy
1283 TVector3.DotProduct(Direction, PlaneDir) > 0
1284 - jesli nie to trzeba odwrocic Normal. *)
1285 if TVector3.DotProduct(Direction, PlaneDir) < 0 then
1286 Result := -PlaneDir
1287 else
1288 Result := PlaneDir;
1289 end;
1290
1291 function PlaneDirNotInDirection(const Plane: TVector4; const Direction: TVector3): TVector3;
1292 var
1293 PlaneDir: TVector3 absolute Plane;
1294 begin
1295 Result := PlaneDirNotInDirection(PlaneDir, Direction);
1296 end;
1297
1298 procedure TwoPlanesIntersectionLine(const Plane0, Plane1: TVector4;
1299 out Line0, LineVector: TVector3);
1300 var
1301 Plane0Dir: TVector3 absolute Plane0;
1302 Plane1Dir: TVector3 absolute Plane1;
1303 NonZeroIndex, Index1, Index2: T3DAxis;
1304 PlaneWithNonZeroIndex1: PVector4;
1305 PlaneMultiply, Sum_Index2, Sum_3: Single;
1306 begin
1307 LineVector := TVector3.CrossProduct(Plane0Dir, Plane1Dir);
1308
1309 NonZeroIndex := MaxAbsVectorCoord(LineVector);
1310 if IsZero(LineVector[NonZeroIndex]) then
1311 raise EPlanesParallel.Create(
1312 'Unable to calculate intersection line of two planes ' +
1313 Plane0.ToRawString + ' and ' + Plane1.ToRawString + ' because ' +
1314 'planes are parallel');
1315
1316 { Since LineVector[NonZeroIndex] <> 0, we know that we can find exactly
1317 one point on this line by assuming that Point[NonZeroIndex] = 0. }
1318 Line0.Data[NonZeroIndex] := 0;
1319 RestOf3DCoords(NonZeroIndex, Index1, Index2);
1320
1321 { Now we must solve
1322 Plane0[Index1] * Line0[Index1] + Plane0[Index2] * Line0[Index2] + Plane0.W = 0
1323 Plane1[Index1] * Line0[Index1] + Plane1[Index2] * Line0[Index2] + Plane1.W = 0
1324 We want to sum these two equations to eliminate Line0[Index1]:
1325 + Sum_Index2 * Line0[Index2] + Sum_3 = 0
1326 }
1327 if not IsZero(Plane0[Index1]) then
1328 begin
1329 PlaneWithNonZeroIndex1 := @Plane0;
1330 PlaneMultiply := - Plane1[Index1] / Plane0[Index1];
1331 Sum_Index2 := Plane0[Index2] * PlaneMultiply + Plane1[Index2];
1332 Sum_3 := Plane0.W * PlaneMultiply + Plane1.W;
1333 end else
1334 if not IsZero(Plane1[Index1]) then
1335 begin
1336 PlaneWithNonZeroIndex1 := @Plane1;
1337 PlaneMultiply := - Plane0[Index1] / Plane1[Index1];
1338 Sum_Index2 := Plane0[Index2] + Plane1[Index2] * PlaneMultiply;
1339 Sum_3 := Plane0.W + Plane1.W * PlaneMultiply;
1340 end else
1341 begin
1342 { If Plane0[Index1] = Plane1[Index1] = 0, this is simple.
1343 Sum_Index2 := Plane0[Index2] + Plane1[Index2];
1344 Sum_3 := Plane0.W + Plane1.W ;
1345 PlaneWithNonZeroIndex1 := ???;
1346 But it's useless, because then I will not be able to calculate
1347 Line0[Index1] (after obtaining Line0[Index2]).
1348 TODO -- some proof that this cannot happen for correct input ? }
1349 raise Exception.Create('Cannot calculate intersection line of two planes');
1350 end;
1351
1352 { Now we know that
1353 Sum_Index2 * Line0[Index2] + Sum_3 = 0
1354 Sum_Index2 must be <> 0, since we know that Line0[Index2] must be uniquely
1355 determined ? Right ? TODO -- I'm not sure, how to prove this simply ?
1356 }
1357 Line0.Data[Index2] := - Sum_3 / Sum_Index2;
1358
1359 { Note we have
1360 PlaneWithNonZeroIndex1^[Index1] * Line0[Index1] +
1361 PlaneWithNonZeroIndex1^[Index2] * Line0[Index2] +
1362 PlaneWithNonZeroIndex1^.W = 0
1363 All is known except Line0[Index1],
1364 PlaneWithNonZeroIndex1^[Index1] is for sure <> 0. }
1365 Line0.Data[Index1] := -
1366 (PlaneWithNonZeroIndex1^[Index2] * Line0[Index2] +
1367 PlaneWithNonZeroIndex1^.W) /
1368 PlaneWithNonZeroIndex1^[Index1];
1369 end;
1370
1371 function Lines2DIntersection(const Line0, Line1: TVector3): TVector2;
1372 var
1373 Ratio, Divide: Single;
1374 begin
1375 { Only one from Line0.X, Line0.Y may be zero.
1376 Take larger one for numerical stability. }
1377 if Abs(Line0.X) > Abs(Line0.Y) then
1378 begin
1379 Ratio := Line1.X / Line0.X;
1380
1381 { we have equations
1382 Line0.X * x + Line0.Y * y + Line0.Z = 0
1383 Line1.X * x + Line1.Y * y + Line1.Z = 0
1384 Multiply first equation by Ratio and subtract to 2nd one:
1385 y * (Line0.Y * Ratio - Line1.Y) + Line0.Z * Ratio - Line1.Z = 0 }
1386 Divide := Line0.Y * Ratio - Line1.Y;
1387 if Divide = 0 then
1388 raise ELinesParallel.Create('Lines are parallel, Lines2DIntersection not possible');
1389 Result.Y := - (Line0.Z * Ratio - Line1.Z) / Divide;
1390 Result.X := - (Line0.Y * Result.Y + Line0.Z) / Line0.X;
1391 end else
1392 begin
1393 Ratio := Line1.Y / Line0.Y;
1394
1395 { we have equations
1396 Line0.X * x + Line0.Y * y + Line0.Z = 0
1397 Line1.X * x + Line1.Y * y + Line1.Z = 0
1398 Multiply first equation by Ratio and subtract to 2nd one:
1399 x * (Line0.X * Ratio - Line1.X) + Line0.Z * Ratio - Line1.Z = 0 }
1400 Divide := Line0.X * Ratio - Line1.X;
1401 if Divide = 0 then
1402 raise ELinesParallel.Create('Lines are parallel, Lines2DIntersection not possible');
1403 Result.X := - (Line0.Z * Ratio - Line1.Z) / Divide;
1404 Result.Y := - (Line0.X * Result.X + Line0.Z) / Line0.Y;
1405 end;
1406
1407 { tests: (checking should write zeros)
1408 Writeln('intersection 2d: ', Line0.ToString, ' ',
1409 Line1.ToString, ' gives ', Result.ToString, ' checking: ',
1410 FloatToNiceStr(Line0.X * Result.X + Line0.Y * Result.Y + Line0.Z), ' ',
1411 FloatToNiceStr(Line1.X * Result.X + Line1.Y * Result.Y + Line1.Z)); }
1412 end;
1413
1414 function ThreePlanesIntersectionPoint(
1415 const Plane0, Plane1, Plane2: TVector4): TVector3;
1416 var
1417 Line0, LineVector: TVector3;
1418 begin
1419 TwoPlanesIntersectionLine(Plane0, Plane1, Line0, LineVector);
1420 if not TryPlaneLineIntersection(Result, Plane2, Line0, LineVector) then
1421 raise Exception.Create('Cannot calculate intersection point of three planes :' +
1422 'intersection line of first two planes is parallel to the 3rd plane');
1423 end;
1424
1425 function PlaneMove(const Plane: TVector4;
1426 const Move: TVector3): TVector4;
1427 begin
1428 { Given a plane Ax + By + Cz + D = 0.
1429 We want to find a new plane, moved by Move.
1430 Actually, we want to find only new D, since we know that (A, B, C)
1431 is a normal vector of the plane, so it doesn't change.
1432
1433 Math says: old plane equation is OK for point (x, y, z) if and only if
1434 new plane equation is OK for (x, y, z) + Move. Therefore
1435 Ax + By + Cz + D = 0 iff
1436 A * (x + Move.X) + B * (y + Move.Y) + C * (z + Move.Z) + NewD = 0
1437 The 2nd equation can be rewritten as
1438 Ax + By + Cz + NewD + A * Move.X + B * Move.Y + C * Move.Z = 0
1439 so
1440 NewD = D - (A * Move.X + B * Move.Y + C * Move.Z);
1441 }
1442
1443 Result := Plane;
1444 Result.W := Result.W - (
1445 Plane.X * Move.X +
1446 Plane.Y * Move.Y +
1447 Plane.Z * Move.Z);
1448 end;
1449
1450 procedure PlaneMoveVar(var Plane: TVector4; const Move: TVector3);
1451 begin
1452 Plane.W := Plane.W - (
1453 Plane.X * Move.X +
1454 Plane.Y * Move.Y +
1455 Plane.Z * Move.Z);
1456 end;
1457
1458 function PlaneAntiMove(const Plane: TVector4;
1459 const Move: TVector3): TVector4;
1460 begin
1461 { Like PlaneMove, but Move vector is negated.
1462 So we just do "Result.W +=" instead of "Result.W -=". }
1463
1464 Result := Plane;
1465 Result.W := Result.W + (
1466 { Use parenthesis to group this expression, this way it's calculated
1467 in a similar order to PlaneMove, which increses it's numerical
1468 stability. Confirmed by TTestCastleVectors.TestPlaneMoveRandom,
1469 if you have these parenthesis you can have smaller epsilon to compare). }
1470 Plane.X * Move.X +
1471 Plane.Y * Move.Y +
1472 Plane.Z * Move.Z);
1473 end;
1474
1475 function VectorsSamePlaneDirections(const V1, V2: TVector3;
1476 const Plane: TVector4): boolean;
1477 var
1478 PlaneDir: TVector3 absolute Plane;
1479 V1Dot, V2Dot: Single;
1480 begin
1481 V1Dot := TVector3.DotProduct(V1, PlaneDir);
1482 V2Dot := TVector3.DotProduct(V2, PlaneDir);
1483 Result := IsZero(V1Dot) or IsZero(V2Dot) or ((V1Dot > 0) = (V2Dot > 0));
1484 end;
1485
1486 function VectorsSamePlaneDirections(const V1, V2: TVector3;
1487 const PlaneDir: TVector3): boolean;
1488 var
1489 V1Dot, V2Dot: Single;
1490 begin
1491 V1Dot := TVector3.DotProduct(V1, PlaneDir);
1492 V2Dot := TVector3.DotProduct(V2, PlaneDir);
1493 Result := IsZero(V1Dot) or IsZero(V2Dot) or ((V1Dot > 0) = (V2Dot > 0));
1494 end;
1495
1496 function PointsSamePlaneSides(const p1, p2: TVector3; const Plane: TVector4): boolean;
1497 var
1498 p1Side, p2Side: Single;
1499 begin
1500 p1Side := p1.X*Plane.X + p1.Y*Plane.Y + p1.Z*Plane.Z + Plane.W;
1501 p2Side := p2.X*Plane.X + p2.Y*Plane.Y + p2.Z*Plane.Z + Plane.W;
1502 Result := IsZero(p1Side) or IsZero(p2Side) or ((p1Side > 0) = (p2Side > 0));
1503 end;
1504
1505 function PlaneDirNotInDirection(const PlaneDir, Direction: TVector3): TVector3;
1506 begin
1507 if TVector3.DotProduct(Direction, PlaneDir) > 0 then
1508 Result := -PlaneDir
1509 else
1510 Result := PlaneDir;
1511 end;
1512
1513 function PointsDistance(const V1, V2: TVector2): Single;
1514 begin
1515 { Result := Sqrt(PointsDistanceSqr(V1, V2));, expanded for speed }
1516 Result := Sqrt( Sqr(V2.X-V1.X) + Sqr(V2.Y-V1.Y) );
1517 end;
1518
1519 function PointsDistance(const V1, V2: TVector3): Single;
1520 begin
1521 { Result := Sqrt(PointsDistanceSqr(V1, V2));, expanded for speed }
1522 Result := Sqrt( Sqr(V2.X-V1.X) + Sqr(V2.Y-V1.Y) + Sqr(V2.Z-V1.Z) );
1523 end;
1524
1525 function PointsDistanceSqr(const V1, V2: TVector3): Single;
1526 begin
1527 { Result := (v2 - v1).LengthSqr;, expanded for speed }
1528 Result := Sqr(V2.X-V1.X) + Sqr(V2.Y-V1.Y) + Sqr(V2.Z-V1.Z);
1529 end;
1530
1531 function PointsDistanceSqr(const V1, V2: TVector2): Single;
1532 begin
1533 { Result := (v2 - v1).LengthSqr;, expanded for speed }
1534 Result := Sqr(V2.X-V1.X) + Sqr(V2.Y-V1.Y);
1535 end;
1536
1537 function PointsDistance2DSqr(const V1, V2: TVector3; const IgnoreIndex: Integer): Single;
1538 begin
1539 {$IFNDEF FPC}
1540 Result := 0; // Make the Delphi Compiler Happy
1541 {$ENDIF}
1542 case IgnoreIndex of
1543 0: Result := Sqr(V2.Y - V1.Y) + Sqr(V2.Z - V1.Z);
1544 1: Result := Sqr(V2.Z - V1.Z) + Sqr(V2.X - V1.X);
1545 2: Result := Sqr(V2.X - V1.X) + Sqr(V2.Y - V1.Y);
1546 else PointsDistance2DSqr_InvalidIgnoreIndex;
1547 end;
1548 end;
1549
1550 function VectorsPerp(const V1, V2: TVector3): boolean;
1551 begin
1552 (* Naive implementation:
1553
1554 Result := CosAngleBetweenVectors(V1, V2) = 0;
1555
1556 But if you look how CosAngleBetweenVectors is calculated,
1557 it can be optimized. *)
1558 Result := IsZero(TVector3.DotProduct(V1, V2));
1559 end;
1560
1561 function VectorsParallel(const V1, V2: TVector3): boolean;
1562 var
1563 mc, c1, c2: T3DAxis;
1564 Scale: Single;
1565 begin
1566 mc := MaxAbsVectorCoord(v1);
1567 if IsZero(V1[mc]) then Exit(true);
1568
1569 Scale := V2[mc] / V1[mc];
1570 RestOf3DCoords(mc, c1, c2);
1571 Result := SameValue(V1[c1] * Scale, V2[c1]) and
1572 SameValue(V1[c2] * Scale, V2[c2]);
1573 end;
1574
1575 procedure MakeVectorsAngleRadOnTheirPlane(var v1: TVector3;
1576 const v2: TVector3; const AngleRad: Single; const ResultWhenParallel: TVector3);
1577 var
1578 rotAxis: TVector3;
1579 v1len: Single;
1580 begin
1581 v1len := v1.Length;
1582 rotAxis := TVector3.CrossProduct(V1, V2);
1583 if rotAxis.IsZero then
1584 V1 := ResultWhenParallel
1585 else
1586 V1 := RotatePointAroundAxisRad(-AngleRad, v2, rotAxis).AdjustToLength(v1len);
1587 end;
1588
1589 procedure MakeVectorsAngle90OnTheirPlane(var v1: TVector3;
1590 const v2: TVector3; const ResultWhenParallel: TVector3);
1591 var
1592 rotAxis: TVector3;
1593 v1len: Single;
1594 begin
1595 v1len := v1.Length;
1596 rotAxis := TVector3.CrossProduct(V1, V2);
1597 if rotAxis.IsZero then
1598 V1 := ResultWhenParallel
1599 else
1600 V1 := RotatePointAroundAxisMinus90(v2, rotAxis).AdjustToLength(v1len);
1601 end;
1602
1603 procedure MakeVectorsOrthoOnTheirPlane(var v1: TVector3; const v2: TVector3);
1604 begin
1605 MakeVectorsAngle90OnTheirPlane(V1, V2, AnyOrthogonalVector(V2));
1606 // MakeVectorsAngleRadOnTheirPlane(V1, V2, Pi / 2, AnyOrthogonalVector(V2));
1607 end;
1608
1609 function MakeVectorOrthogonal(const V1, V2: TVector3): TVector3;
1610 begin
1611 Result := V1;
1612 MakeVectorsOrthoOnTheirPlane(Result, V2);
1613 end;
1614
1615 function AnyOrthogonalVector(const V: TVector3): TVector3;
1616 begin
1617 { This uses a simple trick to make an orthogonal vector:
1618 if you take @code(Result := (V.Y, -V.X, 0)) then the dot product
1619 between the Result and V is zero, so they are orthogonal.
1620 There's also a small check needed to use a similar but different version
1621 when the only non-zero component of V is V.Z. }
1622
1623 if IsZero(V.X) and IsZero(V.Y) then
1624 begin
1625 Result.X := 0;
1626 Result.Y := V.Z;
1627 Result.Z := -V.Y;
1628 end else
1629 begin
1630 Result.X := V.Y;
1631 Result.Y := -V.X;
1632 Result.Z := 0;
1633 end;
1634 end;
1635
1636 function AnyOrthogonalVector(const V: TVector2): TVector2;
1637 begin
1638 Result.X := V.Y;
1639 Result.Y := -V.X;
1640 end;
1641
1642 function IsLineParallelToPlane(const lineVector: TVector3; const plane: TVector4): boolean;
1643 var
1644 PlaneDir: TVector3 absolute plane;
1645 begin
1646 Result := VectorsPerp(lineVector, PlaneDir);
1647 end;
1648
1649 function IsLineParallelToSimplePlane(const lineVector: TVector3;
1650 const PlaneConstCoord: T3DAxis): boolean;
1651 begin
1652 Result := IsZero(lineVector[PlaneConstCoord]);
1653 end;
1654
1655 function AreParallelVectorsSameDirection(
1656 const Vector1, Vector2: TVector3): boolean;
1657 var
1658 Coord: Integer;
1659 begin
1660 { Assuming that Vector1 is non-zero, MaxAbsVectorCoord(Vector1)
1661 must be non-zero. }
1662 Coord := MaxAbsVectorCoord(Vector1);
1663
1664 Result := (Vector1[Coord] > 0) = (Vector2[Coord] > 0);
1665 end;
1666
1667 function PointOnPlaneClosestToPoint(const Plane: TVector4; const Point: TVector3): TVector3;
1668 var
1669 D: Single;
1670 PlaneDir: TVector3 absolute Plane;
1671 begin
1672 { We know that
1673
1674 Result = Point + D * PlaneDir
1675 dot(PlaneDir, Result) + Plane.W = 0
1676
1677 So
1678
1679 dot(PlaneDir, Point + D * PlaneDir) + Plane.W = 0
1680
1681 We can expand the dot definition for 3D now, and get an equation
1682 to calculate D.
1683 }
1684
1685 D := -(
1686 Plane.X * Point.X +
1687 Plane.Y * Point.Y +
1688 Plane.Z * Point.Z +
1689 Plane.W ) /
1690 PlaneDir.LengthSqr;
1691 Result := Point + PlaneDir * D;
1692 end;
1693
1694 function PointToPlaneDistanceSqr(const Point: TVector3;
1695 const Plane: TVector4): Single;
1696 begin
1697 Result :=
1698 Sqr(Plane.X * Point.X +
1699 Plane.Y * Point.Y +
1700 Plane.Z * Point.Z +
1701 Plane.W) /
1702 (Sqr(Plane.X) + Sqr(Plane.Y) + Sqr(Plane.Z));
1703 end;
1704
1705 function PointToNormalizedPlaneDistance(const Point: TVector3;
1706 const Plane: TVector4): Single;
1707 begin
1708 Result :=
1709 Abs(Plane.X * Point.X +
1710 Plane.Y * Point.Y +
1711 Plane.Z * Point.Z +
1712 Plane.W);
1713 end;
1714
1715 function PointToPlaneDistance(const Point: TVector3;
1716 const Plane: TVector4): Single;
1717 begin
1718 Result :=
1719 Abs(Plane.X * Point.X +
1720 Plane.Y * Point.Y +
1721 Plane.Z * Point.Z +
1722 Plane.W) /
1723 Sqrt(Sqr(Plane.X) + Sqr(Plane.Y) + Sqr(Plane.Z));
1724 end;
1725
1726 function PointToSimplePlaneDistance(const point: TVector3;
1727 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single): Single;
1728 begin
1729 Result := Abs(point[PlaneConstCoord]-PlaneConstValue);
1730 end;
1731
1732 function PointOnLineClosestToPoint(
1733 const line0, lineVector, point: TVector3): TVector3;
1734 var
1735 d: Single;
1736 begin
1737 (*
1738 We know that (Result-Point) and LineVector (or Result - Line0) are orthogonal.
1739
1740 (Result[0]-point[0])*(lineVector[0]) +
1741 (Result[1]-point[1])*(lineVector[1]) +
1742 (Result[2]-point[2])*(lineVector[2]) = 0 czyli
1743 Result[0]*lineVector[0] +
1744 Result[1]*lineVector[1] +
1745 Result[2]*lineVector[2] = point[0]*lineVector[0] +
1746 point[1]*lineVector[1] +
1747 point[2]*lineVector[2]
1748
1749 We know Result can be expresssed as
1750
1751 Result = line0 + lineVector * d
1752
1753 So
1754
1755 Result[0] = line0[0] + lineVector[0]*d
1756 Result[1] = line0[1] + lineVector[1]*d
1757 Result[2] = line0[2] + lineVector[2]*d
1758
1759 So 4 equations, 4 unknowns, solving:
1760
1761 (line0[0] + lineVector[0]*d)*lineVector[0]+
1762 (line0[1] + lineVector[1]*d)*lineVector[1]+
1763 (line0[2] + lineVector[2]*d)*lineVector[2] = point[0]*lineVector[0] +
1764 point[1]*lineVector[1] +
1765 point[2]*lineVector[2]
1766 d*(Sqr(lineVector[0])+ Sqr(lineVector[1])+ Sqr(lineVector[2]) ) =
1767 d*lineVector.LengthSqr =
1768 lineVector[0]*(point[0]-line0[0]) +
1769 lineVector[1]*(point[1]-line0[1]) +
1770 lineVector[2]*(point[2]-line0[2]);
1771
1772 And we can calculate d now. *)
1773 d := (lineVector.X * (point.X-line0.X) +
1774 lineVector.Y * (point.Y-line0.Y) +
1775 lineVector.Z * (point.Z-line0.Z) ) / lineVector.LengthSqr;
1776 Result := line0 + lineVector * d;
1777 end;
1778
1779 function PointOnLineClosestToPoint(
1780 const line0, lineVector, point: TVector2): TVector2;
1781 var
1782 d: Single;
1783 begin
1784 d := (lineVector.X * (point.X-line0.X) +
1785 lineVector.Y * (point.Y-line0.Y) ) / lineVector.LengthSqr;
1786 Result := line0 + lineVector * d;
1787 end;
1788
1789 function PointToLineDistanceSqr(const point, line0, lineVector: TVector3): Single;
1790 begin
1791 Result := PointsDistanceSqr(point, PointOnLineClosestToPoint(line0, lineVector, point));
1792 end;
1793
1794 function TryPlaneLineIntersection(out t: Single;
1795 const plane: TVector4; const line0, lineVector: TVector3): boolean;
1796 var
1797 PlaneDir: TVector3 absolute plane;
1798 Dot: Single;
1799 begin
1800 Dot := TVector3.DotProduct(LineVector, PlaneDir);
1801 if not IsZero(Dot) then
1802 begin
1803 Result := true;
1804 t := -(plane.X*line0.X + plane.Y*line0.Y + plane.Z*line0.Z + plane.W)/Dot;
1805 end else
1806 Result := false;
1807 end;
1808
1809 function TryPlaneLineIntersection(out intersection: TVector3;
1810 const plane: TVector4; const line0, lineVector: TVector3): boolean;
1811 var
1812 t: Single;
1813 begin
1814 Result := TryPlaneLineIntersection(t, Plane, Line0, LineVector);
1815 if Result then Intersection := Line0 + LineVector * t;
1816 end;
1817
1818 function TryPlaneRayIntersection(out Intersection: TVector3;
1819 const Plane: TVector4; const RayOrigin, RayDirection: TVector3): boolean;
1820 var
1821 MaybeT: Single;
1822 begin
1823 Result := TryPlaneLineIntersection(MaybeT, Plane, RayOrigin, RayDirection) and (MaybeT >= 0);
1824 if Result then Intersection := RayOrigin + RayDirection * MaybeT;
1825 end;
1826
1827 function TryPlaneRayIntersection(
1828 out Intersection: TVector3; out T: Single;
1829 const Plane: TVector4; const RayOrigin, RayDirection: TVector3): boolean;
1830 var
1831 MaybeT: Single;
1832 begin
1833 Result := TryPlaneLineIntersection(MaybeT, Plane, RayOrigin, RayDirection) and (MaybeT >= 0);
1834 if Result then
1835 begin
1836 // Intersection := RayOrigin + RayDirection * MaybeT;
1837 // powyzsza instrukcja zapisana ponizej w 3 linijkach dziala nieco szybciej:
1838 Intersection := RayDirection;
1839 Intersection := Intersection * MaybeT;
1840 Intersection := Intersection + RayOrigin;
1841
1842 t := MaybeT;
1843 end;
1844 end;
1845
1846 function TryPlaneSegmentDirIntersection(out Intersection: TVector3;
1847 const Plane: TVector4; const Segment0, SegmentVector: TVector3): boolean;
1848 var
1849 MaybeT: Single;
1850 begin
1851 Result := TryPlaneLineIntersection(MaybeT, Plane, Segment0, SegmentVector) and
1852 (MaybeT >= 0) and (MaybeT <= 1);
1853 if Result then Intersection := Segment0 + SegmentVector * MaybeT;
1854 end;
1855
1856 function TryPlaneSegmentDirIntersection(
1857 out Intersection: TVector3; out T: Single;
1858 const Plane: TVector4; const Segment0, SegmentVector: TVector3): boolean;
1859 var
1860 MaybeT: Single;
1861 begin
1862 Result := TryPlaneLineIntersection(MaybeT, Plane, Segment0, SegmentVector) and
1863 (MaybeT >= 0) and (MaybeT <= 1);
1864 if Result then
1865 begin
1866 // Intersection := Segment0 + SegmentVector * MaybeT;
1867 // powyzsza instrukcja zapisana ponizej w 3 linijkach dziala nieco szybciej:
1868 Intersection := SegmentVector;
1869 Intersection := Intersection * MaybeT;
1870 Intersection := Intersection + Segment0;
1871
1872 t := MaybeT;
1873 end;
1874 end;
1875
1876 { TrySimplePlaneRayIntersection ---------------------------------------------- }
1877
1878 function TrySimplePlaneRayIntersection(out Intersection: TVector3;
1879 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1880 const RayOrigin, RayDirection: TVector3): boolean;
1881 var
1882 T: Single;
1883 begin
1884 Result := TrySimplePlaneRayIntersection(T, PlaneConstCoord, PlaneConstValue, RayOrigin, RayDirection);
1885 if Result then
1886 Intersection := RayOrigin + RayDirection * T;
1887 end;
1888
1889 function TrySimplePlaneRayIntersection(
1890 out Intersection: TVector3; out T: Single;
1891 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1892 const RayOrigin, RayDirection: TVector3): boolean;
1893 begin
1894 Result := TrySimplePlaneRayIntersection(T, PlaneConstCoord, PlaneConstValue, RayOrigin, RayDirection);
1895 if Result then
1896 Intersection := RayOrigin + RayDirection * T;
1897 end;
1898
1899 function TrySimplePlaneRayIntersection(out T: Single;
1900 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1901 const RayOrigin, RayDirection: TVector3): boolean;
1902 begin
1903 Result := not IsLineParallelToSimplePlane(RayDirection, PlaneConstCoord);
1904 if Result then
1905 begin
1906 T := (PlaneConstValue-RayOrigin[PlaneConstCoord]) / RayDirection[PlaneConstCoord];
1907 Result := T >= 0;
1908 end;
1909 end;
1910
1911 { TrySimplePlaneSegmentIntersection ------------------------------------------ }
1912
1913 function TrySimplePlaneSegmentIntersection(out Intersection: TVector3;
1914 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1915 const Pos1, Pos2: TVector3): boolean;
1916 var
1917 T: Single;
1918 begin
1919 Result := TrySimplePlaneSegmentIntersection(T, PlaneConstCoord, PlaneConstValue, Pos1, Pos2);
1920 if Result then
1921 Intersection := Pos1 + (Pos2 - Pos1) * T;
1922 end;
1923
1924 function TrySimplePlaneSegmentIntersection(
1925 out Intersection: TVector3; out T: Single;
1926 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1927 const Pos1, Pos2: TVector3): boolean;
1928 begin
1929 Result := TrySimplePlaneSegmentIntersection(T, PlaneConstCoord, PlaneConstValue, Pos1, Pos2);
1930 if Result then
1931 Intersection := Pos1 + (Pos2 - Pos1) * T;
1932 end;
1933
1934 function TrySimplePlaneSegmentIntersection(out T: Single;
1935 const PlaneConstCoord: T3DAxis; const PlaneConstValue: Single;
1936 const Pos1, Pos2: TVector3): boolean;
1937 var
1938 SegmentVector: TVector3;
1939 begin
1940 SegmentVector := Pos2 - Pos1;
1941
1942 Result := not IsLineParallelToSimplePlane(SegmentVector, PlaneConstCoord);
1943 if Result then
1944 begin
1945 T := (PlaneConstValue-Pos1[PlaneConstCoord]) / SegmentVector[PlaneConstCoord];
1946 Result := (T >= 0) and (T <= 1);
1947 end;
1948 end;
1949
1950 { others --------------------------------------------------------------------- }
1951
1952 function IsPointOnSegmentLineWithinSegment(const intersection, pos1, pos2: TVector3): boolean;
1953 var
1954 c: T3DAxis;
1955 begin
1956 { project points on the best axis-aligned plane }
1957 c := MaxAbsVectorCoord(Pos1 - Pos2);
1958 Result := ((pos1[c] <= intersection[c]) and (intersection[c] <= pos2[c])) or
1959 ((pos1[c] >= intersection[c]) and (intersection[c] >= pos2[c]));
1960 end;
1961
1962 function IsPointOnSegmentLineWithinSegment(const intersection, pos1, pos2: TVector2): boolean;
1963 var
1964 c: T3DAxis;
1965 begin
1966 { project points on the best axis-aligned plane }
1967 c := MaxAbsVectorCoord(Pos1 - Pos2);
1968 Result := ((pos1[c] <= intersection[c]) and (intersection[c] <= pos2[c])) or
1969 ((pos1[c] >= intersection[c]) and (intersection[c] >= pos2[c]));
1970 end;
1971
1972 function Line2DFrom2Points(const P1, P2: TVector2): TVector3;
1973 begin
1974 Result := Line2DFromOriginVector(P1, P2 - P1);
1975 end;
1976
1977 function LineOfTwoDifferentPoints2D(const P1, P2: TVector2): TVector3;
1978 begin
1979 Result := Line2DFromOriginVector(P1, P2 - P1);
1980 end;
1981
1982 function Line2DFromOriginVector(const Line0, LineVector: TVector2): TVector3;
1983 var
1984 AxisGood, AxisOther: Integer;
1985 begin
1986 { Set AxisGood to LineVector coordinate that is definitely non-zero,
1987 let AxisOther be the other one. }
1988 AxisGood := MaxAbsVectorCoord(LineVector);
1989 AxisOther := 1 - AxisGood;
1990
1991 { We want to make Result.XY and LineVector orthogonal (this is how 2D line equation Ax+By+C works).
1992
1993 So their dot product = 0.
1994
1995 Let Result[AxisOther] = -1 and then we can construct
1996 Result[AxisGood] = LineVector[AxisOther] / LineVector[AxisGood].
1997 }
1998 Result.Data[AxisOther] := -1;
1999 Result.Data[AxisGood] := LineVector.Data[AxisOther] / LineVector[AxisGood];
2000 Result.Z := - (Result.X * Line0.X + Result.Y * Line0.Y);
2001 end;
2002
2003 function IsSpheresCollision(const Sphere1Center: TVector3; const Sphere1Radius: Single;
2004 const Sphere2Center: TVector3; const Sphere2Radius: Single): boolean;
2005 begin
2006 Result := PointsDistanceSqr(Sphere1Center, Sphere2Center)<=
2007 Sqr(Sphere1Radius+Sphere2Radius);
2008 end;
2009
2010 function PointToSegmentDistanceSqr(const point, pos1, pos2: TVector3): Single;
2011 var
2012 Closest: TVector3;
2013 begin
2014 Closest := PointOnLineClosestToPoint(pos1, pos2 - pos1, point);
2015 if IsPointOnSegmentLineWithinSegment(Closest, pos1, pos2) then
2016 Result := PointsDistanceSqr(Closest, point) else
2017 Result := Min(PointsDistanceSqr(pos1, point),
2018 PointsDistanceSqr(pos2, point));
2019 end;
2020
2021 function PlaneTransform(const Plane: TVector4; const Matrix: TMatrix4): TVector4;
2022 var
2023 MaxCoord: Integer;
2024 PlaneDir: TVector3 absolute Plane;
2025 NewPlaneDir: TVector3 absolute Result;
2026 PlanePoint, NewPlanePoint: TVector3;
2027 begin
2028 { calculate point that for sure lies on a plane.
2029 For this, we need a plane direction coordinate that isn't zero
2030 --- we know that such coordinate exists, since plane direction cannot be zero.
2031 For maximum numeric stability, choose largest coordinate. }
2032 MaxCoord := MaxAbsVectorCoord(PlaneDir);
2033 PlanePoint := TVector3.Zero;
2034 PlanePoint.Data[MaxCoord] := -Plane.W / Plane[MaxCoord];
2035
2036 NewPlanePoint := Matrix.MultPoint(PlanePoint);
2037 NewPlaneDir := Matrix.MultDirection(PlaneDir);
2038 Result.W := -TVector3.DotProduct(NewPlanePoint, NewPlaneDir);
2039 end;
2040
2041 function IsTunnelSphereCollision(const Tunnel1, Tunnel2: TVector3;
2042 const TunnelRadius: Single; const SphereCenter: TVector3;
2043 const SphereRadius: Single): boolean;
2044 begin
2045 Result := PointToSegmentDistanceSqr(SphereCenter, Tunnel1, Tunnel2)<=
2046 Sqr(SphereRadius+TunnelRadius);
2047 end;
2048
2049 function IsSegmentSphereCollision(const pos1, pos2, SphereCenter: TVector3;
2050 const SphereRadius: Single): boolean;
2051 var
2052 SphereRadiusSqr: Single;
2053 Intersect: TVector3;
2054 begin
2055 SphereRadiusSqr := Sqr(SphereRadius);
2056 Result:= (PointsDistanceSqr(pos1, SphereCenter) <= SphereRadiusSqr) or
2057 (PointsDistanceSqr(pos2, SphereCenter) <= SphereRadiusSqr);
2058 if not Result then
2059 begin
2060 Intersect := PointOnLineClosestToPoint(pos1, pos2 - pos1, SphereCenter);
2061 Result := IsPointOnSegmentLineWithinSegment(Intersect, pos1, pos2) and
2062 (PointsDistanceSqr(Intersect, SphereCenter) <= SphereRadiusSqr);
2063 end;
2064 end;
2065
2066 { Solve intersection routine with a ray that resolved into a quadratic
2067 equation. The solution is such T >= 0 that
2068 A * T^2 + B * T + C = 0 }
2069 function TryRayIntersectionQuadraticEquation(out T: Single;
2070 const A, B, C: Single): boolean;
2071 var
2072 Delta, T1, T2: Single;
2073 begin
2074 Delta := Sqr(B) - 4 * A * C;
2075
2076 if Delta < 0 then
2077 Result := false else
2078 if Delta = 0 then
2079 begin
2080 T := -B / (2 * A);
2081 Result := T >= 0;
2082 end else
2083 begin
2084 Delta := Sqrt(Delta);
2085
2086 { There are two solutions, choose closest to RayOrigin (smallest)
2087 but >= 0 (the one < 0 does not fall on ray). }
2088 T1 := (-B - Delta) / (2 * A);
2089 T2 := (-B + Delta) / (2 * A);
2090 OrderUp(T1, T2);
2091 if T1 >= 0 then
2092 begin
2093 T := T1;
2094 Result := true;
2095 end else
2096 if T2 >= 0 then
2097 begin
2098 T := T2;
2099 Result := true;
2100 end else
2101 Result := false;
2102 end;
2103 end;
2104
2105 function TrySphereRayIntersection(out Intersection: TVector3;
2106 const SphereCenter: TVector3; const SphereRadius: Single;
2107 const RayOrigin, RayDirection: TVector3): boolean;
2108 var
2109 T, A, B, C: Single;
2110 RayOriginMinusCenter: TVector3;
2111 begin
2112 { Intersection = RayOrigin + RayDirection * T,
2113 Also Distance(Intersection, SphereCenter) = SphereRadius,
2114 so Distance(RayOrigin + RayDirection * T, SphereCenter) = SphereRadius.
2115
2116 Expand this, and use to calculate T: we get a quadratic equation for T.
2117 A * T^2 + B * T + C = 0. }
2118 RayOriginMinusCenter := RayOrigin - SphereCenter;
2119 A := Sqr(RayDirection.X) +
2120 Sqr(RayDirection.Y) +
2121 Sqr(RayDirection.Z);
2122 B := 2 * RayDirection.X * RayOriginMinusCenter.X +
2123 2 * RayDirection.Y * RayOriginMinusCenter.Y +
2124 2 * RayDirection.Z * RayOriginMinusCenter.Z;
2125 C := Sqr(RayOriginMinusCenter.X) +
2126 Sqr(RayOriginMinusCenter.Y) +
2127 Sqr(RayOriginMinusCenter.Z) - Sqr(SphereRadius);
2128
2129 Result := TryRayIntersectionQuadraticEquation(T, A, B, C);
2130 if Result then
2131 Intersection := RayOrigin + RayDirection * T;
2132 end;
2133
2134 function TryCylinderRayIntersection(out Intersection: TVector3;
2135 const CylinderAxisOrigin, CylinderAxis: TVector3;
2136 const CylinderRadius: Single;
2137 const RayOrigin, RayDirection: TVector3): boolean;
2138 var
2139 T, AA, BB, CC: Single;
2140 X, Y, B: TVector3;
2141 begin
2142 { We know Intersection = RayOrigin + RayDirection * T.
2143 For cylinder, normalize CylinderAxis and then
2144
2145 TVector3.CrossProduct(Intersection - CylinderAxisOrigin, CylinderAxis).Length
2146 = CylinderRadius
2147
2148 (For why, see http://en.wikipedia.org/wiki/Cross_product:
2149 length of TVector3.CrossProduct is the area of parallelogram between it's vectors.
2150 This is equal to area of CylinderRadius * length CylinderAxis in this case.)
2151 Got the idea from oliii post on
2152 http://www.gamedev.net/community/forums/topic.asp?topic_id=467789
2153
2154 Insert ray equation into cylinder equation, and solve for T. }
2155
2156 X := RayOrigin - CylinderAxisOrigin;
2157 Y := RayDirection;
2158 B := CylinderAxis.Normalize;
2159
2160 { Now let A = X + Y * T, then A x B.Length^2 = CylinderRadius^2.
2161 Solve for T. Expanding this by hand would be *real* pain,
2162 so I used open-source maxima (http://maxima.sourceforge.net/):
2163
2164 display2d:false$
2165 a0: x0 + y0 * t;
2166 a1: x1 + y1 * t;
2167 a2: x2 + y2 * t;
2168 rsqr: (a0 * b1 - b0 * a1)^2 + (a1 * b2 - a2 * b1)^2 + (a2 * b0 + a0 * b2)^2;
2169 expand (rsqr);
2170
2171 At this point I just took the maxima output, and grouped by
2172 hand 30 sum items to get AA, BB, CC such that
2173 AA * T^2 + BB * T + CC = 0. (I could probably let maxima do this also,
2174 but was too lazy to read the docs :)
2175
2176 And CC gets additional "- CylinderRadius^2".
2177 }
2178
2179 AA := Sqr(B.Y)*Sqr(Y.Z) + Sqr(B.X)*Sqr(Y.Z) - 2*B.Y*B.Z*Y.Y*Y.Z
2180 + 2*B.X*B.Z*Y.X*Y.Z + Sqr(B.Z)*Sqr(Y.Y) + Sqr(B.X)*Sqr(Y.Y)
2181 - 2*B.X*B.Y*Y.X*Y.Y + Sqr(B.Z)*Sqr(Y.X) + Sqr(B.Y)*Sqr(Y.X);
2182
2183 BB := 2*Sqr(B.Y)*X.Z*Y.Z + 2*Sqr(B.X)*X.Z*Y.Z - 2*B.Y*B.Z*X.Y*Y.Z
2184 + 2*B.X*B.Z*X.X*Y.Z - 2*B.Y*B.Z*X.Z*Y.Y + 2*Sqr(B.Z)*X.Y*Y.Y
2185 + 2*Sqr(B.X)*X.Y*Y.Y - 2*B.X*B.Y*X.X*Y.Y + 2*B.X*B.Z*X.Z*Y.X
2186 - 2*B.X*B.Y*X.Y*Y.X + 2*Sqr(B.Z)*X.X*Y.X + 2*Sqr(B.Y)*X.X*Y.X;
2187
2188 CC := Sqr(B.Y)*Sqr(X.Z) + Sqr(B.X)*Sqr(X.Z) - 2*B.Y*B.Z*X.Y*X.Z
2189 + 2*B.X*B.Z*X.X*X.Z + Sqr(B.Z)*Sqr(X.Y) + Sqr(B.X)*Sqr(X.Y)
2190 - 2*B.X*B.Y*X.X*X.Y + Sqr(B.Z)*Sqr(X.X) + Sqr(B.Y)*Sqr(X.X)
2191 - Sqr(CylinderRadius);
2192
2193 Result := TryRayIntersectionQuadraticEquation(T, AA, BB, CC);
2194 if Result then
2195 Intersection := RayOrigin + RayDirection * T;
2196 end;
2197
2198 function PointOnLineClosestToLine(
2199 out Intersection: TVector3;
2200 const Line1Origin, Line1Vector, Line2Origin, Line2Vector: TVector3): Boolean;
2201 var
2202 Line0, LineVector, Ray0, RayVector: TVector3;
2203 N: TVector3;
2204 {Dist, }LineF: Single;
2205 Ax: Integer;
2206 ProjectAxisX, ProjectAxisY: TVector3;
2207 ProjectedIntersection, ProjectLine0, ProjectLineVector, ProjectRay0, ProjectRayVector: TVector2;
2208 begin
2209 Line0 := Line1Origin;
2210 LineVector := Line1Vector;
2211 Ray0 := Line2Origin;
2212 RayVector := Line2Vector;
2213
2214 { See calculate distance between 2 lines in 3D:
2215 https://math.stackexchange.com/questions/2213165/find-shortest-distance-between-lines-in-3d
2216 Observation: there must be N,
2217 orthogonal to LineVector and RayVector,
2218 that determines the vector between 2 closest points on 2 lines. }
2219 N := TVector3.CrossProduct(LineVector, RayVector);
2220 if N.IsZero then
2221 Exit(false); // ray parallel to axis, no sensible answer
2222
2223 // N := N.Normalize; // it is not necessary to normalize for anything below
2224
2225 // Dist := TVector3.DotProduct(N, Line0 - Ray0){ / N.Length}; // not needed in this approach
2226
2227 { Project our 2 lines on 2D }
2228 ProjectAxisX := AnyOrthogonalVector(N);
2229 ProjectAxisY := TVector3.CrossProduct(N, ProjectAxisX);
2230
2231 ProjectLine0 := Vector2(
2232 TVector3.DotProduct(ProjectAxisX, Line0),
2233 TVector3.DotProduct(ProjectAxisY, Line0)
2234 );
2235 ProjectLineVector := Vector2(
2236 TVector3.DotProduct(ProjectAxisX, LineVector),
2237 TVector3.DotProduct(ProjectAxisY, LineVector)
2238 );
2239 ProjectRay0 := Vector2(
2240 TVector3.DotProduct(ProjectAxisX, Ray0),
2241 TVector3.DotProduct(ProjectAxisY, Ray0)
2242 );
2243 ProjectRayVector := Vector2(
2244 TVector3.DotProduct(ProjectAxisX, RayVector),
2245 TVector3.DotProduct(ProjectAxisY, RayVector)
2246 );
2247
2248 ProjectedIntersection := Lines2DIntersection(
2249 Line2DFromOriginVector(ProjectLine0, ProjectLineVector),
2250 Line2DFromOriginVector(ProjectRay0, ProjectRayVector)
2251 );
2252
2253 Ax := MaxAbsVectorCoord(ProjectLineVector); // choose non-zero coordinate
2254 LineF := (ProjectedIntersection[Ax] - ProjectLine0[Ax]) / ProjectLineVector[Ax];
2255
2256 Result := true;
2257 Intersection := Line0 + LineF * LineVector;
2258 end;
2259
2260 { matrix transforms for 3D graphics ----------------------------------------- }
2261
2262 function TranslationMatrix(const Transl: TVector3): TMatrix4;
2263 begin
2264 Result := TMatrix4.Identity;
2265 Result.Data[3, 0] := Transl.X;
2266 Result.Data[3, 1] := Transl.Y;
2267 Result.Data[3, 2] := Transl.Z;
2268 end;
2269
2270 function TranslationMatrix(const X, Y, Z: Single): TMatrix4;
2271 begin
2272 Result := TMatrix4.Identity;
2273 Result.Data[3, 0] := X;
2274 Result.Data[3, 1] := Y;
2275 Result.Data[3, 2] := Z;
2276 end;
2277
2278 procedure TranslationMatrices(const X, Y, Z: Single;
2279 out Matrix, InvertedMatrix: TMatrix4);
2280 begin
2281 Matrix := TMatrix4.Identity;
2282 Matrix.Data[3, 0] := X;
2283 Matrix.Data[3, 1] := Y;
2284 Matrix.Data[3, 2] := Z;
2285
2286 InvertedMatrix := TMatrix4.Identity;
2287 InvertedMatrix.Data[3, 0] := -X;
2288 InvertedMatrix.Data[3, 1] := -Y;
2289 InvertedMatrix.Data[3, 2] := -Z;
2290 end;
2291
2292 procedure TranslationMatrices(const Transl: TVector3;
2293 out Matrix, InvertedMatrix: TMatrix4);
2294 begin
2295 Matrix := TMatrix4.Identity;
2296 Matrix.Data[3, 0] := Transl.X;
2297 Matrix.Data[3, 1] := Transl.Y;
2298 Matrix.Data[3, 2] := Transl.Z;
2299
2300 InvertedMatrix := TMatrix4.Identity;
2301 InvertedMatrix.Data[3, 0] := -Transl.X;
2302 InvertedMatrix.Data[3, 1] := -Transl.Y;
2303 InvertedMatrix.Data[3, 2] := -Transl.Z;
2304 end;
2305
2306 procedure MultMatrixTranslation(var M: TMatrix4;
2307 const Transl: TVector3);
2308 var
2309 NewColumn: TVector4;
2310 begin
2311 NewColumn := M.Columns[3];
2312 NewColumn.X := NewColumn.X + (M.Data[0, 0] * Transl.X + M.Data[1, 0] * Transl.Y + M.Data[2, 0] * Transl.Z);
2313 NewColumn.Y := NewColumn.Y + (M.Data[0, 1] * Transl.X + M.Data[1, 1] * Transl.Y + M.Data[2, 1] * Transl.Z);
2314 NewColumn.Z := NewColumn.Z + (M.Data[0, 2] * Transl.X + M.Data[1, 2] * Transl.Y + M.Data[2, 2] * Transl.Z);
2315 NewColumn.W := NewColumn.W + (M.Data[0, 3] * Transl.X + M.Data[1, 3] * Transl.Y + M.Data[2, 3] * Transl.Z);
2316 M.Columns[3] := NewColumn;
2317 end;
2318
2319 procedure MultMatricesTranslation(var M, MInvert: TMatrix4;
2320 const Transl: TVector3);
2321 var
2322 NewColumn: TVector4;
2323 { OldLastRow may use the same space as NewColumn }
2324 OldLastRow: TVector4 absolute NewColumn;
2325 begin
2326 NewColumn := M.Columns[3];
2327 NewColumn.X := NewColumn.X + (M.Data[0, 0] * Transl.X + M.Data[1, 0] * Transl.Y + M.Data[2, 0] * Transl.Z);
2328 NewColumn.Y := NewColumn.Y + (M.Data[0, 1] * Transl.X + M.Data[1, 1] * Transl.Y + M.Data[2, 1] * Transl.Z);
2329 NewColumn.Z := NewColumn.Z + (M.Data[0, 2] * Transl.X + M.Data[1, 2] * Transl.Y + M.Data[2, 2] * Transl.Z);
2330 NewColumn.W := NewColumn.W + (M.Data[0, 3] * Transl.X + M.Data[1, 3] * Transl.Y + M.Data[2, 3] * Transl.Z);
2331 M.Columns[3] := NewColumn;
2332
2333 OldLastRow.X := MInvert.Data[0, 3];
2334 OldLastRow.Y := MInvert.Data[1, 3];
2335 OldLastRow.Z := MInvert.Data[2, 3];
2336 OldLastRow.W := MInvert.Data[3, 3];
2337
2338 MInvert.Data[0, 0] := MInvert.Data[0, 0] - Transl.X * OldLastRow.X;
2339 MInvert.Data[1, 0] := MInvert.Data[1, 0] - Transl.X * OldLastRow.Y;
2340 MInvert.Data[2, 0] := MInvert.Data[2, 0] - Transl.X * OldLastRow.Z;
2341 MInvert.Data[3, 0] := MInvert.Data[3, 0] - Transl.X * OldLastRow.W;
2342 MInvert.Data[0, 1] := MInvert.Data[0, 1] - Transl.Y * OldLastRow.X;
2343 MInvert.Data[1, 1] := MInvert.Data[1, 1] - Transl.Y * OldLastRow.Y;
2344 MInvert.Data[2, 1] := MInvert.Data[2, 1] - Transl.Y * OldLastRow.Z;
2345 MInvert.Data[3, 1] := MInvert.Data[3, 1] - Transl.Y * OldLastRow.W;
2346 MInvert.Data[0, 2] := MInvert.Data[0, 2] - Transl.Z * OldLastRow.X;
2347 MInvert.Data[1, 2] := MInvert.Data[1, 2] - Transl.Z * OldLastRow.Y;
2348 MInvert.Data[2, 2] := MInvert.Data[2, 2] - Transl.Z * OldLastRow.Z;
2349 MInvert.Data[3, 2] := MInvert.Data[3, 2] - Transl.Z * OldLastRow.W;
2350 end;
2351
2352 function TransformToCoords(const V, NewX, NewY, NewZ: TVector3): TVector3;
2353 begin
2354 Result.X := V.X * NewX.X + V.Y * NewY.X + V.Z * NewZ.X;
2355 Result.Y := V.X * NewX.Y + V.Y * NewY.Y + V.Z * NewZ.Y;
2356 Result.Z := V.X * NewX.Z + V.Y * NewY.Z + V.Z * NewZ.Z;
2357 end;
2358
2359 function TransformToCoordsMatrix(const NewOrigin,
2360 NewX, NewY, NewZ: TVector3): TMatrix4;
2361 var
2362 i: integer;
2363 begin
2364 for i := 0 to 2 do
2365 begin
2366 Result.Data[0, i] := NewX[i];
2367 Result.Data[1, i] := NewY[i];
2368 Result.Data[2, i] := NewZ[i];
2369 Result.Data[3, i] := NewOrigin[i];
2370 end;
2371 { bottom row }
2372 Result.Data[0, 3] := 0;
2373 Result.Data[1, 3] := 0;
2374 Result.Data[2, 3] := 0;
2375 Result.Data[3, 3] := 1;
2376 end;
2377
2378 function TransformToCoordsMatrix(const NewX, NewY, NewZ: TVector3): TMatrix4;
2379 var
2380 i: integer;
2381 begin
2382 for i := 0 to 2 do
2383 begin
2384 Result.Data[0, i] := NewX[i];
2385 Result.Data[1, i] := NewY[i];
2386 Result.Data[2, i] := NewZ[i];
2387 end;
2388 { right column }
2389 Result.Data[3, 0] := 0;
2390 Result.Data[3, 1] := 0;
2391 Result.Data[3, 2] := 0;
2392 { bottom row }
2393 Result.Data[0, 3] := 0;
2394 Result.Data[1, 3] := 0;
2395 Result.Data[2, 3] := 0;
2396 Result.Data[3, 3] := 1;
2397 end;
2398
2399 function TransformToCoordsNoScaleMatrix(const NewOrigin,
2400 NewX, NewY, NewZ: TVector3): TMatrix4;
2401 begin
2402 Result := TransformToCoordsMatrix(NewOrigin,
2403 NewX.Normalize, NewY.Normalize, NewZ.Normalize);
2404 end;
2405
2406 function TransformFromCoordsMatrix(const OldOrigin,
2407 OldX, OldY, OldZ: TVector3): TMatrix4;
2408 var
2409 i: integer;
2410 begin
2411 for i := 0 to 2 do
2412 begin
2413 { Difference between TrasformToCoords and TransformFromCoords:
2414 up-left 3x3 matrix is applied in a transposed manner,
2415 compared with TrasformToCoords. }
2416 Result.Data[i, 0] := OldX[i];
2417 Result.Data[i, 1] := OldY[i];
2418 Result.Data[i, 2] := OldZ[i];
2419 end;
2420
2421 { Another difference between TrasformToCoords and TransformFromCoords:
2422 - OldOrigin must be negated here
2423 - OldOrigin must have directions applied
2424 See e.g. Global Illumination Compendium by Philip Dutre, section (15). }
2425 Result.Data[3, 0] := -TVector3.DotProduct(OldOrigin, OldX);
2426 Result.Data[3, 1] := -TVector3.DotProduct(OldOrigin, OldY);
2427 Result.Data[3, 2] := -TVector3.DotProduct(OldOrigin, OldZ);
2428
2429 { bottom row }
2430 Result.Data[0, 3] := 0;
2431 Result.Data[1, 3] := 0;
2432 Result.Data[2, 3] := 0;
2433 Result.Data[3, 3] := 1;
2434 end;
2435
2436 function TransformFromCoordsMatrix(const OldX, OldY, OldZ: TVector3): TMatrix4;
2437 var
2438 i: integer;
2439 begin
2440 for i := 0 to 2 do
2441 begin
2442 { Difference between TrasformToCoords and TransformFromCoords:
2443 up-left 3x3 matrix is applied in a transposed manner,
2444 compared with TrasformToCoords. }
2445 Result.Data[i, 0] := OldX[i];
2446 Result.Data[i, 1] := OldY[i];
2447 Result.Data[i, 2] := OldZ[i];
2448 end;
2449
2450 { right column }
2451 Result.Data[3, 0] := 0;
2452 Result.Data[3, 1] := 0;
2453 Result.Data[3, 2] := 0;
2454 { bottom row }
2455 Result.Data[0, 3] := 0;
2456 Result.Data[1, 3] := 0;
2457 Result.Data[2, 3] := 0;
2458 Result.Data[3, 3] := 1;
2459 end;
2460
2461 function TransformFromCoordsNoScaleMatrix(const OldOrigin,
2462 OldX, OldY, OldZ: TVector3): TMatrix4;
2463 begin
2464 Result := TransformFromCoordsMatrix(OldOrigin,
2465 OldX.Normalize, OldY.Normalize, OldZ.Normalize);
2466 end;
2467
2468 procedure TransformCoordsMatrices(const NewX, NewY, NewZ: TVector3;
2469 out ToCoords, FromCoords: TMatrix4);
2470 begin
2471 ToCoords := TransformToCoordsMatrix(NewX, NewY, NewZ);
2472 FromCoords := TransformFromCoordsMatrix(NewX, NewY, NewZ);
2473 end;
2474
2475 function TViewVectors.Matrix: TMatrix4;
2476 begin
2477 Result := LookDirMatrix(Translation, Direction, Up);
2478 end;
2479
2480 function TViewVectors.RotationMatrix: TMatrix4;
2481 begin
2482 { TODO: We don't use FastLookDirMatrix for now,
2483 because we aren't sure are Direction / Up normalized
2484 and orthogonal in all cases.
2485 We could check / fix it in the future (make Direction / Up normalized
2486 and orthogonal) and then use faster FastLookDirMatrix. }
2487
2488 Result := LookDirMatrix(TVector3.Zero, Direction, Up);
2489 end;
2490
2491 function LookAtMatrix(const Eye, Center, Up: TVector3): TMatrix4;
2492 begin
2493 Result := LookDirMatrix(Eye, Center - Eye, Up);
2494 end;
2495
2496 function LookDirMatrix(const Eye, Dir, Up: TVector3): TMatrix4;
2497 var
2498 GoodDir, GoodUp, Side: TVector3;
2499 begin
2500 Side := TVector3.CrossProduct(Dir, Up).Normalize;
2501 GoodDir := Dir.Normalize;
2502
2503 { Recalculate GoodUp from Side and GoodDir. This way:
2504 1. We make sure GoodUp is orthogonal to Side and GoodDir.
2505 The Up was already orthogonal to Side,
2506 but it was not necessarily orthogonal to GoodDir.
2507 2. We make sure GoodUp is normalized (vector product of normalized
2508 vectors is also normalized).
2509 This is done looking at gluLookAt implementation in
2510 SGI Sample OpenGL Implementation. }
2511 GoodUp := TVector3.CrossProduct(Side, GoodDir);
2512
2513 Result := LookDirMatrix(Eye, GoodDir, Side, GoodUp);
2514 end;
2515
2516 function LookDirMatrix(const Eye, Dir, Side, Up: TVector3): TMatrix4;
2517 begin
2518 { VectorNegate on Dir, since in right-handed coordinate system
2519 you look in the -Z direction. }
2520 Result := TransformFromCoordsMatrix(Eye, Side, Up, -Dir);
2521 end;
2522
2523 function FastLookDirMatrix(const Direction, Up: TVector3): TMatrix4;
2524 var
2525 Side: TVector3;
2526 i: integer;
2527 begin
2528 Side := TVector3.CrossProduct(Direction, Up);
2529
2530 { Make TransformToCoordsMatrix with origin zero now. }
2531
2532 for i := 0 to 2 do
2533 begin
2534 Result.Data[i, 0] := Side[i];
2535 Result.Data[i, 1] := Up[i];
2536 Result.Data[i, 2] := -Direction[i]; { negate Direction, since it goes to -Z }
2537 end;
2538
2539 { bottom row and right column }
2540 Result.Data[3, 0] := 0;
2541 Result.Data[3, 1] := 0;
2542 Result.Data[3, 2] := 0;
2543
2544 Result.Data[0, 3] := 0;
2545 Result.Data[1, 3] := 0;
2546 Result.Data[2, 3] := 0;
2547
2548 Result.Data[3, 3] := 1;
2549 end;
2550
2551 function InverseFastLookDirMatrix(const Direction, Up: TVector3): TMatrix4;
2552 var
2553 Side: TVector3;
2554 i: integer;
2555 begin
2556 Side := TVector3.CrossProduct(Direction, Up);
2557
2558 { Inverse of LookDirMatrix is now to make
2559 TransformToCoordsMatrix with origin zero. }
2560
2561 for i := 0 to 2 do
2562 begin
2563 Result.Data[0, i] := Side[i];
2564 Result.Data[1, i] := Up[i];
2565 Result.Data[2, i] := -Direction[i]; { negate Direction, since it goes to -Z }
2566 end;
2567
2568 { bottom row and right column }
2569 Result.Data[3, 0] := 0;
2570 Result.Data[3, 1] := 0;
2571 Result.Data[3, 2] := 0;
2572
2573 Result.Data[0, 3] := 0;
2574 Result.Data[1, 3] := 0;
2575 Result.Data[2, 3] := 0;
2576
2577 Result.Data[3, 3] := 1;
2578 end;
2579
2580 function ModelViewToNormalMatrix(const M: TMatrix4): TMatrix3;
2581 var
2582 D: Single;
2583 M3: TMatrix3;
2584 begin
2585 Move(M.Data[0], M3.Data[0], SizeOf(TVector3));
2586 Move(M.Data[1], M3.Data[1], SizeOf(TVector3));
2587 Move(M.Data[2], M3.Data[2], SizeOf(TVector3));
2588 D := M3.Determinant;
2589 { Comparing "IsZero(D)" would not be OK,
2590 see TTestCastleVectors.TestEpsilonInModelViewToNormalMatrix ,
2591 https://github.com/castle-engine/castle-model-viewer/issues/35 }
2592 //if IsZero(D) then
2593 if D = 0 then
2594 { modelview not invertible, nothing good to do but we have to continue
2595 without errors, since this can happen with arbitrary 3D scenes. }
2596 Result := M3
2597 else
2598 Result := M3.Inverse(D).Transpose;
2599 end;
2600
2601 function VectorMultTransposedSameVector(const V: TVector3): TMatrix4;
2602 begin
2603 (* Naive version:
2604
2605 for i := 0 to 2 do { i = column, j = row }
2606 for j := 0 to 2 do
2607 Result.Data[i, j] := V.Data[i]*V.Data[j];
2608
2609 Expanded and optimized version below. *)
2610
2611 {$ifdef FPC}
2612 Assert(SizeOf(Result) mod SizeOf(DWord) = 0);
2613 FillDWord(Result, SizeOf(Result) div SizeOf(DWord), 0);
2614 {$else}
2615 FillChar(Result, SizeOf(Result), 0);
2616 {$endif}
2617
2618 Result.Data[0, 0] := Sqr(V.X);
2619 Result.Data[1, 1] := Sqr(V.Y);
2620 Result.Data[2, 2] := Sqr(V.Z);
2621
2622 Result.Data[0, 1] := V.X * V.Y; Result.Data[1, 0] := Result.Data[0, 1];
2623 Result.Data[0, 2] := V.X * V.Z; Result.Data[2, 0] := Result.Data[0, 2];
2624 Result.Data[1, 2] := V.Y * V.Z; Result.Data[2, 1] := Result.Data[1, 2];
2625
2626 { Fill the last row and column like an identity matrix.
2627 Note that FillDWord above already took care of zeros. }
2628 Result.Data[3, 3] := 1;
2629 end;
2630
2631 function ScalingMatrix(const ScaleFactor: TVector3): TMatrix4;
2632 begin
2633 Result := TMatrix4.Identity;
2634 Result.Data[0, 0] := ScaleFactor.X;
2635 Result.Data[1, 1] := ScaleFactor.Y;
2636 Result.Data[2, 2] := ScaleFactor.Z;
2637 end;
2638
2639 procedure ScalingMatrices(const ScaleFactor: TVector3;
2640 InvertedMatrixIdentityIfNotExists: boolean;
2641 out Matrix, InvertedMatrix: TMatrix4);
2642 begin
2643 Matrix := TMatrix4.Identity;
2644 Matrix.Data[0, 0] := ScaleFactor.X;
2645 Matrix.Data[1, 1] := ScaleFactor.Y;
2646 Matrix.Data[2, 2] := ScaleFactor.Z;
2647
2648 InvertedMatrix := TMatrix4.Identity;
2649 if not
2650 (InvertedMatrixIdentityIfNotExists and
2651 ( IsZero(ScaleFactor.X) or
2652 IsZero(ScaleFactor.Y) or
2653 IsZero(ScaleFactor.Z) )) then
2654 begin
2655 InvertedMatrix.Data[0, 0] := 1 / ScaleFactor.X;
2656 InvertedMatrix.Data[1, 1] := 1 / ScaleFactor.Y;
2657 InvertedMatrix.Data[2, 2] := 1 / ScaleFactor.Z;
2658 end;
2659 end;
2660
2661 function RotationMatrix(const AxisAngle: TVector4): TMatrix4;
2662 var
2663 Axis: TVector3 absolute AxisAngle;
2664 begin
2665 Result := RotationMatrixRad(AxisAngle.W, Axis);
2666 end;
2667
2668 function RotationMatrixRad(const AngleRad: Single;
2669 const Axis: TVector3): TMatrix4;
2670 var
2671 NormAxis: TVector3;
2672 AxisLen, S, C: Single;
2673 begin
2674 // NormAxis := Axis.Normalize;
2675 { Instead of calling Axis.Normalize, we do normalization here.
2676 This way we can react nicer (for zero additional cost) to Axis being
2677 exactly zero (which is an easy mistake to make e.g. when editing Rotation
2678 in CGE editor).
2679 We'll return an identity matrix instead of invalid matrix
2680 that would likely make transformed model invisible.
2681 We still don't officially tolerate such Axis value. }
2682 AxisLen := Axis.Length;
2683 if AxisLen = 0 then
2684 Exit(TMatrix4.Identity);
2685 AxisLen := 1 / AxisLen;
2686 NormAxis.X := Axis.X * AxisLen;
2687 NormAxis.Y := Axis.Y * AxisLen;
2688 NormAxis.Z := Axis.Z * AxisLen;
2689
2690 { Using SinCos that returns 2x Single (not 2x Float),
2691 available in both FPC and Delphi now
2692 ( https://gitlab.com/freepascal.org/fpc/source/-/issues/22663 ,
2693 https://gitlab.com/freepascal.org/fpc/source/-/commit/1da4c0c3ce617e14fd6cdaaa660c2d8e43b56e20 ) }
2694 SinCos(AngleRad, S, C);
2695
2696 Result := VectorMultTransposedSameVector(NormAxis);
2697
2698 { We do not touch the last column and row of Result in the following code,
2699 treating Result like a 3x3 matrix. The last column and row are already Ok. }
2700
2701 { Expanded Result := Result + (IdentityMatrix3 - Result) * AngleCos; }
2702 Result.Data[0, 0] := Result.Data[0, 0] + (1 - Result.Data[0, 0]) * C;
2703 Result.Data[1, 0] := Result.Data[1, 0] + - Result.Data[1, 0] * C;
2704 Result.Data[2, 0] := Result.Data[2, 0] + - Result.Data[2, 0] * C;
2705
2706 Result.Data[0, 1] := Result.Data[0, 1] + - Result.Data[0, 1] * C;
2707 Result.Data[1, 1] := Result.Data[1, 1] + (1 - Result.Data[1, 1]) * C;
2708 Result.Data[2, 1] := Result.Data[2, 1] + - Result.Data[2, 1] * C;
2709
2710 Result.Data[0, 2] := Result.Data[0, 2] + - Result.Data[0, 2] * C;
2711 Result.Data[1, 2] := Result.Data[1, 2] + - Result.Data[1, 2] * C;
2712 Result.Data[2, 2] := Result.Data[2, 2] + (1 - Result.Data[2, 2]) * C;
2713
2714 NormAxis.X := NormAxis.X * S;
2715 NormAxis.Y := NormAxis.Y * S;
2716 NormAxis.Z := NormAxis.Z * S;
2717
2718 { Add M3 (from OpenGL matrix equations) }
2719 Result.Data[1, 0] := Result.Data[1, 0] + -NormAxis.Z;
2720 Result.Data[2, 0] := Result.Data[2, 0] + NormAxis.Y;
2721
2722 Result.Data[0, 1] := Result.Data[0, 1] + NormAxis.Z;
2723 Result.Data[2, 1] := Result.Data[2, 1] + -NormAxis.X;
2724
2725 Result.Data[0, 2] := Result.Data[0, 2] + -NormAxis.Y;
2726 Result.Data[1, 2] := Result.Data[1, 2] + NormAxis.X;
2727 end;
2728
2729 procedure RotationMatricesRad(const AxisAngle: TVector4;
2730 out Matrix, InvertedMatrix: TMatrix4);
2731 var
2732 Axis: TVector3 absolute AxisAngle;
2733 begin
2734 RotationMatricesRad(AxisAngle.W, Axis, Matrix, InvertedMatrix);
2735 end;
2736
2737 procedure RotationMatricesRad(const AngleRad: Single;
2738 const Axis: TVector3;
2739 out Matrix, InvertedMatrix: TMatrix4);
2740 var
2741 NormAxis: TVector3;
2742 V: Single;
2743 AxisLen, S, C: Single;
2744 begin
2745 // NormAxis := Axis.Normalize;
2746 { Instead of calling Axis.Normalize, we do normalization here.
2747 This way we can react nicer (for zero additional cost) to Axis being
2748 exactly zero (which is an easy mistake to make e.g. when editing Rotation
2749 in CGE editor).
2750 We'll return an identity matrix instead of invalid matrix
2751 that would likely make transformed model invisible.
2752 We still don't officially tolerate such Axis value. }
2753 AxisLen := Axis.Length;
2754 if AxisLen = 0 then
2755 begin
2756 Matrix := TMatrix4.Identity;
2757 InvertedMatrix := TMatrix4.Identity;
2758 Exit;
2759 end;
2760 AxisLen := 1 / AxisLen;
2761 NormAxis.X := Axis.X * AxisLen;
2762 NormAxis.Y := Axis.Y * AxisLen;
2763 NormAxis.Z := Axis.Z * AxisLen;
2764
2765 { Using SinCos that returns 2x Single (not 2x Float),
2766 available in both FPC and Delphi now
2767 ( https://gitlab.com/freepascal.org/fpc/source/-/issues/22663 ,
2768 https://gitlab.com/freepascal.org/fpc/source/-/commit/1da4c0c3ce617e14fd6cdaaa660c2d8e43b56e20 ) }
2769 SinCos(AngleRad, S, C);
2770
2771 Matrix := VectorMultTransposedSameVector(NormAxis);
2772
2773 { We do not touch the last column and row of Matrix in the following code,
2774 treating Matrix like a 3x3 matrix. The last column and row are already Ok. }
2775
2776 { Expanded Matrix := Matrix + (IdentityMatrix3 - Matrix) * AngleCos; }
2777 Matrix.Data[0, 0] := Matrix.Data[0, 0] + (1 - Matrix.Data[0, 0]) * C;
2778 Matrix.Data[1, 0] := Matrix.Data[1, 0] + - Matrix.Data[1, 0] * C;
2779 Matrix.Data[2, 0] := Matrix.Data[2, 0] + - Matrix.Data[2, 0] * C;
2780
2781 Matrix.Data[0, 1] := Matrix.Data[0, 1] + - Matrix.Data[0, 1] * C;
2782 Matrix.Data[1, 1] := Matrix.Data[1, 1] + (1 - Matrix.Data[1, 1]) * C;
2783 Matrix.Data[2, 1] := Matrix.Data[2, 1] + - Matrix.Data[2, 1] * C;
2784
2785 Matrix.Data[0, 2] := Matrix.Data[0, 2] + - Matrix.Data[0, 2] * C;
2786 Matrix.Data[1, 2] := Matrix.Data[1, 2] + - Matrix.Data[1, 2] * C;
2787 Matrix.Data[2, 2] := Matrix.Data[2, 2] + (1 - Matrix.Data[2, 2]) * C;
2788
2789 { Up to this point, calculated Matrix is also good for InvertedMatrix }
2790 InvertedMatrix := Matrix;
2791
2792 NormAxis.X := NormAxis.X * S;
2793 NormAxis.Y := NormAxis.Y * S;
2794 NormAxis.Z := NormAxis.Z * S;
2795
2796 { Now add M3 to Matrix, and subtract M3 from InvertedMatrix.
2797 That's because for the inverted rotation, AngleSin is negated,
2798 so the M3 should be subtracted. }
2799 V := -NormAxis.Z; Matrix.Data[1, 0] := Matrix.Data[1, 0] + V; InvertedMatrix.Data[1, 0] := InvertedMatrix.Data[1, 0] - V;
2800 V := NormAxis.Y; Matrix.Data[2, 0] := Matrix.Data[2, 0] + V; InvertedMatrix.Data[2, 0] := InvertedMatrix.Data[2, 0] - V;
2801
2802 V := NormAxis.Z; Matrix.Data[0, 1] := Matrix.Data[0, 1] + V; InvertedMatrix.Data[0, 1] := InvertedMatrix.Data[0, 1] - V;
2803 V := -NormAxis.X; Matrix.Data[2, 1] := Matrix.Data[2, 1] + V; InvertedMatrix.Data[2, 1] := InvertedMatrix.Data[2, 1] - V;
2804
2805 V := -NormAxis.Y; Matrix.Data[0, 2] := Matrix.Data[0, 2] + V; InvertedMatrix.Data[0, 2] := InvertedMatrix.Data[0, 2] - V;
2806 V := NormAxis.X; Matrix.Data[1, 2] := Matrix.Data[1, 2] + V; InvertedMatrix.Data[1, 2] := InvertedMatrix.Data[1, 2] - V;
2807 end;
2808
2809 function RotationMatrixDeg(const AngleDeg: Single; const Axis: TVector3): TMatrix4;
2810 begin
2811 Result := RotationMatrixRad(DegToRad(AngleDeg), Axis);
2812 end;
2813
2814 function RotationMatrixDeg(const AngleDeg: Single;
2815 const AxisX, AxisY, AxisZ: Single): TMatrix4;
2816 begin
2817 Result := RotationMatrixRad(DegToRad(AngleDeg), Vector3(AxisX, AxisY, AxisZ));
2818 end;
2819
2820 function RotationMatrixRad(const AngleRad: Single;
2821 const AxisX, AxisY, AxisZ: Single): TMatrix4;
2822 begin
2823 Result := RotationMatrixRad(AngleRad, Vector3(AxisX, AxisY, AxisZ));
2824 end;
2825
2826 function RotatePoint2D(const Point: TVector2; const AngleRad: Single): TVector2;
2827 var
2828 S, C: Single;
2829 begin
2830 { Using SinCos that returns 2x Single (not 2x Float),
2831 available in both FPC and Delphi now
2832 ( https://gitlab.com/freepascal.org/fpc/source/-/issues/22663 ,
2833 https://gitlab.com/freepascal.org/fpc/source/-/commit/1da4c0c3ce617e14fd6cdaaa660c2d8e43b56e20 ) }
2834 SinCos(AngleRad, S, C);
2835
2836 Result.X := Point.X * C - Point.Y * S;
2837 Result.Y := Point.X * S + Point.Y * C;
2838 end;
2839
2840 function RotationNegate(const Rotation: TVector4): TVector4;
2841 begin
2842 Result := Rotation;
2843 Result.W := -Result.W;
2844 end;
2845
2846 function Approximate3DScale(const X, Y, Z: Single): Single;
2847 begin
2848 if (X * Y < 0) or
2849 (X * Z < 0) or
2850 (Y * X < 0) then
2851 { If some values have opposite signs, it's better to make
2852 an average of absolute values. This way a scale like (-1, 1, 1),
2853 that flips X but preserves size, results in 1 (not 1/3).
2854 Bug reproduce: escape with mirrored map parts. }
2855 Result := (Abs(X) + Abs(Y) + Abs(Z)) / 3
2856 else
2857 Result := ( X + Y + Z ) / 3;
2858 end;
2859
2860 function Approximate3DScale(const V: TVector3): Single;
2861 begin
2862 Result := Approximate3DScale(V.X, V.Y, V.Z);
2863 end;
2864
2865 function Approximate3DScale(const M: TMatrix4): Single;
2866 var
2867 Scale: TVector3;
2868 begin
2869 { See MatrixDecompose }
2870 Scale.X := Vector3(M.Data[0, 0], M.Data[0, 1], M.Data[0, 2]).Length;
2871 Scale.Y := Vector3(M.Data[1, 0], M.Data[1, 1], M.Data[1, 2]).Length;
2872 Scale.Z := Vector3(M.Data[2, 0], M.Data[2, 1], M.Data[2, 2]).Length;
2873 Result := Approximate3DScale(Scale);
2874 end;
2875
2876 function Approximate2DScale(const X, Y: Single): Single;
2877 begin
2878 if (X * Y < 0) then
2879 { If X and Y have opposite signs, it's better to make
2880 an average of absolute values. This way a scale like (-1, 1),
2881 that flips X but preserves Y, results in 1 (not 0). }
2882 Result := (Abs(X) + Abs(Y)) / 2
2883 else
2884 Result := ( X + Y ) / 2;
2885 end;
2886
2887 function Approximate2DScale(const V: TVector2): Single;
2888 begin
2889 Result := Approximate2DScale(V.X, V.Y);
2890 end;
2891
2892 function SmoothTowards(const Source, Target, SecondsPassed,
2893 Speed: Single): Single;
2894 begin
2895 Result := Source +
2896 Min(1, SecondsPassed * Speed) * (Target - Source);
2897 end;
2898
2899 function SmoothTowards(const Source, Target: TVector2;
2900 const SecondsPassed, Speed: Single): TVector2;
2901 begin
2902 Result := Source +
2903 Min(1, SecondsPassed * Speed) * (Target - Source);
2904 end;
2905
2906 function SmoothTowards(const Source, Target: TVector3;
2907 const SecondsPassed, Speed: Single): TVector3;
2908 begin
2909 Result := Source +
2910 Min(1, SecondsPassed * Speed) * (Target - Source);
2911 end;
2912
2913 {$endif read_implementation}