Debian Codegraph @

src/transform/castlefrustum.pas

raw
1 {
2 Copyright 2005-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Frustum object (TFrustum) and helpers. }
17 unit CastleFrustum;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses CastleVectors, CastleBoxes;
24
25 type
26 { Order of planes of TFrustum.
27
28 (This order is the same as the order of params to
29 procedure FrustumProjectionMatrix and OpenGL's glFrustum routine.
30 Article [http://www2.ravensoft.com/users/ggribb/plane%20extraction.pdf]
31 has swapped bottom and top positions). }
32 TFrustumPlane = (fpLeft, fpRight, fpBottom, fpTop, fpNear, fpFar);
33
34 TFrustumPoints = packed array [0..7] of TVector4;
35
36 TFrustumPointsSingle = TFrustumPoints deprecated 'use TFrustumPoints';
37
38 TFrustumPointsDouble = packed array [0..7] of TVector4Double
39 {$ifdef FPC}deprecated 'use Single-precision TFrustumPoints'{$endif};
40
41 const
42 FrustumPointsQuadsIndexes: packed array [TFrustumPlane, 0..3] of UInt16 =
43 ( (0, 3, 7, 4),
44 (1, 2, 6, 5),
45 (2, 3, 7, 6),
46 (0, 1, 5, 4),
47 (0, 1, 2, 3),
48 (4, 5, 6, 7) );
49
50 { Useful if you want to draw frustum obtained from
51 TFrustum.CalculatePoints.
52
53 It's guaranteed that the first 4 items
54 touch only the first 4 (near plane) points of the frustum --- useful
55 if you want to draw only the near plane rect.
56
57 When TFrustum.FarInfinity, other points may be in infinity. }
58 FrustumPointsLinesIndexes: packed array [0..11, 0..1] of UInt16 =
59 ( (0, 1), (1, 2), (2, 3), (3, 0),
60 (4, 5), (5, 6), (6, 7), (7, 4),
61 (0, 4), (1, 5), (2, 6), (3, 7)
62 );
63
64 type
65 { See @link(TFrustum.SphereCollisionPossible) for description
66 what each value of this type means. }
67 TFrustumCollisionPossible =
68 ( fcNoCollision,
69 fcSomeCollisionPossible,
70 fcInsideFrustum );
71
72 { Viewing frustum, defined as 6 plane equations.
73 Calculating and operating on such frustum.
74 Frustums with far plane in infinity (typically used in conjunction
75 with shadow volumes) are fully supported by all methods (we just have
76 5 frustum planes then).
77
78 We define this using ObjectPascal old-style "object", to have comfort
79 and low-overhead at the same time. }
80 TFrustum = record
81 private
82 procedure NormalizePlanes;
83 { Last plane index.
84 High(TFrustumPlane), or Pred(High(TFrustumPlane)) if FarInfinity. }
85 function LastPlane: TFrustumPlane;
86 public
87 { Calculate frustum, knowing the combined matrix (modelview * projection). }
88 constructor Init(const Matrix: TMatrix4); overload;
89
90 { Calculate frustum, knowing projection and modelview matrices.
91 This is equivalent to 1-parameter Init
92 with Matrix = ModelviewMatrix * ProjectionMatrix.
93
94 You can calculate camera matrix (usual modelview in this case) e.g.
95 using @link(TCastleCamera.Matrix).
96 You can calculate projection matrix e.g. using
97 @link(TProjection.Matrix).
98 Pass them to this routine and you get your current viewing frustum. }
99 constructor Init(const ProjectionMatrix, ModelviewMatrix: TMatrix4); overload;
100 public
101 { Six planes defining the frustum.
102 Direction vectors of these planes must point to the inside of the frustum.
103 Currently, they are always normalized.
104
105 Note that if projection has far plane in infinity (indicated by
106 FarInfinity) then the far plane will be invalid ---
107 first three values of it's equation will be 0.
108 Always check @link(FarInfinity) before accessing that plane. }
109 Planes: array [TFrustumPlane] of TVector4;
110
111 FarInfinity: boolean;
112
113 { Calculate 8 points of frustum. These points are simply
114 calculated doing ThreePlanesIntersectionPoint on appropriate planes.
115
116 Using these points you can easily draw given frustum on screen.
117 Use FrustumPointsQuadsIndexes or FrustumPointsLinesIndexes
118 to obtain indexes matching these FrustumPoints for rendering.
119
120 Note that when the far plane is in infinity,
121 the 4 points of the far plane will be "in infinity",
122 that is will have 4th component set to zero. Or, equivalently,
123 they will be directions. Homogeneous coordinates allow us for this,
124 and you can even render such points using @link(TCastleRenderUnlitMesh).
125
126 @raises(EPlanesParallel If Frustum doesn't have planes of any
127 valid frustum.)
128 }
129 procedure CalculatePoints(out FrustumPoints: TFrustumPoints); overload;
130
131 procedure CalculatePoints(out FrustumPoints: TFrustumPointsDouble); overload;
132 deprecated 'use the overload on TFrustumPoints (Single-precision); it may calculate parts using Double-precision internally, to be correct';
133
134 { Checks for collision between frustum and sphere.
135
136 Check is done fast, but is not accurate, that's why this function's
137 name contains "CollisionPossible". It returns:
138
139 fcNoCollision when it's sure that there no collision,
140
141 fcSomeCollisionPossible when some collision is possible,
142 but nothing is sure. There *probably* is some collision,
143 but it's not difficult to find some special situations where there
144 is no collision but this function answers fcSomeCollisionPossible.
145 There actually may be either no collision,
146 or only part of sphere may be inside frustum.
147
148 Note that it's guaranteed that if the whole sphere
149 (or the whole box in case of Box3DCollisionPossible)
150 is inside the frustum that fcInsideFrustum will be returned,
151 not fcSomeCollisionPossible.
152
153 fcInsideFrustum if sphere is for sure inside the frustum.
154
155 So this function usually cannot be used for some precise collision
156 detection, but it can be used for e.g. optimizing your graphic engine
157 by doing frustum culling. Note that fcInsideFrustum result
158 is often useful when you're comparing your frustum with
159 bounding volume of some tree (e.g. octree) node: fcInsideFrustum
160 tells you that not only this node collides with frustum,
161 but also all it's children nodes collide for sure with frustum.
162 This allows you to save some time instead of doing useless
163 recursion down the tree.
164
165 Many useful optimization ideas used in implementing this function
166 were found at
167 [http://www.flipcode.com/articles/article_frustumculling.shtml].
168
169 @seealso TFrustum.Box3DCollisionPossible
170 }
171 function SphereCollisionPossible(
172 const SphereCenter: TVector3; const SphereRadiusSqr: Single):
173 TFrustumCollisionPossible;
174
175 { Checks for collision between frustum and sphere, faster.
176 Like @link(TFrustum.SphereCollisionPossible),
177 but this only returns true (when TFrustum.SphereCollisionPossible
178 would return fcSomeCollisionPossible or fcInsideFrustum)
179 or false (when TFrustum.SphereCollisionPossible
180 would return fcNoCollision).
181
182 Consequently, it runs (very slightly) faster.
183 Use this if you don't need to differentiate between
184 fcSomeCollisionPossible or fcInsideFrustum cases. }
185 function SphereCollisionPossibleSimple(
186 const SphereCenter: TVector3; const SphereRadiusSqr: Single):
187 boolean;
188
189 { Checks for collision between frustum and box.
190 Meaning of return value like @link(SphereCollisionPossible). }
191 function Box3DCollisionPossible(
192 const Box: TBox3D): TFrustumCollisionPossible;
193
194 { Checks for collision between frustum and box, faster.
195 Meaning of return value like @link(SphereCollisionPossibleSimple). }
196 function Box3DCollisionPossibleSimple(
197 const Box: TBox3D): boolean;
198
199 function Move(const M: TVector3): TFrustum;
200 procedure MoveVar(const M: TVector3);
201
202 { Is Direction within a frustum. You can think of
203 direction it as a "point infinitely away in given Direction",
204 like the direction to the sun. Note that this ignores
205 near/far planes of the frustum, only checking the 4 side planes. }
206 function DirectionInside(const Direction: TVector3): boolean;
207
208 { Transform frustum by a matrix.
209
210 @param(M Transformation matrix.
211 This matrix must be "sane": it must transform homogeneous positions
212 into homogeneous positions, and homogeneous directions into
213 homogeneous directions. Also, it must not invert or do other weird stuff
214 (like shear) with directions. To be safe just make sure it's a matrix
215 composed only from translations, rotations, and scale (with all
216 scale parameters being > 0).)
217
218 @raises(ETransformedResultInvalid In some cases when matrix is not sane.) }
219 function Transform(const M: TMatrix4): TFrustum;
220
221 { Transform frustum by a matrix, given inverse transformation.
222
223 This is faster than @link(Transform), so prefer using this if you have
224 an inverse matrix ready.
225 See CGE tests (tests/code/testcastlefrustum.pas) for speed testing code. }
226 function TransformByInverse(const MInverse: TMatrix4): TFrustum;
227
228 function ToNiceStr(const Indent: string): string; deprecated 'use ToString';
229 function ToString(const Indent: string): string;
230 end;
231 PFrustum = ^TFrustum;
232
233 implementation
234
235 {$ifndef FPC}uses CastleUtils;{$endif}
236
237 constructor TFrustum.Init(const Matrix: TMatrix4);
238 begin
239 { Based on [http://www2.ravensoft.com/users/ggribb/plane%20extraction.pdf].
240 Note that position of bottom and top planes in array Frustum is swapped
241 in my code. }
242
243 Planes[fpLeft].X := Matrix.Data[0, 3] + Matrix.Data[0, 0];
244 Planes[fpLeft].Y := Matrix.Data[1, 3] + Matrix.Data[1, 0];
245 Planes[fpLeft].Z := Matrix.Data[2, 3] + Matrix.Data[2, 0];
246 Planes[fpLeft].W := Matrix.Data[3, 3] + Matrix.Data[3, 0];
247
248 Planes[fpRight].X := Matrix.Data[0, 3] - Matrix.Data[0, 0];
249 Planes[fpRight].Y := Matrix.Data[1, 3] - Matrix.Data[1, 0];
250 Planes[fpRight].Z := Matrix.Data[2, 3] - Matrix.Data[2, 0];
251 Planes[fpRight].W := Matrix.Data[3, 3] - Matrix.Data[3, 0];
252
253 Planes[fpBottom].X := Matrix.Data[0, 3] + Matrix.Data[0, 1];
254 Planes[fpBottom].Y := Matrix.Data[1, 3] + Matrix.Data[1, 1];
255 Planes[fpBottom].Z := Matrix.Data[2, 3] + Matrix.Data[2, 1];
256 Planes[fpBottom].W := Matrix.Data[3, 3] + Matrix.Data[3, 1];
257
258 Planes[fpTop].X := Matrix.Data[0, 3] - Matrix.Data[0, 1];
259 Planes[fpTop].Y := Matrix.Data[1, 3] - Matrix.Data[1, 1];
260 Planes[fpTop].Z := Matrix.Data[2, 3] - Matrix.Data[2, 1];
261 Planes[fpTop].W := Matrix.Data[3, 3] - Matrix.Data[3, 1];
262
263 Planes[fpNear].X := Matrix.Data[0, 3] + Matrix.Data[0, 2];
264 Planes[fpNear].Y := Matrix.Data[1, 3] + Matrix.Data[1, 2];
265 Planes[fpNear].Z := Matrix.Data[2, 3] + Matrix.Data[2, 2];
266 Planes[fpNear].W := Matrix.Data[3, 3] + Matrix.Data[3, 2];
267
268 Planes[fpFar].X := Matrix.Data[0, 3] - Matrix.Data[0, 2];
269 Planes[fpFar].Y := Matrix.Data[1, 3] - Matrix.Data[1, 2];
270 Planes[fpFar].Z := Matrix.Data[2, 3] - Matrix.Data[2, 2];
271 Planes[fpFar].W := Matrix.Data[3, 3] - Matrix.Data[3, 2];
272
273 { If Planes[fpFar] has really exactly zero vector,
274 then far plane is in infinity. }
275 FarInfinity :=
276 (Planes[fpFar].X = 0) and
277 (Planes[fpFar].Y = 0) and
278 (Planes[fpFar].Z = 0);
279
280 NormalizePlanes;
281 end;
282
283 procedure TFrustum.NormalizePlanes;
284 var
285 fp: TFrustumPlane;
286 begin
287 for fp := Low(fp) to LastPlane do
288 begin
289 NormalizePlaneVar(Planes[fp]);
290
291 { Previously we used this hack:
292
293 We know that every plane Planes[fp] is correct, i.e. it's direction
294 vector has non-zero length. But sometimes algorithm above calculates
295 such vector with very small length, especially for fpFar plane.
296 This causes problems when I'm later processing this plane,
297 errors cumulate and suddenly something thinks that it has
298 a zero-vector, while actually it is (or was) a vector with
299 very small (but non-zero) length.
300
301 I could do here
302 NormalizePlaneVar(Planes[fp]);
303 instead, but that would be slow (NormalizePlaneVar costs me
304 calculating 1 Sqrt).
305 if PVector3(@Planes[fp].LengthSqr^) < 0.001 then
306 Planes[fp] := Planes[fp] * 100000;
307 }
308 end;
309 end;
310
311 constructor TFrustum.Init(
312 const ProjectionMatrix, ModelviewMatrix: TMatrix4);
313 begin
314 Init(ProjectionMatrix * ModelviewMatrix);
315 end;
316
317 procedure TFrustum.CalculatePoints(out FrustumPoints: TFrustumPoints);
318 { It's better to make these calculations using Double precision. }
319 // This deliberately uses TFrustumPointsDouble
320 // and CalculatePoints based on TFrustumPointsDouble.
321 // They should be internal (private) in this unit in the future.
322 {$warnings off}
323 var
324 FrustumPointsDouble: TFrustumPointsDouble;
325 I: Integer;
326 begin
327 CalculatePoints(FrustumPointsDouble);
328 for I := 0 to High(FrustumPoints) do
329 FrustumPoints[I] := Vector4(FrustumPointsDouble[I]);
330 end;
331 {$warnings on}
332
333 procedure TFrustum.CalculatePoints(out FrustumPoints: TFrustumPointsDouble);
334 var
335 Camera: TVector3Double;
336 begin
337 FrustumPoints[0] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpNear]), Vector4Double(Planes[fpLeft]), Vector4Double(Planes[fpTop])) , 1);
338 FrustumPoints[1] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpNear]), Vector4Double(Planes[fpRight]), Vector4Double(Planes[fpTop])) , 1);
339 FrustumPoints[2] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpNear]), Vector4Double(Planes[fpRight]), Vector4Double(Planes[fpBottom])), 1);
340 FrustumPoints[3] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpNear]), Vector4Double(Planes[fpLeft]), Vector4Double(Planes[fpBottom])), 1);
341
342 if not FarInfinity then
343 begin
344 FrustumPoints[4] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpFar]), Vector4Double(Planes[fpLeft]), Vector4Double(Planes[fpTop])) , 1);
345 FrustumPoints[5] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpFar]), Vector4Double(Planes[fpRight]), Vector4Double(Planes[fpTop])) , 1);
346 FrustumPoints[6] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpFar]), Vector4Double(Planes[fpRight]), Vector4Double(Planes[fpBottom])), 1);
347 FrustumPoints[7] := Vector4Double(ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpFar]), Vector4Double(Planes[fpLeft]), Vector4Double(Planes[fpBottom])), 1);
348 end else
349 begin
350 Camera := ThreePlanesIntersectionPointDouble(Vector4Double(Planes[fpRight]), Vector4Double(Planes[fpLeft]), Vector4Double(Planes[fpTop]));
351
352 FrustumPoints[4] := Vector4Double(FrustumPoints[0].XYZ - Camera, 0);
353 FrustumPoints[5] := Vector4Double(FrustumPoints[1].XYZ - Camera, 0);
354 FrustumPoints[6] := Vector4Double(FrustumPoints[2].XYZ - Camera, 0);
355 FrustumPoints[7] := Vector4Double(FrustumPoints[3].XYZ - Camera, 0);
356 end;
357 end;
358
359 function TFrustum.SphereCollisionPossible(
360 const SphereCenter: TVector3; const SphereRadiusSqr: Single):
361 TFrustumCollisionPossible;
362 var
363 fp: TFrustumPlane;
364 Distance, SqrRealDistance: Single;
365 InsidePlanesCount: Cardinal;
366 begin
367 InsidePlanesCount := 0;
368
369 { If the frustum has far plane in infinity, then ignore this plane.
370 Inc InsidePlanesCount, since the sphere is inside this infinite plane. }
371 if FarInfinity then
372 Inc(InsidePlanesCount);
373
374 { The logic goes like this:
375 if sphere is on the "outside" of *any* of 6 planes, result is NoCollision
376 if sphere is on the "inside" of *all* 6 planes, result is InsideFrustum
377 else SomeCollisionPossible.
378
379 Ideas based on
380 [http://www.flipcode.com/articles/article_frustumculling.shtml]
381 Version below is even better optimized: in case sphere
382 intersects with one plane, but is outside another plane,
383 their version may answer "intersection" (equivalent to my
384 SomeCollisionPossible), without realizing that actually a better
385 answer, NoCollision, exists. }
386
387 { For the sake of maximum speed, I'm not using here things like
388 TVector3.DotProduct or PointToPlaneDistanceSqr }
389 for fp := Low(fp) to LastPlane do
390 begin
391 { This is not a true distance since this is signed }
392 Distance := Planes[fp].X * SphereCenter.X +
393 Planes[fp].Y * SphereCenter.Y +
394 Planes[fp].Z * SphereCenter.Z +
395 Planes[fp].W;
396
397 SqrRealDistance := Sqr(Distance);
398
399 if (Distance < 0) and (SqrRealDistance > SphereRadiusSqr) then
400 begin
401 Result := fcNoCollision;
402 Exit;
403 end else
404 if SqrRealDistance >= SphereRadiusSqr then
405 Inc(InsidePlanesCount);
406 end;
407
408 if InsidePlanesCount = 6 then
409 Result := fcInsideFrustum
410 else
411 Result := fcSomeCollisionPossible;
412 end;
413
414 function TFrustum.SphereCollisionPossibleSimple(
415 const SphereCenter: TVector3; const SphereRadiusSqr: Single):
416 boolean;
417 var
418 fp: TFrustumPlane;
419 Distance, SqrRealDistance: Single;
420 begin
421 for fp := Low(fp) to LastPlane do
422 begin
423 { This is not a true distance since this is signed }
424 Distance := Planes[fp].X * SphereCenter.X +
425 Planes[fp].Y * SphereCenter.Y +
426 Planes[fp].Z * SphereCenter.Z +
427 Planes[fp].W;
428
429 SqrRealDistance := Sqr(Distance);
430
431 if (Distance < 0) and (SqrRealDistance > SphereRadiusSqr) then
432 begin
433 Result := false;
434 Exit;
435 end;
436 end;
437
438 Result := true;
439 end;
440
441 function TFrustum.Box3DCollisionPossible(
442 const Box: TBox3D): TFrustumCollisionPossible;
443
444 { Note: I tried to optimize this function,
445 since it's crucial for TOctree.EnumerateCollidingOctreeItems,
446 and this is crucial for TCastleScene.RenderFrustumOctree,
447 and this is crucial for overall speed of rendering. }
448
449 var
450 fp: TFrustumPlane;
451 InsidePlanesCount: Cardinal;
452 begin
453 if Box.IsEmpty then
454 Exit(fcNoCollision);
455
456 InsidePlanesCount := 0;
457
458 { If the frustum has far plane in infinity, then ignore this plane.
459 Inc InsidePlanesCount, since the box is inside this infinite plane. }
460 if FarInfinity then
461 Inc(InsidePlanesCount);
462
463 { The logic goes like this:
464 if box is on the "outside" of *any* of 6 planes, result is NoCollision
465 if box is on the "inside" of *all* 6 planes, result is InsideFrustum
466 else SomeCollisionPossible. }
467
468 for fp := Low(fp) to LastPlane do
469 begin
470 { Don't be confused by names below: pcOutside means that box
471 is where Planes[fp] normal points, which means *inside* the frustum... }
472 case Box.PlaneCollision(Planes[fp]) of
473 pcInside: Exit(fcNoCollision);
474 pcOutside: Inc(InsidePlanesCount);
475 else ;
476 end;
477 end;
478
479 if InsidePlanesCount = 6 then
480 Result := fcInsideFrustum
481 else
482 Result := fcSomeCollisionPossible;
483 end;
484
485 function TFrustum.Box3DCollisionPossibleSimple(
486 const Box: TBox3D): boolean;
487
488 { Implementation is obviously based on
489 TFrustum.Box3DCollisionPossible above, see there for more comments. }
490
491 var
492 fp: TFrustumPlane;
493 begin
494 if Box.IsEmpty then
495 Exit(false);
496
497 for fp := Low(fp) to LastPlane do
498 { Again, don't be confused by name "Inside" below: pcInside
499 means that box is where Planes[fp] inverted normal points,
500 which means *outside* the frustum... }
501 if Box.PlaneCollisionInside(Planes[fp]) then
502 Exit(false);
503
504 Result := true;
505 end;
506
507 function TFrustum.Move(const M: TVector3): TFrustum;
508 begin
509 Result.Planes[fpLeft ] := PlaneMove(Planes[fpLeft] , M);
510 Result.Planes[fpRight ] := PlaneMove(Planes[fpRight] , M);
511 Result.Planes[fpBottom] := PlaneMove(Planes[fpBottom], M);
512 Result.Planes[fpTop ] := PlaneMove(Planes[fpTop] , M);
513 Result.Planes[fpNear ] := PlaneMove(Planes[fpNear] , M);
514 { This is Ok for frustum with infinite far plane, since
515 PlaneMove will simply keep the far plane invalid }
516 Result.Planes[fpFar ] := PlaneMove(Planes[fpFar] , M);
517 Result.FarInfinity := FarInfinity;
518 Result.NormalizePlanes;
519 end;
520
521 procedure TFrustum.MoveVar(const M: TVector3);
522 begin
523 PlaneMoveVar(Planes[fpLeft] , M);
524 PlaneMoveVar(Planes[fpRight] , M);
525 PlaneMoveVar(Planes[fpBottom], M);
526 PlaneMoveVar(Planes[fpTop] , M);
527 PlaneMoveVar(Planes[fpNear] , M);
528 { This is Ok for frustum with infinite far plane, since
529 PlaneMove will simply keep the far plane invalid }
530 PlaneMoveVar(Planes[fpFar] , M);
531 NormalizePlanes;
532 end;
533
534 function TFrustum.DirectionInside(const Direction: TVector3): boolean;
535 begin
536 { First we check fpTop, since this (usually?) has the highest chance
537 of failing (when Direction is direction of sun high in the sky) }
538 Result := ( Planes[fpTop].X * Direction.X +
539 Planes[fpTop].Y * Direction.Y +
540 Planes[fpTop].Z * Direction.Z >= 0 ) and
541 ( Planes[fpLeft].X * Direction.X +
542 Planes[fpLeft].Y * Direction.Y +
543 Planes[fpLeft].Z * Direction.Z >= 0 ) and
544 ( Planes[fpRight].X * Direction.X +
545 Planes[fpRight].Y * Direction.Y +
546 Planes[fpRight].Z * Direction.Z >= 0 ) and
547 ( Planes[fpBottom].X * Direction.X +
548 Planes[fpBottom].Y * Direction.Y +
549 Planes[fpBottom].Z * Direction.Z >= 0 );
550 end;
551
552 function TFrustum.LastPlane: TFrustumPlane;
553 begin
554 Result := High(TFrustumPlane);
555 Assert(Result = fpFar); // last plane must be far, to make LastPlane logic sensible
556 if FarInfinity then
557 Result := Pred(Result);
558 end;
559
560 function TFrustum.Transform(const M: TMatrix4): TFrustum;
561 var
562 I: TFrustumPlane;
563 begin
564 for I := Low(I) to LastPlane do
565 begin
566 Result.Planes[I] := PlaneTransform(Planes[I], M);
567 { Just like comments in TFrustum.TransformByInverse say,
568 we need to normalize planes.
569 PlaneTransform doesn't preserve plane normalization in case
570 matrix has scale (as autotests show). }
571 NormalizePlaneVar(Result.Planes[I]);
572 end;
573
574 if FarInfinity then
575 Result.Planes[fpFar] := TVector4.Zero;
576 Result.FarInfinity := FarInfinity;
577 end;
578
579 function TFrustum.TransformByInverse(const MInverse: TMatrix4): TFrustum;
580
581 { Multiply by transpose(inverse(M)) to transform plane.
582
583 - This is faster than PlaneTransform since we only need to do one matrix
584 multiplication (in TransposeMultiply), while PlaneTransform needs two.
585
586 Uncomment speed test in TTestCastleFrustum.TestTransformFrustum
587 to check speed gain of TransformByInverse (MInverse.TransposeMultiply)
588 vs Transform (PlaneTransform).
589
590 - See https://stackoverflow.com/questions/7685495/transforming-a-3d-plane-using-a-4x4-matrix
591 for idea.
592
593 - Note: This needs to renormalize the resulting planes
594 in case the MInverse contains scaling.
595 Our TFrustum has always normalized planes (promised in interface),
596 and some code may depend on it -- our collision checking with frustum
597 calculates distances assuming that planes are normalized.
598
599 Testcase: TCastleScene with PreciseCollisions = true
600 (use frustum and octree for rendering optimizations)
601 and multiple shapes and ShapeFrustumCulling = true.
602 I didn't track down the exact code, but some test in TestOctreeWithFrustum
603 inside TCastleScene assumes that frustum planes are normalized.
604 See private-assets/various_test_projects/test_frustum_planes_normalized_or_frustum_culling_bad/ .
605 }
606
607 var
608 I: TFrustumPlane;
609 begin
610 for I := Low(I) to LastPlane do
611 begin
612 Result.Planes[I] := MInverse.TransposeMultiply(Planes[I]);
613 NormalizePlaneVar(Result.Planes[I]);
614 end;
615
616 if FarInfinity then
617 Result.Planes[fpFar] := TVector4.Zero;
618 Result.FarInfinity := FarInfinity;
619 end;
620
621 function TFrustum.ToNiceStr(const Indent: string): string;
622 begin
623 Result := ToString(Indent);
624 end;
625
626 function TFrustum.ToString(const Indent: string): string;
627 var
628 I: TFrustumPlane;
629 begin
630 Result := '';
631 for I := Low(I) to LastPlane do
632 Result := Result + Indent + Planes[I].ToString + LineEnding;
633 if FarInfinity then
634 Result := Result + Indent + '(no far plane, frustum goes to infinity)' + LineEnding;
635 end;
636
637 end.