Debian Codegraph @

src/scene/x3d/x3dnodes_standard_h-anim.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2008-2023 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 THAnimSegmentNode = class;
19 THAnimSiteNode = class;
20 THAnimMotionNode = class;
21
22 { Alter the shape of coordinate-based geometry within parent H-Anim nodes.
23 For example, different HAnimDisplacer may be used for each facial expression. }
24 THAnimDisplacerNode = class(TAbstractGeometricPropertyNode)
25 {$I auto_generated_node_helpers/x3dnodes_hanimdisplacer.inc}
26 end;
27
28 THAnimJointNode = class;
29
30 TVertexJoints = record
31 RestPosition: TVector3;
32 Count: Cardinal;
33 Joints: array of THAnimJointNode;
34 Weights: array of Single;
35 procedure Add(Joint: THAnimJointNode; const Weight: Single);
36 end;
37 PVertexJoints = ^TVertexJoints;
38 TVertexJointsList = {$ifdef FPC}specialize{$endif} TStructList<TVertexJoints>;
39
40 { Central node for moving the animated humanoid. It contains the skeleton,
41 and other information necessary for animation. }
42 THAnimHumanoidNode = class(TAbstractChildNode)
43 strict private
44 type
45 THAnimHumanoidNodeTransformFunctionality = class(TTransformFunctionality)
46 strict private
47 FParent: THAnimHumanoidNode;
48 public
49 constructor Create(const AParent: THAnimHumanoidNode);
50 property Parent: THAnimHumanoidNode read FParent;
51 procedure ApplyTransform(var Transformation: TTransformation); override;
52 end;
53 var
54 FTransformFunctionality: THAnimHumanoidNodeTransformFunctionality;
55 VertexJoints: TVertexJointsList;
56 procedure AddJoint(Node: TX3DNode);
57 protected
58 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
59 procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override;
60 procedure AfterTraverse(StateStack: TX3DGraphTraverseStateStack); override;
61 procedure ParseAfter(Reader: TX3DReaderNames); override;
62 public
63 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
64 destructor Destroy; override;
65 function TransformationChange: TNodeTransformationChange; override;
66
67 { Change the skin (in skinCoord), to follow the animation of joints.
68 Joints that changed are assumed to be already traversed by TX3DNode.Traverse
69 (this prepares field values for AnimateSkinPoint call).
70
71 This method is used by TCastleSceneCore. Don't call this yourself.
72
73 Returns changed X3D coordinates field (or @nil if there is no skin).
74 You should call TX3DField.Changed on it (unless you use it from some
75 TCastleSceneCore initialization, when there's no point in notifying about this). }
76 function AnimateSkin: TMFVec3f;
77
78 {$I auto_generated_node_helpers/x3dnodes_hanimhumanoid.inc}
79 end;
80
81 { Joint of an animated humanoid.
82 Joints are organized in a hierarchy, like bones. }
83 THAnimJointNode = class(TAbstractGroupingNode)
84 strict private
85 type
86 THAnimJointNodeTransformFunctionality = class(TTransformFunctionality)
87 strict private
88 FParent: THAnimJointNode;
89 public
90 constructor Create(const AParent: THAnimJointNode);
91 property Parent: THAnimJointNode read FParent;
92 procedure ApplyTransform(const State: TX3DGraphTraverseState); override;
93 end;
94 var
95 FTransformFunctionality: THAnimJointNodeTransformFunctionality;
96 AnimateSkinTransform: TMatrix4;
97 RestCenter: TVector3;
98 private
99 WarningSkinCoordReferences: Boolean;
100
101 { Animate point, based on it's rest position.
102
103 We used, at one point, to apply here a relative change since last position.
104 - Advantage: no need to remember
105 TVertexJoints.RestPosition or RestCenter.
106 - Disadvantage: cummulation of errors was causing shrinking elbows
107 on seamless3d test model Lucy.
108 - Disadvantage 2: Relative change was causing
109 more complicated code, with the need to switch previous/new
110 transformations (since we cannot apply changes to vertexes during
111 traversing of joints, we had to be very careful: a change must
112 be applied only once, and then relative change must be reset to identity).
113 Without this, we can repply AnimateSkinPoint many times, and it's
114 always valid. }
115 function AnimateSkinPoint(const Point: TVector3): TVector3;
116 protected
117 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
118 procedure ParseAfter(Reader: TX3DReaderNames); override;
119 public
120 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
121 function TransformationChange: TNodeTransformationChange; override;
122
123 {$I auto_generated_node_helpers/x3dnodes_hanimjoint.inc}
124 end;
125
126 { Visible segment of an animated humanoid,
127 always a child of a TJointNode. }
128 THAnimSegmentNode = class(TAbstractGroupingNode)
129 strict private
130 type
131 THAnimSegmentNodeTransformFunctionality = class(TTransformFunctionality)
132 strict private
133 FParent: THAnimSegmentNode;
134 public
135 constructor Create(const AParent: THAnimSegmentNode);
136 property Parent: THAnimSegmentNode read FParent;
137 procedure ApplyTransform(var Transformation: TTransformation); override;
138 end;
139 var
140 FTransformFunctionality: THAnimSegmentNodeTransformFunctionality;
141 protected
142 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
143 public
144 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
145 function TransformationChange: TNodeTransformationChange; override;
146
147 {$I auto_generated_node_helpers/x3dnodes_hanimsegment.inc}
148 end;
149
150 { Motion animation of humanoid (THAnimHumanoidNode) characters.
151 Raw motion data, for example, motion capture data, details
152 the number of frames, the frame display time, and the parameter values
153 for the motion from each channel at each frame.
154
155 @bold(This note is not (yet) implemented in Castle Game Engine).
156 We parse it, but we don't act on the information in any way. }
157 THAnimMotionNode = class(TAbstractChildNode)
158 protected
159 function DefaultContainerFieldInContext(const Version: TX3DVersion;
160 const ParentNode: TX3DNode): String; override;
161 {$I auto_generated_node_helpers/x3dnodes_hanimmotion.inc}
162 end;
163
164 { An attachment point of an animated humanoid,
165 to attach something that held, worm or such by a humanoid. }
166 THAnimSiteNode = class(TAbstractGroupingNode)
167 strict private
168 type
169 THAnimSiteNodeTransformFunctionality = class(TTransformFunctionality)
170 strict private
171 FParent: THAnimSiteNode;
172 public
173 constructor Create(const AParent: THAnimSiteNode);
174 property Parent: THAnimSiteNode read FParent;
175 procedure ApplyTransform(var Transformation: TTransformation); override;
176 end;
177 var
178 FTransformFunctionality: THAnimSiteNodeTransformFunctionality;
179 protected
180 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
181 public
182 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
183 function TransformationChange: TNodeTransformationChange; override;
184
185 {$I auto_generated_node_helpers/x3dnodes_hanimsite.inc}
186 end;
187
188 {$endif read_interface}
189
190 {$ifdef read_implementation}
191
192 { TVertexJoints -------------------------------------------------------------- }
193
194 procedure TVertexJoints.Add(Joint: THAnimJointNode; const Weight: Single);
195 begin
196 Inc(Count);
197 SetLength(Joints , Count);
198 SetLength(Weights, Count);
199 Joints [Count - 1] := Joint;
200 Weights[Count - 1] := Weight;
201 end;
202
203 { THAnimHumanoidNode.THAnimHumanoidNodeTransformFunctionality ------------------------------ }
204
205 constructor THAnimHumanoidNode.THAnimHumanoidNodeTransformFunctionality.Create(const AParent: THAnimHumanoidNode);
206 begin
207 inherited Create(AParent);
208 FParent := AParent;
209 end;
210
211 procedure THAnimHumanoidNode.THAnimHumanoidNodeTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
212 begin
213 inherited;
214
215 Transformation.Multiply(
216 Parent.Center,
217 Parent.Rotation,
218 Parent.Scale,
219 Parent.ScaleOrientation,
220 Parent.Translation);
221 end;
222
223 { THAnimHumanoidNode --------------------------------------------------------- }
224
225 constructor THAnimHumanoidNode.Create(const AX3DName, ABaseUrl: String);
226 begin
227 inherited;
228 FTransformFunctionality := THAnimHumanoidNodeTransformFunctionality.Create(Self);
229 AddFunctionality(FTransformFunctionality);
230
231 { HAnim 1.1 specification uses "humanoidBody" instead of "skeleton",
232 also HAnim 200x specification examples show usage of this (although
233 HAnim 200x specs talks only about "skeleton"). }
234 Fdskeleton.AddAlternativeName('humanoidBody', 0);
235 end;
236
237 destructor THAnimHumanoidNode.Destroy;
238 begin
239 FreeAndNil(VertexJoints);
240 inherited;
241 end;
242
243 function THAnimHumanoidNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
244 begin
245 { Between HAnim 1.0 and 200x hierarchy changed, in 1.0 there's no "skeleton"
246 field but root Joint is just simply placed directly in VRML file.
247 This means that I should simply render Joint node like a Transform,
248 both inside "skeleton" field and outside, and both versions will be happy. }
249 Result := FdSkeleton.Enumerate(Func);
250 if Result <> nil then Exit;
251
252 { To support skinned body, pass skin as an active node too
253 (if not nil, then it will be rendered.)
254 Note that SkinCoord and SkinNormal are not passed as active
255 (they should be referenced inside Skin object). }
256 Result := FdSkin.Enumerate(Func);
257 if Result <> nil then Exit;
258
259 Result := FdViewpoints.Enumerate(Func);
260 if Result <> nil then Exit;
261
262 { Note that joints, segments and sites is not passed to Func --- they
263 should already be part of Joint hierarchy (in skeleton for HAnim 200x
264 or outside of Humanoid node for HAnim 1.0). }
265
266 { Finally, the way we implement HAnimHumanoid is compatible with X3D
267 prototypes for this in
268 http://www.web3d.org/x3d/content/examples/Basic/HumanoidAnimation/BoxMan.wrl
269 Which means that comments above are probably true, as I'm not the
270 only one using this approach. }
271 end;
272
273 procedure THAnimHumanoidNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack);
274 begin
275 inherited;
276 StateStack.Push;
277
278 StateStack.Top.Humanoid := Self;
279 StateStack.Top.HumanoidTransformation.Init;
280
281 FTransformFunctionality.ApplyTransform(StateStack.Top.Transformation);
282 end;
283
284 function THAnimHumanoidNode.AnimateSkin: TMFVec3f;
285
286 function UpdateVertex(const VJ: TVertexJoints): TVector3;
287 var
288 New: TVector3;
289 J: Integer;
290 WeightSum: Single;
291 begin
292 New := TVector3.Zero;
293 WeightSum := 0;
294
295 for J := 0 to VJ.Count - 1 do
296 begin
297 WeightSum := WeightSum + VJ.Weights[J];
298 New := New + (VJ.Joints[J].AnimateSkinPoint(VJ.RestPosition) * VJ.Weights[J]);
299 end;
300
301 { Take the possibility of non-1 weight sum into account.
302 When no joints affect this point, WeightSum = 0, this also works then. }
303 Result := VJ.RestPosition * (1 - WeightSum) + New;
304 end;
305
306 var
307 I: Integer;
308 SkinCoord: TVector3List;
309 begin
310 if not (
311 (FdSkinCoord.Value <> nil) and
312 (FdSkinCoord.Value is TCoordinateNode) and
313 (VertexJoints <> nil)) then Exit(nil);
314
315 Result := TCoordinateNode(FdSkinCoord.Value).FdPoint;
316 SkinCoord := Result.Items;
317 if SkinCoord.Count <> VertexJoints.Count then Exit(nil);
318
319 for I := 0 to VertexJoints.Count - 1 do
320 SkinCoord.L[I] := UpdateVertex(VertexJoints.L[I]);
321 end;
322
323 procedure THAnimHumanoidNode.AfterTraverse(StateStack: TX3DGraphTraverseStateStack);
324 begin
325 AnimateSkin;
326 StateStack.Pop;
327 inherited;
328 end;
329
330 procedure THAnimHumanoidNode.AddJoint(Node: TX3DNode);
331 begin
332 FdJoints.Add(Node);
333 end;
334
335 procedure THAnimHumanoidNode.ParseAfter(Reader: TX3DReaderNames);
336
337 { It is a common mistake to leave HAnimHumanoid.joints empty,
338 which means that CGE would not animate humanoid at all (contrary to other
339 X3D browsers that don't rely on "joints").
340 So we fix the HAnimHumanoid.joints list. }
341 procedure CalculateJoints;
342 begin
343 if FdJoints.Count = 0 then
344 begin
345 EnumerateNodes(THAnimJointNode, {$ifdef FPC}@{$endif} AddJoint, false);
346 if FdJoints.Count <> 0 then
347 WritelnWarning('HAnimHumanoid.joints list was empty, fixed to list all %d joints', [
348 FdJoints.Count
349 ]);
350 end;
351 end;
352
353 procedure CalculateVertexJoints;
354 var
355 SkinCoord: TVector3List;
356 I, J: Integer;
357 SkinCoordIndex: TInt32List;
358 CoordIndex: Integer;
359 Weight: Single;
360 Joint: THAnimJointNode;
361 begin
362 FreeAndNil(VertexJoints);
363 if (FdSkinCoord.Value <> nil) and
364 (FdSkinCoord.Value is TCoordinateNode) then
365 begin
366 SkinCoord := TCoordinateNode(FdSkinCoord.Value).FdPoint.Items;
367 VertexJoints := TVertexJointsList.Create;
368 VertexJoints.Count := SkinCoord.Count;
369
370 for I := 0 to SkinCoord.Count - 1 do
371 begin
372 VertexJoints.L[I].RestPosition := SkinCoord.L[I];
373 VertexJoints.L[I].Count := 0; { initially }
374 end;
375
376 for I := 0 to FdJoints.Count - 1 do
377 if FdJoints[I] is THAnimJointNode then
378 begin
379 Joint := THAnimJointNode(FdJoints[I]);
380 SkinCoordIndex := Joint.FdSkinCoordIndex.Items;
381 for J := 0 to SkinCoordIndex.Count - 1 do
382 begin
383 CoordIndex := SkinCoordIndex.Items[J];
384 if (CoordIndex < 0) or
385 (CoordIndex >= SkinCoord.Count) then
386 begin
387 if not Joint.WarningSkinCoordReferences then
388 begin
389 WritelnWarning('X3D', Format('"%s": skinCoord refers to not existing coordinate index %d (while we have only %d skin coordinates in HAnimHumanoid.skin)', [
390 Joint.NiceName,
391 CoordIndex,
392 SkinCoord.Count
393 ]));
394 Joint.WarningSkinCoordReferences := true;
395 end;
396 Continue;
397 end;
398
399 if J < Joint.FdSkinCoordWeight.Items.Count then
400 Weight := Joint.FdSkinCoordWeight.Items[J] else
401 Weight := 1;
402
403 VertexJoints.L[CoordIndex].Add(Joint, Weight);
404 end;
405 end;
406 end;
407 end;
408
409 begin
410 inherited;
411 CalculateJoints;
412 CalculateVertexJoints;
413 end;
414
415 function THAnimHumanoidNode.TransformationChange: TNodeTransformationChange;
416 begin
417 Result := ntcTransform;
418 end;
419
420 { THAnimJointNode.THAnimJointNodeTransformFunctionality -------------------------- }
421
422 constructor THAnimJointNode.THAnimJointNodeTransformFunctionality.Create(const AParent: THAnimJointNode);
423 begin
424 inherited Create(AParent);
425 FParent := AParent;
426 end;
427
428 procedure THAnimJointNode.THAnimJointNodeTransformFunctionality.ApplyTransform(const State: TX3DGraphTraverseState);
429 var
430 I: Integer;
431 ChildJoint: THAnimJointNode;
432 LocalCenter, NewChildCenter: TVector3;
433 TempToSend: TSFVec3f;
434 begin
435 inherited;
436
437 { Spec says center / scale / scaleOrientation / translation
438 are relative to humanoid root, but rotations are accumulated.
439 http://h-anim.org/Specifications/H-Anim200x/ISO_IEC_FCD_19774/ObjectInterfaces.html
440 So rotations are affected by center/etc. of joints above,
441 which means that I have to apply here LocalCenter, LocalScale and such?
442 But how? TODO: for now, we only apply LocalCenter.
443
444 Fortunately, normal State isn't really used for skinned animation. }
445
446 LocalCenter := State.HumanoidTransformation.InverseTransform.MultPoint(Parent.Center);
447 State.Transformation.Multiply(
448 LocalCenter,
449 Parent.Rotation,
450 Parent.Scale,
451 Parent.ScaleOrientation,
452 Parent.Translation);
453
454 { update State.HumanoidTransformation for child joints. }
455 State.HumanoidTransformation.Multiply(
456 LocalCenter,
457 Parent.Rotation,
458 Parent.Scale,
459 Parent.ScaleOrientation,
460 Parent.Translation);
461
462 Parent.AnimateSkinTransform := State.HumanoidTransformation.Transform;
463
464 { animate centers of children joints }
465 for I := 0 to Parent.FdChildren.Count - 1 do
466 if Parent.FdChildren[I] is THAnimJointNode then
467 begin
468 ChildJoint := THAnimJointNode(Parent.FdChildren[I]);
469
470 { TODO: it's very hacky to update ChildJoint.FdCenter this way.
471 The cleaner way would be to just
472
473 ChildJoint.FdCenter.Send(AnimateSkinPoint(ChildJoint.RestCenter))
474
475 This would already do compare, send event if needed etc. (useful
476 for castle-model-viewer H-Anim joints visualization).
477 But it would also notify the scene (events processor), and this causes
478 slowdown and bugs (on lucy) right now. }
479
480 NewChildCenter := Parent.AnimateSkinPoint(ChildJoint.RestCenter);
481 if not TVector3.PerfectlyEquals(ChildJoint.FdCenter.Value, NewChildCenter) then
482 begin
483 ChildJoint.FdCenter.Value := NewChildCenter;
484
485 if ChildJoint.FdCenter.Exposed then
486 begin
487 TempToSend := TSFVec3f.Create(ChildJoint, false, 'center', NewChildCenter);
488 try
489 ChildJoint.FdCenter.EventOut.Send(TempToSend);
490 finally FreeAndNil(TempToSend) end;
491 end;
492
493 { Note that Send() above will use Scene.NextEventTime
494 which with increase time by a "tick".
495 This is good --- if you'll next want to traverse a parent joint,
496 this center will again be changed, and should be send (otherwise
497 routes e.g. in Humanoid Visualization in castle-model-viewer will not work).
498
499 Note that Scene may be nil now --- reproduce by:
500 castle-model-viewer ~/NextCloud/3dmodels/vrmlx3d/hanim/kambi_hanim_200_spec/hanim_loa_3.wrl }
501 end;
502 end;
503 end;
504
505 { THAnimJointNode ------------------------------------------------------------ }
506
507 constructor THAnimJointNode.Create(const AX3DName, ABaseUrl: String);
508 begin
509 inherited;
510 FTransformFunctionality := THAnimJointNodeTransformFunctionality.Create(Self);
511 AddFunctionality(FTransformFunctionality);
512 AnimateSkinTransform := TMatrix4.Identity;
513 end;
514
515 function THAnimJointNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
516 begin
517 Result := FdChildren.Enumerate(Func);
518 if Result <> nil then Exit;
519 end;
520
521 function THAnimJointNode.AnimateSkinPoint(const Point: TVector3): TVector3;
522 begin
523 Result := AnimateSkinTransform.MultPoint(Point);
524 end;
525
526 procedure THAnimJointNode.ParseAfter(Reader: TX3DReaderNames);
527 begin
528 inherited;
529 RestCenter := FdCenter.Value;
530 end;
531
532 function THAnimJointNode.TransformationChange: TNodeTransformationChange;
533 begin
534 Result := ntcTransform;
535 end;
536
537 { THAnimMotionNode ----------------------------------------------------------- }
538
539 function THAnimMotionNode.DefaultContainerFieldInContext(
540 const Version: TX3DVersion; const ParentNode: TX3DNode): String;
541 begin
542 if ParentNode is THAnimHumanoidNode then // also checks ParentNode <> nil
543 Result := 'motions'
544 else
545 Result := 'children';
546 end;
547
548 { THAnimSegmentNode.THAnimSegmentNodeTransformFunctionality ---------------------------------------- }
549
550 constructor THAnimSegmentNode.THAnimSegmentNodeTransformFunctionality.Create(const AParent: THAnimSegmentNode);
551 begin
552 inherited Create(AParent);
553 FParent := AParent;
554 end;
555
556 procedure THAnimSegmentNode.THAnimSegmentNodeTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
557 begin
558 inherited;
559 Transformation.Multiply(
560 Parent.Rotation,
561 Parent.Scale,
562 Parent.Translation);
563 end;
564
565 { THAnimSegmentNode ---------------------------------------------------------- }
566
567 constructor THAnimSegmentNode.Create(const AX3DName, ABaseUrl: String);
568 begin
569 inherited;
570 FTransformFunctionality := THAnimSegmentNodeTransformFunctionality.Create(Self);
571 AddFunctionality(FTransformFunctionality);
572 end;
573
574 function THAnimSegmentNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
575 begin
576 Result := FdChildren.Enumerate(Func);
577 if Result <> nil then Exit;
578 end;
579
580 function THAnimSegmentNode.TransformationChange: TNodeTransformationChange;
581 begin
582 Result := ntcTransform;
583 end;
584
585 { THAnimSiteNode.THAnimSiteNodeTransformFunctionality ---------------------------------------- }
586
587 constructor THAnimSiteNode.THAnimSiteNodeTransformFunctionality.Create(const AParent: THAnimSiteNode);
588 begin
589 inherited Create(AParent);
590 FParent := AParent;
591 end;
592
593 procedure THAnimSiteNode.THAnimSiteNodeTransformFunctionality.ApplyTransform(var Transformation: TTransformation);
594 begin
595 inherited;
596 Transformation.Multiply(
597 Parent.Center,
598 Parent.Rotation,
599 Parent.Scale,
600 Parent.ScaleOrientation,
601 Parent.Translation);
602 end;
603
604 { THAnimSiteNode ---------------------------------------------------------- }
605
606 constructor THAnimSiteNode.Create(const AX3DName, ABaseUrl: String);
607 begin
608 inherited;
609 FTransformFunctionality := THAnimSiteNodeTransformFunctionality.Create(Self);
610 AddFunctionality(FTransformFunctionality);
611 end;
612
613 function THAnimSiteNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
614 begin
615 Result := FdChildren.Enumerate(Func);
616 if Result <> nil then Exit;
617 end;
618
619 function THAnimSiteNode.TransformationChange: TNodeTransformationChange;
620 begin
621 Result := ntcTransform;
622 end;
623
624 procedure RegisterHAnimNodes;
625 begin
626 NodesManager.RegisterNodeClasses([
627 THAnimDisplacerNode,
628 THAnimHumanoidNode,
629 THAnimJointNode,
630 THAnimMotionNode,
631 THAnimSegmentNode,
632 THAnimSiteNode
633 ]);
634 end;
635
636 {$endif read_implementation}