Debian Codegraph @

src/scene/castleinternalnodeinterpolator.pas

raw
1 {
2 Copyright 2006-2022 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Powerful automatic interpolation for any X3D node hierarchies,
17 able to animate a sequence of any X3D scenes. }
18 unit CastleInternalNodeInterpolator;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses Classes, Generics.Collections,
25 CastleUtils, X3DNodes, CastleBoxes, X3DLoadInternalGLTF;
26
27 type
28 TGetKeyNodeWithTime = procedure (const Index: Cardinal;
29 out KeyNode: TX3DRootNode; out Time: Single) of object;
30
31 TNodeInterpolator = class
32 strict private
33 { Helpers for Load implementation. }
34 class var
35 LoadToX3D_KeyNodes: TX3DNodeList;
36 LoadToX3D_KeyTimes: TSingleList;
37 class procedure LoadToX3D_GetKeyNodeWithTime(const Index: Cardinal;
38 out KeyNode: TX3DRootNode; out Time: Single);
39 public
40 const
41 DefaultScenesPerTime = 30;
42 DefaultEpsilon = 0.001;
43 DefaultAnimationName = 'animation';
44
45 type
46 { Key X3D nodes read from castle-anim-frames. }
47 TAnimation = class
48 { The nodes and associated times read from castle-anim-frames.
49 The list objects are owned (created, destroyed) by this TAnimation instance.
50 The nodes inside KeyNodes are not -- it's the caller responsibility
51 to free or pass them as appropriate (or just call
52 @link(FreeKeyNodesContents) to easily free them).
53 @groupBegin }
54 KeyNodes: TX3DNodeList;
55 KeyTimes: TSingleList;
56 { @groupEnd }
57 Name: string;
58 ScenesPerTime: Cardinal;
59 Epsilon: Single;
60 Loop, Backwards: boolean;
61 BoundingBox: TBox3D;
62
63 constructor Create;
64 destructor Destroy; override;
65 procedure FreeKeyNodesContents;
66 end;
67
68 TAnimationList = class({$ifdef FPC}specialize{$endif} TObjectList<TAnimation>)
69 { Call TAnimation.FreeKeyNodesContents on all the items. }
70 procedure FreeKeyNodesContents;
71 end;
72
73 { X3D nodes series that make an animation.
74 These are like TAnimation, but sometimes with additional
75 interpolated nodes added in between. }
76 TBakedAnimation = class
77 { The nodes for every time step.
78 This is usually more than just "key" nodes, it's filled with intermediate
79 interpolated nodes created by BakeToSequence.
80
81 Just like TAnimation.KeyNodes, the nodes list instance is owned by
82 this TBakedAnimation instance, but it's contents (actual X3D nodes) is not.
83 That is, Nodes.OwnsObjects is @false.
84 Make sure to free (or pass along) the nodes as necessary.
85 In the simplest case, you can call FreeNodesContents,
86 but usually you will pass the nodes furher to LoadToX3D.
87
88 This list is never empty after BakeToSequence call,
89 as you cannot create a sequence from an empty list.
90 The list contains only TX3DRootNode instances.
91 }
92 Nodes: TX3DNodeList;
93
94 TimeBegin, TimeEnd: Single;
95 Name: string;
96 Loop, Backwards: boolean;
97 BoundingBox: TBox3D;
98
99 constructor Create;
100 destructor Destroy; override;
101 procedure FreeNodesContents;
102
103 { Animation duration in seconds. Just TimeEnd - TimeBegin. }
104 function Duration: Single;
105 end;
106
107 TBakedAnimationList = class({$ifdef FPC}specialize{$endif} TObjectList<TBakedAnimation>)
108 procedure FreeNodesContents;
109 end;
110
111 { Load animation data from castle-anim-frames file (in a given URL) to a set of variables.
112 See [https://castle-engine.io/castle_animation_frames.php]
113 for a specification of the file format.
114
115 If you want a comfortable way to load castle-anim-frames from a file,
116 you will usually just use the @link(TCastleScene.Load) method.
117 The @name is more flexible --- it returns the nodes list,
118 which allows you to modify the animation before passing it to @link(LoadToX3D)
119 or other methods.
120
121 Returns a TAnimationList instance.
122 It's the caller responsibility to free this instance (along with it's contents;
123 the list items will be freed automatically with the list,
124 as the list has OwnsObjects = true;
125 but you must manually take care to free (or pass elsewhere)
126 the TAnimation.KeyNodes contents, or just call @link(TAnimationList.FreeKeyNodesContents).)
127 }
128 class function LoadAnimFramesToKeyNodes(const Url: String): TAnimationList; overload;
129 class function LoadAnimFramesToKeyNodes(const Stream: TStream; const BaseUrl: String): TAnimationList; overload;
130
131 { From key nodes, create a series of baked nodes (with final
132 animation pose already calculated) representing an animation.
133
134 KeyNodesCount must always be at least one,
135 you cannot create animation from an empty list.
136
137 The returned animation must be freed by the caller.
138 You should take care to free the contained @link(TBakedAnimation.Nodes)
139 (they are @italic(not) automatically freed by freeing TBakedAnimation).
140
141 It always contains the "key" nodes returned by GetKeyNodeWithTime,
142 so there's no need to free the "key" nodes if you already take care of freeing
143 the resulting nodes.
144
145 We do not set the Name, Loop, Backwards, BoundingBox properties of the TBakedAnimation.
146 Caller should set them, to finalize the initialization of TBakedAnimation. }
147 class function BakeToSequence(const GetKeyNodeWithTime: TGetKeyNodeWithTime;
148 const KeyNodesCount: Cardinal;
149 ScenesPerTime: Cardinal;
150 const Epsilon: Single): TBakedAnimation;
151
152 { Convert a node list to animate (like the one from MD3 loader,
153 or from TNodeInterpolator.BakeToSequence,
154 which may come from castle-anim-frames file or from generated animation)
155 into a simple X3D graph that animates it (using TimeSensor,
156 IntegerSequencer and Switch node, wrapping given here Nodes).
157 This allows to read key nodes from any format,
158 like a castle-anim-frames or MD3, and convert them to a simple X3D animation.
159
160 BakedAnimations list must never be empty. }
161 class function LoadSequenceToX3D(const BakedAnimations: TBakedAnimationList): TX3DRootNode;
162
163 { Load animations (read by @link(LoadAnimFramesToKeyNodes) to a series
164 of key nodes) into a X3D animation.
165
166 This is a combined BakeToSequence (that interpolates and creates
167 intermediate nodes from a list of key nodes) and LoadSequenceToX3D
168 (that converts a sequence of nodes into an animation, using TimeSensor,
169 Switch etc.)
170
171 After calling this, the "key" nodes inside the @link(TAnimation.KeyNodes)
172 become owned by the resulting large X3D node. So there's no need to worry
173 about freeing them anymore, just make sure to free the resulting large node.
174 @bold(If this exits with exception, the @link(TAnimation.KeyNodes) are already freed.)
175 This is weird, but necessary (otherwise we would have to suffer memory leaks,
176 as internal BakeToSequence could already create some intermediate nodes).
177 So, after calling this method, you should only free the TAnimationList instance. }
178 class function LoadToX3D(const Animations: TAnimationList): TX3DRootNode;
179 end;
180
181 implementation
182
183 uses SysUtils, XMLRead, DOM, Math,
184 CastleLog, X3DFields, CastleXmlUtils, CastleFilesUtils, CastleVectors,
185 CastleDownload, CastleUriUtils, X3DLoad, CastleClassUtils, X3DLoadInternalUtils;
186
187 { EModelsStructureDifferent -------------------------------------------------- }
188
189 type
190 EModelsStructureDifferent = class(Exception)
191 constructor CreateFmt(const S: string; const Args: array of const);
192 end;
193
194 constructor EModelsStructureDifferent.CreateFmt(const S: string;
195 const Args: array of const);
196 begin
197 inherited CreateFmt('Models are structurally different: ' + S, Args);
198 end;
199
200 { utilities for TNodeInterpolator.BakeToSequence ----------------------------- }
201
202 { Check that Model1 and Model2 are exactly equal,
203 or that at least interpolating (see NodesLerp) is possible.
204
205 If models are structurally different (which means that even
206 interpolating between Model1 and Model2 is not possible),
207 it will raise EModelsStructureDifferent. }
208 procedure CheckNodesStructurallyEqual(Model1, Model2: TX3DNode;
209 const Epsilon: Single);
210
211 procedure CheckSFNodesStructurallyEqual(Field1, Field2: TSFNode);
212 begin
213 if Field1.WeakLink and Field2.WeakLink then
214 begin
215 { assume equal }
216 end else
217 if (Field1.Value <> nil) and (not Field1.WeakLink) and
218 (Field2.Value <> nil) and (not Field2.WeakLink) then
219 begin
220 CheckNodesStructurallyEqual(Field1.Value, Field2.Value, Epsilon);
221 end else
222 if not ((Field1.Value = nil) and (Field2.Value = nil)) then
223 raise EModelsStructureDifferent.CreateFmt('Field "%s" of type SFNode ' +
224 'is once NULL and once not-NULL', [Field1.X3DName]);
225 end;
226
227 procedure CheckMFNodesStructurallyEqual(Field1, Field2: TMFNode);
228 var
229 I: Integer;
230 begin
231 if Field1.Count <> Field2.Count then
232 raise EModelsStructureDifferent.CreateFmt(
233 'Different number of children in MFNode field "%s": %d vs %d',
234 [Field1.NiceName, Field1.Count, Field2.Count]);
235
236 for I := 0 to Field1.Count - 1 do
237 CheckNodesStructurallyEqual(Field1[I], Field2[I], Epsilon);
238 end;
239
240 var
241 I: Integer;
242 MF1, MF2: TX3DMultField;
243 begin
244 { Yes, Model1 and Model2 must have *exactly* the same classes. }
245 if Model1.ClassType <> Model2.ClassType then
246 raise EModelsStructureDifferent.CreateFmt(
247 'Different nodes classes: "%s" and "%s"',
248 [Model1.ClassName, Model2.ClassName]);
249
250 { Make sure that *Inline content is loaded now. }
251 if Model1 is TInlineNode then
252 begin
253 TInlineNode(Model1).LoadInlined(false);
254 TInlineNode(Model2).LoadInlined(false);
255 end;
256
257 if Model1.X3DName <> Model2.X3DName then
258 raise EModelsStructureDifferent.CreateFmt(
259 'Different names of nodes: "%s" and "%s"',
260 [Model1.X3DName, Model2.X3DName]);
261
262 { We are interested whether Model1.BaseUrl and Model2.BaseUrl will
263 give different results when using them to resolve relative URLs.
264 Simply comparing them is not good --- they may contain filenames
265 at the end. Stripping these filenames with ExtractURIPath
266 is dirty. So we just test CombineURI with a test name. }
267 if Model1.PathFromBaseUrl('test') <> Model2.PathFromBaseUrl('test') then
268 raise EModelsStructureDifferent.CreateFmt(
269 'BaseUrl of nodes different (will resolve relative URLs to different things): "%s" and "%s"',
270 [Model1.BaseUrl, Model2.BaseUrl]);
271
272 if Model1.VRML1ChildrenCount <> Model2.VRML1ChildrenCount then
273 raise EModelsStructureDifferent.CreateFmt(
274 'Different number of Inventor / VRML 1.0 children in nodes: %d vs %d',
275 [Model1.VRML1ChildrenCount, Model2.VRML1ChildrenCount]);
276
277 for I := 0 to Model1.VRML1ChildrenCount - 1 do
278 CheckNodesStructurallyEqual(Model1.VRML1Children[I], Model2.VRML1Children[I], Epsilon);
279
280 { Yes, the situation below can happen. *Usually* when we know
281 that Model1 and Model2 are equal classes then we know that
282 they have the same number of fields of the same type.
283 However, for TX3DUnknownNode, it's not that easy. Two different instances
284 of TX3DUnknownNode class may have completely different fields,
285 so we must safeguard against this. }
286 if Model1.FieldsCount <> Model2.FieldsCount then
287 raise EModelsStructureDifferent.CreateFmt(
288 'Different number of fields in nodes: "%d" and "%d"',
289 [Model1.FieldsCount, Model2.FieldsCount]);
290
291 for I := 0 to Model1.FieldsCount - 1 do
292 begin
293 if Model1.Fields[I].ClassType <> Model2.Fields[I].ClassType then
294 raise EModelsStructureDifferent.CreateFmt(
295 'Different type of field number %d in nodes: "%s" and "%s"',
296 [I, Model1.Fields[I].ClassName, Model2.Fields[I].ClassName]);
297
298 if Model1.Fields[I] is TSFNode then
299 CheckSFNodesStructurallyEqual(
300 TSFNode(Model1.Fields[I]), TSFNode(Model2.Fields[I])) else
301 if Model1.Fields[I] is TMFNode then
302 CheckMFNodesStructurallyEqual(
303 TMFNode(Model1.Fields[I]), TMFNode(Model2.Fields[I])) else
304 if Model1.Fields[I].CanAssignLerp then
305 begin
306 if Model1.Fields[I] is TX3DMultField then
307 begin
308 MF1 := Model1.Fields[I] as TX3DMultField;
309 MF2 := Model2.Fields[I] as TX3DMultField;
310 if MF1.Count <> MF2.Count then
311 raise EModelsStructureDifferent.CreateFmt(
312 'Different length of multiple-value fields "%s" and "%s": "%d" and "%d"',
313 [ MF1.X3DName,
314 MF2.X3DName,
315 MF1.Count,
316 MF2.Count ]);
317 end;
318 { Else we have single-value field that can lerp.
319 No need to check anything in this case,
320 it's ready to go (that is, to lerp). }
321 end else
322 begin
323 { Check fields for equality.
324
325 Some special fields like TInlineNode.FdUrl do not
326 have to be equal, as they don't have any role for the
327 "real" meaning of the model. I mean, if TInlineNode.Inlined
328 contents (loaded from pointed file) have the same structure,
329 then we're happy. And it's handy to allow this --- see e.g.
330 examples/models/gus_1_final.wrl and
331 examples/models/gus_2_final.wrl trick. }
332
333 if not (
334 ( (Model1 is TInlineNode) and (Model1.Fields[I].X3DName = 'url') ) or
335 Model1.Fields[I].Equals(Model2.Fields[I]
336 { TODO: ignored for now, and maybe for ever: , Epsilon })
337 ) then
338 raise EModelsStructureDifferent.CreateFmt(
339 'Fields "%s" (class "%s") are not equal',
340 [Model1.Fields[I].X3DName, Model1.Fields[I].ClassName]);
341 end;
342 end;
343 end;
344
345 { Merge equal children of Model1 and Model2,
346 and check that Model1 and Model2 are exactly equal.
347
348 It assumes that models are structurally equal, i.e. that you
349 already did run CheckNodesStructurallyEqual over them.
350
351 It works recursively: first it checks for every children
352 are they equal. For each pair that is equal, it replaces
353 given children in Model2 with appropriate children of Model1.
354 At the end, if every children pair was equal and additionally
355 if all fields are equal, then it returns true.
356
357 Such copying of references is useful, because then we simply copy given
358 node's reference instead of duplicating this object.
359 This way Model1 and Model2 and all models interpolated along the way
360 can share the same object reference. This is very good, because:
361
362 1. If nodes are equal then creating new object each
363 time would mean that I create a lot of objects with exactly the
364 same contents. So memory is wasted, without any good reason.
365
366 2. For nodes like ImageTexture, this is good because then the image
367 is loaded from the file only once. This means that memory is saved,
368 once again. This also means that in case when texture file doesn't
369 exist, user gets only 1 warning/error message (instead of getting
370 warning/error message for each duplicated TImageTextureNode instance).
371
372 3. Also for nodes like ImageTexture, this means that if we use the same
373 GLRenderer to render every model of the animation,
374 then GLRenderer will recognize this and given texture
375 will be loaded only once for OpenGL. So loading time and
376 memory are saved *once again* (otherwise OpenGL would allocate
377 internal copy of texture for each duplicated node, once again
378 wasting a lot of memory).
379
380 Although 2. and 3. are actually somewhat void right now,
381 as we have a more general cache that caches texture resources
382 even across different nodes right now (the only need is to have
383 equal URLs).
384
385 4. And later the Shape cache in TRendererCache can speed
386 up loading time and conserve memory use, if it sees the same
387 reference to given GeometryNode twice. }
388 function NodesMerge(Model1, Model2: TX3DNode;
389 const Epsilon: Single): boolean;
390
391 function SFNodesMerge(Field1, Field2: TSFNode): boolean;
392 begin
393 Result := true;
394
395 { Equality was already checked by CheckNodesStructurallyEqual,
396 so now if one SFNode value is not nil, we know that the other
397 one is not nil too. }
398 if (Field1.Value <> nil) and
399 (not Field1.WeakLink) and
400 (not Field2.WeakLink) then
401 begin
402 if NodesMerge(Field1.Value, Field2.Value, Epsilon) then
403 Field1.Value := Field2.Value else
404 Result := false;
405 end;
406 end;
407
408 function MFNodesMerge(Field1, Field2: TMFNode): boolean;
409 var
410 I: Integer;
411 begin
412 Result := true;
413
414 { Note that we already know that Counts are equals,
415 checked already by CheckNodesStructurallyEqual. }
416 Assert(Field1.Count = Field2.Count);
417 for I := 0 to Field1.Count - 1 do
418 begin
419 if NodesMerge(Field1[I], Field2[I], Epsilon) then
420 begin
421 { Think of this as
422 Field1[I] := Field2[I]
423 but I can't call this directly, I must use Field1.Replace
424 to not mess reference counts. }
425 Field1.Replace(I, Field2[I]);
426 end else
427 Result := false;
428 end;
429 end;
430
431 var
432 I: Integer;
433 begin
434 Result := true;
435
436 { Note that this loop will iterate over every Children,
437 even if somewhere along the way we will already set Result to false.
438 Even if we already know that Result is false, we stil want to
439 merge Model1 and Model2 children as much as we can. }
440 for I := 0 to Model1.VRML1ChildrenCount - 1 do
441 begin
442 if NodesMerge(Model1.VRML1Children[I], Model2.VRML1Children[I], Epsilon) then
443 begin
444 { Tests: Writeln('merged child ', I, ' of class ',
445 Model1.VRML1Children[I].X3DType); }
446 Model1.VRML1Children[I] := Model2.VRML1Children[I];
447 end else
448 Result := false;
449 end;
450
451 if not Result then Exit;
452
453 for I := 0 to Model1.FieldsCount - 1 do
454 begin
455 if Model1.Fields[I] is TSFNode then
456 begin
457 if not SFNodesMerge(TSFNode(Model1.Fields[I]),
458 TSFNode(Model2.Fields[I])) then
459 Result := false;
460 end else
461 if Model1.Fields[I] is TMFNode then
462 begin
463 if not MFNodesMerge(TMFNode(Model1.Fields[I]),
464 TMFNode(Model2.Fields[I])) then
465 Result := false;
466 end else
467 if Model1.Fields[I].CanAssignLerp then
468 begin
469 if not Model1.Fields[I].Equals(Model2.Fields[I]
470 { TODO: ignored for now, and maybe for ever: , Epsilon }) then
471 Result := false;
472 end;
473
474 { Other fields were already checked by CheckNodesStructurallyEqual }
475 end;
476 end;
477
478 { Linear interpolation between Model1 and Model2.
479 A = 0 means Model1, A = 1 means Model2, A between 0 and 1 is lerp
480 between Model1 and Model2.
481
482 If Model1 and Model2 are the same object (the same references),
483 then this will return just Model1. This way it keeps memory optimization
484 described by NodesMerge. This is also true if both Model1 and Model2
485 are nil: then you can safely call this and it will return also nil. }
486 function NodesLerp(const A: Single; Model1, Model2: TX3DNode): TX3DNode;
487
488 procedure SFNodeLerp(Target, Field1, Field2: TSFNode);
489 begin
490 if (not Field1.WeakLink) and
491 (not Field2.WeakLink) then
492 Target.Value := NodesLerp(A, Field1.Value, Field2.Value)
493 else
494 Target.Value := Field1.Value;
495 end;
496
497 procedure MFNodeLerp(Target, Field1, Field2: TMFNode);
498 var
499 I: Integer;
500 begin
501 for I := 0 to Field1.Count - 1 do
502 Target.Add(NodesLerp(A, Field1[I], Field2[I]));
503 end;
504
505 var
506 I: Integer;
507 begin
508 if Model1 = Model2 then
509 Exit(Model1);
510
511 Result := TX3DNodeClass(Model1.ClassType).Create(Model1.X3DName,
512 Model1.BaseUrl);
513 try
514 { We already loaded all inlines (in CheckNodesStructurallyEqual).
515 We have to mark it now, by setting Loaded := true field as necessary
516 inside inline nodes --- otherwise, they could be loaded again
517 (adding content to already existing nodes, making content loaded
518 more than once). }
519 if Result is TInlineNode then
520 begin
521 TInlineNode(Result).LoadedInlineDirectly;
522 end;
523
524 if Result is TX3DRootNode then
525 begin
526 { copy TX3DRootNode special fields, like TX3DRootNode.DeepCopyCore.
527 This is necessary for WrapRootNode working Ok lower in this file. }
528 TX3DRootNode(Result).HasForceVersion := (Model1 as TX3DRootNode).HasForceVersion;
529 TX3DRootNode(Result).ForceVersion := (Model1 as TX3DRootNode).ForceVersion;
530 TX3DRootNode(Result).Scale := (Model1 as TX3DRootNode).Scale;
531 TX3DRootNode(Result).Profile := (Model1 as TX3DRootNode).Profile;
532 TX3DRootNode(Result).Components.Assign((Model1 as TX3DRootNode).Components);
533 TX3DRootNode(Result).Meta.Assign((Model1 as TX3DRootNode).Meta);
534 end;
535
536 { TODO: the code below doesn't deal efficiently with the situation when single
537 TX3DNode is used as a child many times in one of the nodes.
538 (through "USE" keyword). Code below will then unnecessarily
539 create copies of such things (wasting construction time and memory),
540 instead of reusing the same object reference. }
541 for I := 0 to Model1.VRML1ChildrenCount - 1 do
542 Result.VRML1ChildAdd(NodesLerp(A, Model1.VRML1Children[I], Model2.VRML1Children[I]));
543
544 { TODO: for TX3DUnknownNode, we should fill here Result.Fields.
545 Also for TX3DPrototypeNode. }
546
547 for I := 0 to Model1.FieldsCount - 1 do
548 begin
549 if Model1.Fields[I] is TSFNode then
550 begin
551 SFNodeLerp(
552 (Result.Fields[I] as TSFNode),
553 (Model1.Fields[I] as TSFNode),
554 (Model2.Fields[I] as TSFNode));
555 end else
556 if Model1.Fields[I] is TMFNode then
557 begin
558 MFNodeLerp(
559 (Result.Fields[I] as TMFNode),
560 (Model1.Fields[I] as TMFNode),
561 (Model2.Fields[I] as TMFNode));
562 end else
563 if Model1.Fields[I].CanAssignLerp then
564 begin
565 Result.Fields[I].AssignLerp(A, Model1.Fields[I], Model2.Fields[I]);
566 end else
567 begin
568 { These fields cannot be interpolated.
569 So just copy to Result.Fields[I]. }
570 Result.Fields[I].Assign(Model1.Fields[I]);
571 end;
572 end;
573 except
574 FreeAndNil(Result);
575 raise;
576 end;
577 end;
578
579 { TAnimation ----------------------------------------------------------------- }
580
581 constructor TNodeInterpolator.TAnimation.Create;
582 begin
583 inherited;
584 KeyTimes := TSingleList.Create;
585 KeyNodes := TX3DNodeList.Create(false);
586 end;
587
588 destructor TNodeInterpolator.TAnimation.Destroy;
589 begin
590 FreeAndNil(KeyTimes);
591 FreeAndNil(KeyNodes);
592 inherited;
593 end;
594
595 procedure TNodeInterpolator.TAnimation.FreeKeyNodesContents;
596 var
597 I: Integer;
598 begin
599 for I := 0 to KeyNodes.Count - 1 do
600 begin
601 KeyNodes[I].Free;
602 KeyNodes[I] := nil;
603 end;
604 KeyNodes.Clear;
605 end;
606
607 { TAnimationList ------------------------------------------------------------- }
608
609 procedure TNodeInterpolator.TAnimationList.FreeKeyNodesContents;
610 var
611 I: Integer;
612 begin
613 for I := 0 to Count - 1 do
614 Items[I].FreeKeyNodesContents;
615 end;
616
617 { TBakedAnimation ----------------------------------------------------------------- }
618
619 constructor TNodeInterpolator.TBakedAnimation.Create;
620 begin
621 inherited;
622 Nodes := TX3DNodeList.Create(false);
623 end;
624
625 destructor TNodeInterpolator.TBakedAnimation.Destroy;
626 begin
627 FreeAndNil(Nodes);
628 inherited;
629 end;
630
631 function TNodeInterpolator.TBakedAnimation.Duration: Single;
632 begin
633 Result := TimeEnd - TimeBegin;
634 end;
635
636 procedure TNodeInterpolator.TBakedAnimation.FreeNodesContents;
637 var
638 I: Integer;
639 begin
640 for I := 0 to Nodes.Count - 1 do
641 begin
642 Nodes[I].Free;
643 Nodes[I] := nil;
644 end;
645 Nodes.Clear;
646 end;
647
648 { TBakedAnimationList ------------------------------------------------------------- }
649
650 procedure TNodeInterpolator.TBakedAnimationList.FreeNodesContents;
651 var
652 I: Integer;
653 begin
654 for I := 0 to Count - 1 do
655 Items[I].FreeNodesContents;
656 end;
657
658 { TNodeInterpolator ---------------------------------------------------------- }
659
660 class function TNodeInterpolator.BakeToSequence(
661 const GetKeyNodeWithTime: TGetKeyNodeWithTime;
662 const KeyNodesCount: Cardinal;
663 ScenesPerTime: Cardinal;
664 const Epsilon: Single): TBakedAnimation;
665 var
666 I: Integer;
667 StructurallyEqual, KeyNodesEqual: boolean;
668 LastNodesIndex: Integer;
669 LastKeyNode, NewKeyNode: TX3DRootNode;
670 LastTime, NewTime: Single;
671 NodesIndex: Integer;
672 Nodes: TX3DNodeList;
673 begin
674 ScenesPerTime := Round(ScenesPerTime * BakedAnimationSmoothness);
675
676 Result := TBakedAnimation.Create;
677 try
678 Assert(KeyNodesCount > 0);
679
680 { KeyNodes[0] goes to Nodes[0], that's easy }
681 GetKeyNodeWithTime(0, NewKeyNode, NewTime);
682
683 Nodes := Result.Nodes;
684
685 Nodes.Count := 1;
686 Nodes[0] := NewKeyNode;
687 LastNodesIndex := 0;
688 LastTime := NewTime;
689 LastKeyNode := NewKeyNode;
690
691 { calculate TimeBegin at this point }
692 Result.TimeBegin := NewTime;
693
694 for I := 1 to KeyNodesCount - 1 do
695 begin
696 { Now add KeyNodes[I] }
697 GetKeyNodeWithTime(I, NewKeyNode, NewTime);
698
699 StructurallyEqual := false;
700
701 try
702 CheckNodesStructurallyEqual(LastKeyNode, NewKeyNode, Epsilon);
703 StructurallyEqual := true;
704 except
705 on E: EModelsStructureDifferent do
706 begin
707 WritelnLog('TNodeInterpolator', Format(
708 'Nodes %d and %d structurally different, so animation will not be smoothed between them: ',
709 [I - 1, I]) + E.Message);
710 end;
711 end;
712
713 Nodes.Count := Nodes.Count +
714 Max(1, Round((NewTime - LastTime) * ScenesPerTime));
715
716 if StructurallyEqual then
717 begin
718 { Try to merge it with LastKeyNode.
719 Then initialize Nodes[LastNodesIndex + 1 to Nodes.Count - 1]. }
720 KeyNodesEqual := NodesMerge(NewKeyNode, LastKeyNode, Epsilon);
721 if KeyNodesEqual then
722 begin
723 { In this case don't waste memory, simply reuse Nodes[LastNodesIndex]. }
724 FreeAndNil(NewKeyNode);
725 for NodesIndex := LastNodesIndex + 1 to Nodes.Count - 1 do
726 Nodes[NodesIndex] := Nodes[LastNodesIndex];
727 end else
728 begin
729 for NodesIndex := LastNodesIndex + 1 to Nodes.Count - 2 do
730 Nodes[NodesIndex] := NodesLerp(
731 MapRange(NodesIndex, LastNodesIndex, Nodes.Count - 1, 0.0, 1.0),
732 LastKeyNode, NewKeyNode);
733 Nodes[Nodes.Count - 1] := NewKeyNode;
734 LastKeyNode := NewKeyNode;
735 end;
736 end else
737 begin
738 { We cannot interpolate between last and new node.
739 So just duplicate last node until Nodes.Count - 2,
740 and at Nodes.Last insert new node. }
741 for NodesIndex := LastNodesIndex + 1 to Nodes.Count - 2 do
742 Nodes[NodesIndex] := Nodes[LastNodesIndex];
743 Nodes[Nodes.Count - 1] := NewKeyNode;
744 LastKeyNode := NewKeyNode;
745 end;
746
747 LastTime := NewTime;
748 LastNodesIndex := Nodes.Count - 1;
749 end;
750
751 { calculate TimeEnd at this point }
752 Result.TimeEnd := NewTime;
753
754 except FreeAndNil(Result); raise end;
755 end;
756
757 class function TNodeInterpolator.LoadAnimFramesToKeyNodes(const Url: String): TAnimationList;
758 var
759 Stream: TStream;
760 begin
761 Stream := Download(Url);
762 try
763 Result := LoadAnimFramesToKeyNodes(Stream, Url);
764 finally FreeAndNil(Stream) end;
765 end;
766
767 class function TNodeInterpolator.LoadAnimFramesToKeyNodes(const Stream: TStream; const BaseUrl: String): TAnimationList;
768 const
769 GltfJsonMimeType = 'model/gltf+json';
770
771 function LoadGLTFFromString(const Contents: String; const BaseUrl: String): TX3DRootNode;
772 var
773 SStream: TStringStream;
774 begin
775 SStream := TStringStream.Create(Contents);
776 try
777 Result := LoadNode(SStream, BaseUrl, GltfJsonMimeType);
778 finally FreeAndNil(SStream) end;
779 end;
780
781 { Load <animation> data from a given XML element to a set of variables.
782
783 @param(BaseUrl The URL from which relative
784 URLs inside Element will be resolved. It doesn't
785 have to be absolute, we will expand it to make it absolute
786 if necessary.) }
787 function LoadOneAnimation(Element: TDOMElement): TAnimation;
788 const
789 DefaultLoop = false;
790 DefaultBackwards = false;
791 var
792 AbsoluteBaseUrl: String;
793 FrameElement: TDOMElement;
794 Children: TXMLElementIterator;
795 I: Integer;
796 FrameTime: Single;
797 FrameUrl, MimeType: string;
798 NewNode: TX3DRootNode;
799 Attr: TDOMAttr;
800 FrameBoxCenter, FrameBoxSize: TVector3;
801 begin
802 Result := TAnimation.Create;
803 try
804 AbsoluteBaseUrl := AbsoluteURI(BaseUrl);
805
806 Check(Element.TagName = 'animation', 'Expected an <animation> XML node');
807
808 { Assign default values for optional attributes }
809 Result.Name := DefaultAnimationName;
810 Result.ScenesPerTime := DefaultScenesPerTime;
811 Result.Epsilon := DefaultEpsilon;
812 Result.Loop := DefaultLoop;
813 Result.Backwards := DefaultBackwards;
814 Result.BoundingBox := TBox3D.Empty;
815
816 for I := 0 to Integer(Element.Attributes.Length) - 1 do
817 begin
818 Attr := Element.Attributes.Item[I] as TDOMAttr;
819 if Attr.Name = 'name' then
820 Result.Name := Attr.NodeValue8
821 else
822 if Attr.Name = 'scenes_per_time' then
823 Result.ScenesPerTime := StrToInt(Attr.NodeValue8)
824 else
825 if Attr.Name = 'optimization' then
826 { ignore, for backward compatibility }
827 else
828 if Attr.Name = 'equality_epsilon' then
829 Result.Epsilon := StrToFloatDot(Attr.NodeValue8)
830 else
831 if Attr.Name = 'loop' then
832 Result.Loop := StrToBool(Attr.NodeValue8)
833 else
834 if Attr.Name = 'backwards' then
835 Result.Backwards := StrToBool(Attr.NodeValue8)
836 else
837 raise Exception.CreateFmt('Unknown attribute of <animation> element: "%s"',
838 [Attr.Name]);
839 end;
840
841 Children := Element.ChildrenIterator;
842 try
843 while Children.GetNext do
844 begin
845 FrameElement := Children.Current;
846 Check(FrameElement.TagName = 'frame',
847 'Each child of <animation> element must be a <frame> element');
848
849 if not FrameElement.AttributeSingle('time', FrameTime) then
850 raise Exception.Create('<frame> element must have a "time" attribute');
851 if (Result.KeyTimes.Count > 0) and
852 (FrameTime <= Result.KeyTimes.Last) then
853 raise Exception.Create('Frames within <animation> element must be specified in an increasing time order');
854 Result.KeyTimes.Add(FrameTime);
855
856 if FrameElement.AttributeString('url', FrameUrl) or
857 FrameElement.AttributeString('file_name', FrameUrl) then
858 begin
859 { Make FrameUrl absolute, treating it as relative vs
860 AbsoluteBaseUrl }
861 FrameUrl := CombineURI(AbsoluteBaseUrl, FrameUrl);
862 NewNode := LoadNode(FrameUrl);
863 end else
864 begin
865 MimeType := FrameElement.AttributeStringDef('mime_type', '');
866 if (MimeType = '') or (MimeType = 'model/x3d+xml') then
867 NewNode := LoadX3DXmlInternal(FrameElement.ChildElement('X3D'), AbsoluteBaseUrl)
868 else
869 if (MimeType = GltfJsonMimeType) then
870 NewNode := LoadGLTFFromString(FrameElement.TextData, AbsoluteBaseUrl)
871 else
872 raise Exception.CreateFmt('Cannot use mime_type "%s" for a frame in castle-anim-frames', [
873 MimeType
874 ]);
875 end;
876
877 if FrameElement.AttributeVector3('bounding_box_center', FrameBoxCenter) and
878 FrameElement.AttributeVector3('bounding_box_size', FrameBoxSize) then
879 begin
880 Result.BoundingBox.Include(Box3DAroundPoint(FrameBoxCenter, FrameBoxSize));
881 end;
882
883 Result.KeyNodes.Add(NewNode);
884 end;
885 finally FreeAndNil(Children) end;
886
887 if Result.KeyNodes.Count = 0 then
888 raise Exception.Create('At least one <frame> is required within <animation> element');
889 except
890 { in case of trouble, clear the partial KeyNodes contents }
891 Result.FreeKeyNodesContents;
892 FreeAndNil(Result);
893 raise;
894 end;
895 end;
896
897 var
898 Document: TXMLDocument;
899 Children: TXMLElementIterator;
900 begin
901 ReadXMLFile(Document, Stream);
902
903 try
904 Result := TAnimationList.Create;
905 try
906 if Document.DocumentElement.TagName = 'animation' then
907 begin
908 Result.Add(LoadOneAnimation(Document.DocumentElement));
909 end else
910 begin
911 Check(Document.DocumentElement.TagName = 'animations',
912 'Expected an <animations> XML node at the root of castle-anim-frames, eventually an <animation> node for single-animation files.');
913
914 Children := Document.DocumentElement.ChildrenIterator;
915 try
916 while Children.GetNext do
917 Result.Add(LoadOneAnimation(Children.Current));
918 finally FreeAndNil(Children) end;
919
920 if Result.Count = 0 then
921 raise Exception.Create('No animations (no <animation> elements) inside the castle-anim-frames file');
922 end;
923 except
924 Result.FreeKeyNodesContents;
925 FreeAndNil(Result);
926 raise;
927 end;
928 finally FreeAndNil(Document); end;
929 end;
930
931 class function TNodeInterpolator.LoadSequenceToX3D(const BakedAnimations: TBakedAnimationList): TX3DRootNode;
932 var
933 BaseUrl: String;
934
935 { For VRML 1.0, wrap the contents in SeparateGroup. Prevents leaking
936 transformations between switch node children (testcase:
937 castle-game/data/creatures/alien/walk.kanim). Possibly it could be done
938 differently at higher level (because this is a switch, so it should
939 block leaking anyway, but probably Switch for X3D doesn't work for VRML 1.0
940 so well...). But it's obsolete VRML 1.0, so the hack is acceptable:) }
941 function WrapRootNode(const RootNode: TX3DRootNode): TAbstractChildNode;
942 begin
943 if RootNode.HasForceVersion and (RootNode.ForceVersion.Major <= 1) then
944 begin
945 Result := TSeparatorNode_1.Create('', BaseUrl);
946 Result.VRML1ChildAdd(RootNode);
947 end else
948 Result := RootNode;
949 end;
950
951 function WrapInCollisionNode(
952 const VisibleNode: TX3DNode; const Box: TBox3D): TCollisionNode;
953 begin
954 Result := TCollisionNode.Create('', BaseUrl);
955 Result.CollideAsBox(VisibleNode, Box);
956 end;
957
958 function ConvertOneAnimation(
959 const BakedAnimation: TBakedAnimation;
960 const AnimationIndex: Integer;
961 const RootNode: TX3DRootNode;
962 const SwitchChooseAnimation: TSwitchNode): TAbstractChildNode;
963 var
964 AnimationX3DName: string;
965
966 procedure AddAnimationVisibilityRoutes(TimeSensor: TTimeSensorNode);
967 var
968 ValueTrigger: TValueTriggerNode;
969 F: TX3DField;
970 begin
971 ValueTrigger := TValueTriggerNode.Create;
972 ValueTrigger.X3DName := AnimationX3DName + '_ValueTrigger';
973 RootNode.AddChildren(ValueTrigger);
974 RootNode.AddRoute(TimeSensor.EventIsActive, ValueTrigger.EventTrigger);
975
976 F := TSFInt32.Create(nil, true, 'whichChoice', AnimationIndex);
977 ValueTrigger.AddCustomField(F);
978 RootNode.AddRoute(F, SwitchChooseAnimation.FdWhichChoice.EventIn);
979 end;
980
981 var
982 TimeSensor: TTimeSensorNode;
983 IntSequencer: TIntegerSequencerNode;
984 Switch: TSwitchNode;
985 I, NodesCount: Integer;
986 Group: TGroupNode;
987 begin
988 AnimationX3DName := BakedAnimation.Name;
989
990 Group := TGroupNode.Create(
991 AnimationX3DName + '_Group', BaseUrl);
992
993 NodesCount := BakedAnimation.Nodes.Count;
994
995 IntSequencer := TIntegerSequencerNode.Create(
996 AnimationX3DName + '_IntegerSequencer', BaseUrl);
997 { ForceContinuousValue_Changed.Value means that output is send
998 (so Switch.whichChoice is set) even when the range of IntSequencer key
999 didn't change.
1000
1001 This is important in connection with TCastleScene.ResetAnimationState feature:
1002 when it occurs, the Switch.whichChoice is reset, and we expect that next
1003 receive of IntSequencer.fraction_changed will again set Switch.
1004
1005 Testcase:
1006 - deprecated_resource_animations example, load any castle-anim-frames example.
1007 Without this, the animation would jump between 2 frames.
1008 - Also examples/fixed_camera_game/ (shaking humanoid without this)
1009 - Also castle-game (shaking alien shooting animation) }
1010 IntSequencer.ForceContinuousValue_Changed := true;
1011 if BakedAnimation.Backwards then
1012 begin
1013 IntSequencer.FdKey.Count := NodesCount * 2;
1014 IntSequencer.FdKeyValue.Count := NodesCount * 2;
1015 for I := 0 to NodesCount - 1 do
1016 begin
1017 IntSequencer.FdKey.Items[I] := I / IntSequencer.FdKey.Count;
1018 IntSequencer.FdKeyValue.Items[I] := I;
1019 end;
1020 for I := 0 to NodesCount - 1 do
1021 begin
1022 IntSequencer.FdKey.Items[NodesCount + I] := (NodesCount + I) / IntSequencer.FdKey.Count;
1023 IntSequencer.FdKeyValue.Items[NodesCount + I] := NodesCount - 1 - I;
1024 end;
1025 end else
1026 begin
1027 IntSequencer.FdKey.Count := NodesCount;
1028 IntSequencer.FdKeyValue.Count := NodesCount;
1029 for I := 0 to NodesCount - 1 do
1030 begin
1031 IntSequencer.FdKey.Items[I] := I / NodesCount;
1032 IntSequencer.FdKeyValue.Items[I] := I;
1033 end;
1034 end;
1035 Group.AddChildren(IntSequencer);
1036
1037 Switch := TSwitchNode.Create(
1038 AnimationX3DName + '_Switch_ChooseAnimationFrame', BaseUrl);
1039 for I := 0 to NodesCount - 1 do
1040 { Note that duplicates are possible below,
1041 in case two animation frames are exactly equal.
1042 See e.g. evil squirrel in https://github.com/castle-engine/wyrd-forest .
1043 Fortunately AddChildren by default has AllowDuplicates. }
1044 Switch.AddChildren(WrapRootNode(BakedAnimation.Nodes[I] as TX3DRootNode));
1045 Assert(Switch.FdChildren.Count = NodesCount);
1046
1047 { we set whichChoice to 0 to see something before you run the animation }
1048 Switch.WhichChoice := 0;
1049 Group.AddChildren(Switch);
1050
1051 { Name of the TimeSensor is important, this is the animation name,
1052 so don't append there anything ugly like '_TimeSensor'.
1053 Also, place it in the active graph part (outside SwitchChooseAnimation)
1054 to be always listed in Scene.AnimationsList. }
1055 TimeSensor := TTimeSensorNode.Create(AnimationX3DName, BaseUrl);
1056 { castle-anim-frames now works cool with DetectAffectedFields,
1057 so keep it enabled (default).
1058 Our SwitchChooseAnimation.FdWhichChoice.EventIn is detected OK as "affected field".
1059 Testcases:
1060 - examples/animations/deprecated_resource_animations/
1061 - demo-models/bump_mapping/lizardman.
1062 TimeSensor.DetectAffectedFields := true;
1063 }
1064 if BakedAnimation.Backwards then
1065 TimeSensor.CycleInterval := 2 * BakedAnimation.Duration
1066 else
1067 TimeSensor.CycleInterval := BakedAnimation.Duration;
1068 TimeSensor.Loop := BakedAnimation.Loop;
1069 RootNode.AddChildren(TimeSensor);
1070
1071 RootNode.AddRoute(TimeSensor.EventFraction_changed, IntSequencer.EventSet_fraction);
1072 RootNode.AddRoute(IntSequencer.EventValue_changed, Switch.FdWhichChoice);
1073
1074 RootNode.ExportNode(TimeSensor);
1075
1076 AddAnimationVisibilityRoutes(TimeSensor);
1077
1078 { We use WrapInCollisionNode, to make the object
1079 collide always as a bounding box.
1080 Otherwise, initializing collisions for a long series of nodes is really
1081 time-consuming.
1082
1083 We have to implement actual conversion from a series of nodes
1084 -> interpolators to have proper collisions with castle-anim-frames
1085 contents. Even then, it's unsure whether it will be sensible,
1086 as it will cost at runtime. }
1087 Result := WrapInCollisionNode(Group, BakedAnimation.BoundingBox);
1088 end;
1089
1090 var
1091 I: Integer;
1092 SwitchChooseAnimation: TSwitchNode;
1093 begin
1094 Assert(BakedAnimations.Count <> 0);
1095 Assert(BakedAnimations[0].Nodes.Count <> 0);
1096 BaseUrl := BakedAnimations[0].Nodes[0].BaseUrl;
1097
1098 Result := TX3DRootNode.Create('', BaseUrl);
1099
1100 SwitchChooseAnimation := TSwitchNode.Create('ChooseAnimation', BaseUrl);
1101 for I := 0 to BakedAnimations.Count - 1 do
1102 begin
1103 SwitchChooseAnimation.AddChildren(
1104 ConvertOneAnimation(BakedAnimations[I], I, Result, SwitchChooseAnimation));
1105 end;
1106 { we set whichChoice to 0 to see something before you run the animation }
1107 SwitchChooseAnimation.WhichChoice := 0;
1108
1109 Result.AddChildren(SwitchChooseAnimation);
1110 end;
1111
1112 class procedure TNodeInterpolator.LoadToX3D_GetKeyNodeWithTime(const Index: Cardinal;
1113 out KeyNode: TX3DRootNode; out Time: Single);
1114 begin
1115 KeyNode := LoadToX3D_KeyNodes[Index] as TX3DRootNode;
1116 Time := LoadToX3D_KeyTimes[Index];
1117 end;
1118
1119 class function TNodeInterpolator.LoadToX3D(const Animations: TAnimationList): TX3DRootNode;
1120 var
1121 Animation: TAnimation;
1122 BakedAnimations: TBakedAnimationList;
1123 BakedAnimation: TBakedAnimation;
1124 I: Integer;
1125 begin
1126 BakedAnimations := TBakedAnimationList.Create(true);
1127 try
1128 try
1129 for I := 0 to Animations.Count - 1 do
1130 begin
1131 Animation := Animations[I];
1132 LoadToX3D_KeyNodes := Animation.KeyNodes;
1133 LoadToX3D_KeyTimes := Animation.KeyTimes;
1134 BakedAnimation := BakeToSequence(
1135 {$ifdef FPC}@{$endif} LoadToX3D_GetKeyNodeWithTime,
1136 Animation.KeyNodes.Count, Animation.ScenesPerTime, Animation.Epsilon);
1137 BakedAnimation.Name := Animation.Name;
1138 BakedAnimation.Loop := Animation.Loop;
1139 BakedAnimation.Backwards := Animation.Backwards;
1140 BakedAnimation.BoundingBox := Animation.BoundingBox;
1141 BakedAnimations.Add(BakedAnimation);
1142 end;
1143 except
1144 { make sure to free the TBakedAnimation.Nodes inside.
1145 No other way to do it, as BakeToSequence already created some intermediate nodes,
1146 and we have no way of returning them to the caller. }
1147 BakedAnimations.FreeNodesContents;
1148 raise;
1149 end;
1150 Result := LoadSequenceToX3D(BakedAnimations);
1151 finally FreeAndNil(BakedAnimations) end;
1152 end;
1153
1154 function LoadAnimFrames(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
1155 var
1156 Animations: TNodeInterpolator.TAnimationList;
1157 begin
1158 Animations := TNodeInterpolator.LoadAnimFramesToKeyNodes(Stream, BaseUrl);
1159 try
1160 Result := TNodeInterpolator.LoadToX3D(Animations);
1161 finally FreeAndNil(Animations) end;
1162 end;
1163
1164 var
1165 ModelFormat: TModelFormat;
1166 initialization
1167 ModelFormat := TModelFormat.Create;
1168 ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadAnimFrames;
1169 ModelFormat.MimeTypes.Add('application/x-castle-anim-frames');
1170 ModelFormat.FileFilterName := 'Castle Animation Frames (*.castle-anim-frames, *.kanim)';
1171 ModelFormat.Extensions.Add('.castle-anim-frames');
1172 ModelFormat.Extensions.Add('.kanim');
1173 RegisterModelFormat(ModelFormat);
1174 end.