Debian Codegraph @

src/scene/castlesceneinternalshape.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
16 { Shape class for OpenGL rendering.
17 @exclude Internal unit for CastleScene. }
18 unit CastleSceneInternalShape;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses Generics.Collections,
25 X3DNodes, X3DFields, CastleImages, CastleVectors, CastleClassUtils,
26 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
27 CastleGLUtils, CastleInternalRenderer, CastleRenderOptions, CastleShapes;
28
29 type
30 { Shape within a scene rendered using OpenGL.
31 This is TShape extended with some information needed by TCastleScene.
32 Non-internal units never expose instances of this class. }
33 TGLShape = class(TX3DRendererShape)
34 strict private
35 TexturesPrepared: Boolean;
36 { Request from parent TCastleScene to call our PrepareResources at nearest
37 convenient time. }
38 procedure SchedulePrepareResources;
39 function PrepareTexture(Shape: TShape; Texture: TAbstractTextureNode): Pointer;
40 function UnprepareTexture(Shape: TShape; Texture: TAbstractTextureNode): Pointer;
41 public
42 PassedFrustumAndDistanceCulling: Boolean;
43
44 { Used only when TCastleViewport.OcclusionCulling.
45 OcclusionQueryId is 0 if not initialized yet.
46 When it's 0, value of OcclusionQueryAsked doesn't matter,
47 OcclusionQueryAsked is always reset to @false when initializing
48 OcclusionQueryId. }
49 OcclusionQueryId: TGLint;
50 OcclusionQueryAsked: boolean;
51
52 { For Hierarchical Occlusion Culling. }
53 RenderedFrameId: Cardinal;
54
55 { Do not share the cache of this shape with other shapes.
56 Offers tiny optimization when you know that this shape cannot be shared anyway.
57 Never change it after initial render. }
58 DisableSharedCache: Boolean;
59
60 OverrideRenderOptions: TCastleRenderOptions;
61
62 destructor Destroy; override;
63 procedure Changed(const InactiveOnly: boolean;
64 const Changes: TX3DChanges); override;
65 procedure PrepareResources;
66 procedure GLContextClose;
67
68 function UseBlending: Boolean;
69 end;
70
71 { Shape with additional information how to render it inside a world,
72 that allows to render it independently of the containing TCastleScene. }
73 TCollectedShape = class
74 Shape: TGLShape;
75 RenderOptions: TCastleRenderOptions;
76 SceneTransform: TMatrix4;
77 DepthRange: TDepthRange;
78 end;
79
80 TCollectedShapeList = class({$ifdef FPC}specialize{$endif} TObjectList<TCollectedShape>)
81 strict private
82 Camera: TViewVectors;
83
84 function CompareBackToFront2D(
85 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} ShapeA, ShapeB: TCollectedShape): Integer;
86 function CompareBackToFront3DBox(
87 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} ShapeA, ShapeB: TCollectedShape): Integer;
88 function CompareBackToFront3DOrigin(
89 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
90 function CompareBackToFront3DGround(
91 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
92 function CompareBackToFrontCustom(
93 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
94
95 function CompareFrontToBack2D(
96 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
97 function CompareFrontToBack3DBox(
98 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
99 function CompareFrontToBack3DOrigin(
100 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
101 function CompareFrontToBack3DGround(
102 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
103 function CompareFrontToBackCustom(
104 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
105 public
106 { Used when ShapeSort is sortCustom for SortBackToFront or SortFrontToBack. }
107 OnCustomShapeSort: TShapeSortEvent;
108
109 { Sort shapes by distance to camera, farthest first.
110 ShapeSort determines the sorting algorithm.
111 See @link(TShapeSort) documentation. }
112 procedure SortBackToFront(
113 const ACamera: TViewVectors;
114 const ShapeSort: TShapeSortNoAuto);
115
116 { Sort shapes by distance to camera, closest first.
117 ShapeSort determines the sorting algorithm.
118 See @link(TShapeSort) documentation. }
119 procedure SortFrontToBack(
120 const ACamera: TViewVectors;
121 const ShapeSort: TShapeSortNoAuto);
122 end;
123
124 implementation
125
126 uses Generics.Defaults, Math, SysUtils,
127 CastleScene, CastleBoxes;
128
129 { TGLShape --------------------------------------------------------------- }
130
131 destructor TGLShape.Destroy;
132 begin
133 inherited;
134 end;
135
136 procedure TGLShape.Changed(const InactiveOnly: boolean;
137 const Changes: TX3DChanges);
138 begin
139 inherited;
140
141 if Cache <> nil then
142 begin
143 { Ignore changes that don't affect prepared arrays,
144 like transformation, clip planes and everything else that is applied
145 by renderer every time, and doesn't affect TGeometryArrays. }
146
147 if Changes * [
148 chCoordinate,
149 chNormal,
150 chTangent
151 ] <> [] then
152 begin
153 Cache.InvalidateVertexData([vtCoordinate]);
154
155 { Note: When bump mapping is used, upon changing normals -> we need to recalculate tangents.
156 But that is already covered: tangents are also part of vtCoordinate. }
157 end;
158
159 { Note that Changes may contain both chCoordinate and chTextureCoordinate
160 (e.g. in case of batching)
161 in which case both "if" clauses should be entered.
162
163 About chTextureImage:
164 We regenerate arrays when chTextureImage occurred,
165 because it means that potentially non-existing texture (e.g. ImageTexture
166 with empty url, or invalid url) changed to existing (if you set correct
167 ImageTexture.url). This means that number of texture coordinates
168 we need to make has changed.
169 Testcase "animate_symbols", using Unholy spell effect animations.
170
171 TODO: Actually Cache.InvalidateVertexData is often not necessary in case of chTextureImage.
172 It's only necessary when texture existence changed.
173 This could be optimized more.
174 }
175 if Changes * [
176 chTextureImage,
177 chVisibleVRML1State,
178 chGeometryVRML1State,
179 chColorNode,
180 chTextureCoordinate,
181 chGeometry,
182 chGeometryFontChanged,
183 chFontStyle,
184 chFontStyleFontChanged,
185 chWireframe
186 ] <> [] then
187 Cache.InvalidateVertexData(AllVboTypes);
188 end;
189
190 if Changes * [
191 chTextureImage,
192 chTextureRendererProperties,
193 { Needed to make TCastleText.CustomFont change applied OK,
194 otherwise TCastleText could be rendered without blending. }
195 chFontStyleFontChanged
196 ] <> [] then
197 begin
198 TTextureResources.Unprepare(State.MainTexture);
199 { Make next PrepareResources prepare all textures.
200 Testcase:
201 - castle-model-viewer
202 - open demo-models/rendered_texture/rendered_texture_tweak_size.x3dv
203 - use s / S
204 - without this fix, texture would change to none, and never again
205 update RenderedTexture contents. }
206 TexturesPrepared := false;
207 { Make sure PrepareResources is actually called soon. }
208 SchedulePrepareResources;
209 end;
210 end;
211
212 function TGLShape.UnprepareTexture(Shape: TShape; Texture: TAbstractTextureNode): Pointer;
213 begin
214 Result := nil; // let EnumerateTextures to enumerate all textures
215
216 { Do not call TTextureResources.Unprepare
217 (which would do Texture.InternalRendererResourceFree in the end)
218 when Texture is TInternalReusedPixelTextureNode,
219 since this texture may be reused by other scenes.
220
221 Testcase:
222 - create in editor viewport, add TCastleText
223 - add another TCastleText
224 - remove one (any one) TCastleText --
225 the other TCastleText display will be broken
226 if condition "if not (Texture is TInternalReusedPixelTextureNode) then"
227 below gets removed.
228 }
229 if not (Texture is TInternalReusedPixelTextureNode) then
230 TTextureResources.Unprepare(Texture);
231 end;
232
233 function TGLShape.PrepareTexture(Shape: TShape; Texture: TAbstractTextureNode): Pointer;
234 var
235 RenderOptions: TCastleRenderOptions;
236 begin
237 Result := nil; // let EnumerateTextures to enumerate all textures
238
239 // This method only captures textures on this shape
240 Assert(Shape = Self);
241
242 // TODO: add and always depend on local RenderOptions field, not ParentScene? or we need ParentScene anyway?
243 if OverrideRenderOptions <> nil then
244 RenderOptions := OverrideRenderOptions
245 else
246 RenderOptions := TCastleScene(ParentScene).RenderOptions;
247 Assert(RenderOptions <> nil);
248
249 TTextureResources.Prepare(RenderOptions, Texture);
250 end;
251
252 procedure TGLShape.PrepareResources;
253 begin
254 if not TexturesPrepared then
255 begin
256 TexturesPrepared := true;
257 EnumerateTextures({$ifdef FPC}@{$endif} PrepareTexture);
258 end;
259 end;
260
261 procedure TGLShape.GLContextClose;
262
263 { Free Arrays and Vbo of all shapes. }
264 procedure FreeCaches;
265 var
266 Pass: TTotalRenderingPass;
267 begin
268 if Cache <> nil then
269 begin
270 RendererCache.Shape_DecReference(Self, Cache);
271 Assert(Cache = nil, 'At the end of GLContextClose, Cache should be nil');
272 end;
273
274 for Pass := Low(Pass) to High(Pass) do
275 begin
276 if ProgramCache[Pass] <> nil then
277 RendererCache.Program_DecReference(ProgramCache[Pass]);
278 Assert(ProgramCache[Pass] = nil, 'At the end of GLContextClose, all ProgramCache[Pass] should be nil');
279 end;
280 end;
281
282 begin
283 if TexturesPrepared then
284 begin
285 TexturesPrepared := false;
286 EnumerateTextures({$ifdef FPC}@{$endif} UnprepareTexture);
287 end;
288
289 FreeCaches;
290
291 if OcclusionQueryId <> 0 then
292 begin
293 glDeleteQueries(1, @OcclusionQueryId);
294 OcclusionQueryId := 0;
295 end;
296 end;
297
298 function TGLShape.UseBlending: Boolean;
299 begin
300 Result := AlphaChannel = acBlending;
301 end;
302
303 procedure TGLShape.SchedulePrepareResources;
304 begin
305 if ParentScene <> nil then
306 TCastleScene(ParentScene).InternalSchedulePrepareResources;
307 end;
308
309 { TCollectedShape ---------------------------------------------------------- }
310
311 type
312 TCollectedShapeComparer = {$ifdef FPC}specialize{$endif} TComparer<TCollectedShape>;
313
314 function TCollectedShapeList.CompareBackToFront2D(
315 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} ShapeA, ShapeB: TCollectedShape): Integer;
316 var
317 A, B: TBox3D;
318
319 { Representative point of ShapeA in world coordinates.
320 Call only if ShapeA bbox is not empty. }
321 function APoint: TVector3;
322 begin
323 Result := ShapeA.SceneTransform.MultPoint(A.Data[0]);
324 end;
325
326 { Representative point of ShapeA in world coordinates.
327 Call only if ShapeB bbox is not empty. }
328 function BPoint: TVector3;
329 begin
330 Result := ShapeB.SceneTransform.MultPoint(B.Data[0]);
331 end;
332
333 begin
334 A := ShapeA.Shape.BoundingBox;
335 B := ShapeB.Shape.BoundingBox;
336
337 { Note that we ignore camera position/direction for 2D comparison.
338 We merely look at Z coordinates.
339 This way looking at 2D Spine scene from the other side is also Ok.
340
341 For speed, we don't look at bounding box .Center, only at .Data[0].
342 The assumption here is that shape is thin 2D, and it doesn't really
343 matter if we look at min,max or center point if we only compare Z.
344
345 BoundingBox.Data[0].Z ~=
346 BoundingBox.Data[1].Z ~=
347 BoundingBox.Center.Z .
348 }
349
350 if (not A.IsEmpty) and
351 ( B.IsEmpty or
352 ( APoint.Z < BPoint.Z )) then
353 Result := -1
354 else
355 if (not B.IsEmpty) and
356 ( A.IsEmpty or
357 ( BPoint.Z < APoint.Z )) then
358 Result := 1
359 else
360 Result := 0;
361 end;
362
363 function TCollectedShapeList.CompareBackToFront3DBox(
364 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} ShapeA, ShapeB: TCollectedShape): Integer;
365 var
366 A, B: TBox3D;
367
368 { Center of ShapeA in world coordinates.
369 Call only if ShapeA bbox is not empty. }
370 function ACenter: TVector3;
371 begin
372 Result := ShapeA.SceneTransform.MultPoint(A.Center);
373 end;
374
375 { Center of ShapeB in world coordinates.
376 Call only if ShapeB bbox is not empty. }
377 function BCenter: TVector3;
378 begin
379 Result := ShapeB.SceneTransform.MultPoint(B.Center);
380 end;
381
382 begin
383 { We always treat empty box as closer than non-empty.
384 And two empty boxes are always equal.
385
386 Remember that code below must make sure that Result = 0
387 for equal elements (Sort may depend on this). So A > B only when:
388 - A empty, and B non-empty
389 - both non-empty, and A closer
390
391 We compare distances using
392 TVector3.DotProduct(..., Camera.Direction)
393 instead of
394 PointsDistance(...., Camera.Translation)
395
396 This way algorithm works reliably also for completely flat models
397 (like Spine animations or images) aligned to camera as billboards,
398 in 3D, with any camera direction.
399 }
400
401 A := ShapeA.Shape.BoundingBox;
402 B := ShapeB.Shape.BoundingBox;
403
404 if (not A.IsEmpty) and
405 ( B.IsEmpty or
406 ( TVector3.DotProduct(ACenter, Camera.Direction) >
407 TVector3.DotProduct(BCenter, Camera.Direction))) then
408 Result := -1
409 else
410 if (not B.IsEmpty) and
411 ( A.IsEmpty or
412 ( TVector3.DotProduct(BCenter, Camera.Direction) >
413 TVector3.DotProduct(ACenter, Camera.Direction))) then
414 Result := 1
415 else
416 Result := 0;
417 end;
418
419 function TCollectedShapeList.CompareBackToFront3DOrigin(
420 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
421 var
422 PointA, PointB: TVector3;
423 begin
424 PointA := (A.SceneTransform * A.Shape.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
425 PointB := (B.SceneTransform * B.Shape.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
426 Result := Sign(
427 TVector3.DotProduct(PointB, Camera.Direction) -
428 TVector3.DotProduct(PointA, Camera.Direction));
429 end;
430
431 function TCollectedShapeList.CompareBackToFront3DGround(
432 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
433 var
434 PointA, PointB: TVector3;
435 begin
436 { TODO: what's more efficient - MultTransform 2x, or multiply matrix + MultTransform? }
437 PointA := (A.SceneTransform * A.Shape.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
438 PointB := (B.SceneTransform * B.Shape.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
439 PointA.Y := 0;
440 PointB.Y := 0;
441 Result := Sign(
442 TVector3.DotProduct(PointB, Camera.Direction) -
443 TVector3.DotProduct(PointA, Camera.Direction));
444 end;
445
446 function TCollectedShapeList.CompareBackToFrontCustom(
447 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
448 begin
449 Result := OnCustomShapeSort(Camera,
450 A.Shape, B.Shape,
451 A.RenderOptions, B.RenderOptions,
452 A.SceneTransform, B.SceneTransform
453 );
454 end;
455
456 procedure TCollectedShapeList.SortBackToFront(
457 const ACamera: TViewVectors;
458 const ShapeSort: TShapeSortNoAuto);
459 begin
460 Camera := ACamera;
461
462 { sort3DVerticalBillboards is just like sort3D,
463 but project camera direction on Y=0 plane. }
464 if ShapeSort = sort3DVerticalBillboards then
465 Camera.Direction.Y := 0;
466
467 case ShapeSort of
468 sort2D : Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareBackToFront2D));
469 sort3DVerticalBillboards,
470 sort3D : Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareBackToFront3DBox));
471 sort3DOrigin: Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareBackToFront3DOrigin));
472 sort3DGround: Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareBackToFront3DGround));
473 sortCustom :
474 begin
475 // does not sort if OnCustomShapeSort unassigned
476 if Assigned(OnCustomShapeSort) then
477 Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareBackToFrontCustom));
478 end;
479 else ;
480 end;
481 end;
482
483 function TCollectedShapeList.CompareFrontToBack2D(
484 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
485 begin
486 Result := -CompareBackToFront2D(A, B);
487 end;
488
489 function TCollectedShapeList.CompareFrontToBack3DBox(
490 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
491 begin
492 Result := -CompareBackToFront3DBox(A, B);
493 end;
494
495 function TCollectedShapeList.CompareFrontToBack3DOrigin(
496 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
497 begin
498 Result := -CompareBackToFront3DOrigin(A, B);
499 end;
500
501 function TCollectedShapeList.CompareFrontToBack3DGround(
502 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
503 begin
504 Result := -CompareBackToFront3DGround(A, B);
505 end;
506
507 function TCollectedShapeList.CompareFrontToBackCustom(
508 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TCollectedShape): Integer;
509 begin
510 Result := -CompareBackToFrontCustom(A, B);
511 end;
512
513 procedure TCollectedShapeList.SortFrontToBack(
514 const ACamera: TViewVectors;
515 const ShapeSort: TShapeSortNoAuto);
516 begin
517 Camera := ACamera;
518
519 { sort3DVerticalBillboards is just like sort3D,
520 but project camera direction on Y=0 plane. }
521 if ShapeSort = sort3DVerticalBillboards then
522 Camera.Direction.Y := 0;
523
524 case ShapeSort of
525 sort2D : Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareFrontToBack2D));
526 sort3DVerticalBillboards,
527 sort3D : Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareFrontToBack3DBox));
528 sort3DOrigin: Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareFrontToBack3DOrigin));
529 sort3DGround: Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareFrontToBack3DGround));
530 sortCustom :
531 begin
532 // does not sort if OnCustomShapeSort unassigned
533 if Assigned(OnCustomShapeSort) then
534 Sort(TCollectedShapeComparer.Construct({$ifdef FPC}@{$endif} CompareFrontToBackCustom));
535 end;
536 else ;
537 end;
538 end;
539
540 end.