Debian Codegraph @

src/transform/castletriangulate.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 { @abstract(Triangulating a polygon.) }
17 unit CastleTriangulate;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils,
24 CastleVectors, CastleUtils, CastleTriangles;
25
26 type
27 TTriangulatorProc = procedure (const Tri: TVector3Integer) of object;
28
29 { Triangulate potentially non-convex face.
30
31 FaceIndices[0]..FaceIndices[Count - 1] are indices
32 to the Vertices array. They describe the outline of the polygon (face).
33 You can pass FaceIndices = @nil, this is understood that indices
34 are just 0..Count - 1 (in other words, it's equivalent
35 to setting FaceIndices[0] = 0, FaceIndices[1] = 1 etc.).
36
37 For each resulting triangle we will call TriangulatorProc
38 with Tri (first param of TriangulatorProc) containing indices
39 to FaceIndices[] array. We return indices to FaceIndices
40 (not ready vectors from Vertices, not even indices to Vertices[] array)
41 to allow the caller to obtain all information about the triangle.
42 In the simple case, you can just use Vertices[FaceIndices[Tri[0..2]]]
43 to obtain your triangle, in the more sophisticated cases you have
44 other options to e.g. extract other vertex information from whatever
45 data you have (see e.g. VRML/X3D IndexedFaceSet renderer).
46
47 Generated triangles have the same orientation (normal from ccw etc.)
48 as original polygon. This also means that if you're sure that
49 your polygon is planar (and it should be --- although we handle gracefully
50 small deviations from planar, this procedure doesn't actually handle
51 arbitrary (dis)located 3D data) then normal vector of all your
52 triangles is the same.
53
54 Note that you generally shouldn't use this procedure if you @italic(know)
55 that your polygon is convex. Then using this is a waste of time,
56 after all convex polygons can be triangulated much easier.
57 You can use TriangulateConvexFace in this case, which has
58 deliberately very similar interface to this procedure.
59
60 @param(TriangulatorProcData Is just passed unmodified to every
61 TriangulatorProc call (as the second parameter). This is standard
62 method to pass whatever data to your callback.)
63
64 @param(AddToIndices
65 Indexes returned in Tri[0..2] are all incremented by AddToIndices
66 (which may also be negative), this is useful if your FaceIndices
67 is actually a pointer to the middle of some larger indexes array.
68 Just pass 0 if you don't want this.)
69
70 @seeAlso TriangulateConvexFace
71
72 @groupBegin }
73 procedure TriangulateFace(
74 FaceIndices: PInt32Array; Count: Integer;
75 Vertices: PVector3Array; VerticesCount: Integer;
76 TriangulatorProc: TTriangulatorProc;
77 AddToIndices: Integer); overload;
78
79 procedure TriangulateFace(
80 FaceIndices: PInt32Array; Count: Integer;
81 Vertices: TGetVertexFromIndexFunc; TriangulatorProc: TTriangulatorProc;
82 AddToIndices: Integer); overload;
83 { @groupEnd }
84
85 { Triangulate convex polygon.
86
87 This performs very easy triangulation. It has deliberately
88 similar interface to TriangulateFace, so it can be used as drop-in
89 replacement for TriangulateFace, when you know that your face is
90 convex.
91
92 Note that it doesn't even need to know FaceIndices or Vertices,
93 it's enough to know Count.
94
95 This also guarantees consequent triangles orientation, like TriangulateFace.
96
97 @seeAlso TriangulateFace }
98 procedure TriangulateConvexFace(Count: Integer;
99 TriangulatorProc: TTriangulatorProc;
100 AddToIndices: Integer);
101
102 { Calculate normal vector of possibly concave polygon. }
103 function IndexedPolygonNormal(
104 Indices: PInt32Array; IndicesCount: Integer;
105 Vertices: PVector3Array; const VerticesCount: Integer;
106 const ResultForIncorrectPoly: TVector3; const Convex: boolean): TVector3;
107
108 var
109 { Write to Log a @italic(lot) of comments how the triangulation goes.
110 Useful for examples/visualize_triangulation/ . }
111 LogTriangulation: boolean;
112
113 implementation
114
115 uses Math,
116 CastleLog, CastleStringUtils;
117
118 { Do additional operations (normalize some vectors etc.)
119 that in theory should improve numerical stability of this algorithm.
120 These operations do not seem to make any impact in practice in our tests.
121 Define this if you see problems, and suspect they may be solved by this
122 (and if you find a testcase that proves that this is needed, please report,
123 so we will make this working always!). }
124 { $define TRIANGULATION_EXTRA_STABILITY}
125
126 { Implementation idea based on face2tri.C in C++, from mgflib sources.
127
128 The algorithm works by finding and cutting off "ears" from the polygon.
129 "Ear" is a triangle that satisfies:
130 1. it has 1 edge inside the polygon and 2 edges along the polygon border and
131 2. it can be safely cut off from the polygon (without intersecting any edge).
132 Which means that it doesn't contain any other polygon vertex inside.
133
134 When we find an ear, we cut it off, which means
135 - we pass the ear triangle to the callback TriangulatorProc,
136 - the polygon is shrunk, it has one vertex less: this is done by setting
137 Outs (for the corner vertex) to true,
138 - and then we repeat the work for the new polygon, smaller by 1 vertex. }
139
140 procedure TriangulateFace(
141 FaceIndices: PInt32Array; Count: Integer;
142 Vertices: TGetVertexFromIndexFunc; TriangulatorProc: TTriangulatorProc;
143 AddToIndices: Integer);
144
145 { Previous and Next in modulo Count (0.. Count - 1) range. }
146 function Previous(const I: Integer): Integer;
147 begin
148 Result := I - 1;
149 if Result = -1 then
150 Result := Result + Count;
151 end;
152
153 function Next(const I: Integer): Integer;
154 begin
155 Result := (I + 1) mod Count;
156 end;
157
158 procedure NewTriangle(const p0, p1, p2: Integer);
159 begin
160 TriangulatorProc(Vector3Integer(
161 P0 + AddToIndices,
162 P1 + AddToIndices,
163 P2 + AddToIndices));
164 end;
165
166 function Verts(I: Integer): TVector3;
167 begin
168 if FaceIndices <> nil then
169 Result := Vertices(FaceIndices^[I]) else
170 Result := Vertices(I);
171 end;
172
173 { Calculate the most distant vertex from Center. }
174 function GetMostDistantVertex(const Center: TVector3): Integer;
175 var
176 MaxLen, D: Single;
177 I: Integer;
178 begin
179 Result := 0;
180 MaxLen := PointsDistanceSqr(Center, Verts(0));
181 for I := 1 to Count - 1 do
182 begin
183 D := PointsDistanceSqr(Center, Verts(I));
184 if D > MaxLen then
185 begin
186 MaxLen := D;
187 Result := I;
188 end;
189 end;
190 end;
191
192 var
193 { Which vertexes are "out" (removed from the polygon).
194 Initially none (everything is false).
195 When we find an ear triangle, it's corner vertex is removed
196 from the polygon by setting corresponding item of this array to true. }
197 Outs: TBooleanList;
198
199 { Increase Index, until a value with Outs[Result]=false is found. }
200 function NextNotOut(Index: Integer): Integer;
201 begin
202 Result := Index;
203 repeat Result := Next(Result) until not Outs[Result];
204 end;
205
206 { Decrease Index, until a value with Outs[Result]=false is found. }
207 function PreviousNotOut(Index: Integer): Integer;
208 begin
209 Result := Index;
210 repeat Result := Previous(Result) until not Outs[Result];
211 end;
212
213 { Look around for previous and next neighbors to the Middle vertex.
214 Searches to make sure we have a good non-colinear triangle around Middle.
215 Returns false (and does log message) if not possible. }
216 function EarAround(const Middle: Integer; out Previous, Next: Integer;
217 out EarDir: TVector3): boolean; overload;
218 begin
219 { Previous := previous from Middle, with different value. }
220 Previous := Middle;
221 repeat
222 Previous := PreviousNotOut(Previous);
223 until (Previous = Middle) or not TVector3.Equals(Verts(Previous), Verts(Middle));
224 if Previous = Middle then
225 begin
226 WritelnLog('Triangulator', 'All vertexes of given polygon are equal. So polygon doesn''t contain any non-empty triangles.');
227 Exit(false);
228 end;
229
230 { Next := next from Middle, resulting in valid triangle Previous-Middle-Next. }
231 Next := Middle;
232 repeat
233 Next := NextNotOut(Next);
234 EarDir := TriangleDirection(Verts(Previous), Verts(Middle), Verts(Next));
235 { note: no need to check for TVector3.Equals(Verts(Next), Verts(Middle)) anywhere,
236 because if EarDir is non-zero then they had to be different. }
237 until (Next = Previous) or not EarDir.IsZero;
238 if Next = Previous then
239 begin
240 WritelnLog('Triangulator', 'All vertexes of given polygon are collinear. So polygon doesn''t contain any non-empty triangles.');
241 Exit(false);
242 end;
243
244 Result := true;
245 end;
246
247 function EarAround(const Middle: Integer; out Previous, Next: Integer): boolean; overload;
248 var
249 EarDirIgnored: TVector3;
250 begin
251 Result := EarAround(Middle, Previous, Next, EarDirIgnored);
252 end;
253
254 var
255 EpsilonForEmptyCheck: Single;
256
257 { Should vertex Border (lying on the border of triangle V0,V1,V2)
258 be treated as lying inside this triangle (and causing it non-empty).
259 This is the tricky situation: border vertex
260
261 1. *Must* cause EarFound:=false (be considered inside V0,V1,V2) in some cases.
262
263 Consider you have a polygon with 4 vertexes,
264 and 1st and 3rd are equal (have equal position).
265 So a correct triangulation is 2 degenerated (colinear)
266 triangles. But accidentally ignoring the border vertex means
267 that we make one non-degenerated incorrect triangle:
268 2-3-4 (because 1st vertex will not collide with it,
269 as it's equal to 3 so it lies on the border).
270 And then we would fail even more, because we're left
271 with a triangle (Corners = 3) which has orientation
272 reverted from the polygon. So we would make *two* incorrect
273 triangles, and spill the "Impossible to find an ear" warning.
274
275 2. *Cannot* cause EarFound:=false (be considered outside V0,V1,V2) in other cases.
276
277 Consider two triangles joined by a single vertex
278 (that is, two vertexes with equal positions).
279 Clearly, a sensible triangulation exists.
280 But if the middle duplicated vertex will be taken into
281 account, it will block every possible ear triangle.
282 Such shape would not have any possile triangulation.
283
284 This function distinguishes between these two cases.
285 Inside1/2/3 must be the edge comparison results. }
286 function BorderVertexInsideTriangle(const V0, V1, V2, TriangleNormal: TVector3;
287 const Inside1, Inside2, Inside3: Single;
288 const Border: Integer): boolean;
289
290 { Check collision in 2D between a ray and line segment (0,0)-(1,0).
291 Ray0 and RayDirection are projected onto 2D space by assuming that
292 XDirection, YDirection 3D vectors correspond to unit OX and OY vectors in 2D,
293 and Origin corresponds to (0,0) in 2D.
294
295 If ray is parallel to this line segment, answers false (because
296 we use this always in case when we now that ray never lies
297 on the line segment, because our line segment is chosen to be a triangle
298 edge that *does not* contain Border vertex). }
299 function RaySegment01Collision2D(Ray0: TVector3;
300 const RayDirection: TVector3;
301 const Origin, XDirection: TVector3;
302 YDirection: TVector3): boolean;
303 var
304 R0, RDirection: TVector2;
305 X, T, XDirectionLenSqr, YDirectionLenSqr: Single;
306 begin
307 Ray0 := Ray0 - Origin;
308
309 { fix YDirection to be orthogonal to XDirection, to make sure projecting
310 by TVector3.DotProduct is correct }
311 MakeVectorsOrthoOnTheirPlane(YDirection, XDirection);
312
313 XDirectionLenSqr := XDirection.LengthSqr;
314 YDirectionLenSqr := YDirection.LengthSqr;
315
316 R0.X := TVector3.DotProduct(Ray0, XDirection) / XDirectionLenSqr;
317 R0.Y := TVector3.DotProduct(Ray0, YDirection) / YDirectionLenSqr;
318 RDirection.X := TVector3.DotProduct(RayDirection, XDirection) / XDirectionLenSqr;
319 RDirection.Y := TVector3.DotProduct(RayDirection, YDirection) / YDirectionLenSqr;
320
321 if IsZero(RDirection.Y) then Exit(false);
322
323 { we're interested now in intersection on OX axis with ray.
324 R0 + RDirection * T = (X, 0), so
325 T = -R0.y / RDirection.y, and
326 X = R0.x + RDirection.x * T }
327 T := - R0.Y / RDirection.Y;
328 if T < 0 then Exit(false);
329
330 X := R0.X + RDirection.X * T;
331 Result := (0 <= X) and (X <= 1);
332 end;
333
334 var
335 BorderPrevious, BorderNext: Integer;
336 VBorder, BorderEarNormal, PullDirection: TVector3;
337 begin
338 { The two cases can be distinguished by looking at edges
339 around Border. If they go out of V0-V1-V2 triangle,
340 then Border is really outside (case 2. above). Otherwise, it's inside
341 (case 1.). Two neighbors around Border "pull"
342 it either outside or inside to our triangle, this is what
343 PullDirection captures. }
344
345 { if EarAround fails, then everything is colinear, we may as well
346 let EarFound be true. This should not happen, except because
347 of fp inaccuracy: if everything is colinear,
348 then our EarNormal.IsZero check earlier should usually
349 detect this. }
350 if not EarAround(Border, BorderPrevious, BorderNext, BorderEarNormal) then
351 Exit(true);
352
353 VBorder := Verts(Border);
354
355 PullDirection :=
356 (((VBorder + Verts(BorderPrevious) + Verts(BorderNext)) / 3.0) - VBorder)
357 {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif};
358
359 { Some (at least one) of the three Inside1/2/3 values are
360 now between -Epsilon .. +Epsilon, these are the edges where
361 Border lies on. Other Inside1/2/3 values are < -Epsilon,
362 these are the edges where Border in fully inside.
363 Only the former edges should be reconsidered now,
364 looking at PullDirection. If PullDirection pulls the Border vertex
365 outside from the triangle, then we're Ok --- Border vertex is not
366 really inside our triangle. }
367
368 Result :=
369 ( (Inside1 <= -EpsilonForEmptyCheck) and RaySegment01Collision2D(VBorder, PullDirection, V0, V1-V0, V2-V0) ) or
370 ( (Inside2 <= -EpsilonForEmptyCheck) and RaySegment01Collision2D(VBorder, PullDirection, V1, V2-V1, V0-V1) ) or
371 ( (Inside3 <= -EpsilonForEmptyCheck) and RaySegment01Collision2D(VBorder, PullDirection, V2, V0-V2, V1-V2) );
372
373 { Alternative hacky way to calculate this (will work Ok if triangles
374 are not too small, because of 0.01 constant) is below.
375 Testcase when the two ways (above with RaySegment01Collision2D
376 and below with IsPointOnTrianglePlaneWithinTriangle) give different
377 answers is "manor" test from Jan Adamec's Room Arranger.
378
379 Assert(Result = IsPointOnTrianglePlaneWithinTriangle(
380 VBorder + PullDirection * 0.01,
381 Triangle3(V0, V1, V2), TriangleNormal)); }
382
383 if LogTriangulation then
384 WritelnLog('Triangulation', Format('Border vertex %d (part of %d - %d - %d) considered inside triangle? %s.',
385 [Border, BorderPrevious, Border, BorderNext, BoolToStr(Result, true)]));
386 end;
387
388 var
389 Center, EarNormal, E1, E2, E3, V0, V1, V2, PolygonNormal: TVector3;
390 Corners, Start, I, P0, P1, P2: Integer;
391 DistanceSqr: Single;
392 EarFound, FailureWarningDone, ValidEar: boolean;
393 Inside1, Inside2, Inside3: Single;
394 begin
395 if Count = 3 then
396 { For Count = 3 this is trivial, do it fast. }
397 NewTriangle(0, 1, 2) else
398 if Count > 3 then
399 begin
400 EpsilonForEmptyCheck := SingleEpsilon;
401 FailureWarningDone := false;
402
403 { calculate Center := average of all vertexes }
404 Center := TVector3.Zero;
405 for I := 0 to Count - 1 do
406 Center := Center + Verts(I);
407 Center := Center / Count;
408
409 Outs := TBooleanList.Create;
410 try
411 Outs.Count := Count; { TFPGList initialized everything to false }
412
413 { Special version for polygons with 4 points.
414 After determining the 1st ear triangle, we have only one choice for
415 the 2nd triangle, so use it. This is useful in case of quads at the sides
416 of Extrusion, that may be "bend" in various weird ways and not really
417 suitable for triangulation in 2D. See 2nd page of
418 https://sourceforge.net/p/castle-engine/tickets/13/ for example. }
419 if Count = 4 then
420 begin
421 P1 := GetMostDistantVertex(Center);
422 P0 := PreviousNotOut(P1);
423 P2 := NextNotOut(P1);
424 NewTriangle(P0, P1, P2);
425 NewTriangle(P2, NextNotOut(P2), P0);
426 Exit;
427 end;
428
429 { P1 is the most distant vertex, P0 is previous, P2 is next.
430 We calculate them only for the sake of calculating PolygonNormal
431 (they do not determine triangulation in any other way). }
432 P1 := GetMostDistantVertex(Center);
433 if not EarAround(P1, P0, P2, PolygonNormal) then Exit;
434 Assert(not PolygonNormal.IsZero);
435 PolygonNormal := PolygonNormal.Normalize;
436
437 if LogTriangulation then
438 WritelnLog('Triangulation', Format('Most distant vertex: %d. Triangle for PolygonNormal: %d - %d - %d. Polygon normal: %s',
439 [P1, P0, P1, P2, PolygonNormal.ToString]));
440
441 Corners := Count; { Corners = always "how many Outs are false" }
442
443 { This initial P0 value is a "border", used to prevent an infinite loop
444 when we cannot find good ear triangle (which is always possible due
445 to lack of floating-point precision).
446 It will always be increased by first "P0 := NextNotOut(P0);".
447 It must be a valid vertex index, otherwise condition "P0 = Start"
448 could never occur and we would loop forever (testcase:
449 change EpsilonForEmptyCheck to 0, and run on demo_models/x3d/concave.x3dv). }
450 P0 := Count - 1;
451 while Corners >= 3 do
452 begin
453 Start := P0;
454
455 { find next ear triangle }
456 repeat
457 ValidEar := false;
458
459 { increase P0. Set P1 and P2 to vertexes following P0.
460 We will now consider triangle P0-P1-P2 to be removed,
461 where P1 is the corner to be cut off. }
462 P0 := NextNotOut(P0);
463 P1 := NextNotOut(P0);
464 P2 := NextNotOut(P1);
465
466 V0 := Verts(P0);
467 V1 := Verts(P1);
468 V2 := Verts(P2);
469
470 { If P0 returned back to Start value,
471 then we considered every possible corner triangle and it cannot
472 be cut off. IOW, we cannot find any ear triangle,
473 so we cannot triangulate this polygon correctly.
474 Every polygon (with >= 4 vertexes) should have at least
475 2 valid "ears" to cut off, so this indicates that we have problems
476 with floating-point accuracy, or we have self-intersecting
477 polygon. }
478 if P0 = Start then
479 begin
480 if LogTriangulation then
481 WritelnLog('Triangulation', 'Impossible to find an "ear" to cut off, this concave polygon cannot be triangulated.');
482 if not FailureWarningDone then
483 begin
484 WritelnWarning('Triangulator', 'Triangulation of concave polygon failed. ' + 'Polygon is probably self-intersecting (not allowed by VRML / X3D). You can use Castle Game Engine tool in castle_game_engine/examples/visualize_triangulation/ to easily observe the polygon vertexes and triangulation process.');
485 FailureWarningDone := true;
486 end;
487 Break;
488 end;
489
490 EarNormal := TriangleDirection(V0, V1, V2);
491 if EarNormal.IsZero then
492 begin
493 if LogTriangulation then
494 WritelnLog('Triangulation', Format('Triangle %d - %d - %d is colinear, removing.', [P0, P1, P2]));
495 { We know in this case we can safely remove P1.
496 We cannot remove P0 or P2 (even if they are equal),
497 because they are important for the shape of the polygon.
498 Leave ValidEar = false, so it will not be actually returned. }
499 Break;
500 end;
501 EarNormal := EarNormal.Normalize;
502
503 ValidEar := true;
504
505 { DistanceSqr is used to check that P0-P1-P2 has roughly the same
506 orientation as whole polygon, not reverted. }
507 DistanceSqr := PointsDistanceSqr(EarNormal, PolygonNormal);
508 EarFound := DistanceSqr <= 1.0;
509 if LogTriangulation then
510 WritelnLog('Triangulation', Format('Does the ear %d - %d - %d have the same orientation as polygon? %s. (Ear normal: %s, distance to polygon normal: %f.)' ,
511 [P0, P1, P2, BoolToStr(EarFound, true),
512 EarNormal.ToString, Sqrt(DistanceSqr)]));
513
514 { check is the ear triangle non-empty }
515 if EarFound then
516 begin
517 { vectors orthogonal to triangle edges going *outside* from the triangle }
518 E1 := (TVector3.CrossProduct(EarNormal, V0 - V1)) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif};
519 E2 := (TVector3.CrossProduct(EarNormal, V1 - V2)) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif};
520 E3 := (TVector3.CrossProduct(EarNormal, V2 - V0)) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif};
521
522 for I := 0 to Count - 1 do
523 { if we can find a vertex that is
524 - part of the polygon (not "out" yet)
525 - different than P0, P1, P2
526 - inside P0-P1-P2 triangle (this is checked by looking at angle
527 between E? and vector to given vertex, value > 90 degrees means
528 vertex is inside the triangle (for given edge))
529 then the considered triangle is not empty, and it cannot be removed
530 as an ear triangle. }
531 if (not Outs[I]) and
532 (I <> P0) and
533 (I <> P1) and
534 (I <> P2) then
535 begin
536 Inside1 := TVector3.DotProduct(E1, (Verts(I) - {$ifdef TRIANGULATION_EXTRA_STABILITY} (V0+V1)/2.0 {$else} V0 {$endif}) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif});
537 Inside2 := TVector3.DotProduct(E2, (Verts(I) - {$ifdef TRIANGULATION_EXTRA_STABILITY} (V1+V2)/2.0 {$else} V1 {$endif}) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif});
538 Inside3 := TVector3.DotProduct(E3, (Verts(I) - {$ifdef TRIANGULATION_EXTRA_STABILITY} (V2+V0)/2.0 {$else} V2 {$endif}) {$ifdef TRIANGULATION_EXTRA_STABILITY} .Normalize {$endif});
539
540 if ( (Inside1 <= -EpsilonForEmptyCheck) and
541 (Inside2 <= -EpsilonForEmptyCheck) and
542 (Inside3 <= -EpsilonForEmptyCheck) ) or
543 ( (Inside1 <= EpsilonForEmptyCheck) and
544 (Inside2 <= EpsilonForEmptyCheck) and
545 (Inside3 <= EpsilonForEmptyCheck) and
546 BorderVertexInsideTriangle(V0, V1, V2, EarNormal,
547 Inside1, Inside2, Inside3, I) ) then
548 begin
549 if LogTriangulation then
550 WritelnLog('Triangulation', Format('Triangle %d - %d - %d would not be empty: point %d would be inside.', [P0, P1, P2, I]));
551 EarFound := false;
552 Break;
553 end;
554 end;
555 end;
556 until EarFound;
557
558 { ear triangle found, cut if off now }
559 if ValidEar then NewTriangle(P0, P1, P2);
560 Outs[P1] := true;
561 Dec(Corners);
562 end;
563 finally Outs.Free end;
564 end;
565 end;
566
567 type
568 TVerticesGenerator = class
569 Vertices: PVector3Array;
570 VerticesCount: Integer;
571 function Generate(Index: Integer): TVector3;
572 end;
573
574 function TVerticesGenerator.Generate(Index: Integer): TVector3;
575 begin
576 if Index < VerticesCount then
577 Result := Vertices^[Index]
578 else
579 { invalid vertex index. VRML/X3D code will warn about it elsewhere,
580 so do not make warning now --- just make sure we don't crash. }
581 Result := TVector3.Zero;
582 end;
583
584 procedure TriangulateFace(
585 FaceIndices: PInt32Array; Count: Integer;
586 Vertices: PVector3Array; VerticesCount: Integer;
587 TriangulatorProc: TTriangulatorProc;
588 AddToIndices: Integer);
589 var
590 G: TVerticesGenerator;
591 begin
592 G := TVerticesGenerator.Create;
593 try
594 G.Vertices := Vertices;
595 G.VerticesCount := VerticesCount;
596 TriangulateFace(FaceIndices, Count,
597 {$ifdef FPC}@{$endif}G.Generate, TriangulatorProc, AddToIndices);
598 finally FreeAndNil(G); end;
599 end;
600
601 procedure TriangulateConvexFace(Count: Integer;
602 TriangulatorProc: TTriangulatorProc;
603 AddToIndices: Integer);
604
605 procedure NewTriangle(const p0, p1, p2: Integer);
606 begin
607 TriangulatorProc(Vector3Integer(
608 P0 + AddToIndices,
609 P1 + AddToIndices,
610 P2 + AddToIndices));
611 end;
612
613 var
614 I: Integer;
615 begin
616 for I := 0 to Count - 3 do
617 NewTriangle(0, I + 1, I + 2);
618 end;
619
620 function IndexedConcavePolygonNormal(
621 Indices: PInt32Array; Count: Integer;
622 Vertices: PVector3Array; const VerticesCount: Integer;
623 const ResultForIncorrectPoly: TVector3): TVector3;
624
625 { Alternative implementation of IndexedConcavePolygonNormal
626 is to do TriangulateFace on the polygon, sum normal vectors
627 of all generated triangles, and normalize the result.
628 However, this is very unoptimal, as TriangulateFace already calculates
629 PolygonNormal (even EarNormal for each triangle) as it works.
630 The current implementation replicates the beginning part of TriangulateFace job,
631 in a simpler manner. }
632
633 { Previous and Next in modulo Count (0.. Count - 1) range. }
634 function Previous(const I: Integer): Integer;
635 begin
636 Result := I - 1;
637 if Result = -1 then
638 Result := Result + Count;
639 end;
640
641 function Next(const I: Integer): Integer;
642 begin
643 Result := (I + 1) mod Count;
644 end;
645
646 function Verts(const I: Integer): TVector3;
647 var
648 Index: Integer;
649 begin
650 Index := Indices^[I];
651 if Index < VerticesCount then
652 Result := Vertices^[Index]
653 else
654 Result := TVector3.Zero;
655 end;
656
657 { Calculate the most distant vertex from Center. }
658 function GetMostDistantVertex(const Center: TVector3): Integer;
659 var
660 MaxLen, D: Single;
661 I: Integer;
662 begin
663 Result := 0;
664 MaxLen := PointsDistanceSqr(Center, Verts(0));
665 for I := 1 to Count - 1 do
666 begin
667 D := PointsDistanceSqr(Center, Verts(I));
668 if D > MaxLen then
669 begin
670 MaxLen := D;
671 Result := I;
672 end;
673 end;
674 end;
675
676 var
677 Center: TVector3;
678 P0, P1, P2, I: Integer;
679 begin
680 if Count < 3 then
681 Exit(ResultForIncorrectPoly);
682
683 { calculate Center := average of all vertexes }
684 Center := TVector3.Zero;
685 for I := 0 to Count - 1 do
686 Center := Center + Verts(I);
687 Center := Center / Count;
688
689 { P1 is the most distant vertex. }
690 P1 := GetMostDistantVertex(Center);
691
692 { P0 := previous from P1, with different value. }
693 P0 := P1;
694 repeat
695 P0 := Previous(P0);
696 until (P0 = P1) or not TVector3.Equals(Verts(P0), Verts(P1));
697 if P0 = P1 then
698 begin
699 { All vertexes of given polygon are equal. }
700 Exit(ResultForIncorrectPoly);
701 end;
702
703 { P2 := next from P1, resulting in valid triangle P0-P1-P2. }
704 P2 := P1;
705 repeat
706 P2 := Next(P2);
707 Result := TriangleDirection(Verts(P0), Verts(P1), Verts(P2));
708 { note: no need to check for TVector3.Equals(Verts(P2), Verts(P1)) anywhere,
709 because if EarDir is non-zero then they had to be different. }
710 until (P2 = P0) or
711 { use IsPerfectlyZero, not IsZero, to not consider triangle invalid too soon.
712 Testcase: demo-models/x3d/humanoid_pose_concave_test_normals.x3dv }
713 not Result.IsPerfectlyZero;
714 if P2 = P0 then
715 begin
716 { All vertexes of given polygon are collinear. }
717 Exit(ResultForIncorrectPoly);
718 end;
719
720 Result := Result.Normalize;
721 end;
722
723 function IndexedPolygonNormal(
724 Indices: PInt32Array; IndicesCount: Integer;
725 Vertices: PVector3Array; const VerticesCount: Integer;
726 const ResultForIncorrectPoly: TVector3; const Convex: boolean): TVector3;
727 begin
728 if Convex then
729 Result := IndexedConvexPolygonNormal (Indices, IndicesCount, Vertices, VerticesCount, ResultForIncorrectPoly)
730 else
731 Result := IndexedConcavePolygonNormal(Indices, IndicesCount, Vertices, VerticesCount, ResultForIncorrectPoly);
732 end;
733
734 end.