Debian Codegraph @

src/scene/castleshapes.pas

raw
1 {
2 Copyright 2003-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Shape (TShape class) and a simple tree of shapes (TShapeTree class). }
17 unit CastleShapes;
18
19 {$I castleconf.inc}
20
21 { $define SHAPE_ITERATOR_SOPHISTICATED}
22
23 {$I octreeconf.inc}
24
25 interface
26
27 uses SysUtils, Classes, Generics.Collections,
28 CastleVectors, CastleTransform, CastleBoxes, X3DNodes, CastleClassUtils,
29 CastleUtils, CastleInternalTriangleOctree, CastleFrustum, CastleInternalOctree,
30 CastleInternalBaseTriangleOctree, X3DFields, CastleInternalGeometryArrays,
31 CastleTriangles, CastleImages, CastleInternalMaterialProperties,
32 CastleShapeInternalShadowVolumes, CastleRenderOptions, CastleTimeUtils;
33
34 const
35 { }
36 DefLocalTriangleOctreeMaxDepth = 10;
37 { Default octree leaf capacity for TShape.OctreeTriangles.
38
39 This is slightly larger than DefTriangleOctreeLeafCapacity, as this
40 octree will usually be used interactively for collision detection,
41 not by ray-tracer. So octree construction speed is somewhat important,
42 and cannot be too large... }
43 DefLocalTriangleOctreeLeafCapacity = 32;
44 DefLocalTriangleOctreeLimits: TOctreeLimits = (
45 MaxDepth: DefLocalTriangleOctreeMaxDepth;
46 LeafCapacity: DefLocalTriangleOctreeLeafCapacity
47 );
48
49 type
50 { Possible spatial structure types that may be managed by TShape,
51 see TShape.Spatial. }
52 TShapeSpatialStructure = (
53 { Create the TShape.OctreeTriangles.
54 This is an octree containing all triangles. }
55 ssTriangles);
56 TShapeSpatialStructures = set of TShapeSpatialStructure;
57
58 TShape = class;
59 TShapeList = class;
60
61 TShapeTraverseFunc = procedure (const Shape: TShape) of object;
62
63 TEnumerateShapeTexturesFunction = function (Shape: TShape;
64 Texture: TAbstractTextureNode): Pointer of object;
65
66 TTestShapeVisibility = function (Shape: TShape): boolean of object;
67
68 TShapesHash = QWord;
69
70 { Used for @link(TCastleViewport.OnCustomShapeSort).
71
72 When @link(TCastleViewport.OnCustomShapeSort) is assigned
73 and @link(TCastleViewport.BlendingSort) or
74 @link(TCastleViewport.OcclusionSort) indicate sortCustom,
75 this is used to sort shapes.
76
77 It should return value:
78
79 @unorderedList(
80 @item(< 0 if Shape1 is further from camera than Shape2)
81 @item(= 0 if Shape1 is at the same distance from camera than Shape2)
82 @item(> 0 if Shape1 is closer to camera than Shape2)
83 )
84
85 The RenderOptions1, RenderOptions2 specify the rendering options
86 for, respectively, Shape1 and Shape2.
87 Note that if @link(TCastleViewport.DynamicBatching) is used,
88 these shapes may not come from any particular scene,
89 so their @link(TShapeTree.ParentScene) may be @nil.
90 So you cannot rely on e.g. @code(Shape1.ParentScene.RenderOptions) to get
91 the same value as @code(RenderOptions1).
92
93 SceneTransform1, SceneTransform2 specify the shapes transformations.
94 Note that a shape, just like TCastleScene, may be present multiple times
95 in the same viewport (e.g. when you add the same TCastleScene instance
96 multiple times to @link(TCastleViewport.Items), or if you use
97 @link(TCastleTransformReference)). That's why SceneTransform1, SceneTransform2
98 are useful, as they refer to given shape instance, in a particular transformation.
99
100 A sample implementation, doing actually the same thing as standard sort3DOrigin,
101 may look like this:
102
103 @longCode(#
104 function TMyView.MyShapeSort(
105 const Camera: TViewVectors;
106 const Shape1, Shape2: TShape;
107 const RenderOptions1, RenderOptions2: TCastleRenderOptions;
108 const SceneTransform1, SceneTransform2: TMatrix4): Integer;
109 var
110 PointA, PointB: TVector3;
111 begin
112 PointA := (SceneTransform1 * Shape1.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
113 PointB := (SceneTransform2 * Shape2.OriginalState.Transformation.Transform).MultPoint(TVector3.Zero);
114 Result := Sign(
115 TVector3.DotProduct(PointB, Camera.Direction) -
116 TVector3.DotProduct(PointA, Camera.Direction));
117 // Other approach:
118 // Result := Sign(
119 // PointsDistanceSqr(PointB, Camera.Translation) -
120 // PointsDistanceSqr(PointA, Camera.Translation));
121 end;
122 #)
123 }
124 TShapeSortEvent = function (
125 const Camera: TViewVectors;
126 const Shape1, Shape2: TShape;
127 const RenderOptions1, RenderOptions2: TCastleRenderOptions;
128 const SceneTransform1, SceneTransform2: TMatrix4)
129 : Integer of object;
130
131 { Triangle in a 3D model.
132 Helper methods. }
133 TTriangleHelper = record helper for TTriangle
134 { Shape containing this triangle. }
135 function Shape: TShape;
136
137 { State of this shape, containing various information about 3D shape.
138 This is a shortcut for @link(Shape).State. }
139 function State: TX3DGraphTraverseState;
140
141 { Use State.Transform to update triangle @link(TTriangle.World) geometry
142 from triangle @link(TTriangle.Local) geometry. }
143 procedure UpdateWorld;
144
145 { X3D shape node of this triangle. May be @nil in case of VRML 1.0. }
146 function ShapeNode: TAbstractShapeNode;
147
148 { Material information for the material of this triangle.
149 See TMaterialInfo for usage description.
150 Returns @nil when no node determines material properties
151 (which indicates white unlit look).
152
153 Returned TMaterialInfo is valid only as long as the underlying
154 node (TMaterialNode, TPhysicalMaterialNode, TUnlitMaterialNode, TCommonSurfaceShaderNode...) exists.
155 Do not free it yourself, it will be automatically freed. }
156 function MaterialInfo: TMaterialInfo;
157
158 { Return transparency of this triangle's material.
159 Equivalent to MaterialInfo.Transparency, although a little faster. }
160 function Transparency: Single;
161
162 { Returns @true for triangles that are transparent. }
163 function IsTransparent: boolean;
164
165 { Returns @true for triangles that should be ignored by shadow rays.
166 Returns @true for transparent triangles
167 (with Material.Transparency > 0) and non-shadow-casting triangles
168 (with Appearance.shadowCaster = FALSE). }
169 function IgnoreForShadowRays: boolean;
170
171 {$ifndef CONSERVE_TRIANGLE_MEMORY}
172 { For a given position (in world coordinates), return the smooth
173 normal vector at this point, with the resulting normal vector
174 in world coordinates.
175
176 @seealso TTriangle.INormal }
177 function INormalWorldSpace(const Point: TVector3): TVector3;
178 {$endif}
179 end;
180
181 { Tree of shapes.
182
183 Although VRML/X3D model already provides the tree (graph of VRML/X3D nodes),
184 it's a little too complicated to be used at each render call.
185 It's especially true for VRML <= 1.0 (where properties may "leak out"
186 from one node to the next), VRML/X3D >= 2.0 cleaned a lot here but still
187 some work must be done when traversing (like accumulating transformations).
188
189 So we process VRML/X3D tree to this tree, which is much simpler with
190 all the geometry nodes (TAbstractGeometryNode) along with their state
191 (TX3DGraphTraverseState) as leafs (TShape). }
192 TShapeTree = class
193 strict private
194 FParentScene: TX3DEventsEngine;
195 { Cached MaxShapesCount result, or -1 if not in cache yet. }
196 FMaxShapesCount: Integer;
197 private
198 { Used by TShapeTreeIterator. }
199 CachedChildrenList: array [
200 { OnlyActive } Boolean,
201 { OnlyVisible } Boolean,
202 { OnlyCollidable } Boolean ] of TShapeList;
203 CachedChildrenListHash: array [
204 { OnlyActive } Boolean,
205 { OnlyVisible } Boolean,
206 { OnlyCollidable } Boolean ] of TShapesHash;
207 { Automatically set when adding item to TShapeTreeGroup. }
208 FParent: TShapeTree;
209 function MaxShapesCountCore: Integer; virtual; abstract;
210 procedure InvalidateMaxShapesCount;
211 procedure TraverseCore(const Func: TShapeTraverseFunc;
212 const OnlyActive: boolean;
213 const OnlyVisible: boolean;
214 const OnlyCollidable: boolean); virtual; abstract;
215 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
216 const ParentTransformation: TTransformation); virtual; abstract;
217 public
218 constructor Create(const AParentScene: TX3DEventsEngine);
219 destructor Destroy; override;
220
221 { Maximum value of ShapesCount.
222 This is cached, so it's usually instant, in contrast to ShapesCount. }
223 function MaxShapesCount: Integer;
224
225 { Parent TCastleScene instance.
226
227 This cannot be declared here as TCastleScene or TCastleSceneCore
228 (this would create circular unit dependency),
229 but it always is TCastleScene.
230
231 May be @nil (used by shapes created for batching, that don't belong
232 to any scene). }
233 property ParentScene: TX3DEventsEngine read FParentScene write FParentScene;
234
235 { Traverse shapes inside. There are a few alternative ways to do this:
236
237 - Use this method, and have a callback called for each TShape.
238
239 - Use TraverseList, and have a list of TShape.
240
241 - Use TShapeTreeIterator.Create, that has it's own GetNext / Current methods to enumerate.
242 This is no longer advised -- using TraverseList is simpler and equally fast.
243
244 - Use TShapeList.Create(Tree, OnlyActive, OnlyVisible, OnlyCollidable) overload.
245 This is no longer advised -- using TraverseList is simpler and faster.
246 }
247 procedure Traverse(const Func: TShapeTraverseFunc;
248 const OnlyActive: boolean;
249 const OnlyVisible: boolean = false;
250 const OnlyCollidable: boolean = false);
251
252 { Return TShapeList containing the traversed shapes, just like @link(Traverse).
253 Caller should never free the resulting list, it is owned by this TShapeTree instance. }
254 function TraverseList(
255 const OnlyActive: boolean;
256 const OnlyVisible: boolean = false;
257 const OnlyCollidable: boolean = false): TShapeList;
258
259 { How many shapes would be enumerated by @link(Traverse). }
260 function ShapesCount(const OnlyActive: boolean;
261 const OnlyVisible: boolean = false;
262 const OnlyCollidable: boolean = false): Cardinal;
263
264 { Look for shape with Geometry.X3DName = GeometryNodeName.
265 Returns @nil if not found. }
266 function FindGeometryNodeName(const GeometryNodeName: string;
267 OnlyActive: boolean = false): TShape;
268
269 { Look for shape with Geometry that has a parent named ParentNodeName.
270 Parent is searched by Geometry.TryFindParentNodeByName.
271 Returns @nil if not found. }
272 function FindShapeWithParentNamed(const ParentNodeName: string;
273 OnlyActive: boolean = false): TShape;
274
275 { Enumerate all single texture nodes (possibly) used by the shapes.
276 This looks into all shapes (not only active, so e.g. it looks into all
277 Switch/LOD children, not only the chosen one).
278 This checks all possible ways how a texture may be used by a shape,
279 so it looks at material fields,
280 shaders (ComposedShader, CommonSurfaceShader) and more.
281
282 If Enumerate callbacks returns non-nil for some texture, returns it immediately,
283 and stops further processing. }
284 function EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer; virtual; abstract;
285
286 { Describe the shapes tree, recursively (with children),
287 multi-line (ends with newline too). }
288 function DebugInfo(const Indent: string = ''): string; virtual;
289
290 { Describe this shape, not recursively. }
291 function DebugInfoWithoutChildren: String; virtual;
292
293 { Using the TX3DNode.InternalSceneShape field,
294 you can associate X3D node with a number of TShapeTree instances.
295 This allows to map X3D node -> TShapeTree instances instantly
296 (without e.g. searching the shapes tree for it),
297 which is great to do some operations very quickly.
298
299 Right now:
300 - TShapeTreeTransform is associated with node implementing TTransformFunctionality
301 (like TTransformNode, TBillboardNode, TX3DRootNode).
302
303 - TShape is associated with
304 TShapeNode,
305 TAppearanceNode,
306 TAbstractGeometryNode,
307 TCoordinateNode (anything that can be inside TAbstractGeometryNode.CoordField),
308 TNormalNode (anything that can be inside TAbstractGeometryNode.NormalField),
309 TTangentNode (anything that can be inside TAbstractGeometryNode.TangentField),
310 TColorNode, TColorRGBANode (anything that can be inside TAbstractGeometryNode.ColorField),
311 TAbstractMaterialNode (anything that can be in TAppearanceNode.Material),
312 TTextureCoordinateNode and other stuff that can be inside TAbstractGeometryNode.InternalTexCoord,
313 TClipPlaneNode .
314
315 Note that UnAssociateNode should only be called on nodes
316 with which we are associated. Trying to call UnAssociateNode
317 on a node on which we didn't call AssociateNode will have
318 undefined results (for speed).
319
320 It is valid to associate X3D node with TShapeTree multiple times,
321 but it must be unassociated the same number of times.
322
323 @param Node The node with possibly associated shapes. Never @nil.
324 }
325 procedure AssociateNode(const Node: TX3DNode);
326 procedure UnAssociateNode(const Node: TX3DNode);
327 class function AssociatedShape(const Node: TX3DNode; const Index: Integer): TShapeTree; static;
328 class function AssociatedShapesCount(const Node: TX3DNode): Integer; static;
329
330 procedure FastTransformUpdate(var AnythingChanged: Boolean); virtual;
331 end;
332
333 { Shape is a geometry node @link(Geometry) instance and it's
334 @link(State). For VRML >= 2.0, this usually corresponds to
335 a single instance of actual VRML @code(Shape) node.
336 It allows to perform many operations that need to know both geometry
337 and it's current state (parent Shape node, current transformation and such).
338
339 This class caches results of methods LocalBoundingBox, BoundingBox,
340 and most others (see TShapeValidities for hints).
341 This means that things work fast, but this also means that
342 you must manually call @link(Changed)
343 when you changed some properties of Geometry or contents of State.
344
345 But note that you can't change Geometry or State to different
346 objects --- they are readonly properties.
347
348 Also note that if you're using @link(TCastleSceneCore) class
349 then you don't have to worry about calling @link(Changed)
350 of items in @link(TCastleSceneCore.Shapes).
351 All you have to do is to call appropriate @code(Changed*)
352 methods of @link(TCastleSceneCore). }
353 TShape = class(TShapeTree)
354 strict private
355 type
356 TShapeValidities = set of (svLocalBBox, svBBox,
357 svVerticesCount,
358 svTrianglesCount,
359 svBoundingSphere,
360 svNormals);
361 TNormalsCached = (ncSmooth, ncFlat, ncCreaseAngle);
362
363 var
364 FLocalBoundingBox: TBox3D;
365 FBoundingBox: TBox3D;
366 FVerticesCount, FTrianglesCount: Cardinal;
367 Validities: TShapeValidities;
368 FBoundingSphereCenter: TVector3;
369 FBoundingSphereRadiusSqr: Single;
370 FOriginalGeometry: TAbstractGeometryNode;
371 FOriginalState: TX3DGraphTraverseState;
372 FGeometry: TAbstractGeometryNode;
373 FState: TX3DGraphTraverseState;
374
375 FGeometryParentNode,
376 FGeometryGrandParentNode,
377 FGeometryGrandGrandParentNode: TX3DNode;
378
379 FLocalGeometryChangedCount: Cardinal;
380 FDynamicGeometry: Boolean;
381
382 IsCachedMaterialProperty: boolean;
383 CachedMaterialProperty: TMaterialProperty;
384
385 FShadowVolumes: TShapeShadowVolumes;
386
387 { Just like Geometry() and State(), except return @nil if no proxy available
388 (when Geometry would return the same thing as OriginalGeometry).
389 @groupBegin }
390 function ProxyGeometry: TAbstractGeometryNode;
391 function ProxyState: TX3DGraphTraverseState;
392 { @groupEnd }
393
394 procedure ValidateBoundingSphere;
395
396 { Make both FGeometry and FState set.
397 Uses appropriate Proxy calls to initialize them. }
398 procedure ValidateGeometryState;
399
400 { Make both FGeometry and FState nil (unset),
401 freeing eventual instances created by Proxy methods.
402 Next Geometry() or State() call will cause Proxy to be recalculated. }
403 procedure FreeProxy;
404
405 procedure AssociateGeometryState(
406 const AGeometry: TAbstractGeometryNode;
407 const AState: TX3DGraphTraverseState);
408 procedure UnAssociateGeometryState(
409 const AGeometry: TAbstractGeometryNode;
410 const AState: TX3DGraphTraverseState);
411 procedure AssociateGeometryStateNeverProxied(
412 const AGeometry: TAbstractGeometryNode;
413 const AState: TX3DGraphTraverseState);
414 procedure UnAssociateGeometryStateNeverProxied(
415 const AGeometry: TAbstractGeometryNode;
416 const AState: TX3DGraphTraverseState);
417 procedure AssociateProxyGeometryState;
418 procedure UnAssociateProxyGeometryState;
419 strict private
420 function CreateTriangleOctree(const ALimits: TOctreeLimits): TTriangleOctree;
421 strict private
422 FTriangleOctreeLimits: TOctreeLimits;
423
424 FOctreeTriangles: TTriangleOctree;
425
426 FSpatial: TShapeSpatialStructures;
427 procedure SetSpatial(const Value: TShapeSpatialStructures);
428 strict private
429 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
430 { Mailbox, for speeding up collision queries.
431 @groupBegin }
432 MailboxSavedTag: TMailboxTag;
433 MailboxResult: PTriangle;
434 MailboxIntersection: TVector3;
435 MailboxIntersectionDistance: Single;
436 { @groupEnd }
437 {$endif}
438
439 { All fields below are meaningful only when svNormals in Validities.
440 Normals may be assigned only if svNormals in Validities.
441 Moreover, FNormalsCreaseAngle is meaningful only when
442 (svNormals in Validities) and (NormalsCached = ncCreaseAngle). }
443 FNormalsCached: TNormalsCached;
444 FNormalsCachedCcw: boolean;
445 FNormals: TVector3List;
446 FNormalsCreaseAngle: Single;
447
448 { Free and nil FOctreeTriangles. Also, makes sure to call
449 PointingDeviceClear on ParentScene (since some PTriangle pointers
450 were freed). }
451 procedure FreeOctreeTriangles;
452 private
453 function MaxShapesCountCore: Integer; override;
454 procedure TraverseCore(const Func: TShapeTraverseFunc;
455 const OnlyActive: boolean;
456 const OnlyVisible: boolean = false;
457 const OnlyCollidable: boolean = false); override;
458 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
459 const ParentTransformation: TTransformation); override;
460 public
461 { List of TGeneratedShadowMap instances that should affect this shape.
462
463 May be @nil, equal to an empty list.
464
465 Created on-demand, never owns the children.
466 All children are always non-nil TGeneratedShadowMapNode instances.
467
468 @exclude }
469 InternalShadowMaps: TX3DNodeList;
470
471 { Constructor.
472 @param(ParentInfo Recursive information about parents,
473 for the geometry node of given shape.
474 Note that for VRML 2.0/X3D, the immediate parent
475 of geometry node is always TShapeNode.) }
476 constructor Create(const AParentScene: TX3DEventsEngine;
477 const AOriginalGeometry: TAbstractGeometryNode;
478 const AOriginalState: TX3DGraphTraverseState;
479 const ParentInfo: PTraversingInfo);
480 destructor Destroy; override;
481
482 { Original geometry node, that you get from a VRML/X3D graph. }
483 property OriginalGeometry: TAbstractGeometryNode read FOriginalGeometry;
484
485 { Original state, that you get from a VRML/X3D graph. }
486 property OriginalState: TX3DGraphTraverseState read FOriginalState;
487
488 { Geometry of this shape.
489 This may come from initial VRML/X3D node graph (see OriginalGeometry),
490 or it may be processed by @link(TAbstractGeometryNode.Proxy)
491 for easier handling. }
492 function Geometry: TAbstractGeometryNode;
493
494 { State of this shape.
495 This may come from initial VRML/X3D node graph (see OriginalState),
496 or it may be processed by @link(TAbstractGeometryNode.Proxy)
497 for easier handling.
498
499 Owned by this TShape class. }
500 function State: TX3DGraphTraverseState;
501
502 { Bounding box in local shape coordinates, i.e. disregarging all transformations
503 (any TTransformNode, TCastleTransform) done on top of shape. }
504 function LocalBoundingBox: TBox3D;
505
506 { Bounding box in scene coordinates, i.e. in the local coordinates of TCastleSceneCore
507 that owns this shape.
508
509 The idea is that TCastleSceneCore.LocalBoundingBox is calculated
510 just by summing up the Shape.BoundingBox for each shape.
511 So transformations done using TTransformNode are accounted here.
512 Parent TCastleTransform are not accounted here. }
513 function BoundingBox: TBox3D;
514
515 function VerticesCount: Cardinal; overload;
516 function TrianglesCount: Cardinal; overload;
517
518 function VerticesCount(const Ignored: Boolean): Cardinal; overload; deprecated 'use VerticesCount without Boolean argument, it is ignored now';
519 function TrianglesCount(const Ignored: Boolean): Cardinal; overload; deprecated 'use TrianglesCount without Boolean argument, it is ignored now';
520
521 { Decompose the geometry into primitives, with arrays of per-vertex data. }
522 function GeometryArrays: TGeometryArrays;
523
524 { Calculates bounding sphere based on BoundingBox.
525 In the future this may be changed to use BoundingSphere method
526 of @link(TAbstractGeometryNode), when I will implement it.
527 For now, BoundingSphere is always worse approximation of bounding
528 volume than @link(BoundingBox) (i.e. BoundingSphere is always
529 larger) but it may be useful in some cases when
530 detecting collision versus bounding sphere is much faster than detecting
531 them versus bounding box.
532
533 BoundingSphereRadiusSqr = 0 and BoundingSphereCenter is undefined
534 if Box is empty.
535
536 @groupBegin }
537 function BoundingSphereCenter: TVector3;
538 function BoundingSphereRadiusSqr: Single;
539 function BoundingSphereRadius: Single;
540 { @groupEnd }
541
542 { Exactly equivalent to getting
543 @link(BoundingSphereCenter) and @link(BoundingSphereRadiusSqr)
544 and then using @link(TFrustum.SphereCollisionPossible).
545
546 But it may be a little faster since it avoids some small speed problems
547 (like copying memory contents when you get values of
548 BoundingSphereXxx properties and checking twice are
549 BoundingSphereXxx calculated). }
550 function FrustumBoundingSphereCollisionPossible(
551 const Frustum: TFrustum): TFrustumCollisionPossible;
552
553 { Exactly equivalent to getting
554 @link(BoundingSphereCenter) and @link(BoundingSphereRadiusSqr)
555 and then using @link(TFrustum.SphereCollisionPossibleSimple).
556
557 But it may be a little faster since it avoids some small speed problems. }
558 function FrustumBoundingSphereCollisionPossibleSimple(
559 const Frustum: TFrustum): boolean;
560
561 { Notify this shape that you changed a field inside one of it's nodes
562 (automatically done by TCastleSceneCore).
563 This should be called when fields within Shape.Geometry,
564 Shape.State.Last*, Shape.State.ShapeNode or such change.
565
566 Pass InactiveOnly = @true is you know that this shape is fully in
567 inactive X3D graph part (inactive Switch, LOD etc. children).
568
569 Including chTransform in Changes means something more than
570 general chTransform (which means that transformation of children changed,
571 which implicates many things --- not only shape changes).
572 Here, chTransform in Changes means that only the transformation
573 of TShape.State changed (so only on fields ignored by
574 EqualsNoTransform). }
575 procedure Changed(const InactiveOnly: boolean;
576 const Changes: TX3DChanges); virtual;
577
578 { The dynamic octree containing all triangles.
579 It contains only triangles within this shape.
580
581 There is no distinction here between collidable / visible
582 (as for TCastleSceneCore octrees), since only the whole shape may be
583 marked as visible and/or collidable, not particular triangles.
584
585 The triangles are specified in local coordinate system of this shape
586 (that is, they are independent from transformation within State.Transform).
587 This allows the tree to remain unmodified when transformation of this
588 shape changes.
589
590 This is automatically managed (initialized, updated, and used)
591 by parent TCastleSceneCore. You usually don't need to know about this
592 octree from outside.
593
594 To initialize this, add ssTriangles to @link(InternalSpatial) property,
595 otherwise it's @nil. Parent TCastleSceneCore will take care of this
596 (when parent TCastleSceneCore.Spatial contains ssDynamicCollisions, then
597 all shapes contain ssTriangles within their InternalSpatial).
598
599 Parent TCastleSceneCore will take care to keep this octree always updated.
600
601 Parent TCastleSceneCore will also take care of actually using
602 this octree: TCastleSceneCore.OctreeCollisions methods actually use the
603 octrees of specific shapes at the bottom. }
604 function InternalOctreeTriangles: TTriangleOctree;
605
606 { Which spatial structrues (octrees, for now) should be created and managed.
607 This works analogous to TCastleSceneCore.Spatial, but this manages
608 octrees within this TShape.
609
610 Parent TCastleSceneCore will take care to keep this value updated,
611 you should only set TCastleSceneCore.Spatial from the outside. }
612 property InternalSpatial: TShapeSpatialStructures read FSpatial write SetSpatial;
613
614 { Properties of created triangle octrees.
615 See TriangleOctree unit comments for description.
616
617 Default value comes from DefLocalTriangleOctreeLimits.
618
619 They are used only when the octree is created, so usually you
620 want to set them right before changing @link(InternalSpatial) from []
621 to something else. }
622 function InternalTriangleOctreeLimits: POctreeLimits;
623
624 { How should the alpha of the resulting calculation be used.
625 Should we use alpha blending (partial transparency),
626 or alpha test (yes-or-no transparency)
627 or none of it (shape is simply opaque).
628
629 This is determined looking at the @link(TAppearanceNode.AlphaChannel) field.
630 By default, it is acAuto, which in turn means that the final value
631 of this method (which cannot be acAuto) is calculated
632 looking at material, color, texture nodes data (including at texture
633 images contents). }
634 function AlphaChannel: TAlphaChannel;
635 function Blending: boolean; deprecated 'use "AlphaChannel = acBlending"';
636 function Transparent: boolean; deprecated 'use "AlphaChannel = acBlending"';
637
638 { Is the shape visible.
639 Most shapes are visible, except when placed in @link(TCollisionNode.Proxy)
640 (which allows to define invisible shapes, only for collision purposes). }
641 function Visible: boolean;
642
643 { Is the shape collidable.
644 Most shapes are collidable.
645 One exception is when @link(TAbstractShapeNode.Collision) is set to scNone,
646 which disables collisions.
647 Another exception is when the shape is placed inside @link(TCollisionNode) children,
648 and then you use @link(TCollisionNode.Enabled) to turn off collisions,
649 or @link(TCollisionNode.Proxy) to provide alternative geometry for collisions. }
650 function Collidable: boolean;
651
652 { Equivalent to using OctreeTriangles.RayCollision, except this
653 wil use the mailbox. }
654 function RayCollision(
655 const Tag: TMailboxTag;
656 out Intersection: TVector3;
657 out IntersectionDistance: Single;
658 const RayOrigin, RayDirection: TVector3;
659 const ReturnClosestIntersection: boolean;
660 const TriangleToIgnore: PTriangle;
661 const IgnoreMarginAtStart: boolean;
662 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): PTriangle;
663
664 { Equivalent to using OctreeTriangles.SegmentCollision, except this
665 wil use the mailbox. }
666 function SegmentCollision(
667 const Tag: TMailboxTag;
668 out Intersection: TVector3;
669 out IntersectionDistance: Single;
670 const Pos1, Pos2: TVector3;
671 const ReturnClosestIntersection: boolean;
672 const TriangleToIgnore: PTriangle;
673 const IgnoreMarginAtStart: boolean;
674 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): PTriangle;
675
676 { Create normals suitable for this shape.
677
678 You can call this only when Geometry is coordinate-based
679 X3D geometry, implementing Coord and having non-empty coordinates
680 (that is, Geometry.Coord returns @true and sets ACoord <> @nil),
681 and having Geometry.CoordIndex <> @nil.
682
683 For NormalsSmooth, also Geometry.CoordIndex = @nil is allowed,
684 but make sure that Geometry.InternalCoordPolygons is available.
685 See CreateSmoothNormalsCoordinateNode.
686
687 @unorderedList(
688 @item(Smooth normals are perfectly smooth, per-vertex.
689
690 As an exception, you can call this even when coords are currently
691 empty (Geometry.Coord returns @true but ACoord is @nil),
692 then result is also @nil.)
693
694 @item(Flat normals are per-face.
695 Calculated by CreateFlatNormals.)
696
697 @item(Finally NormalsCreaseAngle creates separate
698 normal per index (auto-smoothing by CreaseAngle).)
699 )
700
701 The normals here are cached. So using these methods makes condiderable
702 speedup if the shape will not change (@link(Changed) method) and
703 will need normals many times (e.g. will be rendered many times).
704
705 @groupBegin }
706 function NormalsSmooth(const FromCcw: boolean): TVector3List;
707 function NormalsFlat(const FromCcw: boolean): TVector3List;
708 function NormalsCreaseAngle(const FromCcw: boolean;
709 const CreaseAngle: Single): TVector3List;
710 { @groupEnd }
711
712 function EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer; override;
713
714 { Is the texture node Node possibly used by this shape.
715 This is equivalent to checking does EnumerateShapeTextures return this shape. }
716 function UsesTexture(Node: TAbstractTextureNode): boolean;
717
718 { Check is shape a shadow caster. Looks at Shape's
719 Appearance.shadowCaster field (see
720 https://castle-engine.io/x3d_extensions.php#section_ext_shadow_caster). }
721 function ShadowCaster: boolean;
722
723 { Triangulate shape. Calls TriangleEvent callback for each triangle.
724 LocalTriangulate returns coordinates in local shape transformation
725 (that is, not transformed by State.Transform yet).
726
727 @groupBegin }
728 procedure Triangulate(const TriangleEvent: TTriangleEvent);
729 procedure LocalTriangulate(const TriangleEvent: TTriangleEvent);
730 { @groupEnd }
731
732 function DebugInfoWithoutChildren: String; override;
733 function NiceName: string;
734
735 { Local geometry changes very often (like every frame).
736 This is automatically detected and set to @true.
737 May be used as an optimization hint. }
738 property DynamicGeometry: Boolean read FDynamicGeometry;
739
740 { Shape node in X3D graph.
741 This is always non-nil for X3D, VRML 2 and all model formats that are imported
742 as X3D, like glTF, Spine, sprite sheets and more.
743 This is @nil only for old VRML 1.0 and Inventor model formats. }
744 function Node: TAbstractShapeNode;
745
746 { Parent, grand-parent, grand-grand-parent nodes determined during traversing
747 of the X3D node graph.
748
749 Note that GeometryParentNode is almost always equal to @link(Node),
750 for X3D, VRML 2 and all model formats that are imported
751 as X3D, like glTF, Spine, sprite sheets and more.
752 That's because in VRML 2 and X3D, parent of geometry node must be a TShapeNode.
753
754 Only in old VRML 1.0 and Inventor model formats the GeometryParentNode
755 may be different than @link(Node).
756
757 All these nodes (GeometryParentNode, GeometryGrandParentNode and
758 GeometryGrandGrandParentNode) may be useful if you
759 need to take a different action depending on the parent nodes of this shape.
760
761 @groupBegin }
762 property GeometryParentNode: TX3DNode read FGeometryParentNode;
763 property GeometryGrandParentNode: TX3DNode read FGeometryGrandParentNode;
764 property GeometryGrandGrandParentNode: TX3DNode read FGeometryGrandGrandParentNode;
765 { @groupEnd }
766
767 function GeometryParentNodeName: String; deprecated 'use GeometryParentNode.X3DName';
768 function GeometryGrandParentNodeName: String; deprecated 'use GeometryGrandParentNode.X3DName';
769 function GeometryGrandGrandParentNodeName: String; deprecated 'use GeometryGrandGrandParentNode.X3DName';
770
771 { Material property associated with this shape's material/texture. }
772 function InternalMaterialProperty: TMaterialProperty;
773 function MaterialProperty: TMaterialProperty; deprecated 'use InternalMaterialProperty, or (better) do not use it at all -- this is internal';
774
775 { @exclude }
776 property InternalShadowVolumes: TShapeShadowVolumes read FShadowVolumes;
777
778 { @exclude
779 Called internally by the engine when changing some stuff in shapes.
780 User code should not use it (as we do not guarantee what is OK
781 to change this way, and what should rebuild shapes graph),
782 instead user code should change X3D scene graph,
783 calling @link(TCastleSceneCore.BeforeNodesFree) earlier,
784 and call @link(TX3DField.Changed) after each change. }
785 procedure InternalBeforeChange;
786 { @exclude }
787 procedure InternalAfterChange;
788 end;
789
790 TShapeTreeList = {$ifdef FPC}specialize{$endif} TObjectList<TShapeTree>;
791
792 { Internal (non-leaf) node of the TShapeTree.
793 This is practically just a list of other children
794 (other TShapeTree items).
795
796 All children are considered "active" by this class.
797
798 This class owns it's children TShapeTree.
799 Since TShapeTree is a simple tree structure, there are no duplicates
800 possible, that is given TShapeTree instance may be within only
801 one parent TShapeTree. (VRML node's parenting mechanism is more
802 complicated than this, because of DEF/USE mechanism.) }
803 TShapeTreeGroup = class(TShapeTree)
804 strict private
805 FChildren: TShapeTreeList;
806 procedure ChildrenChanged(Sender: TObject;
807 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Item: TShapeTree;
808 Action: TCollectionNotification);
809 private
810 function MaxShapesCountCore: Integer; override;
811 procedure TraverseCore(const Func: TShapeTraverseFunc;
812 const OnlyActive: boolean;
813 const OnlyVisible: boolean = false;
814 const OnlyCollidable: boolean = false); override;
815 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
816 const ParentTransformation: TTransformation); override;
817 public
818 constructor Create(const AParentScene: TX3DEventsEngine);
819 destructor Destroy; override;
820
821 property Children: TShapeTreeList read FChildren;
822
823 function EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer; override;
824
825 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
826
827 { Start index for TShapeTreeIterator.
828 Must be >= -1 (-1 means to start from 0).
829
830 May be >= Children.Count, even IterateBeginIndex + 1 may
831 be >= Children.Count, i.e. it's Ok if this is already out of range. }
832 function IterateBeginIndex(OnlyActive: boolean): Integer; virtual;
833
834 { End index for TShapeTreeIterator. Valid indexes are < this.
835 This must be <= Children.Count. }
836 function IterateEndIndex(OnlyActive: boolean): Cardinal; virtual;
837
838 {$endif}
839
840 function DebugInfo(const Indent: string = ''): string; override;
841 end;
842
843 { Node of the TShapeTree representing an alternative,
844 choosing one (or none) child from it's children list as active.
845
846 It's ideal for representing the VRML >= 2.0 Switch node
847 (not possible for VRML 1.0 Switch node, as it may affect also other
848 nodes after Switch). Actually, it even has a SwitchNode link that is
849 used to decide which child to choose (using SwitchNode.FdWhichChoice). }
850 TShapeTreeSwitch = class(TShapeTreeGroup)
851 strict private
852 FSwitchNode: TSwitchNode;
853 private
854 procedure TraverseCore(const Func: TShapeTraverseFunc;
855 const OnlyActive: boolean;
856 const OnlyVisible: boolean = false;
857 const OnlyCollidable: boolean = false); override;
858 public
859 property SwitchNode: TSwitchNode read FSwitchNode write FSwitchNode;
860
861 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
862 function IterateBeginIndex(OnlyActive: boolean): Integer; override;
863 function IterateEndIndex(OnlyActive: boolean): Cardinal; override;
864 {$endif}
865
866 function DebugInfoWithoutChildren: String; override;
867 end;
868
869 { Node of the TShapeTree transforming it's children.
870
871 It's ideal for handling VRML 2.0 / X3D Transform node,
872 and similar nodes (MatrixTransform and some H-Anim nodes also act
873 as a transformation node and also may be handled by this). }
874 TShapeTreeTransform = class(TShapeTreeGroup)
875 strict private
876 FTransformFunctionality: TTransformFunctionality;
877 FTransformState: TX3DGraphTraverseState;
878 procedure SetTransformFunctionality(const Value: TTransformFunctionality);
879 private
880 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
881 const ParentTransformation: TTransformation); override;
882 public
883 constructor Create(const AParentScene: TX3DEventsEngine);
884 destructor Destroy; override;
885 procedure FastTransformUpdate(var AnythingChanged: Boolean); override;
886 function DebugInfoWithoutChildren: String; override;
887
888 property TransformFunctionality: TTransformFunctionality
889 read FTransformFunctionality write SetTransformFunctionality;
890
891 function TransformNode: TX3DNode;
892
893 { State right before traversing the TransformNode.
894 Owned by this TShapeTreeTransform instance. You should assign
895 to it when you set TransformNode. }
896 property TransformState: TX3DGraphTraverseState read FTransformState;
897 end;
898
899 { Node of the TShapeTree representing the LOD (level of detail) alternative.
900 It chooses one child from it's children list as active.
901 Represents the VRML >= 2.0 LOD node
902 (not possible for VRML 1.0 LOD node, as it may affect also other
903 nodes after LOD).
904
905 To choose which child is active we need to know the LOD node,
906 with it's transformation in VRML graph.
907 This information is in LODNode and LODInverseTransform properties.
908
909 Also, we need to know the current camera position.
910 This is passed as CameraPosition to CalculateLevel.
911 Note that this class doesn't call CalculateLevel by itself, never.
912 You have to call CalculateLevel, and use it to set Level property,
913 from parent scene to make this LOD work. (Reasoning behind this decision:
914 parent scene has CameraPosition and such, and parent scene
915 knows whether to initiate level_changes event sending.) }
916 TShapeTreeLOD = class(TShapeTreeGroup)
917 strict private
918 FLODNode: TLODNode;
919 FLODInverseTransform: TMatrix4;
920 FLevel: Cardinal;
921 FWasLevel_ChangedSend: boolean;
922 private
923 procedure TraverseCore(const Func: TShapeTraverseFunc;
924 const OnlyActive: boolean;
925 const OnlyVisible: boolean = false;
926 const OnlyCollidable: boolean = false); override;
927 public
928 property LODNode: TLODNode read FLODNode write FLODNode;
929 function LODInverseTransform: PMatrix4;
930
931 { Calculate @link(Level). This only calculates level, doesn't
932 assign @link(Level) property or send level_changed event. }
933 function CalculateLevel(const CameraPosition: TVector3): Cardinal;
934
935 { Current level, that is index of the active child of this LOD node.
936 This is always < Children.Count, unless there are no children.
937 In this case it's 0.
938
939 Should be calculated by CalculateLevel. By default
940 we simply use the first (highest-detail) LOD as active.
941 So if you never assign this (e.g. because TCastleSceneCore.CameraViewKnown
942 = @false, that is user position is never known) we'll always
943 use the highest-detail children. }
944 property Level: Cardinal read FLevel write FLevel default 0;
945
946 property WasLevel_ChangedSend: boolean
947 read FWasLevel_ChangedSend write FWasLevel_ChangedSend default false;
948
949 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
950 function IterateBeginIndex(OnlyActive: boolean): Integer; override;
951 function IterateEndIndex(OnlyActive: boolean): Cardinal; override;
952 {$endif}
953 function DebugInfoWithoutChildren: String; override;
954 end;
955
956 TProximitySensorInstance = class(TShapeTree)
957 strict private
958 FNode: TProximitySensorNode;
959 private
960 function MaxShapesCountCore: Integer; override;
961 procedure TraverseCore(const Func: TShapeTraverseFunc;
962 const OnlyActive: boolean;
963 const OnlyVisible: boolean = false;
964 const OnlyCollidable: boolean = false); override;
965 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
966 const ParentTransformation: TTransformation); override;
967 public
968 InverseTransform: TMatrix4;
969 IsActive: boolean;
970
971 property Node: TProximitySensorNode read FNode write FNode;
972
973 function EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer; override;
974 function DebugInfoWithoutChildren: String; override;
975 end;
976
977 TVisibilitySensorInstance = class(TShapeTree)
978 strict private
979 FNode: TVisibilitySensorNode;
980 private
981 function MaxShapesCountCore: Integer; override;
982 procedure TraverseCore(const Func: TShapeTraverseFunc;
983 const OnlyActive: boolean;
984 const OnlyVisible: boolean = false;
985 const OnlyCollidable: boolean = false); override;
986 procedure FastTransformUpdateCore(var AnythingChanged: Boolean;
987 const ParentTransformation: TTransformation); override;
988 public
989 { Bounding box of this visibility sensor instance,
990 already transformed to global VRML/X3D scene coordinates.
991 That is, transformed by parent Transform and similar nodes. }
992 Box: TBox3D;
993 Transform: TMatrix4;
994
995 property Node: TVisibilitySensorNode read FNode write FNode;
996
997 function EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer; override;
998 function DebugInfoWithoutChildren: String; override;
999 end;
1000
1001 { Iterates over all TShape items that would be enumerated by
1002 Tree.Traverse. Sometimes it's easier to write code using this iterator
1003 than to create callbacks and use TShapeTree.Traverse. }
1004 TShapeTreeIterator = class
1005 strict private
1006 FCurrent: TShape;
1007 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
1008 Info: Pointer;
1009 SingleShapeRemaining: boolean;
1010 FOnlyActive, FOnlyVisible, FOnlyCollidable: boolean;
1011 function CurrentMatches: boolean;
1012 {$else}
1013 List: TShapeList;
1014 CurrentIndex: Integer;
1015 {$endif}
1016 public
1017 constructor Create(const Tree: TShapeTree; const OnlyActive: boolean;
1018 const OnlyVisible: boolean = false;
1019 const OnlyCollidable: boolean = false);
1020 destructor Destroy; override;
1021 function GetNext: boolean;
1022 property Current: TShape read FCurrent;
1023 end deprecated{ 'use Tree.TraverseList(...)'};
1024
1025 TShapeList = class({$ifdef FPC}specialize{$endif} TObjectList<TShape>)
1026 private
1027 { Like regular Add, but parameter is "const" to satisfy TShapeTraverseFunc signature. }
1028 procedure AddConst(const S: TShape);
1029 public
1030 constructor Create; overload;
1031 { Constructor that initializes list contents by traversing given tree. }
1032 constructor Create(const Tree: TShapeTree; const OnlyActive: boolean;
1033 const OnlyVisible: boolean = false;
1034 const OnlyCollidable: boolean = false); overload; deprecated 'use Tree.TraverseList(...)';
1035 end;
1036
1037 var
1038 { If nonzero, disables automatic TShape.DynamicGeometry detection
1039 on every node modification. This is useful if you do some interactive
1040 editing of the shape, but you don't want to mark shape as dynamic. }
1041 DisableAutoDynamicGeometry: Cardinal;
1042
1043 { Log various information about shapes. This displays quite a lot of non-critical
1044 information when opening non-trivial models. }
1045 LogShapes: boolean = false;
1046
1047 type
1048 { Detect the 3D placeholder name set in the external modeler,
1049 like 3D object name set in Blender or 3DS Max.
1050 Assumes that a specific modeler was used to create and export this 3D model.
1051 Each TPlaceholderName function is made to follow the logic of a single
1052 modeler, and they are gathered in PlaceholderNames.
1053
1054 Returns empty string if none.
1055
1056 When implementing this, you may find useful the following properties
1057 of the shape: TShape.OriginalGeometry.X3DName,
1058 TShape.Node.X3DName, TShape.GeometryParentNode.X3DName,
1059 TShape.GeometryGrandParentNode.X3DName,
1060 TShape.GeometryGrandGrandParentNode.X3DName.
1061
1062 Preferably, the result should be unique, only for this VRML/X3D shape.
1063 But in practice it's the responsibility of the modeler
1064 and model author to make it true.
1065 For example, modelers that allow multiple materials on object (like
1066 Blender) @italic(must) split a single 3D object into many VRML/X3D shapes
1067 sometimes.
1068 So just don't use shapes with multiple materials if this shape
1069 may be meaningful for a placeholder.
1070
1071 This is used only by TLevel.Load placeholders.
1072 Ultimately, this should be something that is easy to set when creating
1073 a 3D model in given external modeler.
1074 @italic(Nothing else in our engine depends on a particular modeler
1075 strategy for exporting VRML/X3D models.)
1076
1077 This should be object name (to allow sharing a single mesh underneath).
1078 Except when it's not possible (like for old Blender VRML 1.0 exporter,
1079 when only mesh names are stored in VRML/X3D exported files),
1080 in which case it can be a mesh name. }
1081 TPlaceholderName = function (const Shape: TShape): string;
1082 TPlaceholderNames = class({$ifdef FPC}specialize{$endif} TDictionary<string, TPlaceholderName>)
1083 strict private
1084 function GetItems(const AKey: string): TPlaceholderName;
1085 procedure SetItems(const AKey: string; const AValue: TPlaceholderName);
1086 public
1087 { Access dictionary items.
1088 Setting this is allowed regardless if the key previously existed or not,
1089 in other words: setting this does AddOrSetValue, contrary to the ancestor TDictionary
1090 that only allows setting when the key already exists. }
1091 property Items [const AKey: string]: TPlaceholderName read GetItems write SetItems; default;
1092 end;
1093
1094 var
1095 PlaceholderNames: TPlaceholderNames;
1096
1097 implementation
1098
1099 uses Generics.Defaults, Math,
1100 CastleSceneCore, CastleInternalNormals, CastleLog,
1101 CastleStringUtils, CastleInternalArraysGenerator, CastleUriUtils;
1102
1103 const
1104 UnknownTexCoord: TTriangle4 = (Data: (
1105 (X: 0; Y: 0; Z: 0; W: 1),
1106 (X: 0; Y: 0; Z: 0; W: 1),
1107 (X: 0; Y: 0; Z: 0; W: 1)
1108 ));
1109
1110 { TTriangleHelper ------------------------------------------------------------ }
1111
1112 function TTriangleHelper.Shape: TShape;
1113 begin
1114 Assert(InternalShape is TShape); // will be optimized out in RELEASE mode
1115 Result := TShape(InternalShape);
1116 end;
1117
1118 function TTriangleHelper.State: TX3DGraphTraverseState;
1119 begin
1120 Result := TShape(InternalShape).State;
1121 end;
1122
1123 procedure TTriangleHelper.UpdateWorld;
1124 begin
1125 World.Triangle := Local.Triangle.Transform(State.Transformation.Transform);
1126 {$ifndef CONSERVE_TRIANGLE_MEMORY_MORE}
1127 World.Plane := World.Triangle.NormalizedPlane;
1128 World.Area := World.Triangle.Area;
1129 {$endif}
1130 end;
1131
1132 function TTriangleHelper.ShapeNode: TAbstractShapeNode;
1133 begin
1134 Result := State.ShapeNode;
1135 end;
1136
1137 function TTriangleHelper.MaterialInfo: TMaterialInfo;
1138 begin
1139 Result := State.MaterialInfo;
1140 end;
1141
1142 function TTriangleHelper.Transparency: Single;
1143 var
1144 M: TMaterialInfo;
1145 begin
1146 M := MaterialInfo;
1147 if M <> nil then
1148 Result := M.Transparency
1149 else
1150 Result := 0;
1151 end;
1152
1153 function TTriangleHelper.IsTransparent: boolean;
1154 begin
1155 Result := Transparency > SingleEpsilon;
1156 end;
1157
1158 function TTriangleHelper.IgnoreForShadowRays: boolean;
1159
1160 function NonShadowCaster(State: TX3DGraphTraverseState): boolean;
1161 var
1162 Shape: TAbstractShapeNode;
1163 begin
1164 Shape := State.ShapeNode;
1165 Result :=
1166 (Shape <> nil) and
1167 (Shape.Appearance <> nil) and
1168 (not Shape.Appearance.ShadowCaster);
1169 end;
1170
1171 begin
1172 Result := ({ IsTransparent } Transparency > SingleEpsilon) or
1173 NonShadowCaster(State);
1174 end;
1175
1176 {$ifndef CONSERVE_TRIANGLE_MEMORY}
1177 function TTriangleHelper.INormalWorldSpace(const Point: TVector3): TVector3;
1178 begin
1179 Result := State.Transformation.Transform.MultDirection(INormalCore(Point)).Normalize;
1180 end;
1181 {$endif not CONSERVE_TRIANGLE_MEMORY}
1182
1183 { TShapeTree ------------------------------------------------------------ }
1184
1185 constructor TShapeTree.Create(const AParentScene: TX3DEventsEngine);
1186 begin
1187 inherited Create;
1188 FParentScene := AParentScene;
1189 FMaxShapesCount := -1;
1190 end;
1191
1192 destructor TShapeTree.Destroy;
1193 var
1194 OnlyActive: Boolean;
1195 OnlyVisible: Boolean;
1196 OnlyCollidable: Boolean;
1197 begin
1198 for OnlyActive := Low(Boolean) to High(Boolean) do
1199 for OnlyVisible := Low(Boolean) to High(Boolean) do
1200 for OnlyCollidable := Low(Boolean) to High(Boolean) do
1201 FreeAndNil(CachedChildrenList[OnlyActive, OnlyVisible, OnlyCollidable]);
1202 inherited;
1203 end;
1204
1205 function TShapeTree.MaxShapesCount: Integer;
1206 begin
1207 if FMaxShapesCount = -1 then
1208 FMaxShapesCount := MaxShapesCountCore;
1209 Result := FMaxShapesCount;
1210 end;
1211
1212 function TShapeTree.FindGeometryNodeName(
1213 const GeometryNodeName: string; OnlyActive: boolean): TShape;
1214 var
1215 ShapeList: TShapeList;
1216 Shape: TShape;
1217 begin
1218 ShapeList := TraverseList(OnlyActive);
1219 for Shape in ShapeList do
1220 begin
1221 Result := Shape;
1222 if Result.OriginalGeometry.X3DName = GeometryNodeName then Exit;
1223 end;
1224 Result := nil;
1225 end;
1226
1227 function TShapeTree.FindShapeWithParentNamed(
1228 const ParentNodeName: string; OnlyActive: boolean): TShape;
1229 var
1230 ShapeList: TShapeList;
1231 Shape: TShape;
1232 begin
1233 ShapeList := TraverseList(OnlyActive);
1234 for Shape in ShapeList do
1235 begin
1236 Result := Shape;
1237 if Result.OriginalGeometry.TryFindParentByName(ParentNodeName) <> nil then Exit;
1238 end;
1239 Result := nil;
1240 end;
1241
1242 procedure TShapeTree.AssociateNode(const Node: TX3DNode);
1243 var
1244 OldShapeTree: TShapeTree;
1245 begin
1246 { InternalSceneShape is either nil, TShapeTree or TShapeTreeList.
1247 Memory usage is important here -- we have a lot of nodes in larger scenes,
1248 and in many cases a Node is associated with at most one TShapeTree.
1249 So we optimize this common case. }
1250
1251 if Node.InternalSceneShape = nil then
1252 Node.InternalSceneShape := Self
1253 else
1254 if Node.InternalSceneShape <> nil then
1255 begin
1256 { comparing ClassType is faster than "InternalSceneShape is TShapeTreeList",
1257 and enough in this case. }
1258 if Node.InternalSceneShape.ClassType <> TShapeTreeList then
1259 begin
1260 // convert Node.InternalSceneShape into list with 1 item
1261 Assert(Node.InternalSceneShape is TShapeTree);
1262 OldShapeTree := TShapeTree(Node.InternalSceneShape);
1263 Node.InternalSceneShape := TShapeTreeList.Create(false);
1264 TShapeTreeList(Node.InternalSceneShape).Add(OldShapeTree);
1265 end;
1266 TShapeTreeList(Node.InternalSceneShape).Add(Self);
1267 end;
1268 end;
1269
1270 procedure TShapeTree.UnAssociateNode(const Node: TX3DNode);
1271 begin
1272 if Node.InternalSceneShape = Self then
1273 Node.InternalSceneShape := nil
1274 else
1275 begin
1276 if Node.InternalSceneShape = nil then
1277 begin
1278 WritelnWarning('Calling %s.UnAssociateNode on X3D node that is already not associated with anything: %s. This can happen when you manually change nodes.',
1279 [ClassName, Node.NiceName]);
1280 Exit;
1281 end;
1282
1283 { TODO: Node.InternalSceneShape may be TGLShape here,
1284 see testcase from "DirectionalLight crash in CGE" from Jan Adamec.
1285
1286 As a temporary workaround,
1287 instead of failing assertion "Assert(Node.InternalSceneShape is TShapeTreeList);"
1288 or crashing at reading "TShapeTreeList(Node.InternalSceneShape).Count",
1289 detect it and behave gracefully for now.
1290
1291 This should be investigated and fixed properly.
1292 But also, processing of CastleInternalShadowMaps, which is likely
1293 the fault of this, is doomed to be removed in favor of different
1294 shadow maps application for
1295 https://github.com/castle-engine/castle-engine/issues/284 anyway.
1296 }
1297 if not (Node.InternalSceneShape is TShapeTreeList) then
1298 begin
1299 WritelnWarning('TODO: Calling %s.UnAssociateNode on X3D node that is associated with something unexpected: %s.',
1300 [ClassName, Node.NiceName]);
1301 Node.InternalSceneShape := nil;
1302 Exit;
1303 end;
1304
1305 Assert(Node.InternalSceneShape is TShapeTreeList);
1306 if TShapeTreeList(Node.InternalSceneShape).Count = 1 then
1307 begin
1308 Assert(TShapeTreeList(Node.InternalSceneShape)[0] = Self);
1309 Node.InternalSceneShape.Free;
1310 Node.InternalSceneShape := nil;
1311 end else
1312 TShapeTreeList(Node.InternalSceneShape).Remove(Self);
1313 end;
1314 end;
1315
1316 class function TShapeTree.AssociatedShape(const Node: TX3DNode; const Index: Integer): TShapeTree; {$ifdef FPC}static;{$endif}
1317 begin
1318 if Node.InternalSceneShape.ClassType = TShapeTreeList then
1319 Result := TShapeTreeList(Node.InternalSceneShape)[Index]
1320 else
1321 Result := TShapeTree(Node.InternalSceneShape);
1322 end;
1323
1324 class function TShapeTree.AssociatedShapesCount(const Node: TX3DNode): Integer; {$ifdef FPC}static;{$endif}
1325 begin
1326 if Node.InternalSceneShape = nil then
1327 Result := 0
1328 else
1329 if Node.InternalSceneShape.ClassType <> TShapeTreeList then
1330 begin
1331 Assert(Node.InternalSceneShape is TShapeTree);
1332 Result := 1;
1333 end else
1334 Result := TShapeTreeList(Node.InternalSceneShape).Count;
1335 end;
1336
1337 procedure TShapeTree.InvalidateMaxShapesCount;
1338 begin
1339 FMaxShapesCount := -1;
1340 if FParent <> nil then
1341 FParent.InvalidateMaxShapesCount;
1342 end;
1343
1344 function TShapeTree.TraverseList(const OnlyActive, OnlyVisible, OnlyCollidable: Boolean): TShapeList;
1345 var
1346 CurrentShapesHash: TShapesHash;
1347
1348 { Call TraverseCore, gather shapes to a new list. }
1349 procedure TraverseCoreToList;
1350 begin
1351 Result := TShapeList.Create;
1352 { Set Capacity, to make AddToList calls faster.
1353 Note that we use MaxShapesCount instead of ShapesCount,
1354 since MaxShapesCount is usually instant, while ShapesCount...
1355 now ShapesCount depends on TraverseList, so it would cause infinite loop. }
1356 Result.Capacity := MaxShapesCount;
1357 TraverseCore({$ifdef FPC}@{$endif} Result.AddConst, OnlyActive, OnlyVisible, OnlyCollidable);
1358 CachedChildrenListHash[OnlyActive, OnlyVisible, OnlyCollidable] := CurrentShapesHash;
1359 CachedChildrenList[OnlyActive, OnlyVisible, OnlyCollidable] := Result;
1360 end;
1361
1362 begin
1363 Result := CachedChildrenList[OnlyActive, OnlyVisible, OnlyCollidable];
1364 if Result <> nil then
1365 begin
1366 if FParentScene <> nil then
1367 CurrentShapesHash := TCastleSceneCore(FParentScene).InternalShapesHash
1368 else
1369 CurrentShapesHash := 0;
1370 if CurrentShapesHash <> CachedChildrenListHash[OnlyActive, OnlyVisible, OnlyCollidable] then
1371 begin
1372 FreeAndNil(CachedChildrenList[OnlyActive, OnlyVisible, OnlyCollidable]);
1373 TraverseCoreToList;
1374 end;
1375 end else
1376 begin
1377 TraverseCoreToList;
1378 end;
1379 end;
1380
1381 procedure TShapeTree.Traverse(const Func: TShapeTraverseFunc;
1382 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
1383 var
1384 I: Integer;
1385 List: TShapeList;
1386 begin
1387 List := TraverseList(OnlyActive, OnlyVisible, OnlyCollidable);
1388 for I := 0 to List.Count - 1 do
1389 Func(List[I]);
1390 end;
1391
1392 function TShapeTree.ShapesCount(
1393 const OnlyActive, OnlyVisible, OnlyCollidable: boolean): Cardinal;
1394 begin
1395 // Since TraverseList is optimized now by caching, this method can just call TraverseList
1396 Result := TraverseList(OnlyActive, OnlyVisible, OnlyCollidable).Count;
1397 end;
1398
1399 procedure TShapeTree.FastTransformUpdate(var AnythingChanged: Boolean);
1400 var
1401 T: TTransformation;
1402 begin
1403 T.Init;
1404 FastTransformUpdateCore(AnythingChanged, T);
1405 end;
1406
1407 function TShapeTree.DebugInfo(const Indent: String): String;
1408 begin
1409 Result := Indent + DebugInfoWithoutChildren + NL;
1410 end;
1411
1412 function TShapeTree.DebugInfoWithoutChildren: String;
1413 begin
1414 Result := ClassName;
1415 end;
1416
1417 { TShape -------------------------------------------------------------- }
1418
1419 constructor TShape.Create(const AParentScene: TX3DEventsEngine;
1420 const AOriginalGeometry: TAbstractGeometryNode;
1421 const AOriginalState: TX3DGraphTraverseState;
1422 const ParentInfo: PTraversingInfo);
1423 var
1424 PI: PTraversingInfo;
1425 begin
1426 inherited Create(AParentScene);
1427
1428 FTriangleOctreeLimits := DefLocalTriangleOctreeLimits;
1429 FShadowVolumes := TShapeShadowVolumes.Create(Self);
1430
1431 FOriginalGeometry := AOriginalGeometry;
1432 FOriginalState := AOriginalState;
1433
1434 AssociateGeometryState(FOriginalGeometry, FOriginalState);
1435 AssociateGeometryStateNeverProxied(FOriginalGeometry, FOriginalState);
1436
1437 PI := ParentInfo;
1438 if PI <> nil then
1439 begin
1440 FGeometryParentNode := PI^.Node;
1441 PI := PI^.ParentInfo;
1442 if PI <> nil then
1443 begin
1444 FGeometryGrandParentNode := PI^.Node;
1445 PI := PI^.ParentInfo;
1446 if PI <> nil then
1447 FGeometryGrandGrandParentNode := PI^.Node;
1448 end;
1449 end;
1450
1451 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
1452 MailboxSavedTag := -1;
1453 {$endif}
1454 end;
1455
1456 destructor TShape.Destroy;
1457 begin
1458 FreeAndNil(InternalShadowMaps);
1459 FreeAndNil(FShadowVolumes);
1460 FreeProxy;
1461 FreeAndNil(FNormals);
1462 if FOriginalState <> nil then // when exception occurs in constructor, may be nil
1463 begin
1464 UnAssociateGeometryState(FOriginalGeometry, FOriginalState);
1465 UnAssociateGeometryStateNeverProxied(FOriginalGeometry, FOriginalState);
1466 FreeAndNil(FOriginalState);
1467 end;
1468 FreeOctreeTriangles;
1469 inherited;
1470 end;
1471
1472 function TShape.GeometryParentNodeName: String;
1473 begin
1474 if GeometryParentNode <> nil then
1475 Result := GeometryParentNode.X3DName
1476 else
1477 Result := '';
1478 end;
1479
1480 function TShape.GeometryGrandParentNodeName: String;
1481 begin
1482 if GeometryGrandParentNode <> nil then
1483 Result := GeometryGrandParentNode.X3DName
1484 else
1485 Result := '';
1486 end;
1487
1488 function TShape.GeometryGrandGrandParentNodeName: String;
1489 begin
1490 if GeometryGrandGrandParentNode <> nil then
1491 Result := GeometryGrandGrandParentNode.X3DName
1492 else
1493 Result := '';
1494 end;
1495
1496 procedure TShape.AssociateGeometryState(
1497 const AGeometry: TAbstractGeometryNode;
1498 const AState: TX3DGraphTraverseState);
1499 begin
1500 if AGeometry <> nil then
1501 begin
1502 AssociateNode(AGeometry);
1503 if (AGeometry.ColorField <> nil) and
1504 (AGeometry.ColorField.Value <> nil) then
1505 AssociateNode(AGeometry.ColorField.Value);
1506 if (AGeometry.CoordField <> nil) and
1507 (AGeometry.CoordField.Value <> nil) then
1508 AssociateNode(AGeometry.CoordField.Value);
1509 if (AGeometry.NormalField <> nil) and
1510 (AGeometry.NormalField.Value <> nil) then
1511 AssociateNode(AGeometry.NormalField.Value);
1512 if (AGeometry.TangentField <> nil) and
1513 (AGeometry.TangentField.Value <> nil) then
1514 AssociateNode(AGeometry.TangentField.Value);
1515 if (AGeometry.TexCoordField <> nil) and
1516 (AGeometry.TexCoordField.Value <> nil) and
1517 { TODO: This workarounds assertion failure in UnAssociateNode
1518 when using shadow maps on a primitive, like Sphere.
1519 Reproducible by castle-model-viewer (open and close
1520 demo-models/shadow_maps/primitives.x3dv )
1521 and automatic tests (when TTestOpeningAndRendering3D.TestScene
1522 opens and closes tests/data/warning_when_new_node_as_shadow_map_light.x3dv ).
1523 The cause is unknown.
1524 But in any case, associating with TMultiTextureCoordinateNode
1525 is not really useful (we should associate with children of it). }
1526 (not (AGeometry.TexCoordField.Value is TMultiTextureCoordinateNode)) then
1527 AssociateNode(AGeometry.TexCoordField.Value);
1528 end;
1529 end;
1530
1531 procedure TShape.AssociateGeometryStateNeverProxied(
1532 const AGeometry: TAbstractGeometryNode;
1533 const AState: TX3DGraphTraverseState);
1534 var
1535 I: Integer;
1536 begin
1537 if AState <> nil then
1538 begin
1539 if AState.ShapeNode <> nil then
1540 begin
1541 AssociateNode(AState.ShapeNode);
1542 if AState.ShapeNode.Appearance <> nil then
1543 begin
1544 AssociateNode(AState.ShapeNode.Appearance);
1545 if AState.ShapeNode.Appearance.Material <> nil then
1546 AssociateNode(AState.ShapeNode.Appearance.Material);
1547 end;
1548 end;
1549 if AState.ClipPlanes <> nil then
1550 for I := 0 to AState.ClipPlanes.Count - 1 do
1551 AssociateNode(AState.ClipPlanes[I].Node);
1552 end;
1553 end;
1554
1555 procedure TShape.UnAssociateGeometryState(
1556 const AGeometry: TAbstractGeometryNode;
1557 const AState: TX3DGraphTraverseState);
1558 begin
1559 if AGeometry <> nil then
1560 begin
1561 UnAssociateNode(AGeometry);
1562 if (AGeometry.ColorField <> nil) and
1563 (AGeometry.ColorField.Value <> nil) then
1564 UnAssociateNode(AGeometry.ColorField.Value);
1565 if (AGeometry.CoordField <> nil) and
1566 (AGeometry.CoordField.Value <> nil) then
1567 UnAssociateNode(AGeometry.CoordField.Value);
1568 if (AGeometry.NormalField <> nil) and
1569 (AGeometry.NormalField.Value <> nil) then
1570 UnAssociateNode(AGeometry.NormalField.Value);
1571 if (AGeometry.TangentField <> nil) and
1572 (AGeometry.TangentField.Value <> nil) then
1573 UnAssociateNode(AGeometry.TangentField.Value);
1574 if (AGeometry.TexCoordField <> nil) and
1575 (AGeometry.TexCoordField.Value <> nil) and
1576 (not (AGeometry.TexCoordField.Value is TMultiTextureCoordinateNode)) then
1577 UnAssociateNode(AGeometry.TexCoordField.Value);
1578 end;
1579 end;
1580
1581 procedure TShape.UnAssociateGeometryStateNeverProxied(
1582 const AGeometry: TAbstractGeometryNode;
1583 const AState: TX3DGraphTraverseState);
1584 var
1585 I: Integer;
1586 begin
1587 if AState <> nil then
1588 begin
1589 if AState.ShapeNode <> nil then
1590 begin
1591 UnAssociateNode(AState.ShapeNode);
1592 if AState.ShapeNode.Appearance <> nil then
1593 begin
1594 UnAssociateNode(AState.ShapeNode.Appearance);
1595 if AState.ShapeNode.Appearance.Material <> nil then
1596 UnAssociateNode(AState.ShapeNode.Appearance.Material);
1597 end;
1598 end;
1599 if AState.ClipPlanes <> nil then
1600 for I := 0 to AState.ClipPlanes.Count - 1 do
1601 UnAssociateNode(AState.ClipPlanes[I].Node);
1602 end;
1603 end;
1604
1605 procedure TShape.AssociateProxyGeometryState;
1606 begin
1607 Assert(FGeometry <> nil);
1608 Assert(FState <> nil);
1609
1610 { For speed, do not even call AssociateGeometryState
1611 when the proxy is equal to actual nodes.
1612 This way in an usual case, a geometry node will have only 1 associated shape,
1613 which is best for memory usage. }
1614
1615 if (FGeometry <> FOriginalGeometry) or
1616 (FState <> FOriginalState) then
1617 begin
1618 AssociateGeometryState(FGeometry, FState);
1619 end;
1620 end;
1621
1622 procedure TShape.UnAssociateProxyGeometryState;
1623 begin
1624 Assert(FGeometry <> nil);
1625 Assert(FState <> nil);
1626
1627 if (FGeometry <> FOriginalGeometry) or
1628 (FState <> FOriginalState) then
1629 begin
1630 UnAssociateGeometryState(FGeometry, FState);
1631 end;
1632 end;
1633
1634 procedure TShape.FreeOctreeTriangles;
1635 begin
1636 { secure against ParentScene = nil, since this may be called from destructor }
1637
1638 if ParentScene <> nil then
1639 begin
1640 { Some PTriangles will be freed. Make sure to clear
1641 PointingDeviceOverItem, unless they belong to a different shape. }
1642 if (TCastleSceneCore(ParentScene).PointingDeviceOverItem <> nil) and
1643 (TCastleSceneCore(ParentScene).PointingDeviceOverItem^.Shape = Self) then
1644 TCastleSceneCore(ParentScene).PointingDeviceClear;
1645 end;
1646
1647 FreeAndNil(FOctreeTriangles);
1648 end;
1649
1650 function TShape.InternalOctreeTriangles: TTriangleOctree;
1651 var
1652 TimeStart: TCastleProfilerTime;
1653 S: String;
1654 begin
1655 if (ssTriangles in InternalSpatial) and (FOctreeTriangles = nil) then
1656 begin
1657 S := 'Creating octree for shape ' + NiceName;
1658 if LogChanges then
1659 WritelnLog('X3D changes (octree)', S);
1660 TimeStart := Profiler.Start(S);
1661 try
1662 FOctreeTriangles := CreateTriangleOctree(FTriangleOctreeLimits);
1663 finally
1664 Profiler.Stop(TimeStart);
1665 end;
1666 end;
1667
1668 Result := FOctreeTriangles;
1669 end;
1670
1671 function TShape.InternalTriangleOctreeLimits: POctreeLimits;
1672 begin
1673 Result := @FTriangleOctreeLimits;
1674 end;
1675
1676 function TShape.LocalBoundingBox: TBox3D;
1677 begin
1678 if not (svLocalBBox in Validities) then
1679 begin
1680 FLocalBoundingBox := OriginalGeometry.LocalBoundingBox(OriginalState,
1681 ProxyGeometry, ProxyState);
1682 Include(Validities, svLocalBBox);
1683 end;
1684 Result := FLocalBoundingBox;
1685 end;
1686
1687 function TShape.BoundingBox: TBox3D;
1688 begin
1689 if not (svBBox in Validities) then
1690 begin
1691 FBoundingBox := OriginalGeometry.BoundingBox(OriginalState,
1692 ProxyGeometry, ProxyState);
1693 Include(Validities, svBBox);
1694 end;
1695 Result := FBoundingBox;
1696 end;
1697
1698 function TShape.VerticesCount: Cardinal;
1699
1700 procedure Calculate;
1701 begin
1702 FVerticesCount := OriginalGeometry.VerticesCount(
1703 OriginalState, ProxyGeometry, ProxyState);
1704 end;
1705
1706 begin
1707 if not (svVerticesCount in Validities) then
1708 begin
1709 Calculate;
1710 Include(Validities, svVerticesCount);
1711 end;
1712 Result := FVerticesCount;
1713 end;
1714
1715 function TShape.TrianglesCount: Cardinal;
1716
1717 procedure Calculate;
1718 begin
1719 FTrianglesCount := OriginalGeometry.TrianglesCount(
1720 OriginalState, ProxyGeometry, ProxyState);
1721 end;
1722
1723 begin
1724 if not (svTrianglesCount in Validities) then
1725 begin
1726 Calculate;
1727 Include(Validities, svTrianglesCount);
1728 end;
1729 Result := FTrianglesCount;
1730 end;
1731
1732 function TShape.VerticesCount(const Ignored: Boolean): Cardinal;
1733 begin
1734 Result := VerticesCount();
1735 end;
1736
1737 function TShape.TrianglesCount(const Ignored: Boolean): Cardinal;
1738 begin
1739 Result := TrianglesCount();
1740 end;
1741
1742 function TShape.GeometryArrays: TGeometryArrays;
1743 var
1744 G: TAbstractGeometryNode;
1745 S: TX3DGraphTraverseState;
1746
1747 procedure TexCoordsNeededForMapping(var Needed: Cardinal; const Mapping: String);
1748 var
1749 Index: Integer;
1750 begin
1751 if G.FindTextureMapping(Mapping, Index, false) <> nil then
1752 MaxVar(Needed, Index + 1);
1753 end;
1754
1755 function TexCoordsNeeded: Cardinal;
1756 var
1757 Tex: TAbstractTextureNode;
1758 SurfaceShader: TCommonSurfaceShaderNode;
1759 MatPhong: TMaterialNode;
1760 MatPhysical: TPhysicalMaterialNode;
1761 MatOne: TAbstractOneSidedMaterialNode;
1762 begin
1763 Tex := S.MainTexture;
1764
1765 if Tex is TMultiTextureNode then
1766 Result := TMultiTextureNode(Tex).FdTexture.Count
1767 else
1768 if Tex <> nil then
1769 Result := 1
1770 else
1771 Result := 0;
1772
1773 { we need at least 1 texture coordinate if some special texture
1774 (not necessarily diffuse texture) is used }
1775 if (S.ShapeNode <> nil) and
1776 (S.ShapeNode.Appearance <> nil) then
1777 begin
1778 // CommonSurfaceShader can only be non-nil if Appearance is non-nil
1779 {$warnings off} // using deprecated to keep backward compatibility
1780 SurfaceShader := S.ShapeNode.CommonSurfaceShader;
1781 {$warnings on}
1782 if SurfaceShader <> nil then
1783 begin
1784 if SurfaceShader.MultiDiffuseAlphaTexture <> nil then
1785 MaxVar(Result, SurfaceShader.DiffuseTextureCoordinatesId + 1); // TODO test X3DOM/InstantReality are they using DiffuseTextureCoordinatesId in this case
1786 if SurfaceShader.DiffuseTexture <> nil then
1787 MaxVar(Result, SurfaceShader.DiffuseTextureCoordinatesId + 1);
1788 if SurfaceShader.NormalTexture <> nil then
1789 MaxVar(Result, SurfaceShader.NormalTextureCoordinatesId + 1);
1790 if SurfaceShader.AmbientTexture <> nil then
1791 MaxVar(Result, SurfaceShader.AmbientTextureCoordinatesId + 1);
1792 if SurfaceShader.SpecularTexture <> nil then
1793 MaxVar(Result, SurfaceShader.SpecularTextureCoordinatesId + 1);
1794 if SurfaceShader.ShininessTexture <> nil then
1795 MaxVar(Result, SurfaceShader.ShininessTextureCoordinatesId + 1);
1796 end else
1797 begin
1798 if S.ShapeNode.Appearance.NormalMap <> nil then
1799 MaxVar(Result, 1);
1800 if S.ShapeNode.Appearance.Material is TAbstractOneSidedMaterialNode then
1801 begin
1802 MatOne := TAbstractOneSidedMaterialNode(S.ShapeNode.Appearance.Material);
1803 if MatOne.EmissiveTexture <> nil then
1804 TexCoordsNeededForMapping(Result, MatOne.EmissiveTextureMapping);
1805 if MatOne.NormalTexture <> nil then
1806 TexCoordsNeededForMapping(Result, MatOne.NormalTextureMapping);
1807 end;
1808 if S.ShapeNode.Appearance.Material is TMaterialNode then
1809 begin
1810 MatPhong := TMaterialNode(S.ShapeNode.Appearance.Material);
1811 if MatPhong.AmbientTexture <> nil then
1812 TexCoordsNeededForMapping(Result, MatPhong.AmbientTextureMapping);
1813 if MatPhong.DiffuseTexture <> nil then
1814 TexCoordsNeededForMapping(Result, MatPhong.DiffuseTextureMapping);
1815 if MatPhong.ShininessTexture <> nil then
1816 TexCoordsNeededForMapping(Result, MatPhong.ShininessTextureMapping);
1817 if MatPhong.SpecularTexture <> nil then
1818 TexCoordsNeededForMapping(Result, MatPhong.SpecularTextureMapping);
1819 if MatPhong.OcclusionTexture <> nil then
1820 TexCoordsNeededForMapping(Result, MatPhong.OcclusionTextureMapping);
1821 end;
1822 if S.ShapeNode.Appearance.Material is TPhysicalMaterialNode then
1823 begin
1824 MatPhysical := TPhysicalMaterialNode(S.ShapeNode.Appearance.Material);
1825 if MatPhysical.BaseTexture <> nil then
1826 TexCoordsNeededForMapping(Result, MatPhysical.BaseTextureMapping);
1827 if MatPhysical.MetallicRoughnessTexture <> nil then
1828 TexCoordsNeededForMapping(Result, MatPhysical.MetallicRoughnessTextureMapping);
1829 if MatPhysical.OcclusionTexture <> nil then
1830 TexCoordsNeededForMapping(Result, MatPhysical.OcclusionTextureMapping);
1831 end;
1832 end;
1833 end;
1834
1835 if OriginalGeometry.FontTextureNode <> nil then
1836 Inc(Result);
1837 end;
1838
1839 function ArrayForBox(Box: TBox3D): TGeometryArrays;
1840 begin
1841 { When there's no TArraysGenerator suitable, then we have an unsupported node.
1842
1843 For now, we make an array describing a single quad: this shape's
1844 bounding box in XY plane. The reason for this is historical
1845 (this was a proper shape to approximate collision with 2D Text nodes;
1846 but they do not get anymore into this procedure, as they are implemented
1847 by a proxy that renders them through QuadSet or such node). }
1848
1849 Result := TGeometryArrays.Create;
1850 if not Box.IsEmpty then
1851 begin
1852 Result.Primitive := gpTriangleFan;
1853 Result.Count := 4;
1854
1855 Result.Position(0)^ := Vector3(Box.Data[0][0], Box.Data[0][1], Box.Data[0][2]);
1856 Result.Position(1)^ := Vector3(Box.Data[1][0], Box.Data[0][1], Box.Data[0][2]);
1857 Result.Position(2)^ := Vector3(Box.Data[1][0], Box.Data[1][1], Box.Data[0][2]);
1858 Result.Position(3)^ := Vector3(Box.Data[0][0], Box.Data[1][1], Box.Data[0][2]);
1859
1860 Result.Normal(0)^ := TVector3.One[2];
1861 Result.Normal(1)^ := TVector3.One[2];
1862 Result.Normal(2)^ := TVector3.One[2];
1863 Result.Normal(3)^ := TVector3.One[2];
1864 end;
1865 end;
1866
1867 var
1868 GeneratorClass: TArraysGeneratorClass;
1869 Generator: TArraysGenerator;
1870 begin
1871 G := Geometry;
1872 S := State;
1873 GeneratorClass := GetArraysGenerator(G);
1874 if GeneratorClass <> nil then
1875 begin
1876 Generator := GeneratorClass.Create(Self);
1877 try
1878 Generator.TexCoordsNeeded := TexCoordsNeeded;
1879 Generator.FacesNeeded := true;
1880 { Leave the rest of Generator properties as default }
1881 Result := Generator.GenerateArrays;
1882 finally FreeAndNil(Generator) end;
1883 end else
1884 Result := ArrayForBox(LocalBoundingBox);
1885 end;
1886
1887 procedure TShape.FreeProxy;
1888 begin
1889 if LogChanges and
1890 { OriginalGeometry should always be <> nil, but just in case
1891 (e.g. running from destructor, or with bad state) check. }
1892 (OriginalGeometry <> nil) and
1893 (
1894 ( (FGeometry <> OriginalGeometry) and (FGeometry <> nil) ) or
1895 ( (FState <> OriginalState ) and (FState <> nil) )
1896 ) then
1897 WritelnLog('X3D changes', 'Releasing the Proxy geometry of ' + OriginalGeometry.ClassName);
1898
1899 if FGeometry <> nil then
1900 UnAssociateProxyGeometryState;
1901
1902 if FGeometry <> OriginalGeometry then
1903 FreeAndNil(FGeometry)
1904 else
1905 FGeometry := nil;
1906
1907 if FState <> OriginalState then
1908 FreeAndNil(FState)
1909 else
1910 FState := nil;
1911
1912 Assert(FGeometry = nil);
1913 Assert(FState = nil);
1914 end;
1915
1916 procedure TShape.Changed(const InactiveOnly: boolean;
1917 const Changes: TX3DChanges);
1918
1919 { Called when local geometry changed.
1920
1921 "Local" means that we're concerned here about changes visible
1922 in shape local coordinate system. E.g. things that only change our
1923 transformation (State.Transform) do not cause "local" geometry changes.
1924
1925 "Geometry" means that we're concerned only about changes to topology
1926 --- vertexes, edges, faces, how they connect each other.
1927 Things that affect only appearance (e.g. whole Shape.appearance content
1928 in stuff for VRML >= 2.0) is not relevant here. E.g. changing
1929 material color does not cause "local" geometry changes.
1930
1931 This frees the octree (will be recreated on Octree* call).
1932 Also removes cached normals.
1933 Also notifies parent scene about this change. }
1934 procedure LocalGeometryChanged(const ChangedOnlyCoord: boolean);
1935 begin
1936 if FLocalGeometryChangedCount <> 0 then
1937 begin
1938 if DisableAutoDynamicGeometry = 0 then
1939 FDynamicGeometry := true;
1940 end else
1941 Inc(FLocalGeometryChangedCount); // for now, only increase FLocalGeometryChangedCount to 1
1942
1943 if (FOctreeTriangles <> nil) and
1944 { Do not recreate octree if it's based only on our bounding box,
1945 and our bounding box is stored in TShapeNode.Box (so it doesn't change when
1946 geometry changes).
1947 This is the case with glTF skinned animation. }
1948 not (
1949 (Node <> nil) and
1950 (Node.Collision in [scBox, scNone]) and
1951 (not Node.BBox.IsEmpty)
1952 ) then
1953 FreeOctreeTriangles;
1954
1955 { Remove cached normals }
1956 FreeAndNil(FNormals);
1957 Exclude(Validities, svNormals);
1958
1959 { Remove from Validities things that depend on geometry.
1960 Local geometry change means that also global (world-space) geometry changed. }
1961 Validities := Validities - [svLocalBBox, svBBox,
1962 svVerticesCount,
1963 svTrianglesCount,
1964 svBoundingSphere,
1965 svNormals];
1966
1967 { Clear variables after removing fvTrianglesList* }
1968 FShadowVolumes.InvalidateTrianglesListShadowCasters;
1969
1970 { Edges topology possibly changed. }
1971 if not ChangedOnlyCoord then
1972 { When ChangedOnlyCoord, we don't do InvalidateManifoldAndBorderEdges,
1973 and this an important optimization (makes mesh deformation cheaper). }
1974 FShadowVolumes.InvalidateManifoldAndBorderEdges;
1975
1976 if ParentScene <> nil then
1977 begin
1978 if ChangedOnlyCoord then
1979 TCastleSceneCore(ParentScene).DoGeometryChanged(gcLocalGeometryChangedCoord, Self)
1980 else
1981 TCastleSceneCore(ParentScene).DoGeometryChanged(gcLocalGeometryChanged, Self);
1982 end;
1983 end;
1984
1985 begin
1986 { Remember to code everything here to act only when some stuff
1987 is included inside Changed value. For example, when
1988 Changes = [chClipPlane], there's no need to do anything here. }
1989
1990 { When Proxy needs to be recalculated.
1991 Include chVisibleVRML1State, since even MaterialBinding may change VRML 1.0
1992 proxies. }
1993 if Changes * [
1994 chCoordinate,
1995 chNormal,
1996 chTangent,
1997 chVisibleVRML1State,
1998 chGeometryVRML1State,
1999 chTextureCoordinate,
2000 chGeometry,
2001 chGeometryFontChanged,
2002 chWireframe,
2003 chFontStyle,
2004 chFontStyleFontChanged
2005 ] <> [] then
2006 FreeProxy;
2007
2008 { When bounding volumes in global coordinates changed.
2009 Probably only chTransform is really needed here
2010 (testcase: upwind_turbine.x3d), as other flags already cause other changes
2011 that invalidate global bboxes anyway. }
2012 if Changes * [
2013 chTransform,
2014 chCoordinate,
2015 chGeometry,
2016 chGeometryFontChanged,
2017 chGeometryVRML1State,
2018 chEverything,
2019 chFontStyle,
2020 chFontStyleFontChanged
2021 ] <> [] then
2022 Validities := Validities - [svBBox, svBoundingSphere];
2023
2024 { Changes to actual geometry that are limited to Coordinate (topology or other things don't change). }
2025 if chCoordinate in Changes then
2026 LocalGeometryChanged(true);
2027
2028 { Changes to actual geometry (other). }
2029 if Changes * [
2030 chGeometry,
2031 chGeometryFontChanged,
2032 chGeometryVRML1State,
2033 chWireframe,
2034 chFontStyle,
2035 chFontStyleFontChanged
2036 ] <> [] then
2037 LocalGeometryChanged(false);
2038
2039 if Changes * [chBBox] <> [] then
2040 begin
2041 Validities := Validities - [svLocalBBox, svBBox];
2042 if (Node <> nil) and (Node.Collision in [scBox, scNone]) then
2043 FreeOctreeTriangles; // bbox changed, so simple octree based on bbox also changed
2044 end;
2045
2046 { Recreate TTextNode.FontTextureNode when FontStyle parameters,
2047 like font family/bold/italic changed. }
2048 if Changes * [
2049 chGeometryFontChanged,
2050 chFontStyleFontChanged
2051 ] <> [] then
2052 (FOriginalGeometry as TTextNode).FontChanged;
2053
2054 if (ParentScene <> nil) and (not InactiveOnly) then
2055 TCastleSceneCore(ParentScene).VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]);
2056 end;
2057
2058 procedure TShape.ValidateBoundingSphere;
2059 begin
2060 if not (svBoundingSphere in Validities) then
2061 begin
2062 BoundingBox.BoundingSphere(FBoundingSphereCenter, FBoundingSphereRadiusSqr);
2063 Include(Validities, svBoundingSphere);
2064 end;
2065 end;
2066
2067 function TShape.BoundingSphereCenter: TVector3;
2068 begin
2069 ValidateBoundingSphere;
2070 Result := FBoundingSphereCenter;
2071 end;
2072
2073 function TShape.BoundingSphereRadiusSqr: Single;
2074 begin
2075 ValidateBoundingSphere;
2076 Result := FBoundingSphereRadiusSqr;
2077 end;
2078
2079 function TShape.BoundingSphereRadius: Single;
2080 begin
2081 Result := Sqrt(BoundingSphereRadiusSqr);
2082 end;
2083
2084 function TShape.FrustumBoundingSphereCollisionPossible(
2085 const Frustum: TFrustum): TFrustumCollisionPossible;
2086 begin
2087 ValidateBoundingSphere;
2088 Result := Frustum.SphereCollisionPossible(
2089 FBoundingSphereCenter, FBoundingSphereRadiusSqr);
2090 end;
2091
2092 function TShape.FrustumBoundingSphereCollisionPossibleSimple(
2093 const Frustum: TFrustum): boolean;
2094 begin
2095 ValidateBoundingSphere;
2096 Result := Frustum.SphereCollisionPossibleSimple(
2097 FBoundingSphereCenter, FBoundingSphereRadiusSqr);
2098 end;
2099
2100 function TShape.CreateTriangleOctree(
2101 const ALimits: TOctreeLimits): TTriangleOctree;
2102
2103 procedure LocalTriangulateBox(const Box: TBox3D);
2104
2105 procedure LocalTriangulateRect(const constCoord: T3DAxis;
2106 const constCoordValue, x1, y1, x2, y2: Single);
2107 var
2108 Position, Normal: TTriangle3;
2109 i: Integer;
2110 c1, c2: T3DAxis;
2111
2112 procedure TriAssign(TriIndex: integer; c1value, c2value: Single);
2113 begin
2114 Position.Data[TriIndex].Data[c1] := c1value;
2115 Position.Data[TriIndex].Data[c2] := c2value;
2116 end;
2117
2118 begin
2119 RestOf3DCoords(constCoord, c1, c2);
2120
2121 for I := 0 to 2 do
2122 begin
2123 Position.Data[I].Data[ConstCoord] := ConstCoordValue;
2124 {$warnings off} // silence FPC warning about Normal uninitialized
2125 Normal.Data[I].Data[C1] := 0;
2126 {$warnings on}
2127 Normal.Data[I].Data[C2] := 0;
2128 Normal.Data[I].Data[ConstCoord] := 1; { TODO: or -1 }
2129 end;
2130
2131 TriAssign(0, x1, y1);
2132 TriAssign(1, x1, y2);
2133 TriAssign(2, x2, y2);
2134 Result.AddItemTriangle(Self, Position, Normal, UnknownTexCoord, UnknownFaceIndex);
2135 TriAssign(0, x1, y1);
2136 TriAssign(1, x2, y2);
2137 TriAssign(2, x2, y1);
2138 Result.AddItemTriangle(Self, Position, Normal, UnknownTexCoord, UnknownFaceIndex);
2139 end;
2140
2141 var
2142 I, XCoord, YCoord: T3DAxis;
2143 begin
2144 for I := 0 to 2 do
2145 begin
2146 RestOf3DCoords(I, XCoord, YCoord);
2147 LocalTriangulateRect(I, Box.Data[0][I], Box.Data[0][XCoord], Box.Data[0][YCoord], Box.Data[1][XCoord], Box.Data[1][YCoord]);
2148 LocalTriangulateRect(I, Box.Data[1][I], Box.Data[0][XCoord], Box.Data[0][YCoord], Box.Data[1][XCoord], Box.Data[1][YCoord]);
2149 end;
2150 { We have 12 triangles, DefTriangleOctreeLeafCapacity should be at least 12,
2151 and tree root should remain leaf.
2152 This should be a simple tree. }
2153 Assert(Result.TreeRoot.IsLeaf);
2154 end;
2155
2156 begin
2157 Result := TTriangleOctree.Create(ALimits, LocalBoundingBox);
2158 try
2159 if (Node <> nil) and (Node.Collision in [scBox, scNone]) then
2160 begin
2161 { Add 12 triangles for 6 cube (LocalBoundingBox) sides. }
2162 Result.Triangles.Capacity := 12;
2163 LocalTriangulateBox(LocalBoundingBox);
2164 end else
2165 begin
2166 Result.Triangles.Capacity := TrianglesCount;
2167 LocalTriangulate({$ifdef FPC}@{$endif}Result.AddItemTriangle);
2168 end;
2169 except Result.Free; raise end;
2170
2171 { $define CASTLE_DEBUG_OCTREE_DUPLICATION}
2172 {$ifdef CASTLE_DEBUG_OCTREE_DUPLICATION}
2173 WritelnLog('Triangles In Shape Octree Stats', '%d items in octree, %d items in octree''s leafs, duplication %f. Size of items in bytes: %d * %d = %d',
2174 [Result.TotalItemsInOctree,
2175 Result.TotalItemsInLeafs,
2176 Result.TotalItemsInLeafs / Result.TotalItemsInOctree,
2177 Result.Triangles.Count,
2178 SizeOf(TTriangle),
2179 Result.Triangles.Count * SizeOf(TTriangle)]);
2180 {$endif}
2181 end;
2182
2183 procedure TShape.SetSpatial(const Value: TShapeSpatialStructures);
2184 var
2185 Old, New: boolean;
2186 begin
2187 if FSpatial <> Value then
2188 begin
2189 Old := ssTriangles in InternalSpatial;
2190 New := ssTriangles in Value;
2191
2192 FSpatial := Value;
2193
2194 { Handle OctreeTriangles }
2195
2196 if Old and not New then
2197 FreeOctreeTriangles;
2198 if New and not Old then
2199 { We do not strictly need to create FOctreeTriangles now,
2200 we could let it be created on-demand.
2201 But experience shows that it is better to create it now.
2202 Otherwise moving around the scene would create sudden stutters
2203 as we load octrees, for each shape separately, when needed.
2204
2205 Note: we were loading not-on-demand before 2010, and switched
2206 to only on-demand in
2207 https://github.com/castle-engine/castle-engine/commit/d5030af3a3372fccaeb2472e9d0bd390190b5f2a .
2208 But it was wrong.
2209 "Lynch" demo https://github.com/michaliskambi/lynch
2210 clearly shows that on-demand causes bad delays at playing.
2211 Moreover, TCastleSceneCore.SetSpatial was actually workarounding
2212 it (calling "Shape.InternalOctreeTriangles" right after setting
2213 "Shape.InternalSpatial := Value") for some time,
2214 but it just wasn't perfect,
2215 because if we did "Scene.Spatial := [ssDynamicCollisions]"
2216 but later "Scene.URL := ..." then didn't create octree for new shapes.
2217
2218 Note: InternalOctreeTriangles only does the job if FSpatial is already set to non-empty.
2219 }
2220 InternalOctreeTriangles;
2221 end;
2222 end;
2223
2224 function TShape.Transparent: boolean;
2225 begin
2226 Result := AlphaChannel = acBlending;
2227 end;
2228
2229 function TShape.Blending: boolean;
2230 begin
2231 Result := AlphaChannel = acBlending;
2232 end;
2233
2234 function TShape.AlphaChannel: TAlphaChannel;
2235
2236 function DetectAlphaBlending: boolean;
2237
2238 { All the "transparency" field values are greater than zero.
2239 So the blending should be used when rendering.
2240
2241 Note that when "transparency" field is empty, then we assume
2242 a default transparency (0) should be used. So AllMaterialsTransparent
2243 is @false then (contrary to the strict definition of "all",
2244 which should be true for empty sets).
2245
2246 This potentially isn't efficient (iterating over all materials
2247 every time we need to return AlphaChannel) but it doesn't matter much,
2248 this is only for deprecated VRML 1.0. }
2249 function AllMaterialsTransparent(const Node: TMaterialNode_1): boolean;
2250 var
2251 i: Integer;
2252 begin
2253 if Node.FdTransparency.Items.Count = 0 then
2254 result := TMaterialInfo.DefaultTransparency > SingleEpsilon else
2255 begin
2256 for i := 0 to Node.FdTransparency.Items.Count-1 do
2257 if Node.FdTransparency.Items.L[i] <= SingleEpsilon then
2258 Exit(false);
2259 result := true;
2260 end;
2261 end;
2262
2263 var
2264 M: TMaterialInfo;
2265 Tex: TAbstractTextureNode;
2266 begin
2267 if State.ShapeNode <> nil then
2268 begin
2269 M := State.MaterialInfo;
2270 Result := (M <> nil) and (M.Transparency > SingleEpsilon);
2271 end else
2272 { For VRML 1.0, there may be multiple materials on a node.
2273 Some of them may be transparent, some not --- we arbitrarily
2274 decide for now that AllMaterialsTransparent decides whether
2275 blending should be used or not. We may change this in the
2276 future to AnyMaterialsTransparent, since this will be more
2277 consistent with X3D ColorRGBA treatment?
2278
2279 We do not try to split node into multiple instances.
2280 This is difficult and memory-consuming task, so we just
2281 depend on VRML author to split his geometry nodes if he
2282 wants it.
2283
2284 Obviously, we also drop the idea of splitting the geometry
2285 into separate triangles and deciding whether to use blending
2286 for each separate triangle. Or to sort every separate triangle.
2287 This would obviously get very very slow for models with lots
2288 of triangles. }
2289 Result := AllMaterialsTransparent(State.VRML1State.Material);
2290
2291 if Geometry.InternalColorRGBA <> nil then
2292 Result := true;
2293
2294 { If texture exists with full range alpha channel then use blending.
2295 Note that State.Texture may be TMultiTextureNode --- that's Ok,
2296 it has AlphaChannel = atFullRange
2297 if any child has atFullRange. So it automatically works Ok too. }
2298 Tex := State.MainTexture;
2299 if (Tex <> nil) and (Tex.AlphaChannelFinal = acBlending) then
2300 Result := true;
2301
2302 Tex := OriginalGeometry.FontTextureNode;
2303 if (Tex <> nil) and (Tex.AlphaChannelFinal = acBlending) then
2304 Result := true;
2305 end;
2306
2307 function DetectAlphaTest: Boolean;
2308 var
2309 TextureNode: TAbstractTextureNode;
2310 FontTextureNode: TAbstractTexture2DNode;
2311 TexturesAlphaChannel: TAlphaChannel;
2312 begin
2313 TextureNode := State.MainTexture;
2314 FontTextureNode := OriginalGeometry.FontTextureNode;
2315
2316 { This works also for TextureNode being TMultiTextureNode,
2317 since it has smartly calculated AlphaChannel based on children. }
2318 TexturesAlphaChannel := acNone;
2319 if TextureNode <> nil then
2320 AlphaMaxVar(TexturesAlphaChannel, TextureNode.AlphaChannelFinal);
2321 if FontTextureNode <> nil then
2322 AlphaMaxVar(TexturesAlphaChannel, FontTextureNode.AlphaChannelFinal);
2323 Result := TexturesAlphaChannel = acTest;
2324 end;
2325
2326 { TODO: DetectAlphaBlending and DetectAlphaTest both look at alpha channel
2327 of textures. They should share some part of a single implementation. }
2328
2329 const
2330 AlphaModeToChannel: array [TAlphaMode] of TAutoAlphaChannel = (
2331 { amAuto -> } acAuto,
2332 { amOpaque -> } acNone,
2333 { amMask -> } acTest,
2334 { amBlend -> } acBlending
2335 );
2336 begin
2337 { Check whether Appearance.alphaMode or alphaChannel field is set to something <> "AUTO".
2338 This is the simplest option, in which we don't need to run our "auto detection"
2339 below. }
2340 if (State.ShapeNode <> nil) and
2341 (State.ShapeNode.Appearance <> nil) and
2342 (State.ShapeNode.Appearance.AlphaMode <> amAuto) then
2343 Exit(AlphaModeToChannel[State.ShapeNode.Appearance.AlphaMode]);
2344
2345 if (State.ShapeNode <> nil) and
2346 (State.ShapeNode.Appearance <> nil) and
2347 (State.ShapeNode.Appearance.AlphaChannel <> acAuto) then
2348 Exit(State.ShapeNode.Appearance.AlphaChannel);
2349
2350 if DetectAlphaBlending then
2351 Exit(acBlending)
2352 else
2353 if DetectAlphaTest then
2354 Exit(acTest)
2355 else
2356 Exit(acNone);
2357 end;
2358
2359 procedure TShape.TraverseCore(const Func: TShapeTraverseFunc;
2360 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
2361 begin
2362 if ((not OnlyVisible) or Visible) and
2363 ((not OnlyCollidable) or Collidable) then
2364 Func(Self);
2365 end;
2366
2367 procedure TShape.FastTransformUpdateCore(var AnythingChanged: Boolean;
2368 const ParentTransformation: TTransformation);
2369 begin
2370 State.Transformation := ParentTransformation;
2371
2372 // Changed(false, [chTransform]);
2373 // a bit faster:
2374 Validities := Validities - [svBBox, svBoundingSphere];
2375
2376 AnythingChanged := true;
2377 end;
2378
2379 function TShape.MaxShapesCountCore: Integer;
2380 begin
2381 Result := 1;
2382 end;
2383
2384 function TShape.Visible: boolean;
2385 begin
2386 Result := State.InsideInvisible = 0;
2387 end;
2388
2389 function TShape.Collidable: boolean;
2390 begin
2391 Result := State.InsideIgnoreCollision = 0;
2392 if (Node <> nil) and
2393 (Node.Collision = scNone) then
2394 Result := false;
2395 end;
2396
2397 function TShape.RayCollision(
2398 const Tag: TMailboxTag;
2399 out Intersection: TVector3;
2400 out IntersectionDistance: Single;
2401 const RayOrigin, RayDirection: TVector3;
2402 const ReturnClosestIntersection: boolean;
2403 const TriangleToIgnore: PTriangle;
2404 const IgnoreMarginAtStart: boolean;
2405 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): PTriangle;
2406 begin
2407 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
2408 if MailboxSavedTag = Tag then
2409 begin
2410 Result := MailboxResult;
2411 if Result <> nil then
2412 begin
2413 Intersection := MailboxIntersection;
2414 IntersectionDistance := MailboxIntersectionDistance;
2415 end;
2416 end else
2417 begin
2418 {$endif}
2419
2420 Result := InternalOctreeTriangles.RayCollision(
2421 Intersection, IntersectionDistance, RayOrigin, RayDirection,
2422 ReturnClosestIntersection,
2423 TriangleToIgnore, IgnoreMarginAtStart, TrianglesToIgnoreFunc);
2424
2425 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
2426 { save result to mailbox }
2427 MailboxSavedTag := Tag;
2428 MailboxResult := Result;
2429 if Result <> nil then
2430 begin
2431 MailboxIntersection := Intersection;
2432 MailboxIntersectionDistance := IntersectionDistance;
2433 end;
2434 end;
2435 {$endif}
2436 end;
2437
2438 function TShape.SegmentCollision(
2439 const Tag: TMailboxTag;
2440 out Intersection: TVector3;
2441 out IntersectionDistance: Single;
2442 const Pos1, Pos2: TVector3;
2443 const ReturnClosestIntersection: boolean;
2444 const TriangleToIgnore: PTriangle;
2445 const IgnoreMarginAtStart: boolean;
2446 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): PTriangle;
2447 begin
2448 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
2449 if MailboxSavedTag = Tag then
2450 begin
2451 Result := MailboxResult;
2452 if Result <> nil then
2453 begin
2454 Intersection := MailboxIntersection;
2455 IntersectionDistance := MailboxIntersectionDistance;
2456 end;
2457 end else
2458 begin
2459 {$endif}
2460
2461 Result := InternalOctreeTriangles.SegmentCollision(
2462 Intersection, IntersectionDistance, Pos1, Pos2,
2463 ReturnClosestIntersection,
2464 TriangleToIgnore, IgnoreMarginAtStart, TrianglesToIgnoreFunc);
2465
2466 {$ifdef SHAPE_OCTREE_USE_MAILBOX}
2467 { save result to mailbox }
2468 MailboxSavedTag := Tag;
2469 MailboxResult := Result;
2470 if Result <> nil then
2471 begin
2472 MailboxIntersection := Intersection;
2473 MailboxIntersectionDistance := IntersectionDistance;
2474 end;
2475 end;
2476 {$endif}
2477 end;
2478
2479 function TShape.NormalsSmooth(const FromCcw: boolean): TVector3List;
2480 var
2481 G: TAbstractGeometryNode;
2482 S: TX3DGraphTraverseState;
2483 begin
2484 if not (
2485 (svNormals in Validities) and
2486 (FNormalsCached = ncSmooth) and
2487 (FNormalsCachedCcw = FromCcw)
2488 ) then
2489 begin
2490 if LogShapes then
2491 WritelnLog('Normals', 'Calculating shape smooth normals');
2492
2493 { Free previous normals }
2494 FreeAndNil(FNormals);
2495 Exclude(Validities, svNormals);
2496
2497 G := Geometry;
2498 S := State;
2499
2500 FNormals := CreateSmoothNormalsCoordinateNode(G, S, FromCcw);
2501 FNormalsCached := ncSmooth;
2502 FNormalsCachedCcw := FromCcw;
2503 Include(Validities, svNormals);
2504 end;
2505
2506 Result := FNormals;
2507 end;
2508
2509 function TShape.NormalsFlat(const FromCcw: boolean): TVector3List;
2510 var
2511 G: TAbstractGeometryNode;
2512 S: TX3DGraphTraverseState;
2513 begin
2514 if not (
2515 (svNormals in Validities) and
2516 (FNormalsCached = ncFlat) and
2517 (FNormalsCachedCcw = FromCcw)
2518 ) then
2519 begin
2520 if LogShapes then
2521 WritelnLog('Normals', 'Calculating shape flat normals');
2522
2523 { Free previous normals }
2524 FreeAndNil(FNormals);
2525 Exclude(Validities, svNormals);
2526
2527 G := Geometry;
2528 S := State;
2529
2530 FNormals := CreateFlatNormals(G.CoordIndexField.Items,
2531 G.InternalCoordinates(S).Items, FromCcw, G.Convex);
2532 FNormalsCached := ncFlat;
2533 FNormalsCachedCcw := FromCcw;
2534 Include(Validities, svNormals);
2535 end;
2536
2537 Result := FNormals;
2538 end;
2539
2540 function TShape.NormalsCreaseAngle(const FromCcw: boolean;
2541 const CreaseAngle: Single): TVector3List;
2542 var
2543 G: TAbstractGeometryNode;
2544 S: TX3DGraphTraverseState;
2545 begin
2546 if not (
2547 (svNormals in Validities) and
2548 (FNormalsCached = ncCreaseAngle) and
2549 (FNormalsCachedCcw = FromCcw) and
2550 (FNormalsCreaseAngle = CreaseAngle)
2551 ) then
2552 begin
2553 if LogShapes then
2554 WritelnLog('Normals', 'Calculating shape CreaseAngle normals');
2555
2556 { Free previous normals }
2557 FreeAndNil(FNormals);
2558 Exclude(Validities, svNormals);
2559
2560 G := Geometry;
2561 S := State;
2562
2563 FNormals := CreateNormals(G.CoordIndexField.Items,
2564 G.InternalCoordinates(S).Items, CreaseAngle, FromCcw, G.Convex);
2565 FNormalsCached := ncCreaseAngle;
2566 FNormalsCachedCcw := FromCcw;
2567 FNormalsCreaseAngle := CreaseAngle;
2568 Include(Validities, svNormals);
2569 end;
2570
2571 Result := FNormals;
2572 end;
2573
2574 function TShape.EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer;
2575
2576 { Handle Tex being any TAbstractSingleTextureNode.
2577 Ignores Tex = nil. }
2578 function HandleSingleTextureNode(Tex: TX3DNode): Pointer;
2579 begin
2580 if Tex is TAbstractTextureNode then
2581 Result := Enumerate(Self, TAbstractTextureNode(Tex))
2582 else
2583 Result := nil;
2584 end;
2585
2586 function HandleIDecls(IDecls: TX3DInterfaceDeclarationList): Pointer; overload; forward;
2587
2588 function HandleIDecls(Nodes: TMFNode): Pointer; overload;
2589 var
2590 I: Integer;
2591 begin
2592 Result := nil;
2593 for I := 0 to Nodes.Count - 1 do
2594 begin
2595 Result := HandleIDecls(Nodes[I].InterfaceDeclarations);
2596 if Result <> nil then Exit;
2597 end;
2598 end;
2599
2600 function HandleIDecls(Nodes: TX3DNodeList): Pointer; overload;
2601 var
2602 I: Integer;
2603 begin
2604 Result := nil;
2605 for I := 0 to Nodes.Count - 1 do
2606 begin
2607 Result := HandleIDecls(Nodes[I].InterfaceDeclarations);
2608 if Result <> nil then Exit;
2609 end;
2610 end;
2611
2612 { Handle Tex being any TAbstractTextureNode.
2613 Ignores Tex = nil case. }
2614 function HandleTextureNode(Tex: TX3DNode): Pointer;
2615 var
2616 I: Integer;
2617 begin
2618 Result := nil;
2619
2620 if Tex is TAbstractTextureNode then
2621 begin
2622 if Tex is TAbstractSingleTextureNode then
2623 begin
2624 { Texture node may use more texture nodes through it's "effects" field. }
2625 Result := HandleIDecls(TAbstractSingleTextureNode(Tex).FdEffects);
2626 if Result <> nil then Exit;
2627 end;
2628
2629 if Tex is TMultiTextureNode then
2630 begin
2631 Result := Enumerate(Self, TMultiTextureNode(Tex));
2632 if Result <> nil then Exit;
2633
2634 for I := 0 to TMultiTextureNode(Tex).FdTexture.Count - 1 do
2635 begin
2636 Result := HandleSingleTextureNode(TMultiTextureNode(Tex).FdTexture[I]);
2637 if Result <> nil then Exit;
2638 end;
2639 end else
2640 Result := HandleSingleTextureNode(Tex);
2641 end;
2642 end;
2643
2644 procedure HandleEnvironmentLight(const EnvLight: TEnvironmentLightNode);
2645 begin
2646 Result := HandleSingleTextureNode(EnvLight.FdDiffuseTexture.Value);
2647 if Result <> nil then Exit;
2648 Result := HandleSingleTextureNode(EnvLight.FdSpecularTexture.Value);
2649 if Result <> nil then Exit;
2650 end;
2651
2652 { Scan IDecls for SFNode and MFNode fields, handling texture nodes inside. }
2653 function HandleIDecls(IDecls: TX3DInterfaceDeclarationList): Pointer;
2654 var
2655 I, J: Integer;
2656 UniformField: TX3DField;
2657 begin
2658 Result := nil;
2659 if IDecls <> nil then
2660 for I := 0 to IDecls.Count - 1 do
2661 begin
2662 UniformField := IDecls.Items[I].Field;
2663
2664 if UniformField <> nil then
2665 begin
2666 if UniformField is TSFNode then
2667 begin
2668 Result := HandleTextureNode(TSFNode(UniformField).Value);
2669 if Result <> nil then Exit;
2670 end else
2671 if UniformField is TMFNode then
2672 begin
2673 for J := 0 to TMFNode(UniformField).Count - 1 do
2674 begin
2675 Result := HandleTextureNode(TMFNode(UniformField)[J]);
2676 if Result <> nil then Exit;
2677 end;
2678 end;
2679 end;
2680 end;
2681 end;
2682
2683 function HandleCommonSurfaceShader(SurfaceShader: TCommonSurfaceShaderNode): Pointer;
2684 begin
2685 Result := HandleTextureNode(SurfaceShader.FdAlphaTexture.Value);
2686 if Result <> nil then Exit;
2687 Result := HandleTextureNode(SurfaceShader.FdAmbientTexture.Value);
2688 if Result <> nil then Exit;
2689 Result := HandleTextureNode(SurfaceShader.FdDiffuseTexture.Value);
2690 if Result <> nil then Exit;
2691 Result := HandleTextureNode(SurfaceShader.FdDiffuseDisplacementTexture.Value);
2692 if Result <> nil then Exit;
2693 Result := HandleTextureNode(SurfaceShader.FdDisplacementTexture.Value);
2694 if Result <> nil then Exit;
2695 Result := HandleTextureNode(SurfaceShader.FdEmissiveTexture.Value);
2696 if Result <> nil then Exit;
2697 Result := HandleTextureNode(SurfaceShader.FdEnvironmentTexture.Value);
2698 if Result <> nil then Exit;
2699 Result := HandleTextureNode(SurfaceShader.FdMultiDiffuseAlphaTexture.Value);
2700 if Result <> nil then Exit;
2701 Result := HandleTextureNode(SurfaceShader.FdMultiEmmisiveAmbientIntensityTexture.Value);
2702 if Result <> nil then Exit;
2703 Result := HandleTextureNode(SurfaceShader.FdMultiSpecularShininessTexture.Value);
2704 if Result <> nil then Exit;
2705 Result := HandleTextureNode(SurfaceShader.FdMultiVisibilityTexture.Value);
2706 if Result <> nil then Exit;
2707 Result := HandleTextureNode(SurfaceShader.FdNormalTexture.Value);
2708 if Result <> nil then Exit;
2709 Result := HandleTextureNode(SurfaceShader.FdReflectionTexture.Value);
2710 if Result <> nil then Exit;
2711 Result := HandleTextureNode(SurfaceShader.FdShininessTexture.Value);
2712 if Result <> nil then Exit;
2713 Result := HandleTextureNode(SurfaceShader.FdSpecularTexture.Value);
2714 if Result <> nil then Exit;
2715 Result := HandleTextureNode(SurfaceShader.FdTransmissionTexture.Value);
2716 if Result <> nil then Exit;
2717 end;
2718
2719 function HandleOneSidedMaterial(const Mat: TAbstractOneSidedMaterialNode): Pointer;
2720 begin
2721 Result := HandleTextureNode(Mat.FdEmissiveTexture.Value);
2722 if Result <> nil then Exit;
2723 Result := HandleTextureNode(Mat.FdNormalTexture.Value);
2724 if Result <> nil then Exit;
2725 end;
2726
2727 function HandleMaterial(const Mat: TMaterialNode): Pointer;
2728 begin
2729 Result := HandleTextureNode(Mat.FdAmbientTexture.Value);
2730 if Result <> nil then Exit;
2731 Result := HandleTextureNode(Mat.FdDiffuseTexture.Value);
2732 if Result <> nil then Exit;
2733 Result := HandleTextureNode(Mat.FdShininessTexture.Value);
2734 if Result <> nil then Exit;
2735 Result := HandleTextureNode(Mat.FdSpecularTexture.Value);
2736 if Result <> nil then Exit;
2737 Result := HandleTextureNode(Mat.FdOcclusionTexture.Value);
2738 if Result <> nil then Exit;
2739 end;
2740
2741 function HandlePhysicalMaterial(const Mat: TPhysicalMaterialNode): Pointer;
2742 begin
2743 Result := HandleTextureNode(Mat.FdBaseTexture.Value);
2744 if Result <> nil then Exit;
2745 Result := HandleTextureNode(Mat.FdMetallicRoughnessTexture.Value);
2746 if Result <> nil then Exit;
2747 Result := HandleTextureNode(Mat.FdOcclusionTexture.Value);
2748 if Result <> nil then Exit;
2749 end;
2750
2751 var
2752 SurfaceShader: TCommonSurfaceShaderNode;
2753 I: Integer;
2754 App: TAppearanceNode;
2755 Lights: TLightInstancesList;
2756 begin
2757 Result := HandleTextureNode(State.VRML1State.Texture2);
2758 if Result <> nil then Exit;
2759
2760 if (State.ShapeNode <> nil) and
2761 (State.ShapeNode.Appearance <> nil) then
2762 begin
2763 App := State.ShapeNode.Appearance;
2764
2765 if App.FdMaterial.Value is TAbstractOneSidedMaterialNode then
2766 begin
2767 Result := HandleOneSidedMaterial(TAbstractOneSidedMaterialNode(App.FdMaterial.Value));
2768 if Result <> nil then Exit;
2769 end;
2770
2771 if App.FdMaterial.Value is TMaterialNode then
2772 begin
2773 Result := HandleMaterial(TMaterialNode(App.FdMaterial.Value));
2774 if Result <> nil then Exit;
2775 end;
2776
2777 if App.FdMaterial.Value is TPhysicalMaterialNode then
2778 begin
2779 Result := HandlePhysicalMaterial(TPhysicalMaterialNode(App.FdMaterial.Value));
2780 if Result <> nil then Exit;
2781 end;
2782
2783 Result := HandleTextureNode(App.FdTexture.Value);
2784 if Result <> nil then Exit;
2785
2786 Result := HandleTextureNode(App.FdNormalMap.Value);
2787 if Result <> nil then Exit;
2788
2789 HandleIDecls(App.FdShaders);
2790 HandleIDecls(App.FdEffects);
2791
2792 { CommonSurfaceShader can be non-nil only when App is non-nil }
2793 {$warnings off} // using deprecated to keep backward compatibility
2794 SurfaceShader := State.ShapeNode.CommonSurfaceShader;
2795 {$warnings on}
2796 if SurfaceShader <> nil then
2797 begin
2798 HandleCommonSurfaceShader(SurfaceShader);
2799 if Result <> nil then Exit;
2800 end;
2801 end;
2802
2803 Lights := State.Lights;
2804 if Lights <> nil then
2805 for I := 0 to Lights.Count - 1 do
2806 begin
2807 if Lights.L[I].Node is TEnvironmentLightNode then
2808 begin
2809 HandleEnvironmentLight(TEnvironmentLightNode(Lights.L[I].Node));
2810 if Result <> nil then Exit;
2811 end;
2812
2813 Result := HandleIDecls(Lights.L[I].Node.FdEffects);
2814 if Result <> nil then Exit;
2815 end;
2816
2817 if State.Effects <> nil then
2818 HandleIDecls(State.Effects);
2819
2820 Result := HandleTextureNode(OriginalGeometry.FontTextureNode);
2821 if Result <> nil then Exit;
2822
2823 if InternalShadowMaps <> nil then
2824 for I := 0 to InternalShadowMaps.Count - 1 do
2825 begin
2826 Result := HandleTextureNode(InternalShadowMaps[I] as TGeneratedShadowMapNode);
2827 if Result <> nil then Exit;
2828 end;
2829 end;
2830
2831 type
2832 TUsesTextureHelper = class
2833 Node: TAbstractTextureNode;
2834 function HandleTexture(Shape: TShape; Texture: TAbstractTextureNode): Pointer;
2835 end;
2836
2837 function TUsesTextureHelper.HandleTexture(Shape: TShape;
2838 Texture: TAbstractTextureNode): Pointer;
2839 begin
2840 if Texture = Node then
2841 Result := Texture { anything non-nil } else
2842 Result := nil;
2843 end;
2844
2845 function TShape.UsesTexture(Node: TAbstractTextureNode): boolean;
2846 var
2847 Helper: TUsesTextureHelper;
2848 begin
2849 Helper := TUsesTextureHelper.Create;
2850 try
2851 Helper.Node := Node;
2852 Result := EnumerateTextures(
2853 {$ifdef FPC}@{$endif}Helper.HandleTexture) <> nil;
2854 finally Helper.Free end;
2855 end;
2856
2857 function TShape.ShadowCaster: boolean;
2858 var
2859 S: TAbstractShapeNode;
2860 A: TX3DNode;
2861 begin
2862 Result := true;
2863
2864 S := State.ShapeNode;
2865 if S <> nil then
2866 begin
2867 A := S.FdAppearance.Value;
2868 if (A <> nil) and
2869 (A is TAppearanceNode) then
2870 Result := TAppearanceNode(A).FdShadowCaster.Value;
2871 end;
2872 end;
2873
2874 procedure TShape.ValidateGeometryState;
2875 begin
2876 if FGeometry = nil then
2877 begin
2878 Assert(FState = nil);
2879 FState := OriginalState;
2880
2881 try
2882 FGeometry := OriginalGeometry.Proxy(FState);
2883 if FGeometry <> nil then
2884 AssociateProxyGeometryState;
2885 except
2886 { in case of trouble, remember to keep both
2887 FGeometry and FState nil.
2888 Never let one of them be nil, while other it not. }
2889 FState := nil;
2890 raise;
2891 end;
2892
2893 if FGeometry = nil then
2894 begin
2895 FGeometry := OriginalGeometry;
2896 FState := OriginalState;
2897 end;
2898 end;
2899 end;
2900
2901 function TShape.Geometry: TAbstractGeometryNode;
2902 begin
2903 ValidateGeometryState;
2904 Result := FGeometry;
2905 end;
2906
2907 function TShape.State: TX3DGraphTraverseState;
2908 begin
2909 ValidateGeometryState;
2910 Result := FState;
2911 end;
2912
2913 function TShape.ProxyGeometry: TAbstractGeometryNode;
2914 begin
2915 Result := Geometry;
2916 if Result = OriginalGeometry then Result := nil;
2917 end;
2918
2919 function TShape.ProxyState: TX3DGraphTraverseState;
2920 begin
2921 if Geometry <> OriginalGeometry then
2922 Result := State else
2923 Result := nil;
2924 end;
2925
2926 procedure TShape.LocalTriangulate(const TriangleEvent: TTriangleEvent);
2927 var
2928 Arrays: TGeometryArrays;
2929 RangeBeginIndex: Integer;
2930
2931 { Call TriangleEvent once. Give indexes to Arrays (Arrays.Indexes,
2932 if assigned, otherwise direct coordinates), relative to RangeBeginIndex. }
2933 procedure Triangle(const I1, I2, I3: Cardinal);
2934 var
2935 VI1, VI2, VI3: Integer;
2936 Position, Normal: TTriangle3;
2937 TexCoord: TTriangle4;
2938 Face: TFaceIndex;
2939 begin
2940 if Arrays.Indexes <> nil then
2941 begin
2942 VI1 := Arrays.Indexes[RangeBeginIndex + I1];
2943 VI2 := Arrays.Indexes[RangeBeginIndex + I2];
2944 VI3 := Arrays.Indexes[RangeBeginIndex + I3];
2945 end else
2946 begin
2947 VI1 := RangeBeginIndex + I1;
2948 VI2 := RangeBeginIndex + I2;
2949 VI3 := RangeBeginIndex + I3;
2950 end;
2951 Position.Data[0] := Arrays.Position(VI1)^;
2952 Position.Data[1] := Arrays.Position(VI2)^;
2953 Position.Data[2] := Arrays.Position(VI3)^;
2954 Normal.Data[0] := Arrays.Normal(VI1)^;
2955 Normal.Data[1] := Arrays.Normal(VI2)^;
2956 Normal.Data[2] := Arrays.Normal(VI3)^;
2957
2958 if (Arrays.TexCoords.Count <> 0) and
2959 (Arrays.TexCoords[0] <> nil) and
2960 (Arrays.TexCoords[0].Generation = tgExplicit) then
2961 begin
2962 case Arrays.TexCoords[0].Dimensions of
2963 2: begin
2964 TexCoord.Data[0] := Vector4(Arrays.TexCoord2D(0, VI1)^, 0, 1);
2965 TexCoord.Data[1] := Vector4(Arrays.TexCoord2D(0, VI2)^, 0, 1);
2966 TexCoord.Data[2] := Vector4(Arrays.TexCoord2D(0, VI3)^, 0, 1);
2967 end;
2968 3: begin
2969 TexCoord.Data[0] := Vector4(Arrays.TexCoord3D(0, VI1)^, 1);
2970 TexCoord.Data[1] := Vector4(Arrays.TexCoord3D(0, VI2)^, 1);
2971 TexCoord.Data[2] := Vector4(Arrays.TexCoord3D(0, VI3)^, 1);
2972 end;
2973 4: begin
2974 TexCoord.Data[0] := Arrays.TexCoord4D(0, VI1)^;
2975 TexCoord.Data[1] := Arrays.TexCoord4D(0, VI2)^;
2976 TexCoord.Data[2] := Arrays.TexCoord4D(0, VI3)^;
2977 end;
2978 {$ifndef COMPILER_CASE_ANALYSIS}
2979 else raise EInternalError.Create('Arrays.TexCoord[0].Dimensions? at TShape.localtriangulate');
2980 {$endif}
2981 end;
2982 end else
2983 TexCoord := UnknownTexCoord;
2984
2985 if Arrays.Faces <> nil then
2986 Face := Arrays.Faces.L[RangeBeginIndex + I1]
2987 else
2988 Face := UnknownFaceIndex;
2989
2990 TriangleEvent(Self, Position, Normal, TexCoord, Face);
2991 end;
2992
2993 { Call NewTriangle, triangulating indexes 0 .. Count - 1. }
2994 procedure TriangulateRange(const Count: Cardinal);
2995 var
2996 I: Cardinal;
2997 NormalOrder: boolean;
2998 begin
2999 case Arrays.Primitive of
3000 gpTriangles:
3001 begin
3002 I := 0;
3003 while I + 2 < Count do
3004 begin
3005 Triangle(I, I + 1, I + 2);
3006 Inc(I, 3);
3007 end;
3008 end;
3009 gpTriangleFan:
3010 begin
3011 I := 0;
3012 while I + 2 < Count do
3013 begin
3014 Triangle(0, I + 1, I + 2);
3015 Inc(I);
3016 end;
3017 end;
3018 gpTriangleStrip:
3019 begin
3020 I := 0;
3021 NormalOrder := true;
3022 while I + 2 < Count do
3023 begin
3024 if NormalOrder then
3025 Triangle(I , I + 1, I + 2) else
3026 Triangle(I + 1, I , I + 2);
3027 NormalOrder := not NormalOrder;
3028 Inc(I);
3029 end;
3030 end;
3031 else { gpLineStrip, gpPoints don't make triangles } ;
3032 end;
3033 end;
3034
3035 var
3036 Count: Cardinal;
3037 I: Integer;
3038 begin
3039 Arrays := GeometryArrays;
3040 try
3041 if Arrays.Indexes <> nil then
3042 Count := Arrays.IndexesCount else
3043 Count := Arrays.Count;
3044 RangeBeginIndex := 0;
3045 if Arrays.Counts = nil then
3046 TriangulateRange(Count) else
3047 for I := 0 to Arrays.Counts.Count - 1 do
3048 begin
3049 TriangulateRange(Arrays.Counts[I]);
3050 RangeBeginIndex := RangeBeginIndex + Arrays.Counts[I];
3051 end;
3052 finally FreeAndNil(Arrays) end;
3053 end;
3054
3055 type
3056 TTriangulateRedirect = class
3057 Transform: PMatrix4;
3058 TriangleEvent: TTriangleEvent;
3059 procedure LocalNewTriangle(Shape: TObject;
3060 const Position: TTriangle3;
3061 const Normal: TTriangle3; const TexCoord: TTriangle4;
3062 const Face: TFaceIndex);
3063 end;
3064
3065 procedure TTriangulateRedirect.LocalNewTriangle(Shape: TObject;
3066 const Position: TTriangle3;
3067 const Normal: TTriangle3; const TexCoord: TTriangle4;
3068 const Face: TFaceIndex);
3069 begin
3070 TriangleEvent(Shape, Position.Transform(Transform^), Normal, TexCoord, Face);
3071 end;
3072
3073 procedure TShape.Triangulate(const TriangleEvent: TTriangleEvent);
3074 var
3075 TR: TTriangulateRedirect;
3076 begin
3077 TR := TTriangulateRedirect.Create;
3078 try
3079 TR.Transform := @(State.Transformation.Transform);
3080 TR.TriangleEvent := TriangleEvent;
3081 LocalTriangulate({$ifdef FPC}@{$endif}TR.LocalNewTriangle);
3082 finally FreeAndNil(TR) end;
3083 end;
3084
3085 function TShape.DebugInfoWithoutChildren: String;
3086 begin
3087 Result := NiceName;
3088 end;
3089
3090 function TShape.NiceName: string;
3091 begin
3092 Result := OriginalGeometry.NiceName;
3093
3094 { Slash / seems like a nice way to show it, since it is like a path, just in X3D tree. }
3095
3096 if FGeometryParentNode <> nil then
3097 Result := FGeometryParentNode.X3DName + '/' + Result;
3098
3099 if FGeometryGrandParentNode <> nil then
3100 Result := FGeometryGrandParentNode.X3DName + '/' + Result;
3101
3102 if FGeometryGrandGrandParentNode <> nil then
3103 Result := FGeometryGrandGrandParentNode.X3DName + '/' + Result;
3104 end;
3105
3106 function TShape.Node: TAbstractShapeNode;
3107 begin
3108 Result := State.ShapeNode;
3109 end;
3110
3111 function TShape.MaterialProperty: TMaterialProperty;
3112 begin
3113 Result := InternalMaterialProperty;
3114 end;
3115
3116 procedure TShape.InternalBeforeChange;
3117 begin
3118 FreeProxy;
3119 UnAssociateGeometryState(FOriginalGeometry, FOriginalState);
3120 UnAssociateGeometryStateNeverProxied(FOriginalGeometry, FOriginalState);
3121 end;
3122
3123 procedure TShape.InternalAfterChange;
3124 begin
3125 AssociateGeometryState(FOriginalGeometry, FOriginalState);
3126 AssociateGeometryStateNeverProxied(FOriginalGeometry, FOriginalState);
3127 end;
3128
3129 function TShape.InternalMaterialProperty: TMaterialProperty;
3130 var
3131 TextureUrl: String;
3132 begin
3133 if IsCachedMaterialProperty then
3134 Exit(CachedMaterialProperty);
3135
3136 Result := nil;
3137
3138 if Node <> nil then
3139 begin
3140 { VRML 2.0/X3D version: refer to TAppearanceNode.MaterialProperty }
3141 if Node.Appearance <> nil then
3142 Result := Node.Appearance.InternalMaterialProperty;
3143 end else
3144 begin
3145 { VRML 1.0 version: calculate it directly here }
3146 TextureUrl := State.VRML1State.Texture2.FdFileName.Value;
3147 if TextureUrl <> '' then
3148 Result := MaterialProperties.FindTextureBaseName(
3149 DeleteURIExt(ExtractURIName(TextureUrl)));
3150 end;
3151
3152 IsCachedMaterialProperty := true;
3153 CachedMaterialProperty := Result;
3154 end;
3155
3156 { TShapeTreeGroup -------------------------------------------------------- }
3157
3158 constructor TShapeTreeGroup.Create(const AParentScene: TX3DEventsEngine);
3159 begin
3160 inherited;
3161 FChildren := TShapeTreeList.Create(true);
3162 FChildren.OnNotify := {$ifdef FPC}@{$endif} ChildrenChanged;
3163 end;
3164
3165 destructor TShapeTreeGroup.Destroy;
3166 begin
3167 FreeAndNil(FChildren);
3168 inherited;
3169 end;
3170
3171 procedure TShapeTreeGroup.ChildrenChanged(Sender: TObject;
3172 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Item: TShapeTree;
3173 Action: TCollectionNotification);
3174 begin
3175 if Action = cnAdded then
3176 Item.FParent := Self;
3177 if Action in [cnExtracted, cnRemoved] then
3178 Item.FParent := nil;
3179 InvalidateMaxShapesCount;
3180 if ParentScene <> nil then
3181 TCastleSceneCore(ParentScene).InternalIncShapesHash;
3182 end;
3183
3184 procedure TShapeTreeGroup.TraverseCore(const Func: TShapeTraverseFunc;
3185 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3186 var
3187 I: Integer;
3188 begin
3189 for I := 0 to FChildren.Count - 1 do
3190 FChildren.Items[I].Traverse(Func, OnlyActive, OnlyVisible, OnlyCollidable);
3191 end;
3192
3193 procedure TShapeTreeGroup.FastTransformUpdateCore(var AnythingChanged: Boolean;
3194 const ParentTransformation: TTransformation);
3195 var
3196 I: Integer;
3197 begin
3198 for I := 0 to FChildren.Count - 1 do
3199 FChildren.Items[I].FastTransformUpdateCore(AnythingChanged, ParentTransformation);
3200 end;
3201
3202 function TShapeTreeGroup.MaxShapesCountCore: Integer;
3203 var
3204 I: Integer;
3205 begin
3206 Result := 0;
3207 for I := 0 to FChildren.Count - 1 do
3208 Result := Result + FChildren.Items[I].MaxShapesCount;
3209 end;
3210
3211 function TShapeTreeGroup.EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer;
3212 var
3213 I: Integer;
3214 begin
3215 Result := nil;
3216 for I := 0 to FChildren.Count - 1 do
3217 begin
3218 Result := FChildren.Items[I].EnumerateTextures(Enumerate);
3219 if Result <> nil then Exit;
3220 end;
3221 end;
3222
3223 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
3224 function TShapeTreeGroup.IterateBeginIndex(OnlyActive: boolean): Integer;
3225 begin
3226 Result := -1;
3227 end;
3228
3229 function TShapeTreeGroup.IterateEndIndex(OnlyActive: boolean): Cardinal;
3230 begin
3231 Result := FChildren.Count;
3232 end;
3233 {$endif}
3234
3235 function TShapeTreeGroup.DebugInfo(const Indent: string): string;
3236 var
3237 I: Integer;
3238 begin
3239 Result := inherited; // will use DebugInfoWithoutChildren
3240 for I := 0 to FChildren.Count - 1 do
3241 Result := Result + FChildren[I].DebugInfo(Indent + Format(' %3d:', [I]));
3242 end;
3243
3244 { TShapeTreeSwitch ------------------------------------------------------- }
3245
3246 procedure TShapeTreeSwitch.TraverseCore(const Func: TShapeTraverseFunc;
3247 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3248 var
3249 WhichChoice: Integer;
3250 begin
3251 if OnlyActive then
3252 begin
3253 WhichChoice := SwitchNode.FdWhichChoice.Value;
3254 if (WhichChoice >= 0) and
3255 (WhichChoice < Children.Count) then
3256 Children.Items[WhichChoice].Traverse(Func, OnlyActive, OnlyVisible, OnlyCollidable);
3257 end else
3258 inherited;
3259 end;
3260
3261 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
3262 function TShapeTreeSwitch.IterateBeginIndex(OnlyActive: boolean): Integer;
3263 var
3264 WhichChoice: Integer;
3265 begin
3266 if OnlyActive then
3267 begin
3268 WhichChoice := SwitchNode.FdWhichChoice.Value;
3269 if WhichChoice >= 0 then
3270 { It's ok if whichChoice is >= children count,
3271 iterator will check this. }
3272 Result := WhichChoice - 1 else
3273 Result := -1 { whatever; IterateCount will be 0 anyway };
3274 end else
3275 Result := inherited;
3276 end;
3277
3278 function TShapeTreeSwitch.IterateEndIndex(OnlyActive: boolean): Cardinal;
3279 var
3280 WhichChoice: Integer;
3281 begin
3282 if OnlyActive then
3283 begin
3284 WhichChoice := SwitchNode.FdWhichChoice.Value;
3285 if (WhichChoice >= 0) and
3286 (WhichChoice < Children.Count) then
3287 Result := WhichChoice + 1 else
3288 Result := 0;
3289 end else
3290 Result := inherited;
3291 end;
3292 {$endif}
3293
3294 function TShapeTreeSwitch.DebugInfoWithoutChildren: String;
3295 begin
3296 Result := 'Switch (' + SwitchNode.X3DName + ')';
3297 end;
3298
3299 { TShapeTreeTransform ---------------------------------------------------- }
3300
3301 constructor TShapeTreeTransform.Create(const AParentScene: TX3DEventsEngine);
3302 begin
3303 inherited;
3304 FTransformState := TX3DGraphTraverseState.Create;
3305 end;
3306
3307 destructor TShapeTreeTransform.Destroy;
3308 begin
3309 if FTransformFunctionality <> nil then
3310 UnAssociateNode(FTransformFunctionality.Parent);
3311 FreeAndNil(FTransformState);
3312 inherited;
3313 end;
3314
3315 procedure TShapeTreeTransform.SetTransformFunctionality(const Value: TTransformFunctionality);
3316 begin
3317 if FTransformFunctionality <> Value then
3318 begin
3319 if FTransformFunctionality <> nil then
3320 UnAssociateNode(FTransformFunctionality.Parent);
3321 FTransformFunctionality := Value;
3322 if FTransformFunctionality <> nil then
3323 AssociateNode(FTransformFunctionality.Parent);
3324 end;
3325 end;
3326
3327 procedure TShapeTreeTransform.FastTransformUpdate(var AnythingChanged: Boolean);
3328 begin
3329 FastTransformUpdateCore(AnythingChanged, FTransformState.Transformation);
3330 end;
3331
3332 procedure TShapeTreeTransform.FastTransformUpdateCore(var AnythingChanged: Boolean;
3333 const ParentTransformation: TTransformation);
3334 var
3335 NewTransformation: TTransformation;
3336 begin
3337 NewTransformation := ParentTransformation;
3338
3339 { Keep FTransformState up-to-date.
3340 This is not necessary when OptimizeExtensiveTransformations = true,
3341 so we don't do it to conserve speed. }
3342 if not OptimizeExtensiveTransformations then
3343 begin
3344 FTransformState.Transformation := ParentTransformation;
3345 end;
3346
3347 TransformFunctionality.ApplyTransform(NewTransformation);
3348
3349 inherited FastTransformUpdateCore(AnythingChanged, NewTransformation);
3350 end;
3351
3352 function TShapeTreeTransform.TransformNode: TX3DNode;
3353 begin
3354 Result := TransformFunctionality.Parent;
3355 end;
3356
3357 function TShapeTreeTransform.DebugInfoWithoutChildren: String;
3358 var
3359 TransformNodeName: String;
3360 begin
3361 if TransformFunctionality <> nil then
3362 TransformNodeName := TransformFunctionality.Parent.NiceName
3363 else
3364 TransformNodeName := 'nil';
3365 Result := ClassName + ' (' + TransformNodeName + ')';
3366 end;
3367
3368 { TShapeTreeLOD ------------------------------------------------------- }
3369
3370 function TShapeTreeLOD.LODInverseTransform: PMatrix4;
3371 begin
3372 Result := @FLODInverseTransform;
3373 end;
3374
3375 function TShapeTreeLOD.CalculateLevel(const CameraPosition: TVector3): Cardinal;
3376 var
3377 Camera: TVector3;
3378 Dummy: Single;
3379 begin
3380 if (Children.Count = 0) or
3381 (LODNode.FdRange.Count = 0) then
3382 Result := 0 else
3383 begin
3384 try
3385 Camera := LODInverseTransform^.MultPoint(CameraPosition);
3386 Result := KeyRange(LODNode.FdRange.Items,
3387 PointsDistance(Camera, LODNode.FdCenter.Value), Dummy);
3388 { Now we know Result is between 0..LODNode.FdRange.Count.
3389 Following X3D spec "Specifying too few levels will result in
3390 the last level being used repeatedly for the lowest levels of detail",
3391 so just clamp to last children. }
3392 MinVar(Result, Children.Count - 1);
3393 except
3394 on E: ETransformedResultInvalid do
3395 begin
3396 WritelnWarning('VRML/X3D', Format('Cannot transform camera position %s to LOD node local coordinate space, transformation results in direction (not point): %s',
3397 [ CameraPosition.ToRawString, E.Message ]));
3398 Result := 0;
3399 end;
3400 end;
3401 end;
3402
3403 Assert(
3404 ( (Children.Count = 0) and (Result = 0) ) or
3405 ( (Children.Count > 0) and (Result < Cardinal(Children.Count)) ) );
3406 end;
3407
3408 procedure TShapeTreeLOD.TraverseCore(const Func: TShapeTraverseFunc;
3409 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3410 begin
3411 if Children.Count > 0 then
3412 begin
3413 if OnlyActive then
3414 { Now we know that Level < Children.Count, no need to check it. }
3415 Children.Items[Level].Traverse(Func, OnlyActive, OnlyVisible, OnlyCollidable)
3416 else
3417 inherited;
3418 end;
3419 end;
3420
3421 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
3422 function TShapeTreeLOD.IterateBeginIndex(OnlyActive: boolean): Integer;
3423 begin
3424 if (Children.Count > 0) and OnlyActive then
3425 Result := Level - 1 else
3426 Result := inherited;
3427 end;
3428
3429 function TShapeTreeLOD.IterateEndIndex(OnlyActive: boolean): Cardinal;
3430 begin
3431 if (Children.Count > 0) and OnlyActive then
3432 Result := Level + 1 else
3433 Result := inherited;
3434 end;
3435 {$endif}
3436
3437 function TShapeTreeLOD.DebugInfoWithoutChildren: String;
3438 begin
3439 Result := 'LOD (' + LODNode.X3DName + ')';
3440 end;
3441
3442 { TProximitySensorInstance ---------------------------------------------- }
3443
3444 procedure TProximitySensorInstance.TraverseCore(const Func: TShapeTraverseFunc;
3445 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3446 begin
3447 { Nothing to do: no geometry shapes, no children here }
3448 end;
3449
3450 function TProximitySensorInstance.MaxShapesCountCore: Integer;
3451 begin
3452 { This is not a TShape instance, and has no TShape children. }
3453 Result := 0;
3454 end;
3455
3456 procedure TProximitySensorInstance.FastTransformUpdateCore(var AnythingChanged: Boolean;
3457 const ParentTransformation: TTransformation);
3458 begin
3459 { Nothing to do: This is not a TShape instance, and has no TShape children. }
3460 end;
3461
3462 function TProximitySensorInstance.EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer;
3463 begin
3464 { Nothing to do: no geometry shapes, no children here }
3465 Result := nil;
3466 end;
3467
3468 function TProximitySensorInstance.DebugInfoWithoutChildren: String;
3469 begin
3470 Result := 'ProximitySensor (' + Node.X3DName + ')';
3471 end;
3472
3473 { TVisibilitySensorInstance ---------------------------------------------- }
3474
3475 procedure TVisibilitySensorInstance.TraverseCore(const Func: TShapeTraverseFunc;
3476 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3477 begin
3478 { Nothing to do: no geometry shapes, no children here }
3479 end;
3480
3481 procedure TVisibilitySensorInstance.FastTransformUpdateCore(var AnythingChanged: Boolean;
3482 const ParentTransformation: TTransformation);
3483 begin
3484 { Nothing to do: This is not a TShape instance, and has no TShape children. }
3485 end;
3486
3487 function TVisibilitySensorInstance.MaxShapesCountCore: Integer;
3488 begin
3489 { This is not a TShape instance, and has no TShape children. }
3490 Result := 0;
3491 end;
3492
3493 function TVisibilitySensorInstance.EnumerateTextures(const Enumerate: TEnumerateShapeTexturesFunction): Pointer;
3494 begin
3495 { Nothing to do: no geometry shapes, no children here }
3496 Result := nil;
3497 end;
3498
3499 function TVisibilitySensorInstance.DebugInfoWithoutChildren: String;
3500 begin
3501 Result := 'VisibilitySensor (' + Node.X3DName + ')';
3502 end;
3503
3504 { TShapeTreeIterator ----------------------------------------------------- }
3505
3506 { When SHAPE_ITERATOR_SOPHISTICATED is defined, we use a complicated
3507 implementation that has a nice O(1) speed for constructor and all
3508 GetNext calls (well, actually some calls may have O(depth), but most
3509 will not). It traverses one step further in each GetNext.
3510 It's building a simple stack of items to make efficient push/pop while
3511 walking down/up the tree of TShapesTree.
3512
3513 When SHAPE_ITERATOR_SOPHISTICATED is not defined, we use a very simple
3514 implementation: just call Tree.Traverse,
3515 collecting shapes to a list in constructor. Then simply iterate
3516 over this list. This makes constructor time large (equal to traversing time,
3517 so O(leaves count)), although GetNext is lighting fast.
3518
3519 Theoretically, the sophisticated version was supposed to be much better,
3520 as speed is always O(1) and memory use is much smaller
3521 (only the depth of the shapes tree, as opposed to the number of all leaves).
3522
3523 In practice however, it turned out that the sophisticated version
3524 was useless. Time measures shown that "naive" and simple
3525 version is even very very slightly faster in some cases.
3526 Time measure is in castle_game_engine/tests/testscenecore.pas,
3527 define ITERATOR_SPEED_TEST and test for yourself.
3528
3529 So in practice good memory allocator in FPC
3530 (as this is the bottleneck of the naive version, since List is potentially
3531 resized on adding each new shape) outperforms the sophisticated algorithm.
3532
3533 Later: We also improved the unsophisticated performance using CachedChildrenList.
3534
3535 So right now we're back to simple version. Maybe the "sophisticated"
3536 implementation will be restored some day... Just define
3537 SHAPE_ITERATOR_SOPHISTICATED. }
3538
3539 {$ifdef SHAPE_ITERATOR_SOPHISTICATED}
3540
3541 type
3542 { To efficiently implement TShapeTreeIterator, we have to
3543 use an efficient stack push/pop when entering TShapeTreeGroup
3544 (this includes TShapeTreeSwitch), and remember current Index
3545 within current group.
3546
3547 Note that this follows the logic of implemented Traverse methods.
3548 There's no way to efficiently (without e.g. first collecting to a list)
3549 realize iterator with actually calling Traverse methods. }
3550 PIteratorInfo = ^TIteratorInfo;
3551 TIteratorInfo = record
3552 Group: TShapeTreeGroup;
3553 Index: Integer;
3554 GroupCount: Cardinal;
3555 Parent: PIteratorInfo;
3556 end;
3557
3558 {$define IteratorInfo := PIteratorInfo(Info)}
3559
3560 { Check Current for FOnlyVisible and FOnlyCollidable flags. }
3561 function TShapeTreeIterator.CurrentMatches: boolean;
3562 begin
3563 if FOnlyVisible and FOnlyCollidable then
3564 Result := (Current <> nil) and Current.Visible and Current.Collidable else
3565 if FOnlyVisible then
3566 Result := (Current <> nil) and Current.Visible else
3567 if FOnlyCollidable then
3568 Result := (Current <> nil) and Current.Collidable else
3569 Result := (Current <> nil);
3570 end;
3571
3572 constructor TShapeTreeIterator.Create(const Tree: TShapeTree;
3573 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3574 begin
3575 inherited Create;
3576
3577 FOnlyActive := OnlyActive;
3578 FOnlyVisible := OnlyVisible;
3579 FOnlyCollidable := OnlyCollidable;
3580
3581 if Tree is TShapeTreeGroup then
3582 begin
3583 New(IteratorInfo);
3584 IteratorInfo^.Group := TShapeTreeGroup(Tree);
3585 IteratorInfo^.Index := IteratorInfo^.Group.IterateBeginIndex(OnlyActive);
3586 IteratorInfo^.GroupCount := IteratorInfo^.Group.IterateEndIndex(OnlyActive);
3587 IteratorInfo^.Parent := nil;
3588 end else
3589 begin
3590 { When the whole tree is one single TShape, this is a special case
3591 marked by IteratorInfo = nil and using SingleShapeRemaining.
3592 FCurrent is just constant in this case. }
3593 Assert(Tree is TShape);
3594 FCurrent := TShape(Tree);
3595 IteratorInfo := nil;
3596 SingleShapeRemaining := true;
3597 end;
3598 end;
3599
3600 destructor TShapeTreeIterator.Destroy;
3601
3602 procedure Done(I: PIteratorInfo);
3603 begin
3604 if I <> nil then
3605 begin
3606 Done(I^.Parent);
3607 Dispose(I);
3608 end;
3609 end;
3610
3611 begin
3612 Done(IteratorInfo);
3613 inherited;
3614 end;
3615
3616 function TShapeTreeIterator.GetNext: boolean;
3617 var
3618 ParentInfo: PIteratorInfo;
3619 Child: TShapeTree;
3620 begin
3621 if IteratorInfo <> nil then
3622 begin
3623 repeat
3624 Inc(IteratorInfo^.Index);
3625 Assert(IteratorInfo^.Index >= 0);
3626 Assert(IteratorInfo^.Index > IteratorInfo^.Group.IterateBeginIndex(FOnlyActive));
3627
3628 if Cardinal(IteratorInfo^.Index) < IteratorInfo^.GroupCount then
3629 begin
3630 Child := IteratorInfo^.Group.Children.Items[IteratorInfo^.Index];
3631 if Child is TShape then
3632 begin
3633 FCurrent := TShape(Child);
3634
3635 if CurrentMatches then
3636 Result := true else
3637 Result := GetNext;
3638
3639 Exit;
3640 end else
3641 begin
3642 Assert(Child is TShapeTreeGroup);
3643 ParentInfo := IteratorInfo;
3644 New(IteratorInfo);
3645 IteratorInfo^.Group := TShapeTreeGroup(Child);
3646 IteratorInfo^.Index := IteratorInfo^.Group.IterateBeginIndex(FOnlyActive);
3647 IteratorInfo^.GroupCount := IteratorInfo^.Group.IterateEndIndex(FOnlyActive);
3648 IteratorInfo^.Parent := ParentInfo;
3649 end;
3650 end else
3651 begin
3652 ParentInfo := IteratorInfo^.Parent;
3653 if ParentInfo <> nil then
3654 begin
3655 Dispose(IteratorInfo);
3656 IteratorInfo := ParentInfo;
3657 end else
3658 Exit(false);
3659 end;
3660 until false;
3661 end else
3662 begin
3663 Result := SingleShapeRemaining;
3664 SingleShapeRemaining := false;
3665 { FCurrent already set in constructor }
3666
3667 if Result and (not CurrentMatches) then
3668 Result := false;
3669 end;
3670 end;
3671
3672 {$undef IteratorInfo}
3673
3674 {$else SHAPE_ITERATOR_SOPHISTICATED}
3675
3676 constructor TShapeTreeIterator.Create(const Tree: TShapeTree;
3677 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3678 begin
3679 inherited Create;
3680 List := Tree.TraverseList(OnlyActive, OnlyVisible, OnlyCollidable);
3681 CurrentIndex := -1;
3682 end;
3683
3684 destructor TShapeTreeIterator.Destroy;
3685 begin
3686 inherited;
3687 end;
3688
3689 function TShapeTreeIterator.GetNext: boolean;
3690 begin
3691 Inc(CurrentIndex);
3692 Result := CurrentIndex < List.Count;
3693 if Result then
3694 FCurrent := List.Items[CurrentIndex];
3695 end;
3696
3697 {$endif SHAPE_ITERATOR_SOPHISTICATED}
3698
3699 { TShapeList ------------------------------------------------------- }
3700
3701 constructor TShapeList.Create;
3702 begin
3703 inherited Create(false);
3704 end;
3705
3706 constructor TShapeList.Create(const Tree: TShapeTree;
3707 const OnlyActive, OnlyVisible, OnlyCollidable: boolean);
3708 begin
3709 Create;
3710 { Set Capacity, to make following operations faster.
3711 Note that we use MaxShapesCount instead of ShapesCount,
3712 since MaxShapesCount is usually instant.
3713 Testcase of speedup: e.g. profiling animate_3d_model_by_code_2. }
3714 Capacity := Tree.MaxShapesCount;
3715 { This method uses Tree.Traverse that uses Tree.TraverseList that creates a list,
3716 iterates over it, and here we add results to another list...
3717 This is clearly a waste of time. That's why this method is deprecated. }
3718 Tree.Traverse({$ifdef FPC}@{$endif} AddConst, OnlyActive, OnlyVisible, OnlyCollidable);
3719 end;
3720
3721 procedure TShapeList.AddConst(const S: TShape);
3722 begin
3723 Add(S);
3724 end;
3725
3726 { TPlaceholderNames ------------------------------------------------------- }
3727
3728 function TPlaceholderNames.GetItems(const AKey: string): TPlaceholderName;
3729 begin
3730 Result := inherited Items[AKey];
3731 end;
3732
3733 procedure TPlaceholderNames.SetItems(const AKey: string; const AValue: TPlaceholderName);
3734 begin
3735 AddOrSetValue(AKey, AValue);
3736 end;
3737
3738 function X3DShapePlaceholder(const Shape: TShape): string;
3739 begin
3740 { Shape.Node may be nil for old VRML 1.0 or Inventor. }
3741 if Shape.Node <> nil then
3742 Result := Shape.Node.X3DName
3743 else
3744 Result := '';
3745 end;
3746
3747 function BlenderPlaceholder(const Shape: TShape): string;
3748 begin
3749 Result := '';
3750 if Shape.OriginalGeometry is TAbstractGeometryNode_1 then
3751 begin
3752 { Geometry node generated by Blender VRML 1.0 exporter has one parent,
3753 its mesh. The mesh node may have many parents representing its objects
3754 (unfortunately, the object names are not recorded in exported file,
3755 so we use mesh name for BlenderPlaceholder. }
3756 if Shape.GeometryParentNode <> nil then
3757 Result := Shape.GeometryParentNode.X3DName;
3758 end else
3759 begin
3760 { For VRML 2.0 and X3D exporter, the situation is quite similar.
3761 We look at parent of the Shape node (mesh Group)
3762 and parent of it (object Transform).
3763 The object names are available.
3764
3765 For VRML 2.0 we have to remove ME_ and OB_ prefixes from node names.
3766 Somewhere around/before 2.64a X3D exporter also added _ifs_TRANSFORM suffix,
3767 remove it.
3768
3769 Note that we assume X3D exporter from Blender >= 2.57.
3770 Earlier Blender X3D exporters were a little different (it seems,
3771 probably because of mesh splitting added in 2.57),
3772 we don't handle them.
3773
3774 This also works for glTF exporter in Blender 2.82a,
3775 imported to X3D nodes by CGE.
3776 In this case, the name comes from Blender mesh name (not Blender object name),
3777 and has no prefixes/suffixes.
3778 It is still in GeometryGrandGrandParentNode.X3DName, because of how
3779 X3DLoadInternalGltf organizes data.
3780 }
3781
3782 // not needed:
3783 // if Shape.GeometryGrandParentNode <> nil then
3784 // BlenderMeshName := PrefixRemove('ME_', GeometryGrandParentNode.X3DName, false);
3785
3786 if Shape.GeometryGrandGrandParentNode <> nil then
3787 Result := SuffixRemove('_ifs_TRANSFORM', PrefixRemove('OB_',
3788 Shape.GeometryGrandGrandParentNode.X3DName, false), false);
3789 end;
3790 end;
3791
3792 initialization
3793 PlaceholderNames := TPlaceholderNames.Create;
3794 PlaceholderNames['x3dshape'] := @X3DShapePlaceholder;
3795 PlaceholderNames['blender'] := @BlenderPlaceholder;
3796 finalization
3797 FreeAndNil(PlaceholderNames);
3798 end.