Debian Codegraph @

src/scene/castleshapeinternalshadowvolumes.pas

raw
1 {
2 Copyright 2003-2023 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 { Internal data for shadow volumes rendering in shapes. }
16 unit CastleShapeInternalShadowVolumes;
17
18 {$I castleconf.inc}
19
20 interface
21
22 uses Generics.Collections,
23 CastleUtils, CastleVectors, CastleTriangles;
24
25 type
26 { Edge that is between exactly two triangles.
27 It's used by @link(TShapeShadowVolumes.ManifoldEdges),
28 and this is crucial for rendering silhouette shadow volumes in OpenGL. }
29 TManifoldEdge = record
30 { Index to get vertexes of this edge.
31
32 During rendering, the edge is defined by these two vertexes:
33 - Triangles[0][VertexIndex]
34 - Triangles[0][(VertexIndex + 1) mod 3]
35
36 These are indexes to @link(TShapeShadowVolumes.TrianglesListShadowCasters)
37 in turn. This way if a shape changes during animation,
38 we need to recalculate @link(TShapeShadowVolumes.TrianglesListShadowCasters),
39 but the @link(TShapeShadowVolumes.ManifoldEdges) and
40 @link(TShapeShadowVolumes.BorderEdges) may stay unchanged. }
41 VertexIndex: Cardinal;
42
43 { Indexes to @link(TShapeShadowVolumes.TrianglesListShadowCasters) array }
44 Triangles: array [0..1] of Cardinal;
45
46 { These are vertex values at VertexIndex and (VertexIndex+1)mod 3 positions,
47 but @italic(only at generation of manifold edges time).
48 Updating this data later would be costly.
49 However, using these when generating
50 makes a great speed-up when generating manifold edges.
51
52 Memory cost is acceptable: assume we have model with 10 000 faces,
53 so 15 000 edges (assuming it's correctly closed manifold), so we waste
54 15 000 * 2 * SizeOf(TVector3) = 360 000 bytes... that's really nothing
55 to worry (we waste much more on other things).
56
57 Checked with "The Castle": indeed, this costs about 1 MB memory
58 (out of 218 MB...), with really lot of creatures... On the other hand,
59 this causes small speed-up when loading: loading creatures is about
60 5 seconds faster (18 with, 23 without this).
61
62 So memory loss is small, speed gain is noticeable (but still small),
63 implementation code is a little simplified, so we're keeping this for now. }
64 V0, V1: TVector3;
65 end;
66 PManifoldEdge = ^TManifoldEdge;
67
68 TManifoldEdgeList = {$ifdef FPC}specialize{$endif} TStructList<TManifoldEdge>;
69
70 { Edge that has one neighbor, i.e. border edge.
71 It's used by @link(TShapeShadowVolumes.BorderEdges),
72 and this is crucial for rendering silhouette shadow volumes in OpenGL. }
73 TBorderEdge = record
74 { Index to get vertex of this edge.
75 The actual edge's vertexes are not recorded here (this way
76 we don't have to update this when the shape changes during animation).
77 You should get them as the VertexIndex
78 and (VertexIndex+1) mod 3 vertexes of the triangle TriangleIndex. }
79 VertexIndex: Cardinal;
80
81 { Index to @link(TShapeShadowVolumes.TrianglesListShadowCasters) array. }
82 TriangleIndex: Cardinal;
83 end;
84 PBorderEdge = ^TBorderEdge;
85
86 TBorderEdgeList = {$ifdef FPC}specialize{$endif} TStructList<TBorderEdge>;
87
88 { Triangles array for shadow casting shape. In local shape coordinates. }
89 TTrianglesShadowCastersList = TTriangle3List;
90
91 TShapeShadowVolumes = class
92 strict private
93 type
94 TValidities = set of (
95 svTrianglesListShadowCasters,
96 svManifoldAndBorderEdges
97 );
98 var
99 Validities: TValidities;
100 FTrianglesListShadowCasters: TTrianglesShadowCastersList;
101 FManifoldEdges: TManifoldEdgeList;
102 FBorderEdges: TBorderEdgeList;
103 procedure CalculateIfNeededManifoldAndBorderEdges;
104 public
105 FShape: TObject;
106
107 constructor Create(const AShape: TObject);
108 destructor Destroy; override;
109
110 { Removes svManifoldAndBorderEdges from Validities,
111 and clears FManifold/BordEdges variables. }
112 procedure InvalidateManifoldAndBorderEdges;
113
114 { Removes svTrianglesListShadowCasters from Validities,
115 and clears FTrianglesListShadowCasters variable. }
116 procedure InvalidateTrianglesListShadowCasters;
117
118 { Returns an array of triangles that should be shadow casters
119 for this scene.
120
121 Results of these functions are cached, and are also owned by this object.
122 So don't modify it, don't free it. }
123 function TrianglesListShadowCasters: TTrianglesShadowCastersList;
124
125 { ManifoldEdges is a list of edges that have exactly @bold(two) neighbor
126 triangles, and BorderEdges is a list of edges that have exactly @bold(one)
127 neighbor triangle. These are crucial for rendering shadows using shadow
128 volumes.
129
130 Edges with more than two neighbors are allowed. If an edge has an odd
131 number of neighbors, it will be placed in BorderEdges. Every other pair
132 of neighbors will be "paired" and placed as one manifold edge inside
133 ManifoldEdges. So actually edge with exactly 1 neighbor (odd number,
134 so makes one BorderEdges item) and edge with exactly 2 neighbors
135 (even number, one pair of triangles, makes one item in ManifoldEdges)
136 --- they are just a special case of a general rule, that allows any
137 neighbors number.
138
139 Note that vertexes must be consistently ordered in triangles.
140 For two neighboring triangles, if one triangle's edge has
141 order V0, V1, then on the neighbor triangle the order must be reversed
142 (V1, V0). This is true in almost all situations, for example
143 if you have a closed solid object and all outside faces are ordered
144 consistently (all CCW or all CW).
145 Failure to order consistently will result in edges not being "paired",
146 i.e. we will not recognize that some 2 edges are in fact one edge between
147 two neighboring triangles --- and this will result in more edges in
148 BorderEdges.
149
150 Both of these lists are calculated at once, i.e. when you call ManifoldEdges
151 or BorderEdges for the 1st time, actually both ManifoldEdges and
152 BorderEdges are calculated at once. If all edges are in ManifoldEdges,
153 then the scene is a correct closed manifold, or rather it's composed
154 from any number of closed manifolds.
155
156 Results of these functions are cached, and are also owned by this object.
157 So don't modify it, don't free it.
158
159 This uses TrianglesListShadowCasters.
160
161 @groupBegin }
162 function ManifoldEdges: TManifoldEdgeList;
163 function BorderEdges: TBorderEdgeList;
164 { @groupEnd }
165
166 procedure PrepareResources;
167 procedure FreeResources;
168 end;
169
170 implementation
171
172 uses SysUtils,
173 CastleShapes, X3DNodes, CastleLog, CastleTransform,
174 CastleRenderOptions;
175
176 constructor TShapeShadowVolumes.Create(const AShape: TObject);
177 begin
178 inherited Create;
179 FShape := AShape;
180 end;
181
182 destructor TShapeShadowVolumes.Destroy;
183 begin
184 { free FTrianglesList* variables }
185 InvalidateTrianglesListShadowCasters;
186 { frees FManifoldEdges, FBorderEdges if needed }
187 InvalidateManifoldAndBorderEdges;
188 inherited;
189 end;
190
191 { triangles list ------------------------------------------------------------- }
192
193 type
194 TTriangleAdder = class
195 TriangleList: TTriangle3List;
196 procedure AddTriangle(Shape: TObject;
197 const Triangle: TTriangle3;
198 const Normal: TTriangle3; const TexCoord: TTriangle4;
199 const Face: TFaceIndex);
200 end;
201
202 procedure TTriangleAdder.AddTriangle(Shape: TObject;
203 const Triangle: TTriangle3;
204 const Normal: TTriangle3; const TexCoord: TTriangle4;
205 const Face: TFaceIndex);
206 begin
207 if Triangle.IsValid then
208 TriangleList.Add(Triangle);
209 end;
210
211 function TShapeShadowVolumes.TrianglesListShadowCasters: TTrianglesShadowCastersList;
212
213 function CreateTrianglesListShadowCasters: TTrianglesShadowCastersList;
214
215 function ShadowCaster(AShape: TShape): boolean;
216 var
217 Shape: TAbstractShapeNode;
218 begin
219 Shape := AShape.State.ShapeNode;
220 Result := not (
221 (Shape <> nil) and
222 (Shape.FdAppearance.Value <> nil) and
223 (Shape.FdAppearance.Value is TAppearanceNode) and
224 (not TAppearanceNode(Shape.FdAppearance.Value).FdShadowCaster.Value));
225 end;
226
227 var
228 TriangleAdder: TTriangleAdder;
229 Shape: TShape;
230 begin
231 Shape := TShape(FShape);
232
233 Result := TTrianglesShadowCastersList.Create;
234 try
235 Result.Capacity := Shape.TrianglesCount;
236 TriangleAdder := TTriangleAdder.Create;
237 try
238 TriangleAdder.TriangleList := Result;
239 if ShadowCaster(Shape) then
240 Shape.LocalTriangulate({$ifdef FPC}@{$endif}TriangleAdder.AddTriangle);
241 if LogShadowVolumes then
242 WritelnLog('Shadow volumes', Format('Shadows casters triangles: %d',
243 [Result.Count]));
244 finally FreeAndNil(TriangleAdder) end;
245 except Result.Free; raise end;
246 end;
247
248 begin
249 if not (svTrianglesListShadowCasters in Validities) then
250 begin
251 FreeAndNil(FTrianglesListShadowCasters);
252 FTrianglesListShadowCasters := CreateTrianglesListShadowCasters;
253 Include(Validities, svTrianglesListShadowCasters);
254 end;
255
256 Result := FTrianglesListShadowCasters;
257 end;
258
259 procedure TShapeShadowVolumes.InvalidateTrianglesListShadowCasters;
260 begin
261 Exclude(Validities, svTrianglesListShadowCasters);
262 FreeAndNil(FTrianglesListShadowCasters);
263 end;
264
265 { edges lists ------------------------------------------------------------- }
266
267 procedure TShapeShadowVolumes.CalculateIfNeededManifoldAndBorderEdges;
268
269 { Sets FManifoldEdges and FBorderEdges. Assumes that FManifoldEdges and
270 FBorderEdges are @nil on enter. }
271 procedure CalculateManifoldAndBorderEdges;
272
273 { If the counterpart of this edge (edge from neighbor) exists in
274 EdgesSingle, then it adds this edge (along with it's counterpart)
275 to FManifoldEdges.
276
277 Otherwise, it just adds the edge to EdgesSingle. This can happen
278 if it's the 1st time this edge occurs, or maybe the 3d one, 5th...
279 all odd occurrences, assuming that ordering of faces is consistent,
280 so that counterpart edges are properly detected. }
281 procedure AddEdgeCheckManifold(
282 EdgesSingle: TManifoldEdgeList;
283 const TriangleIndex: Cardinal;
284 const V0: TVector3;
285 const V1: TVector3;
286 const VertexIndex: Cardinal;
287 Triangles: TTriangle3List);
288 var
289 I: Integer;
290 EdgePtr: PManifoldEdge;
291 begin
292 if EdgesSingle.Count <> 0 then
293 begin
294 EdgePtr := PManifoldEdge(EdgesSingle.L);
295 for I := 0 to EdgesSingle.Count - 1 do
296 begin
297 { It would also be possible to get EdgePtr^.V0/1 by code like
298
299 TrianglePtr := @Triangles.L[EdgePtr^.Triangles[0]];
300 EdgeV0 := @TrianglePtr^[EdgePtr^.VertexIndex];
301 EdgeV1 := @TrianglePtr^[(EdgePtr^.VertexIndex + 1) mod 3];
302
303 But, see TManifoldEdge.V0/1 comments --- current version is
304 a little faster.
305 }
306
307 { Triangles must be consistently ordered on a manifold,
308 so the second time an edge is present, we know it must
309 be in different order. So we compare V0 with EdgeV1
310 (and V1 with EdgeV0), no need to compare V1 with EdgeV1. }
311 if TVector3.PerfectlyEquals(V0, EdgePtr^.V1) and
312 TVector3.PerfectlyEquals(V1, EdgePtr^.V0) then
313 begin
314 EdgePtr^.Triangles[1] := TriangleIndex;
315
316 { Move edge to FManifoldEdges: it has 2 neighboring triangles now. }
317 FManifoldEdges.Add^ := EdgePtr^;
318
319 { Remove this from EdgesSingle.
320 Note that we delete from EdgesSingle fast, using assignment and
321 deleting only from the end (normal Delete would want to shift
322 EdgesSingle contents in memory, to preserve order of items;
323 but we don't care about order). }
324 EdgePtr^ := EdgesSingle.L[EdgesSingle.Count - 1];
325 EdgesSingle.Count := EdgesSingle.Count - 1;
326
327 Exit;
328 end;
329 Inc(EdgePtr);
330 end;
331 end;
332
333 { New edge: add new item to EdgesSingle }
334 EdgePtr := PManifoldEdge(EdgesSingle.Add);
335 EdgePtr^.VertexIndex := VertexIndex;
336 EdgePtr^.Triangles[0] := TriangleIndex;
337 EdgePtr^.V0 := V0;
338 EdgePtr^.V1 := V1;
339 end;
340
341 var
342 I: Integer;
343 Triangles: TTriangle3List;
344 TrianglePtr: PTriangle3;
345 EdgesSingle: TManifoldEdgeList;
346 begin
347 Assert(FManifoldEdges = nil);
348 Assert(FBorderEdges = nil);
349
350 { It's important here that TrianglesListShadowCasters guarantees that only
351 valid triangles are included. Otherwise degenerate triangles could make
352 shadow volumes rendering result bad. }
353 Triangles := TrianglesListShadowCasters;
354
355 FManifoldEdges := TManifoldEdgeList.Create;
356 { There is a precise relation between number of edges and number of faces
357 on a closed manifold: E = T * 3 / 2. }
358 FManifoldEdges.Capacity := Triangles.Count * 3 div 2;
359
360 { EdgesSingle are edges that have no neighbor,
361 i.e. have only one adjacent triangle. At the end, what's left here
362 will be simply copied to BorderEdges. }
363 EdgesSingle := TManifoldEdgeList.Create;
364 try
365 EdgesSingle.Capacity := Triangles.Count * 3 div 2;
366
367 TrianglePtr := PTriangle3(Triangles.L);
368 for I := 0 to Triangles.Count - 1 do
369 begin
370 { TrianglePtr points to Triangles[I] now }
371 AddEdgeCheckManifold(EdgesSingle, I, TrianglePtr^.Data[0], TrianglePtr^.Data[1], 0, Triangles);
372 AddEdgeCheckManifold(EdgesSingle, I, TrianglePtr^.Data[1], TrianglePtr^.Data[2], 1, Triangles);
373 AddEdgeCheckManifold(EdgesSingle, I, TrianglePtr^.Data[2], TrianglePtr^.Data[0], 2, Triangles);
374 Inc(TrianglePtr);
375 end;
376
377 FBorderEdges := TBorderEdgeList.Create;
378
379 if EdgesSingle.Count <> 0 then
380 begin
381 { scene not a perfect manifold: less than 2 faces for some edges
382 (the case with more than 2 is already eliminated above).
383 So we copy EdgesSingle to BorderEdges. }
384 FBorderEdges.Count := EdgesSingle.Count;
385 for I := 0 to EdgesSingle.Count - 1 do
386 begin
387 FBorderEdges.L[I].VertexIndex := EdgesSingle.L[I].VertexIndex;
388 FBorderEdges.L[I].TriangleIndex := EdgesSingle.L[I].Triangles[0];
389 end;
390 end;
391 finally FreeAndNil(EdgesSingle); end;
392
393 if LogShadowVolumes then
394 WritelnLog('Shadow volumes', Format(
395 'Edges: %d manifold, %d border',
396 [FManifoldEdges.Count, FBorderEdges.Count] ));
397 end;
398
399 begin
400 if not (svManifoldAndBorderEdges in Validities) then
401 begin
402 CalculateManifoldAndBorderEdges;
403 Include(Validities, svManifoldAndBorderEdges);
404 end;
405 end;
406
407 function TShapeShadowVolumes.ManifoldEdges: TManifoldEdgeList;
408 begin
409 CalculateIfNeededManifoldAndBorderEdges;
410 Result := FManifoldEdges;
411 end;
412
413 function TShapeShadowVolumes.BorderEdges: TBorderEdgeList;
414 begin
415 CalculateIfNeededManifoldAndBorderEdges;
416 Result := FBorderEdges;
417 end;
418
419 procedure TShapeShadowVolumes.InvalidateManifoldAndBorderEdges;
420 begin
421 Exclude(Validities, svManifoldAndBorderEdges);
422 FreeAndNil(FManifoldEdges);
423 FreeAndNil(FBorderEdges);
424 end;
425
426 procedure TShapeShadowVolumes.PrepareResources;
427 begin
428 TrianglesListShadowCasters;
429 ManifoldEdges;
430 end;
431
432 procedure TShapeShadowVolumes.FreeResources;
433 begin
434 InvalidateTrianglesListShadowCasters;
435 InvalidateManifoldAndBorderEdges;
436 end;
437
438 end.