Debian Codegraph @

src/transform/castletriangles.pas

raw
1 {
2 Copyright 2003-2022 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 { Triangles. In 2D, 3D and 4D space. }
17 unit CastleTriangles;
18
19 {$I castleconf.inc}
20 {$I octreeconf.inc}
21
22 interface
23
24 uses Generics.Collections,
25 CastleUtils, CastleVectors;
26
27 type
28 { Triangle in 2D space. }
29 TTriangle2 = record
30 Data: packed array [0..2] of TVector2;
31
32 { Multiline triangle description. }
33 function ToString: string;
34 end;
35
36 PTriangle2 = ^TTriangle2;
37
38 { Triangle in 3D space.
39
40 Triangle's three points must not be collinear,
41 i.e. routines in this unit generally don't accept "degenerated" triangles
42 that are not really triangles. So 3D triangle must unambiguously
43 define some plane in the 3D space. The only function in this unit
44 that is able to handle "degenerated" triangles is @link(TTriangle3.IsValid),
45 which is exactly used to check whether the triangle is degenerated. }
46 TTriangle3 = record
47 public
48 type
49 TIndex = 0..2;
50 strict private
51 function GetItems(const Index: TIndex): TVector3;
52 procedure SetItems(const Index: TIndex; const Value: TVector3);
53 public
54 Data: packed array [TIndex] of TVector3;
55
56 { Access the points of the triangle.
57 This is the same as accessing @link(Data) field,
58 it is also the default record property so you can just write @code(MyTriangle[0])
59 instead of @code(MyTriangle.Items[0]) or @code(MyTriangle.Data[0]). }
60 property Items [const Index: TIndex]: TVector3 read GetItems write SetItems; default;
61
62 { Multiline triangle description. }
63 function ToString: string;
64
65 { Check does the triangle define a correct plane in 3D space.
66 That is, check does the triangle not degenerate to a point or line segment
67 (which can happen when some points are at the same position, or are colinear). }
68 function IsValid: boolean;
69
70 { Like a normal vector of a triangle (see @link(Normal)), but not necessarily normalized. }
71 function Direction: TVector3;
72
73 { Normal vector of a triangle. Returns vector pointing our from CCW triangle
74 side (for right-handed coordinate system), and orthogonal to triangle plane.
75 For degenerated triangles (when @link(IsValid) would return @false),
76 we return zero vector. }
77 function Normal: TVector3;
78
79 { Plane of the triangle. Note that this has many possible solutions
80 (plane representation as equation @code(Ax + By + Cz + D = 0)
81 is not unambiguous), this just returns some solution deterministically.
82
83 It's guaranteed that the direction of this plane (i.e. first 3 items
84 of returned vector) will be in the same direction as calcualted by
85 @link(Direction), which means that it points outward from CCW side of
86 the triangle (assuming right-handed coord system).
87
88 For NormalizedPlane, this direction is also normalized
89 (makes a vector with length 1). This way NormalizedPlane calculates
90 also @link(Normal).
91
92 For three points that do not define a plane, a plane with first three
93 components = 0 is returned. In fact, the 4th component will be zero too
94 in this case (for now), but don't depend on it.
95 @groupBegin }
96 function Plane: TVector4;
97 function NormalizedPlane: TVector4;
98
99 { Transform triangle by 4x4 matrix. This simply transforms each triangle point.
100
101 @raises(ETransformedResultInvalid Raised when matrix
102 will transform some point to a direction (vector with 4th component
103 equal zero). In this case we just cannot interpret the result as a 3D point.) }
104 function Transform(const M: TMatrix4): TTriangle3;
105
106 { Surface area of 3D triangle.
107 This works for degenerated (equal to line segment or even single point)
108 triangles too: returns 0 for them.
109
110 @groupBegin }
111 function Area: Single;
112 function AreaSqr: Single;
113 { @groupEnd }
114
115 { Random triangle point, chosen with a constant density for triangle area. }
116 function RandomPoint: TVector3;
117
118 { For a given Point lying on a given Triangle, calculate it's barycentric
119 coordinates.
120
121 The resulting Barycentric coordinates can be used for linearly
122 interpolating values along the triangle, as they satisfy the equation:
123
124 @preformatted(
125 Result.X * Triangle.Data[0] +
126 Result.Y * Triangle.Data[1] +
127 Result.Z * Triangle.Data[2] = Point
128 )
129
130 See also [http://en.wikipedia.org/wiki/Barycentric_coordinate_system_%28mathematics%29] }
131 function Barycentric(const Point: TVector3): TVector3;
132 end;
133
134 TTriangle3List = {$ifdef FPC}specialize{$endif} TStructList<TTriangle3>;
135
136 PTriangle3 = ^TTriangle3;
137
138 { Triangle in 4D (or 3D homogeneous) space. }
139 TTriangle4 = record
140 Data: packed array [0..2] of TVector4;
141
142 { Multiline triangle description. }
143 function ToString: string;
144 end;
145
146 PTriangle4 = ^TTriangle4;
147
148 TTriangle2Single = TTriangle2 deprecated 'use TTriangle2';
149 TTriangle3Single = TTriangle3 deprecated 'use TTriangle3';
150 TTriangle4Single = TTriangle4 deprecated 'use TTriangle4';
151
152 PTriangle2Single = PTriangle2 deprecated 'use PTriangle2';
153 PTriangle3Single = PTriangle3 deprecated 'use PTriangle3';
154 PTriangle4Single = PTriangle4 deprecated 'use PTriangle4';
155
156 function Triangle2(const P0, P1, P2: TVector2): TTriangle2;
157 function Triangle3(const P0, P1, P2: TVector3): TTriangle3;
158
159 { Normal vector of a triangle defined as three indexes intro vertex array.
160 VerticesStride is the shift between vertex values in the array,
161 VerticesStride = 0 behaves like VerticesStride = SizeOf(TVector3). }
162 function IndexedTriangleNormal(const Indexes: TVector3Cardinal;
163 VerticesArray: PVector3; VerticesStride: integer): TVector3;
164
165 type
166 { Triangle expressed in particular coordinate system, for TTriangle. }
167 TTriangleGeometry = record
168 Triangle: TTriangle3;
169
170 { Area of the triangle. }
171 {$ifdef CONSERVE_TRIANGLE_MEMORY_MORE}
172 function Area: Single;
173 {$else}
174 Area: Single;
175 {$endif}
176
177 {$ifdef CONSERVE_TRIANGLE_MEMORY_MORE}
178 function Plane: TVector4;
179 function Normal: TVector3;
180 {$else}
181 case Integer of
182 0: ({ Triangle normal, a 3D plane containing our Triangle, with normalized
183 direction vector. }
184 Plane: TVector4;);
185 1: (Normal: TVector3;);
186 {$endif}
187 end;
188
189 { TFaceIndex ----------------------------------------------------------------- }
190
191 type
192 { Describe a range of indexes where the face (polygon and such) is located.
193
194 When a triangle is part of a face defined by the coordIndex field
195 (like in IndexedFaceSet) then this describes where
196 in this coordIndex this face is located. This is useful for
197 editing / removing a face corresponding to a given triangle.
198
199 Otherwise, both IndexBegin and IndexEnd are -1. }
200 TFaceIndex = record
201 IndexBegin, IndexEnd: Integer;
202 end;
203
204 TFaceIndexesList = {$ifdef FPC}specialize{$endif} TStructList<TFaceIndex>;
205
206 const
207 UnknownFaceIndex: TFaceIndex = (IndexBegin: -1; IndexEnd: -1);
208
209 { TTriangle ------------------------------------------------------------------ }
210
211 type
212 TMailboxTag = Int64;
213
214 { Triangle in 3D.
215 This object should always be initialized by @link(Init),
216 and updated only by it's methods (never modify fields of
217 this object directly). }
218 TTriangle = record
219 public
220 { Geometry of this item.
221 We need two geometry descriptions:
222
223 @unorderedList(
224
225 @item(Local is based on initial Triangle, given when constructing
226 this TTriangle. It's constant for this TTriangle. It's used
227 by octree collision routines, that is things like
228 TBaseTrianglesOctree.SphereCollision, TBaseTrianglesOctree.RayCollision
229 and such expect parameters in the same coord space.
230
231 This may be local coord space of this shape (this is used
232 by TShape.OctreeTriangles) or world coord space
233 (this is used by TCastleSceneCore.OctreeTriangles).)
234
235 @item(World is the geometry of Local transformed to be in world
236 coordinates. Initially, World is just a copy of Local.
237
238 If Local already contains world-space geometry, then World
239 can just remain constant, and so is always Local copy.
240
241 If Local contains local shape-space geometry, then World
242 will have to be updated by TTriangle.UpdateWorld whenever some octree item's
243 geometry will be needed in world coords. This will have to be
244 done e.g. by TBaseTrianglesOctree.XxxCollision for each returned item.)
245 ) }
246 Local, World: TTriangleGeometry;
247
248 { Shape containing this triangle.
249 This is always an instance of TShape class, but due
250 to unit dependencies it cannot be declared as such here.
251 Use CastleShapes unit to have a "record helper" method that returns
252 a Shape as TShape instance. }
253 InternalShape: TObject;
254
255 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
256 { Tag of an object (like a ray or a line segment)
257 for which we have saved an
258 intersection result. Intersection result is in
259 MailboxIsIntersection, MailboxIntersection, MailboxIntersectionDistance.
260
261 To make things correct, we obviously assume that every segment
262 and ray have different tags. Also, tag -1 is reserved.
263 In practice, we simply initialize MailboxSavedTag to -1,
264 and each new segment/ray get consecutive tags starting from 0.
265
266 @italic(History): a naive implementation at the beginning
267 was not using tags, instead I had MailboxState (empty, ray or segment)
268 and I was storing ray/line vectors (2 TVector3 values).
269 This had much larger size (6 * SizeOf(Single) + SizeOf(enum) = 28 bytes)
270 than tag, which is important (3D models have easily thousands of
271 TTriangle). And it took longer to compare and assign,
272 so it was working much slower.
273
274 @groupBegin }
275 MailboxSavedTag: TMailboxTag;
276 MailboxIsIntersection: boolean;
277 MailboxIntersection: TVector3;
278 MailboxIntersectionDistance: Single;
279 { @groupEnd }
280 {$endif}
281
282 {$ifndef CONSERVE_TRIANGLE_MEMORY}
283 { Normal vectors, at each triangle vertex. }
284 Normal: TTriangle3;
285
286 { Texture coordinates, for each triangle point.
287
288 Each texture coordinate is a 4D vector, since we may have 3D textures
289 referenced by 4D (homogeneous) coordinates. For normal 2D textures,
290 you can simply take the first 2 components of the vector,
291 and ignore the remaining 2 components. The 3th component is always
292 0 if was not specified (if model had only 2D texture coords).
293 The 4th component is always 1 if was not specified
294 (if model had only 2D or 3D texture coords).
295
296 In case of multi-texturing, this describes coordinates
297 of the first texture unit.
298 In case no texture is defined, this is undefined. }
299 TexCoord: TTriangle4;
300
301 { The indexes of this face, for editing / removing it.
302 See TFaceIndex. }
303 Face: TFaceIndex;
304 {$else}
305
306 { The indexes of this face, for editing / removing it.
307 See TFaceIndex. }
308 function Face: TFaceIndex;
309 {$endif not CONSERVE_TRIANGLE_MEMORY}
310
311 { Initialize new triangle.
312 Given ATriangle must satisfy ATriangle.IsValid. }
313 procedure Init(AShape: TObject;
314 const ATriangle: TTriangle3;
315 const ANormal: TTriangle3; const ATexCoord: TTriangle4;
316 const AFace: TFaceIndex);
317
318 { Check collisions between TTriangle and ray/segment.
319
320 Always use these routines to check for collisions,
321 to use mailboxes if possible. Mailboxes are used only if this was
322 compiled with TRIANGLE_OCTREE_USE_MAILBOX defined.
323
324 Increments TriangleCollisionTestsCounter if actual test was done
325 (that is, if we couldn't use mailbox to get the result quickier).
326
327 @groupBegin }
328 function SegmentDirCollision(
329 out Intersection: TVector3;
330 out IntersectionDistance: Single;
331 const Segment0, SegmentVector: TVector3;
332 const SegmentTag: TMailboxTag): boolean;
333
334 function RayCollision(
335 out Intersection: TVector3;
336 out IntersectionDistance: Single;
337 const RayOrigin, RayDirection: TVector3;
338 const RayTag: TMailboxTag): boolean;
339 { @groupEnd }
340
341 {$ifndef CONSERVE_TRIANGLE_MEMORY}
342
343 { For a given position (in world coordinates), return the texture
344 coordinate at this point. It is an interpolated texture coordinate
345 from our per-vertex texture coordinates in @link(TexCoord) field.
346
347 This assumes that Position actually lies within the triangle.
348
349 The ITexCoord2D returns the same, but cut to the first 2 texture
350 coordinate components. Usable for normal 2D textures.
351 @groupBegin }
352 function ITexCoord(const Point: TVector3): TVector4;
353 function ITexCoord2D(const Point: TVector3): TVector2;
354 { @groupEnd }
355
356 { For a given position (in world coordinates), return the smooth
357 normal vector at this point. It is an interpolated normal
358 from our per-vertex normals in the @link(Normal) field,
359 thus is supports also the case when you have smooth shading
360 (normals change throughout the triangle).
361
362 Like the @link(Normal) field, the returned vector is
363 a normal vector in the local coordinates.
364 Use @link(TTriangleHelper.INormalWorldSpace) to get a normal vector in scene
365 coordinates.
366
367 This assumes that Position actally lies within the triangle. }
368 function INormal(const Point: TVector3): TVector3;
369
370 { Like INormal, but not necessarily normalized. }
371 function INormalCore(const Point: TVector3): TVector3;
372 {$endif}
373 end;
374 PTriangle = ^TTriangle;
375
376 TTriangleList = {$ifdef FPC}specialize{$endif} TStructList<TTriangle>;
377
378 { Return for given Triangle do we want to ignore collisions with it.
379 For now, Sender is always TTriangleOctree. }
380 TTriangleIgnoreFunc = function (const Sender: TObject;
381 const Triangle: PTriangle): boolean of object;
382
383 { Triangle information, called by TShape.LocalTriangulate and such.
384 See the @link(TTriangle) fields documentation for the meaning
385 of parameters of this callback. }
386 TTriangleEvent = procedure (Shape: TObject;
387 const Position: TTriangle3;
388 const Normal: TTriangle3; const TexCoord: TTriangle4;
389 const Face: TFaceIndex) of object;
390
391 T3DTriangleGeometry = TTriangleGeometry deprecated 'use TTriangleGeometry';
392 T3DTriangle = TTriangle deprecated 'use TTriangle';
393 P3DTriangle = PTriangle deprecated 'use PTriangle';
394 T3DTriangleIgnoreFunc = TTriangleIgnoreFunc deprecated 'use TTriangleIgnoreFunc';
395
396 var
397 { Counter of collision tests done by TTriangle when the actual collision
398 calculation had to be done.
399 This counts all calls to TTriangle.SegmentDirCollision and
400 TTriangle.RayCollision when the result had to be actually geometrically
401 calculated (result was not in the cache aka "mailbox").
402
403 It is especially useful to look at this after using some spatial
404 data structure, like an octree. The goal of tree structures is to
405 minimize this number.
406
407 It is a global variable, because that's the most comfortable way to use
408 it. Triangles are usually wrapped in an octree (like TTriangleOctree),
409 or even in an octree of octrees (like TShapeOctree).
410 Tracking collisions using the global variable is most comfortable,
411 instead of spending time on propagating this (purely debugging) information
412 through the octree structures. }
413 TriangleCollisionTestsCounter: Cardinal;
414
415 { polygons ------------------------------------------------------------------- }
416
417 { Calculates normalized normal vector for polygon composed from
418 indexed vertices. Polygon is defines as vertices
419 Verts^[Indices[0]], Verts^[Indices[1]] ... Verts^[Indices[IndicesCount-1]].
420 Returns normal pointing from CCW.
421
422 It's secured against invalid indexes on Indices list (that's the only
423 reason why it takes VertsCount parameter, after all): they are ignored.
424
425 If the polygon is degenerated, that is it doesn't determine a plane in
426 3D space (this includes, but is not limited, to cases when there are
427 less than 3 valid points, like when IndicesCount < 3)
428 then it returns ResultForIncorrectPoly.
429
430 @groupBegin }
431 function IndexedConvexPolygonNormal(
432 Indices: PInt32Array; IndicesCount: integer;
433 Verts: PVector3Array; const VertsCount: Integer;
434 const ResultForIncorrectPoly: TVector3): TVector3; overload;
435 function IndexedConvexPolygonNormal(
436 const Indices: PInt32Array; const IndicesCount: integer;
437 const Verts: PVector3Array; const VertsCount: Integer;
438 const VertsStride: PtrUInt;
439 const ResultForIncorrectPoly: TVector3): TVector3; overload;
440 { @groupEnd }
441
442 { Surface area of indexed convex polygon.
443 Polygon is defines as vertices
444 Verts^[Indices[0]], Verts^[Indices[1]] ... Verts^[Indices[IndicesCount-1]].
445
446 It's secured against invalid indexes on Indices list (that's the only
447 reason why it takes VertsCount parameter, after all): they are ignored.
448
449 @groupBegin }
450 function IndexedConvexPolygonArea(
451 const Indices: PInt32Array; const IndicesCount: integer;
452 const Verts: PVector3Array; const VertsCount: Integer): Single; overload;
453 function IndexedConvexPolygonArea(
454 const Indices: PInt32Array; const IndicesCount: integer;
455 const Verts: PVector3Array; const VertsCount: Integer;
456 const VertsStride: PtrUInt): Single; overload;
457 { @groupEnd }
458
459 { Are the polygon points ordered CCW (counter-clockwise). When viewed
460 with typical camera settings, that is +Y goes up and +X goes right.
461
462 Polygon doesn't have to be convex. Polygon doesn't have to have all triangles
463 valid, that is it's OK if some polygon triangles degenerate into points
464 or line segments.
465
466 Returns something > 0 if polygon is CCW, or < 0 when it's not.
467 Returns zero when polygon has area 0.
468 @groupBegin }
469 function IsPolygon2dCCW(Verts: PVector2Array; const VertsCount: Integer): Single; overload;
470 function IsPolygon2dCCW(const Verts: array of TVector2): Single; overload;
471 { @groupEnd }
472
473 { Calculate polygon area.
474
475 Polygon doesn't have to be convex. Polygon doesn't have to have all triangles
476 valid, that is it's OK if some polygon triangles degenerate into points
477 or line segments.
478
479 @groupBegin }
480 function Polygon2dArea(Verts: PVector2Array; const VertsCount: Integer): Single; overload;
481 function Polygon2dArea(const Verts: array of TVector2): Single; overload;
482 { @groupEnd }
483
484 { Assuming a point lies on a triangle plane,
485 check does it lie inside a triangle.
486 Give first 3 components of triangle plane as TriDir.
487 @groupBegin }
488 function IsPointOnTrianglePlaneWithinTriangle(const P: TVector3;
489 const Tri: TTriangle3; const TriDir: TVector3): boolean; overload;
490 { @groupEnd }
491
492 { Check does point lie inside a triangle, in 2D.
493 @groupBegin }
494 function IsPointWithinTriangle2D(const P: TVector2;
495 const Tri: TTriangle2): boolean; overload;
496 function IsPointWithinTriangle2D(const P: TVector2;
497 const Tri: TTriangle3): boolean; overload;
498 { @groupEnd }
499
500 { Check triangle with line segment collision.
501 You can pass the triangle plane along with a triangle,
502 this will speed calculation.
503 @groupBegin }
504 function IsTriangleSegmentCollision(const Tri: TTriangle3;
505 const TriPlane: TVector4;
506 const Pos1, Pos2: TVector3): boolean; overload;
507 function IsTriangleSegmentCollision(const Tri: TTriangle3;
508 const Pos1, Pos2: TVector3): boolean; overload;
509 { @groupEnd }
510
511 function IsTriangleSphereCollision(const Tri: TTriangle3;
512 const TriPlane: TVector4;
513 const SphereCenter: TVector3; SphereRadius: Single): boolean; overload;
514 function IsTriangleSphereCollision(const Tri: TTriangle3;
515 const SphereCenter: TVector3; SphereRadius: Single): boolean; overload;
516
517 { Test collision between triangle and sphere in 2D.
518 If you use overloaded version with TTriangle3, the Z coordinate
519 of the triangle corners is simply ignored, so everything is projected
520 on the Z=0 plane.
521 @groupBegin }
522 function IsTriangleSphereCollision2D(const Tri: TTriangle2;
523 const SphereCenter: TVector2; SphereRadius: Single): boolean; overload;
524 function IsTriangleSphereCollision2D(const Tri: TTriangle3;
525 const SphereCenter: TVector2; SphereRadius: Single): boolean; overload;
526 { @groupEnd }
527
528 { Calculate triangle with line segment collision.
529 You can pass the triangle plane along with a triangle,
530 this will speed calculation.
531
532 When there's no intersection, returns @false and doesn't modify Intersection
533 or T.
534 @groupBegin }
535 function TryTriangleSegmentCollision(var Intersection: TVector3;
536 const Tri: TTriangle3; const TriPlane: TVector4;
537 const Pos1, Pos2: TVector3): boolean; overload;
538
539 function TryTriangleSegmentDirCollision(var Intersection: TVector3;
540 const Tri: TTriangle3; const TriPlane: TVector4;
541 const Segment0, SegmentVector: TVector3): boolean; overload;
542 function TryTriangleSegmentDirCollision(var Intersection: TVector3; var T: Single;
543 const Tri: TTriangle3; const TriPlane: TVector4;
544 const Segment0, SegmentVector: TVector3): boolean; overload;
545 { @groupEnd }
546
547 { Calculate triangle with ray collision.
548 You can pass the triangle plane along with a triangle,
549 this will speed calculation.
550
551 When there's no intersection, returns @false and doesn't modify Intersection
552 or T.
553 @groupBegin }
554 function TryTriangleRayCollision(var Intersection: TVector3;
555 const Tri: TTriangle3; const TriPlane: TVector4;
556 const RayOrigin, RayDirection: TVector3): boolean; overload;
557 function TryTriangleRayCollision(var Intersection: TVector3; var T: Single;
558 const Tri: TTriangle3; const TriPlane: TVector4;
559 const RayOrigin, RayDirection: TVector3): boolean; overload;
560 { @groupEnd }
561
562 function TriangleDirection(const p0, p1, p2: TVector3): TVector3; overload;
563 function TriangleDir(const p0, p1, p2: TVector3): TVector3; overload; deprecated 'use TriangleDirection';
564 function TriangleNormal(const p0, p1, p2: TVector3): TVector3; overload;
565 function TrianglePlane(const p0, p1, p2: TVector3): TVector4; overload;
566
567 function TriangleDir(const T: TTriangle3): TVector3; overload; deprecated 'use Triangle.Direction';
568 function TriangleNormal(const T: TTriangle3): TVector3; overload; deprecated 'use Triangle.Normal';
569 function TrianglePlane(const T: TTriangle3): TVector4; overload; deprecated 'use Triangle.Plane';
570 function TriangleTransform(const T: TTriangle3; const M: TMatrix4): TTriangle3; deprecated 'use Triangle.Transform';
571 function TriangleNormPlane(const T: TTriangle3): TVector4; deprecated 'use Triangle.NormalizedPlane';
572 function TriangleArea(const T: TTriangle3): Single; deprecated 'use Triangle.Area';
573 function Barycentric(const T: TTriangle3; const Point: TVector3): TVector3; deprecated 'use Triangle.Barycentric';
574 function TriangleToNiceStr(const T: TTriangle3): string; deprecated 'use T.ToString';
575
576 { Calculate tangent (along texture S coordinate, when IsTangent) or bitangent
577 (along texture T coordinate, when IsTangent=false),
578 knowing positions and texture coordinates.
579
580 This procedure can change Triangle*, but only by swapping some vertexes,
581 so we pass Triangle* by reference instead of by value, to avoid
582 needless mem copying.
583
584 Returns @false if cannot be calculated. }
585 function CalculateTangent(const IsTangent: boolean; out Tangent: TVector3;
586 var TriangleCoord: TTriangle3;
587 var TriangleTexCoord: TTriangle2): Boolean;
588
589 implementation
590
591 uses Math;
592
593 function Triangle2(const P0, P1, P2: TVector2): TTriangle2;
594 begin
595 Result.Data[0] := P0;
596 Result.Data[1] := P1;
597 Result.Data[2] := P2;
598 end;
599
600 function Triangle3(const P0, P1, P2: TVector3): TTriangle3;
601 begin
602 Result.Data[0] := P0;
603 Result.Data[1] := P1;
604 Result.Data[2] := P2;
605 end;
606
607 function IndexedTriangleNormal(const Indexes: TVector3Cardinal;
608 VerticesArray: PVector3; VerticesStride: integer): TVector3;
609 var
610 Tri: TTriangle3;
611 i: integer;
612 begin
613 if VerticesStride = 0 then VerticesStride := SizeOf(TVector3);
614 for i := 0 to 2 do
615 Tri.Data[i] := PVector3(PointerAdd(VerticesArray, VerticesStride*Integer(Indexes[i])))^;
616 Result := Tri.Normal;
617 end;
618
619 function IndexedConvexPolygonNormal(
620 Indices: PInt32Array; IndicesCount: integer;
621 Verts: PVector3Array; const VertsCount: Integer;
622 const ResultForIncorrectPoly: TVector3): TVector3;
623 begin
624 Result := IndexedConvexPolygonNormal(
625 Indices, IndicesCount,
626 Verts, VertsCount, SizeOf(TVector3),
627 ResultForIncorrectPoly);
628 end;
629
630 function IndexedConvexPolygonNormal(
631 const Indices: PInt32Array; const IndicesCount: integer;
632 const Verts: PVector3Array; const VertsCount: Integer;
633 const VertsStride: PtrUInt;
634 const ResultForIncorrectPoly: TVector3): TVector3;
635
636 { Like Verts^[Indices[I]] but takes into account VertsStride. }
637 function VertsIndices(const I: Integer): PVector3;
638 begin
639 Result := PVector3(PtrUInt(Verts) + PtrUInt(Indices^[I]) * VertsStride);
640 end;
641
642 var
643 Tri: TTriangle3;
644 I: Integer;
645 begin
646 { We calculate normal vector as an average of normal vectors of
647 polygon's triangles. Not taking into account invalid Indices
648 (pointing beyond the VertsCount range) and degenerated triangles.
649
650 This isn't the fastest method possible, but it's safest.
651 It works Ok even if the polygon isn't precisely planar, or has
652 some degenerate triangles. }
653
654 Result := TVector3.Zero;
655
656 I := 0;
657
658 while (I < IndicesCount) and (Indices^[I] >= VertsCount) do Inc(I);
659 { This secures us against polygons with no valid Indices[].
660 (including case when IndicesCount = 0). }
661 if I >= IndicesCount then
662 Exit(ResultForIncorrectPoly);
663 Tri.Data[0] := VertsIndices(I)^;
664
665 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
666 if I >= IndicesCount then
667 Exit(ResultForIncorrectPoly);
668 Tri.Data[1] := VertsIndices(I)^;
669
670 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
671 if I >= IndicesCount then
672 Exit(ResultForIncorrectPoly);
673 Tri.Data[2] := VertsIndices(I)^;
674
675 if Tri.IsValid then
676 Result := Result + Tri.Normal;
677
678 repeat
679 { find next valid point, which makes another triangle of polygon }
680
681 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
682 if I >= IndicesCount then
683 Break;
684 Tri.Data[1] := Tri.Data[2];
685 Tri.Data[2] := VertsIndices(I)^;
686
687 if Tri.IsValid then
688 Result := Result + Tri.Normal;
689 until false;
690
691 { All triangle normals are summed up now. (Each triangle normal was also
692 normalized, to have equal contribution to the Result.)
693 Normalize Result now, if we had any valid triangle. }
694 if Result.IsZero then
695 Result := ResultForIncorrectPoly
696 else
697 Result := Result.Normalize;
698 end;
699
700 function IndexedConvexPolygonArea(
701 const Indices: PInt32Array; const IndicesCount: integer;
702 const Verts: PVector3Array; const VertsCount: Integer): Single;
703 begin
704 Result := IndexedConvexPolygonArea(
705 Indices, IndicesCount,
706 Verts, VertsCount, SizeOf(TVector3));
707 end;
708
709 function IndexedConvexPolygonArea(
710 const Indices: PInt32Array; const IndicesCount: integer;
711 const Verts: PVector3Array; const VertsCount: Integer;
712 const VertsStride: PtrUInt): Single;
713
714 { Like Verts^[Indices[I]] but takes into account VertsStride. }
715 function VertsIndices(const I: Integer): PVector3;
716 begin
717 Result := PVector3(PtrUInt(Verts) + PtrUInt(Indices^[I]) * VertsStride);
718 end;
719
720 var
721 Tri: TTriangle3;
722 i: integer;
723 begin
724 { We calculate area as a sum of areas of
725 polygon's triangles. Not taking into account invalid Indices
726 (pointing beyond the VertsCount range). }
727
728 Result := 0;
729
730 I := 0;
731
732 while (I < IndicesCount) and (Indices^[I] >= VertsCount) do Inc(I);
733 { This secures us against polygons with no valid Indices[].
734 (including case when IndicesCount = 0). }
735 if I >= IndicesCount then
736 Exit;
737 Tri.Data[0] := VertsIndices(I)^;
738
739 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
740 if I >= IndicesCount then
741 Exit;
742 Tri.Data[1] := VertsIndices(I)^;
743
744 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
745 if I >= IndicesCount then
746 Exit;
747 Tri.Data[2] := VertsIndices(I)^;
748
749 Result := Result + Tri.Area;
750
751 repeat
752 { find next valid point, which makes another triangle of polygon }
753
754 repeat Inc(I) until (I >= IndicesCount) or (Indices^[I] < VertsCount);
755 if I >= IndicesCount then
756 Break;
757 Tri.Data[1] := Tri.Data[2];
758 Tri.Data[2] := VertsIndices(I)^;
759
760 Result := Result + Tri.Area;
761 until false;
762 end;
763
764 function IsPolygon2dCCW(Verts: PVector2Array; const VertsCount: Integer): Single;
765 { licz pole polygonu CCW.
766
767 Implementacja na podstawie "Graphic Gems II", gem I.1
768 W Graphic Gems pisza ze to jest formula na polygon CCW (na plaszczyznie
769 kartezjanskiej, z +X w prawo i +Y w gore) i nie podaja tego Abs() na koncu.
770 Widac jednak ze jesli podamy zamiast wielokata CCW ten sam wielokat ale
771 z wierzcholkami w odwrotnej kolejnosci to procedura policzy dokladnie to samo
772 ale skosy dodatnie zostana teraz policzone jako ujemne a ujemne jako dodatnie.
773 Czyli dostaniemy ujemne pole.
774
775 Mozna wiec wykorzystac powyzszy fakt aby testowac czy polygon jest CCW :
776 brac liczona tu wartosc i jesli >0 to CCW, <0 to CW
777 (jesli =0 to nie wiadomo no i polygony o polu = 0 rzeczywiscie nie maja
778 jednoznacznej orientacji). Moznaby pomyslec ze mozna znalezc prostsze
779 testy na to czy polygon jest CCW - mozna przeciez testowac tylko wyciety
780 z polygonu trojkat. Ale uwaga - wtedy trzebaby uwazac i koniecznie
781 wybrac z polygonu niezdegenerowany trojkat (o niezerowym polu),
782 no chyba ze caly polygon mialby zerowe pole. Tak jak jest nie trzeba
783 sie tym przejmowac i jest prosto.
784
785 W ten sposob ponizsza procedura jednoczesnie liczy pole polygonu
786 (Polygon2dArea jest zaimplementowane jako proste Abs() z wyniku tej
787 funkcji. }
788 var
789 i: Integer;
790 begin
791 Result := 0.0;
792 if VertsCount = 0 then Exit;
793
794 { licze i = 0..VertsCount-2, potem osobno przypadek gdy i = VertsCount-1.
795 Moglbym ujac je razem, dajac zamiast "Verts^[i+1, 1]"
796 "Verts^[(i+1)mod VertsCount, 1]" ale szkoda byloby dawac tu "mod" na potrzebe
797 tylko jednego przypadku. Tak jest optymalniej czasowo. }
798 for i := 0 to VertsCount-2 do
799 Result := Result +
800 Verts^[i].X * Verts^[i+1].Y -
801 Verts^[i].Y * Verts^[i+1].X;
802 Result := Result +
803 Verts^[VertsCount-1].X * Verts^[0].Y -
804 Verts^[VertsCount-1].Y * Verts^[0].X;
805 Result := Result / 2;
806 end;
807
808 function IsPolygon2dCCW(const Verts: array of TVector2): Single;
809 begin
810 Result := IsPolygon2dCCW(@Verts, High(Verts)+1);
811 end;
812
813 function Polygon2dArea(Verts: PVector2Array; const VertsCount: Integer): Single;
814 begin
815 Result := Abs(IsPolygon2dCCW(Verts, VertsCount));
816 end;
817
818 function Polygon2dArea(const Verts: array of TVector2): Single;
819 { We depend on the (internal) fact that IsPolygonCCW
820 returns an area in case of CCW, or -area in case of CW polygon. }
821 begin
822 Result := Polygon2dArea(@Verts, High(Verts) + 1);
823 end;
824
825 { TTriangleGeometry -------------------------------------------------------- }
826
827 {$ifdef CONSERVE_TRIANGLE_MEMORY_MORE}
828 function TTriangleGeometry.Area: Single;
829 begin
830 Result := Triangle.Area;
831 end;
832
833 function TTriangleGeometry.Plane: TVector4;
834 begin
835 Result := Triangle.NormalizedPlane;
836 end;
837
838 function TTriangleGeometry.Normal: TVector3;
839 begin
840 Result := Triangle.Normal;
841 end;
842 {$endif}
843
844 { TTriangle --------------------------------------------------------------- }
845
846 procedure TTriangle.Init(AShape: TObject;
847 const ATriangle: TTriangle3;
848 const ANormal: TTriangle3; const ATexCoord: TTriangle4;
849 const AFace: TFaceIndex);
850 begin
851 Local.Triangle := ATriangle;
852 {$ifndef CONSERVE_TRIANGLE_MEMORY_MORE}
853 Local.Plane := ATriangle.NormalizedPlane;
854 Local.Area := ATriangle.Area;
855 {$endif}
856
857 World := Local;
858
859 InternalShape := AShape;
860
861 {$ifndef CONSERVE_TRIANGLE_MEMORY}
862 Normal := ANormal;
863 TexCoord := ATexCoord;
864 Face := AFace;
865 {$endif not CONSERVE_TRIANGLE_MEMORY}
866
867 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
868 MailboxSavedTag := -1;
869 {$endif}
870 end;
871
872 function TTriangle.SegmentDirCollision(
873 out Intersection: TVector3;
874 out IntersectionDistance: Single;
875 const Segment0, SegmentVector: TVector3;
876 const SegmentTag: TMailboxTag): boolean;
877 begin
878 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
879 if MailboxSavedTag = SegmentTag then
880 begin
881 result := MailboxIsIntersection;
882 if result then
883 begin
884 Intersection := MailboxIntersection;
885 IntersectionDistance := MailboxIntersectionDistance;
886 end;
887 end else
888 begin
889 {$endif}
890
891 Result := TryTriangleSegmentDirCollision(
892 Intersection, IntersectionDistance,
893 Local.Triangle, Local.Plane,
894 Segment0, SegmentVector);
895 Inc(TriangleCollisionTestsCounter);
896
897 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
898 { save result to mailbox }
899 MailboxSavedTag := SegmentTag;
900 MailboxIsIntersection := result;
901 if result then
902 begin
903 MailboxIntersection := Intersection;
904 MailboxIntersectionDistance := IntersectionDistance;
905 end;
906 end;
907 {$endif}
908 end;
909
910 function TTriangle.RayCollision(
911 out Intersection: TVector3;
912 out IntersectionDistance: Single;
913 const RayOrigin, RayDirection: TVector3;
914 const RayTag: TMailboxTag): boolean;
915 begin
916 { uwzgledniam tu fakt ze czesto bedzie wypuszczanych wiele promieni
917 z jednego RayOrigin ale z roznym RayDirection (np. w raytracerze). Wiec lepiej
918 najpierw porownywac przechowywane w skrzynce RayDirection (niz RayOrigin)
919 zeby moc szybciej stwierdzic niezgodnosc. }
920 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
921 if MailboxSavedTag = RayTag then
922 begin
923 result := MailboxIsIntersection;
924 if result then
925 begin
926 Intersection := MailboxIntersection;
927 IntersectionDistance := MailboxIntersectionDistance;
928 end;
929 end else
930 begin
931 {$endif}
932
933 result := TryTriangleRayCollision(
934 Intersection, IntersectionDistance,
935 Local.Triangle, Local.Plane,
936 RayOrigin, RayDirection);
937 Inc(TriangleCollisionTestsCounter);
938
939 {$ifdef TRIANGLE_OCTREE_USE_MAILBOX}
940 { zapisz wyniki do mailboxa }
941 MailboxSavedTag := RayTag;
942 MailboxIsIntersection := result;
943 if result then
944 begin
945 MailboxIntersection := Intersection;
946 MailboxIntersectionDistance := IntersectionDistance;
947 end;
948 end;
949 {$endif}
950 end;
951
952 {$ifndef CONSERVE_TRIANGLE_MEMORY}
953 function TTriangle.ITexCoord(const Point: TVector3): TVector4;
954 var
955 B: TVector3;
956 begin
957 B := World.Triangle.Barycentric(Point);
958 Result := TexCoord.Data[0] * B[0] +
959 TexCoord.Data[1] * B[1] +
960 TexCoord.Data[2] * B[2];
961 end;
962
963 function TTriangle.ITexCoord2D(const Point: TVector3): TVector2;
964 var
965 V: TVector4;
966 begin
967 V := ITexCoord(Point);
968 Move(V, Result, SizeOf(TVector2));
969 end;
970
971 function TTriangle.INormalCore(const Point: TVector3): TVector3;
972 var
973 B: TVector3;
974 begin
975 B := World.Triangle.Barycentric(Point);
976 Result := Normal[0] * B[0] +
977 Normal[1] * B[1] +
978 Normal[2] * B[2];
979 end;
980
981 function TTriangle.INormal(const Point: TVector3): TVector3;
982 begin
983 Result := INormalCore(Point).Normalize;
984 end;
985
986 {$else}
987 function TTriangle.Face: TFaceIndex;
988 begin
989 Result := UnknownFaceIndex;
990 end;
991 {$endif not CONSERVE_TRIANGLE_MEMORY}
992
993 { TTriangle2 ----------------------------------------------------------------- }
994
995 function TTriangle2.ToString: string;
996 begin
997 Result :=
998 Data[0].ToString + NL +
999 Data[1].ToString + NL +
1000 Data[2].ToString + NL;
1001 end;
1002
1003 { TTriangle3 ----------------------------------------------------------------- }
1004
1005 function TTriangle3.IsValid: boolean;
1006 begin
1007 (* We want to check is Tri a "non-degenerated" triangle,
1008 i.e. does not determine a plane in 3D.
1009 So all points must be different, and also must not be colinear.
1010
1011 We can check this by checking
1012 TVector3.CrossProduct(
1013 (Data[2] - Data[1]),
1014 (Data[0] - Data[1])).Length > 0.
1015
1016 This actually exactly corresponds to saying "this triangle has non-zero area".
1017 It also measn that TrianglePlane is non-zero, since it uses the same
1018 TVector3.CrossProduct.
1019 You can calculate this using TTriangle3.Direction, since TTriangle3.Direction calculates
1020 exactly this TVector3.CrossProduct.
1021 *)
1022
1023 { This is incorrect:
1024 It would detect as invalid too much (the tests/data/model_manifold.wrl
1025 would fail then, not all edges detected manifold). }
1026 // Result := not IsZero(Direction.LengthSqr);
1027
1028 { This is incorrect:
1029 It would detect as invalid still too much (the
1030 examples/research_special_rendering_methods/radiance_transfer/data/chinchilla.wrl.gz
1031 would be black then, and not pickable) }
1032 // Result := Direction.LengthSqr > Sqr(SingleEpsilon);
1033
1034 { This used to be used in Castle Game Engine 6.2, and seems to work OK.
1035 But it feels wrong: we can make a valid, arbitrarily small triangle,
1036 and thus any epsilon is wrong. }
1037 // Result := Direction.LengthSqr > Sqr(1e-7);
1038
1039 { This is safer, but slower.
1040 Makes 2 normalizations and this way it can use a larger epsilon.
1041 But it is still not perfect, as TTestCastleTriangles.TestIsValid shows.
1042 This detects as invalid
1043
1044 T[0] := Vector3(5, 0.01, 0);
1045 T[1] := Vector3(0, 0, 0);
1046 T[2] := Vector3(10, 0, 0);
1047 AssertTrue('23', T.IsValid);
1048
1049 ... and only changing 0.01 to 0.1 helps to make it valid.
1050 }
1051 // Result := not IsZero(TVector3.CrossProduct(
1052 // (Data[2] - Data[1]).Normalize,
1053 // (Data[0] - Data[1]).Normalize
1054 // ).LengthSqr);
1055
1056 { This is simple, fast and correct according to tests. }
1057 Result := Direction.LengthSqr > 0;
1058 end;
1059
1060 function TTriangle3.Direction: TVector3;
1061 begin
1062 Result := TVector3.CrossProduct(
1063 Data[2] - Data[1],
1064 Data[0] - Data[1]);
1065 end;
1066
1067 function TTriangle3.Normal: TVector3;
1068 begin
1069 Result := Direction.Normalize;
1070 end;
1071
1072 function TTriangle3.Plane: TVector4;
1073 var
1074 ResultDir: TVector3 absolute Result;
1075 begin
1076 ResultDir := Direction;
1077 (* Punkt Data[0] musi lezec na plane Result. Wiec musi zachodzic
1078
1079 ResulrDir.X * Data[0].X +
1080 ResulrDir.Y * Data[0].Y +
1081 ResulrDir.Z * Data[0].Z
1082 + Result.W = 0
1083
1084 Stad widac jak wyznaczyc Result[3]. *)
1085 Result.W :=
1086 -ResultDir.X * Data[0].X
1087 -ResultDir.Y * Data[0].Y
1088 -ResultDir.Z * Data[0].Z;
1089 end;
1090
1091 function TTriangle3.NormalizedPlane: TVector4;
1092 var
1093 ResultNormal: TVector3 absolute Result;
1094 begin
1095 (* dzialamy tak samo jak TrianglePlane tyle ze teraz uzywamy TriangleNormal
1096 zamiast TriangleNormalNotNorm *)
1097 ResultNormal := Normal;
1098 Result.W :=
1099 -ResultNormal.X * Data[0].X
1100 -ResultNormal.Y * Data[0].Y
1101 -ResultNormal.Z * Data[0].Z;
1102 end;
1103
1104 function TTriangle3.Transform(const M: TMatrix4): TTriangle3;
1105 begin
1106 Result.Data[0] := M.MultPoint(Data[0]);
1107 Result.Data[1] := M.MultPoint(Data[1]);
1108 Result.Data[2] := M.MultPoint(Data[2]);
1109 end;
1110
1111 function TTriangle3.Area: Single;
1112 begin
1113 Result := TVector3.CrossProduct(
1114 Data[1] - Data[0],
1115 Data[2] - Data[0]).Length / 2;
1116 end;
1117
1118 function TTriangle3.AreaSqr: Single;
1119 begin
1120 Result := TVector3.CrossProduct(
1121 Data[1] - Data[0],
1122 Data[2] - Data[0]).LengthSqr / 4;
1123 end;
1124
1125 function TTriangle3.ToString: string;
1126 begin
1127 Result :=
1128 Data[0].ToString + NL +
1129 Data[1].ToString + NL +
1130 Data[2].ToString + NL;
1131 end;
1132
1133 function TTriangle3.RandomPoint: TVector3;
1134 var
1135 r1Sqrt, r2: Single;
1136 begin
1137 { Based on "Global Illumination Compendium" }
1138 r1Sqrt := Sqrt(Random);
1139 r2 := Random;
1140 Result :=
1141 (Data[0] * (1 - r1Sqrt) ) +
1142 (Data[1] * ((1 - r2) * r1Sqrt) ) +
1143 (Data[2] * (r2 * r1Sqrt) );
1144 end;
1145
1146 function TTriangle3.Barycentric(const Point: TVector3): TVector3;
1147
1148 { TODO: a tiny bit of CastleBoxes unit used here, to prevent any dependency
1149 from CastleVectors to CastleBoxes. }
1150 type
1151 TBox3D = record
1152 Data: array [0..1] of TVector3;
1153 end;
1154
1155 function Box3DSizes(const Box: TBox3D): TVector3;
1156 begin
1157 Result.X := Box.Data[1].X - Box.Data[0].X;
1158 Result.Y := Box.Data[1].Y - Box.Data[0].Y;
1159 Result.Z := Box.Data[1].Z - Box.Data[0].Z;
1160 end;
1161
1162 function TriangleBoundingBox: TBox3D;
1163 begin
1164 MinMax(Data[0].X, Data[1].X, Data[2].X, Result.Data[0].X, Result.Data[1].X);
1165 MinMax(Data[0].Y, Data[1].Y, Data[2].Y, Result.Data[0].Y, Result.Data[1].Y);
1166 MinMax(Data[0].Z, Data[1].Z, Data[2].Z, Result.Data[0].Z, Result.Data[1].Z);
1167 end;
1168
1169 var
1170 C1, C2: T3DAxis;
1171 Det: Single;
1172 begin
1173 { Map triangle and point into 2D, where the solution is simpler.
1174 Calculate C1 and C2 --- two largest coordinates of
1175 triangle axis-aligned bounding box. }
1176 RestOf3DCoords(MinVectorCoord(Box3DSizes(TriangleBoundingBox)), C1, C2);
1177
1178 { Now calculate coordinates on 2D, following equations at wikipedia }
1179 Det :=
1180 (Data[1][C2] - Data[2][C2]) * (Data[0][C1] - Data[2][C1]) +
1181 (Data[0][C2] - Data[2][C2]) * (Data[2][C1] - Data[1][C1]);
1182 Result.X := (
1183 (Data[1][C2] - Data[2][C2]) * ( Point[C1] - Data[2][C1]) +
1184 ( Point[C2] - Data[2][C2]) * (Data[2][C1] - Data[1][C1])
1185 ) / Det;
1186 Result.Y := (
1187 ( Point[C2] - Data[2][C2]) * (Data[0][C1] - Data[2][C1]) +
1188 (Data[2][C2] - Data[0][C2]) * ( Point[C1] - Data[2][C1])
1189 ) / Det;
1190 Result.Z := 1 - Result.X - Result.Y;
1191 end;
1192
1193 function TTriangle3.GetItems(const Index: TIndex): TVector3;
1194 begin
1195 Result := Data[Index];
1196 end;
1197
1198 procedure TTriangle3.SetItems(const Index: TIndex; const Value: TVector3);
1199 begin
1200 Data[Index] := Value;
1201 end;
1202
1203 { TTriangle4 ----------------------------------------------------------------- }
1204
1205 function TTriangle4.ToString: string;
1206 begin
1207 Result :=
1208 Data[0].ToString + NL +
1209 Data[1].ToString + NL +
1210 Data[2].ToString + NL;
1211 end;
1212
1213 { others --------------------------------------------------------------------- }
1214
1215 function IsPointOnTrianglePlaneWithinTriangle(const P: TVector3;
1216 const Tri: TTriangle3; const TriDir: TVector3): boolean;
1217
1218 { We tried many approaches for this:
1219 - Check do three angles:
1220 between vectors (t[0]-p) and (t[1]-p),
1221 between vectors (t[1]-p) and (t[2]-p),
1222 between vectors (t[2]-p) and (t[0]-p)
1223 sum to full 360 stopni.
1224 - Cast triangle on the most suitable 2D plane, and check there.
1225
1226 The current algorithm is very slightly faster than the above. It's based on
1227 http://geometryalgorithms.com/Archive/algorithm_0105/algorithm_0105.htm
1228 (still accessible through
1229 http://web.archive.org/web/20081018162011/http://www.geometryalgorithms.com/Archive/algorithm_0105/algorithm_0105.htm
1230 ).
1231
1232 Idea:
1233 - Every point on the plane of our triangle may be expressed as s,t, such that
1234 point = tri[0] + s*u + t*v, where u = tri[1]-tri[0], v = tri[2]-tri[0].
1235 This way 2 triangle edges determine the 2D coordinates axes,
1236 analogous to normal OX and OY axes on a 2D plane.
1237 (We only handle non-degenerate triangles is, so we can assume that
1238 all triangle points are different and u is not parallel to v.)
1239
1240 - Point is within the triangle iff s >= 0 and t >= 0 and s+t <= 1.
1241 (Some reason: note that point = tri[0]*(1-s-t) + tri[1]*s + tri[2]*t,
1242 so s,t are just 2 barycentric coordinates of our point.)
1243
1244 - It remains to find s,t.
1245 Let w = point - tri[0], so w = s*u + t*v.
1246 Let x^ (for x = direction on a plane) mean TVector3.CrossProduct(x, PlaneDir),
1247 so a direction orthogonal to x and still on the plane.
1248 Note some dot product properties:
1249
1250 (a + b).c = a.c + b.c
1251 (x * a).c = x * (a.c)
1252 where a, b, c are some vectors, x is scalar, * is scalar multiplication.
1253
1254 Now make a dot product of both sides of "w = ..." equation with v^,
1255 and use the dot product properties mentioned above:
1256
1257 w.v^ = s*u.v^ + t*v.v^
1258
1259 v.v^ = 0, because v and v^ are orthogonal.
1260 So we can calculate s as
1261
1262 s := w.v^ / (u.v^)
1263
1264 Analogously, we can calculate v.
1265
1266 - With some optimizations, this can be further simplified,
1267 but we found out that the simplified version is actually slightly slower.
1268 }
1269
1270 { $define IsPointOnTrianglePlaneWithinTriangle_Simplified}
1271 {$ifdef IsPointOnTrianglePlaneWithinTriangle_Simplified}
1272
1273 var
1274 S, T, One, UU, UV, VV, WV, WU, Denominator: Single;
1275 W, U, V: TVector3;
1276 begin
1277 U := Tri.Data[1] - Tri.Data[0];
1278 V := Tri.Data[2] - Tri.Data[0];
1279 UV := TVector3.DotProduct(U, V);
1280 UU := U.LengthSqr; { = TVector3.DotProduct(U, U) }
1281 VV := V.LengthSqr; { = TVector3.DotProduct(V, V) }
1282 Denominator := Sqr(UV) - UU * VV;
1283
1284 W := P - Tri.Data[0];
1285 WV := TVector3.DotProduct(W, V);
1286 WU := TVector3.DotProduct(W, U);
1287
1288 One := 1 + SingleEpsilon;
1289
1290 S := (UV * WV - VV * WU) / Denominator;
1291 if (S < -SingleEpsilon) or
1292 { As far as only correctness is concerned, check for S > One isn't needed
1293 here since we will check S+T <= One later anyway.
1294 But for the speed, it's better to make here a quick check
1295 "S > One" and in many cases avoid the long calculation of T.
1296 See ~/3dmodels/rayhunter-demos/raporty/2006-11-12/README:
1297 speed of this procedure has a significant impact
1298 on the ray-tracer speed, so it's really a justified optimization. }
1299 (S > One) then
1300 Exit(false);
1301
1302 T := (UV * WU - UU * WV) / Denominator;
1303 if T < -SingleEpsilon then
1304 Exit(false);
1305
1306 Result := S + T <= One;
1307 end;
1308
1309 {$else}
1310
1311 var
1312 S, T: Single;
1313 W, U, V, Ortho: TVector3;
1314 One: Single;
1315 begin
1316 U := Tri.Data[1] - Tri.Data[0];
1317 V := Tri.Data[2] - Tri.Data[0];
1318 W := P - Tri.Data[0];
1319
1320 One := 1 + SingleEpsilon;
1321
1322 Ortho := TVector3.CrossProduct(V, TriDir);
1323 S := TVector3.DotProduct(W, Ortho) / TVector3.DotProduct(U, Ortho);
1324 if (S < -SingleEpsilon) or
1325 { As far as only correctness is concerned, check for S > One isn't needed
1326 here since we will check S+T <= One later anyway.
1327 But for the speed, it's better to make here a quick check
1328 "S > One" and in many cases avoid the long calculation of T.
1329 See ~/3dmodels/rayhunter-demos/raporty/2006-11-12/README:
1330 speed of this procedure has a significant impact
1331 on the ray-tracer speed, so it's really a justified optimization. }
1332 (S > One) then
1333 Exit(false);
1334
1335 Ortho := TVector3.CrossProduct(U, TriDir);
1336 T := TVector3.DotProduct(W, Ortho) / TVector3.DotProduct(V, Ortho);
1337 if T < -SingleEpsilon then
1338 Exit(false);
1339
1340 Result := S + T <= One;
1341 end;
1342
1343 {$endif IsPointOnTrianglePlaneWithinTriangle_Simplified}
1344
1345 //function IsPointOnTrianglePlaneWithinTriangle(const P: TVector3;
1346 // const Tri: TTriangle3): boolean;
1347 //begin
1348 // Result := IsPointOnTrianglePlaneWithinTriangle(P, Tri, TriangleDirection(Tri));
1349 //end;
1350
1351 function IsPointWithinTriangle2D(const P: TVector2;
1352 const Tri: TTriangle2): boolean;
1353 var
1354 Area, S, T, One: Single;
1355 begin
1356 { see http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d-triangle }
1357 Area := 1 / 2 * (
1358 - Tri.Data[1].Y*Tri.Data[2].X
1359 + Tri.Data[0].Y*(-Tri.Data[1].X + Tri.Data[2].X)
1360 + Tri.Data[0].X*(Tri.Data[1].Y - Tri.Data[2].Y)
1361 + Tri.Data[1].X*Tri.Data[2].Y);
1362
1363 S := 1/(2*Area)*(
1364 Tri.Data[0].Y*Tri.Data[2].X
1365 - Tri.Data[0].X*Tri.Data[2].Y
1366 + (Tri.Data[2].Y - Tri.Data[0].Y) * P.X
1367 + (Tri.Data[0].X - Tri.Data[2].X) * P.Y);
1368
1369 One := 1 + SingleEpsilon;
1370 if (S < -SingleEpsilon) or
1371 { Like in 3D: checking this here is an optimization. }
1372 (S > One) then
1373 Exit(false);
1374
1375 T := 1/(2*Area)*(
1376 Tri.Data[0].X*Tri.Data[1].Y
1377 - Tri.Data[0].Y*Tri.Data[1].X
1378 + (Tri.Data[0].Y - Tri.Data[1].Y) * P.X
1379 + (Tri.Data[1].X - Tri.Data[0].X) * P.Y);
1380
1381 { We could check at the end just this:
1382 Result := (S > 0) and (T > 0) and (1 - S - T > 0);
1383 Our more optimized version tries to exit early, and also applies
1384 SingleEpsilon. }
1385
1386 if T < -SingleEpsilon then
1387 Exit(false);
1388 Result := S + T <= One;
1389 end;
1390
1391 function IsPointWithinTriangle2D(const P: TVector2;
1392 const Tri: TTriangle3): boolean;
1393 var
1394 Tri2D: TTriangle2;
1395 begin
1396 { project Tri on 2D }
1397 Tri2D.Data[0].X := Tri.Data[0].X;
1398 Tri2D.Data[0].Y := Tri.Data[0].Y;
1399
1400 Tri2D.Data[1].X := Tri.Data[1].X;
1401 Tri2D.Data[1].Y := Tri.Data[1].Y;
1402
1403 Tri2D.Data[2].X := Tri.Data[2].X;
1404 Tri2D.Data[2].Y := Tri.Data[2].Y;
1405
1406 Result := IsPointWithinTriangle2D(P, Tri2D);
1407 end;
1408
1409 function IsTriangleSegmentCollision(const Tri: TTriangle3;
1410 const TriPlane: TVector4; const Pos1, Pos2: TVector3): boolean;
1411 var
1412 LineVector, MaybeIntersection: TVector3;
1413 TriDir: TVector3 absolute TriPlane;
1414 begin
1415 LineVector := Pos2 - Pos1;
1416 Result := TryPlaneLineIntersection(MaybeIntersection, TriPlane, Pos1, LineVector) and
1417 IsPointOnSegmentLineWithinSegment(MaybeIntersection, Pos1, Pos2) and
1418 IsPointOnTrianglePlaneWithinTriangle(MaybeIntersection, Tri, TriDir);
1419 end;
1420
1421 function IsTriangleSegmentCollision(const Tri: TTriangle3; const Pos1, Pos2: TVector3): boolean;
1422 begin
1423 Result := IsTriangleSegmentCollision(Tri, Tri.Plane, Pos1, Pos2);
1424 end;
1425
1426 function TryTriangleSegmentCollision(var Intersection: TVector3;
1427 const Tri: TTriangle3; const TriPlane: TVector4;
1428 const Pos1, Pos2: TVector3): boolean;
1429 begin
1430 Result := TryTriangleSegmentDirCollision(Intersection, Tri, TriPlane,
1431 Pos1, Pos2 - Pos1);
1432 end;
1433
1434 function TryTriangleSegmentDirCollision(var Intersection: TVector3; var T: Single;
1435 const Tri: TTriangle3; const TriPlane: TVector4;
1436 const Segment0, SegmentVector: TVector3): boolean;
1437 var
1438 MaybeIntersection: TVector3;
1439 MaybeT: Single;
1440 TriDir: TVector3 absolute TriPlane;
1441 begin
1442 Result := TryPlaneSegmentDirIntersection(MaybeIntersection, MaybeT, TriPlane, Segment0, SegmentVector) and
1443 IsPointOnTrianglePlaneWithinTriangle(MaybeIntersection, Tri, TriDir);
1444 if Result then
1445 begin
1446 Intersection := MaybeIntersection;
1447 T := MaybeT;
1448 end;
1449 end;
1450
1451 function TryTriangleSegmentDirCollision(var Intersection: TVector3;
1452 const Tri: TTriangle3; const TriPlane: TVector4;
1453 const Segment0, SegmentVector: TVector3): boolean;
1454 var
1455 MaybeIntersection: TVector3;
1456 MaybeT: Single;
1457 TriDir: TVector3 absolute TriPlane;
1458 begin
1459 Result := TryPlaneSegmentDirIntersection(MaybeIntersection, MaybeT, TriPlane, Segment0, SegmentVector) and
1460 IsPointOnTrianglePlaneWithinTriangle(MaybeIntersection, Tri, TriDir);
1461 if Result then
1462 Intersection := MaybeIntersection;
1463 end;
1464
1465 function IsTriangleSphereCollision(const Tri: TTriangle3;
1466 const TriPlane: TVector4;
1467 const SphereCenter: TVector3; SphereRadius: Single): boolean;
1468 (*$define HAS_PRECALC_PLANE*)
1469 (*$I castletriangles_istrianglespherecollision.inc*)
1470 (*$undef HAS_PRECALC_PLANE*)
1471
1472 function IsTriangleSphereCollision(const Tri: TTriangle3;
1473 const SphereCenter: TVector3; SphereRadius: Single): boolean;
1474 (*$I castletriangles_istrianglespherecollision.inc*)
1475
1476 function IsTriangleSphereCollision2D(const Tri: TTriangle2;
1477 const SphereCenter: TVector2; SphereRadius: Single): boolean;
1478 var
1479 Intersection: TVector2;
1480 SphereRadiusSqr: Single;
1481 I, NextI: integer;
1482 begin
1483 SphereRadiusSqr := Sqr(SphereRadius);
1484
1485 (* Is SphereCenter within the radius of one of triangle corners.
1486 Note that this case is necessary, it is not fully catched by
1487 "SphereCenter close to one of the triangles' edges" lower. *)
1488 if (PointsDistanceSqr(Tri.Data[0], SphereCenter) <= SphereRadiusSqr) or
1489 (PointsDistanceSqr(Tri.Data[1], SphereCenter) <= SphereRadiusSqr) or
1490 (PointsDistanceSqr(Tri.Data[2], SphereCenter) <= SphereRadiusSqr) then
1491 Exit(true);
1492
1493 if IsPointWithinTriangle2D(SphereCenter, Tri) then
1494 Exit(true);
1495
1496 (* Is SphereCenter close to one of the triangles' edges. *)
1497 for I := 0 to 2 do
1498 begin
1499 NextI := (I + 1) mod 3;
1500 Intersection := PointOnLineClosestToPoint(Tri.Data[I],
1501 Tri.Data[NextI] - Tri.Data[I], SphereCenter);
1502 if IsPointOnSegmentLineWithinSegment(Intersection, Tri.Data[I], Tri.Data[NextI]) and
1503 (PointsDistanceSqr(SphereCenter, Intersection) <= SphereRadiusSqr) then
1504 Exit(true);
1505 end;
1506
1507 Result := false;
1508 end;
1509
1510 function IsTriangleSphereCollision2D(const Tri: TTriangle3;
1511 const SphereCenter: TVector2; SphereRadius: Single): boolean;
1512 var
1513 Tri2D: TTriangle2;
1514 begin
1515 { project Tri on 2D }
1516 Tri2D.Data[0].X := Tri.Data[0].X;
1517 Tri2D.Data[0].Y := Tri.Data[0].Y;
1518
1519 Tri2D.Data[1].X := Tri.Data[1].X;
1520 Tri2D.Data[1].Y := Tri.Data[1].Y;
1521
1522 Tri2D.Data[2].X := Tri.Data[2].X;
1523 Tri2D.Data[2].Y := Tri.Data[2].Y;
1524
1525 Result := IsTriangleSphereCollision2D(Tri2D, SphereCenter, SphereRadius);
1526 end;
1527
1528 function TryTriangleRayCollision(var Intersection: TVector3; var T: Single;
1529 const Tri: TTriangle3; const TriPlane: TVector4;
1530 const RayOrigin, RayDirection: TVector3): boolean;
1531 var
1532 MaybeIntersection: TVector3;
1533 MaybeT: Single;
1534 TriDir: TVector3 absolute TriPlane;
1535 begin
1536 Result := TryPlaneRayIntersection(MaybeIntersection, MaybeT, TriPlane, RayOrigin, RayDirection) and
1537 IsPointOnTrianglePlaneWithinTriangle(MaybeIntersection, Tri, TriDir);
1538 if Result then
1539 begin
1540 Intersection := MaybeIntersection;
1541 T := MaybeT;
1542 end;
1543 end;
1544
1545 function TryTriangleRayCollision(var Intersection: TVector3;
1546 const Tri: TTriangle3; const TriPlane: TVector4;
1547 const RayOrigin, RayDirection: TVector3): boolean;
1548 var
1549 MaybeIntersection: TVector3;
1550 MaybeT: Single;
1551 TriDir: TVector3 absolute TriPlane;
1552 begin
1553 Result := TryPlaneRayIntersection(MaybeIntersection, MaybeT, TriPlane, RayOrigin, RayDirection) and
1554 IsPointOnTrianglePlaneWithinTriangle(MaybeIntersection, Tri, TriDir);
1555 if Result then
1556 Intersection := MaybeIntersection;
1557 end;
1558
1559 function TriangleDirection(const p0, p1, p2: TVector3): TVector3;
1560 begin
1561 Result := TVector3.CrossProduct(
1562 p2 - p1,
1563 p0 - p1);
1564 end;
1565
1566 function TriangleDir(const p0, p1, p2: TVector3): TVector3;
1567 begin
1568 Result := TVector3.CrossProduct(
1569 p2 - p1,
1570 p0 - p1);
1571 end;
1572
1573 function TriangleNormal(const p0, p1, p2: TVector3): TVector3;
1574 begin
1575 Result := TriangleDirection(p0, p1, p2).Normalize;
1576 end;
1577
1578 function TrianglePlane(const p0, p1, p2: TVector3): TVector4;
1579 var
1580 ResultDir: TVector3 absolute Result;
1581 begin
1582 ResultDir := TriangleDirection(p0, p1, p2);
1583 Result.W :=
1584 -ResultDir.X * p0.X
1585 -ResultDir.Y * p0.Y
1586 -ResultDir.Z * p0.Z;
1587 end;
1588
1589 function TriangleDir(const T: TTriangle3): TVector3;
1590 begin
1591 Result := T.Direction;
1592 end;
1593
1594 function TriangleNormal(const T: TTriangle3): TVector3;
1595 begin
1596 Result := T.Normal;
1597 end;
1598
1599 function TrianglePlane(const T: TTriangle3): TVector4;
1600 begin
1601 Result := T.Plane;
1602 end;
1603
1604 function TriangleTransform(const T: TTriangle3;const M: TMatrix4): TTriangle3;
1605 begin
1606 Result := T.Transform(M);
1607 end;
1608
1609 function TriangleNormPlane(const T: TTriangle3): TVector4;
1610 begin
1611 Result := T.NormalizedPlane;
1612 end;
1613
1614 function TriangleArea(const T: TTriangle3): Single;
1615 begin
1616 Result := T.Area;
1617 end;
1618
1619 function Barycentric(const T: TTriangle3; const Point: TVector3): TVector3;
1620 begin
1621 Result := T.Barycentric(Point);
1622 end;
1623
1624 function TriangleToNiceStr(const T: TTriangle3): string; deprecated 'use T.ToString';
1625 begin
1626 Result := T.ToString;
1627 end;
1628
1629 function CalculateTangent(const IsTangent: boolean; out Tangent: TVector3;
1630 var TriangleCoord: TTriangle3;
1631 var TriangleTexCoord: TTriangle2): Boolean;
1632 var
1633 D: TVector2;
1634 LineA, LineBC, DIn3D: TVector3;
1635 MiddleIndex: Integer;
1636 FarthestDistance, NewDistance, Alpha: Single;
1637 SearchCoord, OtherCoord: Cardinal;
1638 begin
1639 if IsTangent then
1640 SearchCoord := 0
1641 else
1642 SearchCoord := 1;
1643 OtherCoord := 1 - SearchCoord;
1644
1645 { choose such that 1st and 2nd points have longest distance along
1646 OtherCoord, so 0 point is in the middle. }
1647
1648 { MiddleIndex means that
1649 MiddleIndex, (MiddleIndex + 1) mod 3 are farthest. }
1650
1651 MiddleIndex := 2;
1652 FarthestDistance := Abs(TriangleTexCoord.Data[0][OtherCoord] - TriangleTexCoord.Data[1][OtherCoord]);
1653
1654 NewDistance := Abs(TriangleTexCoord.Data[1][OtherCoord] - TriangleTexCoord.Data[2][OtherCoord]);
1655 if NewDistance > FarthestDistance then
1656 begin
1657 MiddleIndex := 0;
1658 FarthestDistance := NewDistance;
1659 end;
1660
1661 NewDistance := Abs(TriangleTexCoord.Data[2][OtherCoord] - TriangleTexCoord.Data[0][OtherCoord]);
1662 if NewDistance > FarthestDistance then
1663 begin
1664 MiddleIndex := 1;
1665 FarthestDistance := NewDistance;
1666 end;
1667
1668 if IsZero(FarthestDistance) then
1669 Exit(false);
1670
1671 if MiddleIndex <> 0 then
1672 begin
1673 SwapValues(TriangleTexCoord.Data[0], TriangleTexCoord.Data[MiddleIndex]);
1674 SwapValues(TriangleCoord .Data[0], TriangleCoord .Data[MiddleIndex]);
1675 end;
1676
1677 if IsTangent then
1678 begin
1679 { we want line Y = TriangleTexCoord.Data[0].Y. }
1680 LineA.X := 0;
1681 LineA.Y := 1;
1682 LineA.Z := -TriangleTexCoord.Data[0].Y;
1683 end else
1684 begin
1685 { we want line X = TriangleTexCoord.Data[0].X. }
1686 LineA.X := 1;
1687 LineA.Y := 0;
1688 LineA.Z := -TriangleTexCoord.Data[0].X;
1689 end;
1690 LineBC := Line2DFrom2Points(
1691 TriangleTexCoord.Data[1], TriangleTexCoord.Data[2]);
1692
1693 try
1694 D := Lines2DIntersection(LineA, LineBC);
1695 except
1696 on ELinesParallel do begin Result := false; Exit; end;
1697 end;
1698
1699 { LineBC[0, 1] is vector 2D orthogonal to LineBC.
1700 If Abs(LineBC[0]) is *smaller* then it means that B and C points
1701 are most different on 0 coord. }
1702 if Abs(LineBC[0]) < Abs(LineBC[1]) then
1703 Alpha := ( D[0] - TriangleTexCoord.Data[1].X) /
1704 (TriangleTexCoord.Data[2].X - TriangleTexCoord.Data[1].X) else
1705 Alpha := ( D[1] - TriangleTexCoord.Data[1].Y) /
1706 (TriangleTexCoord.Data[2].Y - TriangleTexCoord.Data[1].Y);
1707
1708 DIn3D :=
1709 (TriangleCoord.Data[1] * (1 - Alpha)) +
1710 (TriangleCoord.Data[2] * Alpha);
1711
1712 if D[SearchCoord] > TriangleTexCoord.Data[0][SearchCoord] then
1713 Tangent := DIn3D - TriangleCoord.Data[0]
1714 else
1715 Tangent := TriangleCoord.Data[0] - DIn3D;
1716
1717 Tangent := Tangent.Normalize;
1718
1719 Result := true;
1720 end;
1721
1722 end.