Debian Codegraph @

src/scene/x3d/x3dnodes_standard_grouping.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18 { Base node that may contain children nodes.
19
20 You should not use this class directly usually,
21 instead use e.g. TAbstractGroupingNode.
22 This class is a common ancestor to help implementing a few similar nodes,
23 like TAbstractGroupingNode and TStaticGroupNode, but it is undefined whether
24 they will always rely on this common ancestor.
25
26 Note: This descends from TAbstractChildNode,
27 so it can be inserted as child of another grouping node.
28 So, you can create a hierarchy of nodes with any depth.
29
30 Handles TTransformFunctionality for any descendant that defines an instance of it. }
31 TAbstractInternalGroupingNode = class(TAbstractChildNode)
32 strict private
33 type
34 TGeneralGroupingEnumerator = class
35 State: TX3DGraphTraverseState;
36 WasPointingDeviceSensor: boolean;
37 function EnumerateChildrenFunction(Node, Child: TX3DNode): Pointer;
38 end;
39 var
40 BeforeTraversePushedState: boolean;
41 TempEnumerator: TGeneralGroupingEnumerator;
42 TempEnumeratorUsed: Boolean;
43 protected
44 { If @true (default implementation in this class), then this really
45 behaves like a grouping node. If @false, this allows everything
46 to "leak out" (transform changes, VRML 1.0 state changes etc.).
47 Possibility useful for VRML 1.0 extension
48 https://castle-engine.io/x3d_extensions.php#section_ext_wwwinline_separate }
49 function SeparateGroup: boolean; virtual;
50
51 procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override;
52 procedure AfterTraverse(StateStack: TX3DGraphTraverseStateStack); override;
53 public
54 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
55 destructor Destroy; override;
56 end;
57
58 { Base node that contains children nodes. }
59 TAbstractGroupingNode = class(TAbstractInternalGroupingNode)
60 strict private
61 type
62 TChildrenArray = array of TAbstractChildNode;
63 function ToChildrenArray(const Nodes: TMFNode): TChildrenArray;
64 procedure EventAddChildrenReceive(
65 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
66 procedure EventRemoveChildrenReceive(
67 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
68 public
69 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
70
71 { Add the nodes as children.
72
73 By default, adding the same node multiple times makes
74 the node present on the list multiple times.
75 This AddChildren behavior is consistent with how
76 @code(FdChildren.Add(Child)) behaves,
77 and consistent with how @link(RemoveChildren) works
78 (it removes only a single copy in case of duplicates).
79 Our engine allows duplicates on the children list ---
80 you can specify them in the X3D file,
81 or you can add them using @link(FdChildren).Add.
82
83 If you specify AllowDuplicates = @false,
84 then adding a node that already exists on the children list is ignored.
85 This has a tiny performance hit (we need to check for existence first),
86 but it is consistent with how X3D event "addChildren" should behave
87 according to the spec.
88 The X3D specification doesn't allow duplicates on the children list.
89
90 This propagates the changes appropriately to the parent TCastleSceneCore,
91 calling TCastleSceneCore.ChangedAll or something similar. }
92 procedure AddChildren(const Children: array of TAbstractChildNode;
93 const AllowDuplicates: Boolean = true); overload;
94 procedure AddChildren(const Child: TAbstractChildNode;
95 const AllowDuplicates: Boolean = true); overload;
96
97 { Remove the nodes from the children list.
98 Removing a node that does not exist on the children list is ignored.
99
100 If a node exists on the current children list multiple times,
101 then a single occurrence of this node is removed,
102 for each occurrence of this node in the parameters list.
103
104 This propagates the changes appropriately to the parent TCastleSceneCore,
105 calling TCastleSceneCore.ChangedAll or something similar. }
106 procedure RemoveChildren(const Children: array of TAbstractChildNode); overload;
107 procedure RemoveChildren(const Child: TAbstractChildNode); overload;
108
109 { Clear all children from the list.
110 This automatically propagates the changes appropriately
111 to the parent TCastleSceneCore. }
112 procedure ClearChildren;
113
114 {$I auto_generated_node_helpers/x3dnodes_x3dgroupingnode.inc}
115 end;
116
117 TAbstractX3DGroupingNode = TAbstractGroupingNode deprecated 'use TAbstractGroupingNode';
118
119 { Contains children nodes without introducing a new transformation.
120 It is equivalent to a TTransformNode containing an identity transform. }
121 TGroupNode = class(TAbstractGroupingNode)
122 protected
123 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
124 public
125 class function ForVRMLVersion(const Version: TX3DVersion): boolean;
126 override;
127 {$I auto_generated_node_helpers/x3dnodes_group.inc}
128 end;
129 TGroupNode_2 = TGroupNode;
130
131 { Map String->Integer. }
132 TStringIntegerMap = class({$ifdef FPC}specialize{$endif} TDictionary<string, Integer>)
133 strict private
134 function GetItems(const AKey: string): Integer;
135 procedure SetItems(const AKey: string; const AValue: Integer);
136 public
137 { Assign contents (all keys, values) of another TStringIntegerMap instance. }
138 procedure Assign(const Source: TStringIntegerMap);
139
140 { Access dictionary items.
141 Setting this is allowed regardless if the key previously existed or not,
142 in other words: setting this does AddOrSetValue, contrary to the ancestor TDictionary
143 that only allows setting when the key already exists. }
144 property Items [const AKey: string]: Integer read GetItems write SetItems; default;
145 end;
146
147 { Node functionality for all X3D transformation nodes.
148 These nodes transform all their children (the ones enumerated
149 by traversing, so all active children).
150
151 The transformation change may be signalled by TX3DField.Changes
152 including chTransform flag. For some special nodes, like Billboard,
153 the transformation changes are automatically managed. }
154 TTransformFunctionality = class(TNodeFunctionality)
155 public
156 { Change State.Transformation for children nodes.
157 Almost all descendants should override only the overload changing
158 TTransformation. }
159 procedure ApplyTransform(const State: TX3DGraphTraverseState); overload; virtual;
160 procedure ApplyTransform(var Transformation: TTransformation); overload; virtual;
161 end;
162
163 { A top-level VRML/X3D node. This is what you get by loading 3D model from file.
164
165 It is declared as a descendant of VRML/X3D >= 2.0 Group node,
166 but it's used with all VRML/X3D versions (including VRML 1.0 and Inventor).
167 This makes things simple (previously we had two separate TX3DRootNode_1
168 and TX3DRootNode, which was complicating stuff).
169 Children (for all VRML/X3D versions) are inside FdChildren field.
170
171 This way VRML/X3D files may have many nodes at the top level
172 (which is a standard feature of VRML/X3D >= 2.0, but we also allow it for
173 VRML 1.0 as a commonly used extension). It may also have prototypes,
174 routes etc. at the root level.
175
176 This also allows us to record in one place some information that
177 is returned by the parser. Like parsed VRML/X3D version, X3D profile,
178 some namespace information (exported names and such). }
179 TX3DRootNode = class(TGroupNode)
180 strict private
181 type
182 TX3DRootNodeTransformFunctionality = class(TTransformFunctionality)
183 strict private
184 FParent: TX3DRootNode;
185 public
186 constructor Create(const AParent: TX3DRootNode);
187 property Parent: TX3DRootNode read FParent;
188 procedure ApplyTransform(var Transformation: TTransformation); override;
189 end;
190 var
191 FTransformFunctionality: TX3DRootNodeTransformFunctionality;
192 FHasForceVersion: boolean;
193 FSaveAsRootNode: boolean;
194 FProfile: string;
195 FComponents: TStringIntegerMap;
196 FMeta: TStringStringMap;
197 FScale: Single;
198 private
199 FPrototypeNames: TX3DPrototypeNames;
200 FExportedNames: TX3DExportList;
201 FImportedNames: TX3DNodeNames;
202
203 { Add the node to this node.
204 It usually means adding to FdChildren, but with some additional checks.
205 FileTopLevel indicates if this TX3DRootNode is actually the root
206 of X3D file, @false means this TX3DRootNode is only a root inside
207 a prototype. }
208 procedure AddRootNode(const NewNode: TX3DNode; const FileTopLevel: Boolean);
209 protected
210 function DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode; override;
211
212 { Root node never saves/restores the traversing state.
213 This means that all state changes "leak out" from a root node.
214 This is a good thing: if root node isn't used as a final TCastleSceneCore.RootNode,
215 then it is placed inside Inline node, which will do save/restore anyway.
216 And this way VRML 1.0 WWWInline with separate=FALSE may also work too. }
217 function SeparateGroup: boolean; override;
218 public
219 ForceVersion: TX3DVersion;
220
221 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
222 destructor Destroy; override;
223 function TransformationChange: TNodeTransformationChange; override;
224
225 { Should SaveToStream take care to nicely save us, treating as
226 a root node of whole VRML file or prototype.
227
228 If this node isn't a root node, you should set this to @false
229 (or saving this node may generate dumb contents).
230 Although, generally, you should avoid using the TX3DRootNode
231 class at all for non-root nodes. }
232 property SaveAsRootNode: boolean read FSaveAsRootNode write FSaveAsRootNode
233 default true;
234
235 { Save contents to the stream.
236
237 If SaveAsRootNode then this is saved in a special way,
238 such that only the contents are written, without surrounding
239 braces (for classic encoding) or XML element (for xml encoding).
240 This way, when saving, we hide the fact that everything was wrapped
241 in an artificial TX3DRootNode. }
242 procedure SaveToStream(Writer: TX3DWriter); override;
243
244 { Set HasForceVersion to @true to force saving this model with
245 given ForceVersion. }
246 property HasForceVersion: boolean
247 read FHasForceVersion write FHasForceVersion default false;
248
249 { Profile required for this X3D file. See X3D spec about profiles.
250 Every X3D file must always define a profile.
251 (However, we use this class also for VRML 1.0 and 2.0 root nodes,
252 where profile is empty.)
253 Relevant only if this node is the root of X3D file. }
254 property Profile: string read FProfile write FProfile;
255
256 { Components and levels required for this X3D file.
257 Relevant if this node is the root of X3D file. }
258 property Components: TStringIntegerMap read FComponents;
259
260 { Meta keys and values of this X3D file.
261 Relevant if this node is the root of X3D file. }
262 property Meta: TStringStringMap read FMeta;
263
264 { Set properties to force saving this node graph as X3D.
265 If we're already configured to save as X3D (current major version >= 3)
266 then do nothing. Otherwise, sets major/minor versions
267 (by default: for X3D 4.0, Interchange profile).
268
269 Provided AMajor must be >= 3, since X3D version is always >= 3.
270
271 This works to indicate convert VRML 2.0 to X3D.
272 We simply change ForceVersion used to save to indicate X3D version.
273 This is a reasonable conversion of VRML 2 -> X3D (except NURBS nodes,
274 which are incompatible between VRML 2.0 and X3D and at this point
275 not dealt by this conversion correctly).
276
277 This should not be used if the original file version
278 indicates that it's an old VRML 1.0 or Inventor file,
279 as we have not implemented convertion from VRML 1.0/Inventor to X3D.
280 So it wil result in VRML 1.0/Inventor nodes saved using
281 the X3D (XML or classic) encoding, which is not a format supported
282 by any X3D reader (even our own).
283 We will display a warning if you attempt this. }
284 procedure ForceSaveAsX3D(const AMajor: Integer = 4;
285 const AMinor: Integer = 0;
286 const AProfile: string = 'Interchange');
287
288 { Global prototype namespace at the end of parsing the file.
289 Useful for things like EXTERNPROTO implementation. }
290 property PrototypeNames: TX3DPrototypeNames read FPrototypeNames;
291
292 { Node names exported from the file by EXPORT keyword.
293 Useful for importing them later, to handle IMPORT/EXPORT X3D mechanism. }
294 property ExportedNames: TX3DExportList read FExportedNames;
295
296 { Node names imported into this file by the IMPORT keyword.
297 You may want to take this into account when searching nodes by name,
298 this allows the user to rename nodes from Inlined files. }
299 property ImportedNames: TX3DNodeNames read FImportedNames;
300
301 { Scale of the model.
302 When loading, this is set to honor @code("UNIT length ...")
303 declaration in X3D 3.3.
304 It scales model such that 1 unit = 1 meter. When one model is inlined
305 inside another (e.g. using X3D Inline node), this is adjusted to
306 the existing scale of the outer model (always to make the resulting
307 complete node graph keep the assumption 1 unit = 1 meter). }
308 property Scale: Single read FScale write FScale {$ifdef FPC}default 1.0{$endif};
309
310 { Export node, to have its name known by X3D graph that includes this graph by "Inline" node.
311
312 Use this if you build X3D graph by hand, and you want do add the EXPORT X3D clause.
313 It adds the clause (using @link(AddExport), so it can be saved back to X3D file
314 reliably) and also makes it immediately working (adding it to the proper namespace).
315
316 @groupBegin }
317 procedure ExportNode(const Node: TX3DNode; const ExportedAlias: string); overload;
318 procedure ExportNode(const Node: TX3DNode); overload;
319 { @groupEnd }
320
321 { @exclude
322 Fix X3D names inside to make sure
323
324 - all nodes have empty, or unique names.
325 - all nodes that are part of ROUTE have non-empty names.
326
327 See https://castle-engine.io/gltf#unique_names
328 for documentation why we do this. }
329 procedure InternalFixNodeNames;
330 end;
331
332 { Children nodes which cannot be modified.
333 StaticGroup children are guaranteed to not change,
334 send events, receive events or contain any USE
335 references outside the StaticGroup.
336 This allows to optimize this content for faster rendering and less memory usage. }
337 TStaticGroupNode = class(TAbstractInternalGroupingNode)
338 protected
339 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
340 {$I auto_generated_node_helpers/x3dnodes_staticgroup.inc}
341 end;
342
343 { Choose only one (or none) of the child nodes for processing.
344 This allows to choose between a number of nodes for processing
345 (rendering, collision detection), and/or to hide some nodes.
346
347 Compatibility node: this class is used for both VRML 97 and X3D.
348 Although field name changed for X3D (in VRML 97, "children"
349 was called "choice"), this is handled seamlessly using our
350 TX3DFieldOrEvent.AddAlternativeField mechanism. In other words,
351 programmer simply works with FdChildren field, and when reading/writing
352 VRML file we take care to actually use either "children" or "choice" name,
353 depending on used VRML version. }
354 TSwitchNode = class(TAbstractGroupingNode)
355 protected
356 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
357 public
358 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
359 class function ForVRMLVersion(const Version: TX3DVersion): boolean;
360 override;
361 function TransformationChange: TNodeTransformationChange; override;
362
363 {$I auto_generated_node_helpers/x3dnodes_switch.inc}
364 end;
365 TSwitchNode_2 = TSwitchNode;
366
367 { Grouping node that transforms (moves, rotates, scales) it's children. }
368 TTransformNode = class(TAbstractGroupingNode)
369 strict private
370 type
371 TTransformNodeTransformFunctionality = class(TTransformFunctionality)
372 strict private
373 FParent: TTransformNode;
374 //WarningNegativeScaleDone: boolean;
375 public
376 constructor Create(const AParent: TTransformNode);
377 property Parent: TTransformNode read FParent;
378 procedure ApplyTransform(var Transformation: TTransformation); override;
379 end;
380 var
381 FTransformFunctionality: TTransformNodeTransformFunctionality;
382 protected
383 { }
384 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
385 public
386 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
387 class function ForVRMLVersion(const Version: TX3DVersion): boolean;
388 override;
389 function TransformationChange: TNodeTransformationChange; override;
390
391 {$I auto_generated_node_helpers/x3dnodes_transform.inc}
392 end;
393 TTransformNode_2 = TTransformNode;
394
395 {$endif read_interface}
396
397 {$ifdef read_implementation}
398
399 { TGeneralGroupingEnumerator ------------------------------------------------- }
400
401 function TAbstractInternalGroupingNode.TGeneralGroupingEnumerator.EnumerateChildrenFunction(
402 Node, Child: TX3DNode): Pointer;
403 begin
404 Result := nil;
405 Child.GroupBeforeTraverse(State, WasPointingDeviceSensor);
406 end;
407
408 procedure GroupBeforeTraverse_AddPointingDeviceSensor(const Child: TX3DNode;
409 const State: TX3DGraphTraverseState; var WasPointingDeviceSensor: Boolean);
410 begin
411 { When we encounter the *first* pointing device sensor within a grouping node,
412 it obscures the other pointing devices (from parent nodes).
413 Other pointing device sensors within the same grouping node are added. }
414
415 if not WasPointingDeviceSensor then
416 begin
417 State.PointingDeviceSensors.Clear;
418 State.PointingDeviceSensors.Transformation := State.Transformation;
419 WasPointingDeviceSensor := true;
420 end;
421
422 State.PointingDeviceSensors.Add(Child);
423 end;
424
425 { TAbstractInternalGroupingNode ------------------------------------------------------ }
426
427 constructor TAbstractInternalGroupingNode.Create(const AX3DName: String = ''; const ABaseUrl: String = '');
428 begin
429 inherited;
430 TempEnumerator := TGeneralGroupingEnumerator.Create;
431 TempEnumeratorUsed := false;
432 end;
433
434 destructor TAbstractInternalGroupingNode.Destroy;
435 begin
436 FreeAndNil(TempEnumerator);
437 inherited;
438 end;
439
440 function TAbstractInternalGroupingNode.SeparateGroup: boolean;
441 begin
442 Result := true;
443 end;
444
445 procedure TAbstractInternalGroupingNode.BeforeTraverse(
446 StateStack: TX3DGraphTraverseStateStack);
447 var
448 Enumerator: TGeneralGroupingEnumerator;
449 begin
450 inherited;
451
452 BeforeTraversePushedState := SeparateGroup;
453 if BeforeTraversePushedState then
454 StateStack.Push;
455
456 if TransformFunctionality <> nil then
457 begin
458 { Note: Applying transformation cannot be done in overriden BeforeTraverse.
459
460 Reason: for storing ClipPlanes transformations, we need to know
461 transformed matrix inside TAbstractInternalGroupingNode.BeforeTraverse implementation.
462 And we also do StateStack.Push inside TAbstractInternalGroupingNode.BeforeTraverse
463 implementation... So ApplyTransform must happen in the middle of
464 TAbstractInternalGroupingNode.BeforeTraverse call. }
465
466 TransformFunctionality.ApplyTransform(StateStack.Top);
467 end;
468
469 { We also use it to collect State.PointingDeviceSensors,
470 as it turns our that the same approach is possible, for the same reasons.
471 And the same goes for State.ClipPlanes.
472 Moreover, we do it all in a single DirectEnumerateActive call,
473 so this doesn't slow down the code.
474 }
475
476 if not TempEnumeratorUsed then
477 begin
478 // for speed, usually we can reuse the same TempEnumerator instance
479 Enumerator := TempEnumerator;
480 TempEnumeratorUsed := true;
481 end else
482 Enumerator := TGeneralGroupingEnumerator.Create;
483
484 try
485 // initialize complete Enumerator state, as it may be a reused TempEnumerator instance
486 Enumerator.State := StateStack.Top;
487 Enumerator.WasPointingDeviceSensor := false;
488
489 { It's a little unclean to test "Self is ...", usually virtual
490 methods should replace such constructs. But in this case, this is
491 just the simplest solution. Anchor node serves as a pointing device
492 for all it's children, so it just places itself in
493 State.PointingDeviceSensors.
494
495 Note that if Anchor node itself has other pointing device sensors
496 directly inside, they can be siblings of Anchor.
497 Tested with InstantReality and g3l_stapes_dbg.wrl from Robert Funnell.
498 So it's correct to just call AddPointingDeviceSensor that wil set
499 WasPointingDeviceSensor := true. }
500 if Self is TAnchorNode then
501 GroupBeforeTraverse_AddPointingDeviceSensor(Self, Enumerator.State, Enumerator.WasPointingDeviceSensor);
502
503 DirectEnumerateActive({$ifdef FPC}@{$endif} Enumerator.EnumerateChildrenFunction);
504 finally
505 if Enumerator = TempEnumerator then
506 TempEnumeratorUsed := false
507 else
508 FreeAndNil(Enumerator);
509 end;
510 end;
511
512 procedure TAbstractInternalGroupingNode.AfterTraverse(
513 StateStack: TX3DGraphTraverseStateStack);
514 begin
515 if BeforeTraversePushedState then
516 StateStack.Pop;
517
518 inherited;
519 end;
520
521 { TAbstractGroupingNode --------------------------------------------------- }
522
523 constructor TAbstractGroupingNode.Create(const AX3DName: String = ''; const ABaseUrl: String = '');
524 begin
525 inherited;
526 EventaddChildren.AddNotification({$ifdef FPC}@{$endif} EventAddChildrenReceive);
527 EventRemoveChildren.AddNotification({$ifdef FPC}@{$endif} EventRemoveChildrenReceive);
528
529 {$ifndef CASTLE_SLIM_NODES}
530 { Calling it "render" is an extension from InstantReality,
531 see [http://instant-reality.com/documentation/nodetype/ChildGroup/].
532 This extension was invented before X3D 4 added it. }
533 FFdVisible.AddAlternativeName('render', 0);
534 {$endif}
535 end;
536
537 function TAbstractGroupingNode.ToChildrenArray(
538 const Nodes: TMFNode): TChildrenArray;
539 var
540 I: Integer;
541 begin
542 SetLength(Result, Nodes.Count);
543 for I := 0 to Nodes.Count - 1 do
544 begin
545 if not (Nodes[I] is TAbstractChildNode) then
546 begin
547 WritelnWarning('X3D', 'Node on addChildren or removeChildren list is not a TAbstractChildNode, ignoring event');
548 SetLength(Result, 0);
549 Exit;
550 end;
551 Result[I] := TAbstractChildNode(Nodes[I]);
552 end;
553 end;
554
555 procedure TAbstractGroupingNode.EventAddChildrenReceive(
556 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
557 begin
558 AddChildren(ToChildrenArray(Value as TMFNode), false);
559 end;
560
561 procedure TAbstractGroupingNode.EventRemoveChildrenReceive(
562 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
563 begin
564 RemoveChildren(ToChildrenArray(Value as TMFNode));
565 end;
566
567 procedure TAbstractGroupingNode.AddChildren(
568 const Children: array of TAbstractChildNode;
569 const AllowDuplicates: Boolean);
570 var
571 N: TAbstractChildNode;
572 begin
573 { ignore empty list, in particular from ToChildrenArray failure }
574 if High(Children) = -1 then Exit;
575
576 { Note: it would be slightly more correct to implement this inside
577 EventAddChildrenReceive, and from AddChildren only create an event
578 "addChildren". This would allow other receivers of EventAddChildren
579 to react to this.
580
581 But it is not necessary in practice,
582 and it would be a little wasteful (creating a temporary TMFNode to send
583 for each AddChildren call). So we don't do it now. }
584
585 for N in Children do
586 if AllowDuplicates or (FdChildren.IndexOf(N) = -1) then
587 FdChildren.Add(N);
588
589 if Scene <> nil then
590 Scene.InternalChangedField(FdChildren, chGroupChildrenAdd);
591 end;
592
593 procedure TAbstractGroupingNode.RemoveChildren(
594 const Children: array of TAbstractChildNode);
595 var
596 N: TAbstractChildNode;
597 begin
598 { ignore empty list, in particular from ToChildrenArray failure }
599 if High(Children) = -1 then Exit;
600
601 { Note that X3D specification directly says
602 "A children field is not allowed to directly contain
603 multiple instances of the same node."
604 Note that I didn't find such notice in VRML 97 specification.
605 This seems to be undefined case in VRML 97?
606
607 But our engine allows it, it makes AddChildren / RemoveChildren
608 faster by default, and it's consistent with normal list operations in Pascal.
609 }
610
611 if Scene <> nil then
612 Scene.BeforeNodesFree;
613
614 for N in Children do
615 FdChildren.Remove(N);
616
617 if Scene <> nil then
618 Scene.InternalChangedField(FdChildren);
619 end;
620
621 procedure TAbstractGroupingNode.AddChildren(
622 const Child: TAbstractChildNode;
623 const AllowDuplicates: Boolean);
624 begin
625 AddChildren([Child], AllowDuplicates);
626 end;
627
628 procedure TAbstractGroupingNode.RemoveChildren(
629 const Child: TAbstractChildNode);
630 begin
631 RemoveChildren([Child]);
632 end;
633
634 procedure TAbstractGroupingNode.ClearChildren;
635 begin
636 if FdChildren.Count <> 0 then
637 begin
638 if Scene <> nil then
639 Scene.BeforeNodesFree;
640 FdChildren.Clear;
641 if Scene <> nil then
642 Scene.ChangedAll;
643 end;
644 end;
645
646 { TGroupNode ----------------------------------------------------------------- }
647
648 class function TGroupNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
649 begin
650 Result := Version.Major >= 2;
651 end;
652
653 function TGroupNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
654 begin
655 Result := inherited;
656 if Result <> nil then Exit;
657
658 Result := FdChildren.Enumerate(Func);
659 if Result <> nil then Exit;
660 end;
661
662 { TStringIntegerMap ---------------------------------------------------------- }
663
664 procedure TStringIntegerMap.Assign(const Source: TStringIntegerMap);
665 var
666 Pair: {$ifdef FPC}TDictionaryPair{$else}TPair<string, Integer>{$endif};
667 begin
668 Clear;
669 for Pair in Source do
670 Items[Pair.Key] := Pair.Value;
671 end;
672
673 function TStringIntegerMap.GetItems(const AKey: string): Integer;
674 begin
675 Result := inherited Items[AKey];
676 end;
677
678 procedure TStringIntegerMap.SetItems(const AKey: string; const AValue: Integer);
679 begin
680 AddOrSetValue(AKey, AValue);
681 end;
682
683 { TTransformFunctionality ---------------------------------------------------- }
684
685 procedure TTransformFunctionality.ApplyTransform(const State: TX3DGraphTraverseState);
686 begin
687 ApplyTransform(State.Transformation);
688 end;
689
690 procedure TTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
691 begin
692 end;
693
694 { TFixNamesHandler ----------------------------------------------------------- }
695
696 { Log renames done by TX3DRootNode.InternalFixNodeNames (to make node names
697 unique).
698
699 It can be spammy, e.g. in case of glTF models in
700 examples/viewport_and_scenes/occlusion_culling/ .
701 It is critical, if someone wants to access renamed nodes using FindNode...
702 but otherwise, it can be confusing (lots of logs,
703 and ignorable when you don't want to search for renamed nodes).
704 }
705 {.$define CASTLE_LOG_NODE_RENAMES}
706
707 type
708 TFixNamesHandler = class
709 strict private
710 var
711 Visited: TList;
712 Prefixes: TStringList;
713 Names: TCastleStringList;
714 {$ifdef CASTLE_LOG_NODE_RENAMES}
715 LogsDone: Cardinal;
716 const
717 MaxLogsDone = 5;
718 {$endif}
719 public
720 constructor Create;
721 destructor Destroy; override;
722 function HandleNode(ParentNode, Node: TX3DNode): Pointer;
723 end;
724
725 constructor TFixNamesHandler.Create;
726 begin
727 inherited;
728 Names := TCastleStringList.Create;
729 Names.CaseSensitive := true;
730 Visited := TList.Create;
731 Prefixes := TStringList.Create;
732 end;
733
734 destructor TFixNamesHandler.Destroy;
735 begin
736 FreeAndNil(Names);
737 FreeAndNil(Visited);
738 FreeAndNil(Prefixes);
739 inherited;
740 end;
741
742 function TFixNamesHandler.HandleNode(ParentNode, Node: TX3DNode): Pointer;
743
744 { Change Node.X3DName to something not yet existing in Names.
745 This knows that Node.X3DName is <> '' and it exists in Names,
746 IOW on entry the Node is named, and the name is not unique. }
747 procedure RenameUniquely(const Node: TX3DNode);
748 type
749 { Type for index used to uniquely rename the node.
750
751 For implementation reasons (we store it in TStringList objects),
752 size of this needs to match Pointer.
753 Again for implementation reasons, needs to be signed, because we sometimes
754 have -1 value in this type (though we don't store this in
755 TStringList objects). }
756 TUniqueNumber = PtrInt;
757
758 procedure RenameUniquelyCore(const Node: TX3DNode; const Prefix: String; NextNumber: TUniqueNumber);
759 var
760 PrefixIndex, MaybeNextNumber: TUniqueNumber;
761 begin
762 { Look for next free number for this prefix.
763
764 If on Prefixes: bump NextNumber to what is in Prefixes + 1,
765 as we know all previous ones are taken.
766
767 This optimization avoids spending longer and longer times
768 to find unique names for names with the same prefix.
769 Testcase: https://github.com/castle-engine/castle-model-viewer/issues/43
770 (received privately by Michalis, due to model being copyrighted).
771 }
772 PrefixIndex := Prefixes.IndexOf(Prefix);
773 if PrefixIndex <> -1 then
774 begin
775 { Delphi rejects using below MaxVar Int64 overload on Win64.
776 For safety, to not assume CPU-specific PtrInt = In64?
777 Makes sense, just implement this without MaxVar. }
778 // MaxVar(NextNumber, PtrInt(Prefixes.Objects[PrefixIndex]) + 1);
779
780 MaybeNextNumber := PtrInt(Prefixes.Objects[PrefixIndex]) + 1;
781 if MaybeNextNumber > NextNumber then
782 NextNumber := MaybeNextNumber;
783 end;
784
785 while Names.IndexOf(Prefix + IntToStr(NextNumber)) <> -1 do
786 Inc(NextNumber);
787 Node.X3DName := Prefix + IntToStr(NextNumber);
788
789 if PrefixIndex <> -1 then
790 Prefixes.Objects[PrefixIndex] := TObject(Pointer(NextNumber))
791 else
792 Prefixes.AddObject(Prefix, TObject(Pointer(NextNumber)));
793 end;
794
795 var
796 I: Integer;
797 Number: TUniqueNumber;
798 {$ifdef CASTLE_LOG_NODE_RENAMES}
799 OriginalName: String;
800 {$endif CASTLE_LOG_NODE_RENAMES}
801 begin
802 {$ifdef CASTLE_LOG_NODE_RENAMES}
803 OriginalName := Node.X3DName;
804 {$endif CASTLE_LOG_NODE_RENAMES}
805
806 I := BackPos('_', Node.X3DName);
807 if I <> 0 then
808 begin
809 Number := StrToIntDef(SEnding(Node.X3DName, I + 1), -1);
810 if Number >= 0 then
811 { Include in prefix the final "_" }
812 RenameUniquelyCore(Node, Copy(Node.X3DName, 1, I), Number + 1)
813 else
814 RenameUniquelyCore(Node, Node.X3DName + '_', 2);
815 end else
816 RenameUniquelyCore(Node, Node.X3DName + '_', 2);
817
818 {$ifdef CASTLE_LOG_NODE_RENAMES}
819 if LogsDone < MaxLogsDone then
820 begin
821 WritelnLog('Renaming node "%s" -> "%s" to have unique name. If you want to query for this node name, we recommend to not rely on the order of renames, and instead make the name unique in the input file.', [
822 OriginalName,
823 Node.X3DName
824 ]);
825 Inc(LogsDone);
826 if LogsDone = MaxLogsDone then
827 WritelnLog('Further renames done in this file will not be reported, to not flood log with messages');
828 end;
829 {$endif CASTLE_LOG_NODE_RENAMES}
830 end;
831
832 { Assuming Node.X3DName <> '', make sure it is unique name. }
833 procedure MakeUniquelyNamed(const Node: TX3DNode);
834 var
835 I: Integer;
836 begin
837 I := Names.IndexOf(Node.X3DName);
838 if I = - 1 then
839 begin
840 // new name
841 Names.AddObject(Node.X3DName, Node);
842 end else
843 if Names.Objects[I] <> Node then
844 begin
845 // name already taken by a different node
846 RenameUniquely(Node);
847 Names.AddObject(Node.X3DName, Node);
848 end;
849 end;
850
851 { Make sure Node has a non-empty name, and unique name.
852 Given Node may be nil (it is ignored then). }
853 procedure MakeNamed(const Node: TX3DNode);
854 begin
855 if (Node <> nil) and (Node.X3DName = '') then
856 begin
857 Node.X3DName := Node.X3DType;
858 if Node.X3DName = '' then
859 Node.X3DName := 'Node';
860 MakeUniquelyNamed(Node);
861 end;
862 end;
863
864 var
865 Route: TX3DRoute;
866 I: Integer;
867 begin
868 Result := nil;
869
870 { early exit if this node was already visited,
871 to save time when traversing graph with DEF/USE. }
872 if Visited.IndexOf(Node) <> -1 then
873 Exit;
874 Visited.Add(Node);
875
876 { make sure node name is unique }
877 if Node.X3DName <> '' then
878 MakeUniquelyNamed(Node);
879
880 { make sure nodes used in ROUTEs are uniquely named }
881 for I := 0 to Node.RoutesCount - 1 do
882 begin
883 Route := Node.Routes[I];
884 { Do not force nodes to be named because of internal (created for PROTO
885 working) routes.
886 Testcase: load and save to X3D any X3D file with protos, like
887 ../../../../demo-models/x3d/tricky_def_use.x3dv
888 The nodes using protos *should not* get automatic names like
889 "DEF YellowSphereByDefault YellowSphereByDefault". }
890 if Route.Internal then Continue;
891 MakeNamed(Route.SourceNode);
892 MakeNamed(Route.DestinationNode);
893 end;
894
895 { Recursively check children.
896
897 Should we descend into TInlineNode?
898 Strictly thinking about X3D namespace, the names don't have to be unique
899 across multiple files, each file is a separate namespace. Actually even prototypes
900 have a separate namespace.
901
902 That said, in CGE our TCastleScene.Node and TX3DRootNode node searching methods
903 access the graph as a whole, because this is much easier to use in normal case
904 (and allows developer to "not care" whether something is wrapped in Inline or not).
905 So for CGE, we just make all names unique.
906
907 So we don't have here condition like
908
909 if not (Node is TInlineNode) then
910
911 Just do this for all nodes.
912
913 Moreover, the ROUTEs have to be fixed in Inlines too.
914 }
915 Node.DirectEnumerateAll({$ifdef FPC}@{$endif} Self.HandleNode);
916 end;
917
918 { TX3DRootNode.TX3DRootNodeTransformFunctionality -------------------------------------- }
919
920 constructor TX3DRootNode.TX3DRootNodeTransformFunctionality.Create(const AParent: TX3DRootNode);
921 begin
922 inherited Create(AParent);
923 FParent := AParent;
924 end;
925
926 procedure TX3DRootNode.TX3DRootNodeTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
927 var
928 Scale: Single;
929 M, IM: TMatrix4;
930 begin
931 inherited;
932
933 Scale := Parent.Scale;
934 if Scale <> 1 then
935 begin
936 ScalingMatrices(Vector3(Scale, Scale, Scale), true, M, IM);
937 Transformation.Transform := Transformation.Transform * M;
938 Transformation.InverseTransform := IM * Transformation.InverseTransform;
939 Transformation.Scale := Transformation.Scale * Scale;
940 end;
941 end;
942
943 { TX3DRootNode --------------------------------------------------------------- }
944
945 constructor TX3DRootNode.Create(const AX3DName, ABaseUrl: String);
946 begin
947 inherited;
948 FComponents := TStringIntegerMap.Create;
949 FMeta := TStringStringMap.Create;
950 FSaveAsRootNode := true;
951 FScale := 1;
952
953 FTransformFunctionality := TX3DRootNodeTransformFunctionality.Create(Self);
954 AddFunctionality(FTransformFunctionality);
955 end;
956
957 destructor TX3DRootNode.Destroy;
958 begin
959 FreeAndNil(FComponents);
960 FreeAndNil(FMeta);
961 FreeAndNil(FPrototypeNames);
962 FreeAndNil(FExportedNames);
963 FreeAndNil(FImportedNames);
964 inherited;
965 end;
966
967 procedure TX3DRootNode.SaveToStream(Writer: TX3DWriter);
968 var
969 I: integer;
970 FileItems: TX3DFileItemList;
971 begin
972 if SaveAsRootNode then
973 begin
974 { Special things for root node saving:
975 - Name is ignored (should be '').
976 - Fields are ignored, except "children", that holds children
977 (for any VRML version, including VRML 1).
978 It's output in a special way, without writing "children [...]" around.
979 Other fields are ignored (should never have any meaning). }
980
981 FileItems := TX3DFileItemList.Create(false);
982 try
983 for I := 0 to PrototypesCount - 1 do
984 FileItems.Add(Prototypes[I]);
985
986 Assert(VRML1ChildrenCount = 0);
987
988 for i := 0 to FdChildren.Count - 1 do
989 FileItems.Add(FdChildren[I]);
990
991 for I := 0 to RoutesCount - 1 do
992 FileItems.Add(Routes[I]);
993
994 for I := 0 to ImportsCount - 1 do
995 FileItems.Add(ImportsList[I]);
996
997 for I := 0 to ExportsCount - 1 do
998 FileItems.Add(ExportsList[I]);
999
1000 FileItems.SaveToStream(Writer);
1001 finally FreeAndNil(FileItems) end;
1002 end else
1003 inherited;
1004 end;
1005
1006 function TX3DRootNode.DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode;
1007 var
1008 Res: TX3DRootNode;
1009 begin
1010 Result := inherited;
1011
1012 Res := Result as TX3DRootNode;
1013
1014 Res.HasForceVersion := HasForceVersion;
1015 Res.ForceVersion := ForceVersion;
1016 Res.Scale := Scale;
1017 Res.Profile := Profile;
1018 Res.Components.Assign(Components);
1019 Res.Meta.Assign(Meta);
1020 if ExportedNames <> nil then
1021 begin
1022 FreeAndNil(Res.FExportedNames);
1023 Res.FExportedNames := ExportedNames.DeepCopy(CopyState);
1024 end;
1025 if ImportedNames <> nil then
1026 begin
1027 FreeAndNil(Res.FImportedNames);
1028 Res.FImportedNames := ImportedNames.DeepCopy(CopyState);
1029 end;
1030 end;
1031
1032 procedure TX3DRootNode.ForceSaveAsX3D(const AMajor, AMinor: Integer;
1033 const AProfile: String);
1034 begin
1035 if AMajor < 3 then
1036 raise Exception.Create('ForceSaveAsX3D requires AMajor >= 3, since this is X3D version and X3D version numbering starts at 3.0');
1037
1038 if HasForceVersion and
1039 (ForceVersion.Major <= 1) then
1040 WritelnWarning('Converting VRML 1.0 or Inventor to X3D is not implemented. You will get VRML 1.0/Inventor nodes encoded like for X3D, which is not much useful, nothing will be able to read this combination.');
1041
1042 if (not HasForceVersion) or
1043 (ForceVersion.Major < 3) then
1044 begin
1045 HasForceVersion := true;
1046 ForceVersion.Major := AMajor;
1047 ForceVersion.Minor := AMinor;
1048 Profile := AProfile;
1049 end;
1050 end;
1051
1052 function TX3DRootNode.SeparateGroup: boolean;
1053 begin
1054 Result := false;
1055 end;
1056
1057 procedure TX3DRootNode.AddRootNode(const NewNode: TX3DNode; const FileTopLevel: Boolean);
1058
1059 procedure TopLevelCheckChild(const Child: TX3DNode);
1060 begin
1061 { Why not do here FdChildren.WarningIfChildNotAllowed(Child)?
1062 It already checks and warns if child is not TAbstractChildNode?
1063
1064 - The warning message of it could be confusing.
1065 It exposes an implementation detail, that we have a
1066 TX3DRootNode that descends from Group node.
1067
1068 - Moreover, we actually allow a bit more than TAbstractChildNode.
1069
1070 - TAbstractGeometryNode_1 to enable VRML 1.0 geometry nodes at top-level,
1071 like in demo-models/vrml_1/castle_extensions/multi_root.wrl .
1072
1073 - LayerSet
1074 - GeoOrigin
1075 See "4.3.2 Root nodes" in X3D 4 spec,
1076 https://www.web3d.org/specifications/X3Dv4Draft/ISO-IEC19775-1v4-IS.proof/Part01/concepts.html#Rootnodes .
1077
1078 Note that we don't allow here metadata nodes (TAbstractMetadataNode)
1079 although spec allows them.
1080 But we insert metadata to TX3DRootNode in a special way,
1081 so that MyScene.RootNode.MetadataXxx[] API works,
1082 and developers can query e.g. MyScene.RootNode.MetadataString['my_key'] .
1083 }
1084
1085 if not (
1086 (Child is TAbstractChildNode) or
1087 (Child is TAbstractGeometryNode_1) or
1088 (Child is TLayerSetNode) or
1089 (Child is TGeoOriginNode)
1090 ) then
1091 WritelnWarning('VRML/X3D', Format('Node "%s" is not allowed at the top level of the X3D file',
1092 [Child.X3DType]));
1093 end;
1094
1095 begin
1096 if FileTopLevel then
1097 begin
1098 if NewNode is TAbstractMetadataNode then
1099 InternalInsertMetadata(TAbstractMetadataNode(NewNode))
1100 else
1101 begin
1102 FdChildren.Add(NewNode);
1103 TopLevelCheckChild(NewNode);
1104 end;
1105 end else
1106 begin
1107 { For prototypes (indicated by FileTopLevel = false),
1108 do not check NewNode class, as anything is valid.
1109 Also, all nodes (even metadata) are just added to FdChildren,
1110 prototype expansion expects that. }
1111 FdChildren.Add(NewNode);
1112 end;
1113 end;
1114
1115 procedure TX3DRootNode.ExportNode(const Node: TX3DNode; const ExportedAlias: string);
1116 var
1117 ExportItem: TX3DExport;
1118 begin
1119 if Node.X3DName = '' then
1120 raise Exception.Create('You cannot export nodes with empty names');
1121
1122 ExportItem := TX3DExport.Create;
1123 AddExport(ExportItem);
1124 ExportItem.ExportedNode := Node;
1125 if ExportedAlias <> Node.X3DName then
1126 ExportItem.ExportedAlias := ExportedAlias;
1127
1128 { merely adding ExportItem is not enough, we have to also replicate what
1129 parsing of EXPORT clause does, and add it to ExportedNames. }
1130 if FExportedNames = nil then
1131 FExportedNames := TX3DExportList.Create(false); // do not own TX3DExport instances, they are owned by TX3DNode.Exports
1132 FExportedNames.Add(ExportItem);
1133 end;
1134
1135 procedure TX3DRootNode.ExportNode(const Node: TX3DNode);
1136 begin
1137 ExportNode(Node, Node.X3DName);
1138 end;
1139
1140 function TX3DRootNode.TransformationChange: TNodeTransformationChange;
1141 begin
1142 Result := ntcTransform;
1143 end;
1144
1145 procedure TX3DRootNode.InternalFixNodeNames;
1146 var
1147 Handler: TFixNamesHandler;
1148 begin
1149 Handler := TFixNamesHandler.Create;
1150 try
1151 Handler.HandleNode(nil, Self);
1152 DirectEnumerateAll({$ifdef FPC}@{$endif} Handler.HandleNode);
1153 finally FreeAndNil(Handler) end;
1154 end;
1155
1156 { TStaticGroupNode ----------------------------------------------------------- }
1157
1158 function TStaticGroupNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
1159 begin
1160 Result := FdChildren.Enumerate(Func);
1161 if Result <> nil then Exit;
1162 end;
1163
1164 { TSwitchNode ---------------------------------------------------------------- }
1165
1166 constructor TSwitchNode.Create(const AX3DName: String = ''; const ABaseUrl: String = '');
1167 begin
1168 inherited;
1169 Fdchildren.AddAlternativeName('choice', 2);
1170 end;
1171
1172 class function TSwitchNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
1173 begin
1174 Result := Version.Major >= 2;
1175 end;
1176
1177 function TSwitchNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
1178 begin
1179 Result := nil;
1180 if Between(FdWhichChoice.Value, 0, FdChildren.Count - 1) then
1181 begin
1182 Result := Func(Self, FdChildren[FdWhichChoice.Value]);
1183 if Result <> nil then Exit;
1184 end;
1185 end;
1186
1187 function TSwitchNode.TransformationChange: TNodeTransformationChange;
1188 begin
1189 Result := ntcSwitch;
1190 end;
1191
1192 { TTransformNode.TTransformNodeTransformFunctionality --------------------------------------- }
1193
1194 constructor TTransformNode.TTransformNodeTransformFunctionality.Create(const AParent: TTransformNode);
1195 begin
1196 inherited Create(AParent);
1197 FParent := AParent;
1198 end;
1199
1200 procedure TTransformNode.TTransformNodeTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
1201 begin
1202 // inherited; // no need to call, conserve speed in this critical place
1203
1204 Transformation.Multiply(
1205 Parent.Center,
1206 Parent.Rotation,
1207 Parent.Scale,
1208 Parent.ScaleOrientation,
1209 Parent.Translation);
1210
1211 {
1212 if ((Fdscale.Value[0] < 0) or
1213 (Fdscale.Value[1] < 0) or
1214 (Fdscale.Value[2] < 0)) and not WarningNegativeScaleDone then
1215 begin
1216 WarningNegativeScaleDone := true;
1217 WritelnLog('VRML/X3D', 'Note: Transform.scale has negative component. It allows some tricks (especially sensible for unlit 2D stuff), but it makes lighting act weird. Make sure you use it only for unlit objects.');
1218 end;
1219 }
1220 end;
1221
1222 { TTransformNode ------------------------------------------------------------- }
1223
1224 constructor TTransformNode.Create(const AX3DName, ABaseUrl: String);
1225 begin
1226 inherited;
1227 FTransformFunctionality := TTransformNodeTransformFunctionality.Create(Self);
1228 AddFunctionality(FTransformFunctionality);
1229 end;
1230
1231 class function TTransformNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
1232 begin
1233 Result := Version.Major >= 2;
1234 end;
1235
1236 function TTransformNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
1237 begin
1238 Result := FdChildren.Enumerate(Func);
1239 if Result <> nil then Exit;
1240 end;
1241
1242 function TTransformNode.TransformationChange: TNodeTransformationChange;
1243 begin
1244 Result := ntcTransform;
1245 end;
1246
1247 procedure RegisterGroupingNodes;
1248 begin
1249 NodesManager.RegisterNodeClasses([
1250 TGroupNode,
1251 TStaticGroupNode,
1252 TSwitchNode,
1253 TTransformNode
1254 ]);
1255 end;
1256 {$endif read_implementation}