Debian Codegraph @

src/scene/x3dcamerautils.pas

raw
1 {
2 Copyright 2003-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Utilities specifically for X3D cameras.
17 @seealso(CastleCameras For our general classes and utilities
18 for camera handling.) }
19 unit X3DCameraUtils;
20
21 {$I castleconf.inc}
22
23 interface
24
25 uses CastleUtils, CastleVectors, CastleBoxes, X3DNodes, CastleProjection,
26 CastleRectangles;
27
28 type
29 { Version of VRML/X3D camera definition. }
30 TX3DCameraVersion = (cvVrml1_Inventor, cvVrml2_X3d);
31
32 const
33 { Standard camera settings given by VRML/X3D specifications.
34 @groupBegin }
35 DefaultX3DCameraPosition: array [TX3DCameraVersion] of TVector3 =
36 ( (X: 0; Y: 0; Z: 1),
37 (X: 0; Y: 0; Z: 10)
38 );
39 DefaultX3DCameraDirection: TVector3 = (X: 0; Y: 0; Z: -1);
40 DefaultX3DCameraUp : TVector3 = (X: 0; Y: 1; Z: 0);
41 DefaultX3DGravityUp : TVector3 = (X: 0; Y: 1; Z: 0);
42 { @groupEnd }
43
44 { Default camera position, direction, view in X3D. }
45 DefaultX3DCameraView: TViewVectors = (
46 Translation: (X: 0; Y: 0; Z: 10);
47 Direction: (X: 0; Y: 0; Z: -1);
48 Up: (X: 0; Y: 1; Z: 0)
49 );
50
51 type
52 { Utility class to set various viewpoint properties,
53 and then generate given viewpoint node. }
54 TMakeX3DViewpoint = class
55 strict private
56 FVersion: TX3DCameraVersion;
57 FXml: Boolean;
58 FPosition, FDirection, FUp, FGravityUp, FCenterOfRotation: TVector3;
59 FPerspectiveFieldOfView: Single;
60 FProjectionType: TProjectionType;
61 FOrthographicFieldOfView: TFloatRectangle;
62 FAutoCenterOfRotation: Boolean;
63 public
64 const
65 { Matches X3D default TViewpointNode.FieldOfView.
66
67 It also matches TCastlePerspective.DefaultFieldOfView,
68 which is good -- our TCastleCamera and friends (like TCastlePerspective)
69 is consistent with X3D in this regard. }
70 DefaultPerspectiveFieldOfView = Pi / 4;
71
72 { Version of VRML or X3D to generate (in ToNode or ToString). }
73 property Version: TX3DCameraVersion read FVersion write FVersion default cvVrml2_X3d;
74 { Whether to use XML encoding in ToString. }
75 property Xml: Boolean read FXml write FXml default true;
76
77 { Position of the camera.
78 By default it is @link(DefaultX3DCameraPosition DefaultX3DCameraPosition[cvVrml2_X3d]). }
79 property Position: TVector3 read FPosition write FPosition;
80 { Direction of the camera.
81 By default it is @link(DefaultX3DCameraDirection). }
82 property Direction: TVector3 read FDirection write FDirection;
83 { Up vector of the camera.
84 By default it is @link(DefaultX3DCameraUp). }
85 property Up: TVector3 read FUp write FUp;
86 { Gravity up vector of the camera.
87 By default it is @link(DefaultX3DGravityUp).}
88 property GravityUp: TVector3 read FGravityUp write FGravityUp;
89
90 { Center of rotation, as should be specified in viewpoint node.
91 By default it is zero, just like @link(TAbstractViewpointNode.CenterOfRotation). }
92 property CenterOfRotation: TVector3 read FCenterOfRotation write FCenterOfRotation;
93
94 { Automatically calculate center of rotation based on scene bounding box.
95 The default (@false) makes X3D default of @link(TAbstractViewpointNode.AutoCenterOfRotation). }
96 property AutoCenterOfRotation: Boolean
97 read FAutoCenterOfRotation write FAutoCenterOfRotation default false;
98
99 { Perspective field of view, in radians. }
100 property PerspectiveFieldOfView: Single read FPerspectiveFieldOfView write FPerspectiveFieldOfView
101 {$ifdef FPC}default DefaultPerspectiveFieldOfView{$endif};
102
103 { TODO: This does not support yet choice perspective/orthographic camera,
104 we always generate perspective node.
105 But we expose relevant properties and they will be used in the future. }
106 property ProjectionType: TProjectionType
107 read FProjectionType write FProjectionType default ptPerspective;
108 property OrthographicFieldOfView: TFloatRectangle
109 read FOrthographicFieldOfView write FOrthographicFieldOfView;
110
111 { }
112 constructor Create;
113
114 { Construct string with VRML/X3D node defining Viewpoint with given
115 properties. }
116 function ToString: String; override;
117
118 { Construct X3D nodes that define viewpoint (maybe with some transformation)
119 with given properties.
120
121 Overloaded version with ViewpointNode parameter returns
122 the TAbstractViewpointNode descendant that is for sure somewhere within
123 the returned node. But the returned node may be a transformation node. }
124 function ToNode(out ViewpointNode: TAbstractViewpointNode): TAbstractChildNode; overload;
125 function ToNode: TAbstractChildNode; overload;
126 end;
127
128 function MakeCameraStr(const Version: TX3DCameraVersion;
129 const Xml: boolean;
130 const Position, Direction, Up, GravityUp: TVector3): string;
131 deprecated 'use TMakeX3DViewpoint with its ToString method';
132 function MakeCameraNode(const Version: TX3DCameraVersion;
133 const BaseUrl: String;
134 const Position, Direction, Up, GravityUp: TVector3): TAbstractChildNode; overload;
135 deprecated 'use TMakeX3DViewpoint with its ToNode method';
136 function MakeCameraNode(const Version: TX3DCameraVersion;
137 const BaseUrl: String;
138 const Position, Direction, Up, GravityUp: TVector3;
139 out ViewpointNode: TAbstractViewpointNode): TAbstractChildNode; overload;
140 deprecated 'use TMakeX3DViewpoint with its ToNode method';
141
142 { Make camera node (like MakeCameraNode) that makes the whole box
143 nicely visible (like CameraViewpointForWholeScene). }
144 function CameraNodeForWholeScene(const Version: TX3DCameraVersion;
145 const BaseUrl: String;
146 const Box: TBox3D;
147 const WantedDirection, WantedUp: Integer;
148 const WantedDirectionPositive, WantedUpPositive: boolean): TAbstractChildNode;
149
150 function MakeCameraNavNode(const Version: TX3DCameraVersion;
151 const BaseUrl: String;
152 const NavigationType: string;
153 const WalkSpeed, VisibilityLimit: Single; const AvatarSize: TVector3;
154 const Headlight: boolean): TNavigationInfoNode;
155
156 implementation
157
158 uses SysUtils, Math,
159 CastleTransform, X3DFields;
160
161 { TMakeX3DViewpoint ---------------------------------------------------------- }
162
163 constructor TMakeX3DViewpoint.Create;
164 begin
165 inherited;
166 FVersion := cvVrml2_X3d;
167 FXml := true;
168
169 FPosition := DefaultX3DCameraPosition[cvVrml2_X3d];
170 FDirection := DefaultX3DCameraDirection;
171 FUp := DefaultX3DCameraUp;
172 FGravityUp := DefaultX3DGravityUp;
173
174 FProjectionType := ptPerspective;
175 FPerspectiveFieldOfView := DefaultPerspectiveFieldOfView;
176 FOrthographicFieldOfView := TFloatRectangle.Empty;
177 end;
178
179 function TMakeX3DViewpoint.ToString: String;
180 const
181 Comment: array [boolean] of string = (
182 '# Generated by %s.' +nl+
183 '# Use castle-model-viewer "Clipboard -> Print Current Camera..." to generate X3D code like below.' +nl+
184 '# Camera settings "encoded" in the X3D declaration below :' +nl+
185 '# position %s' +nl+
186 '# direction %s' +nl+
187 '# up %s' +nl+
188 '# gravityUp %s' +nl,
189
190 '<!-- Generated by %s.' +nl+
191 ' Use castle-model-viewer "Clipboard -> Print Current Camera..." to generate X3D code like below.' +nl+
192 ' Camera settings "encoded" in the X3D declaration below :' +nl+
193 ' position %s' +nl+
194 ' direction %s' +nl+
195 ' up %s' +nl+
196 ' gravityUp %s -->' +nl);
197
198 UntransformedViewpoint: array [TX3DCameraVersion, boolean] of string = (
199 ('PerspectiveCamera {' +nl+
200 ' position %s' +nl+
201 ' orientation %s' +nl+
202 '%s' + // ExtraFields
203 '}',
204
205 '<PerspectiveCamera' +nl+
206 ' position="%s"' +nl+
207 ' orientation="%s"' +nl+
208 '%s' + // ExtraFields
209 '/>'),
210
211 ('Viewpoint {' +nl+
212 ' position %s' +nl+
213 ' orientation %s' +nl+
214 '%s' + // ExtraFields
215 '}',
216
217 '<Viewpoint' +nl+
218 ' position="%s"' +nl+
219 ' orientation="%s"' +nl+
220 '%s' + // ExtraFields
221 '/>')
222 );
223 TransformedViewpoint: array [TX3DCameraVersion, boolean] of string = (
224 ('Separator {' +nl+
225 ' Transform {' +nl+
226 ' translation %s' +nl+
227 ' rotation %s %s' +nl+
228 ' }' +nl+
229 ' PerspectiveCamera {' +nl+
230 ' position 0 0 0 # camera position is expressed by translation' +nl+
231 ' orientation %s' +nl+
232 '%s' + // ExtraFields
233 ' }' +nl+
234 '}',
235
236 '<Separator>' +nl+
237 ' <Transform' +nl+
238 ' translation="%s"' +nl+
239 ' rotation="%s %s"' +nl+
240 ' />' +nl+
241 ' <!-- the camera position is already expressed by the translation above -->' +nl+
242 ' <PerspectiveCamera' +nl+
243 ' position="0 0 0"' +nl+
244 ' orientation="%s"' +nl+
245 '%s' + // ExtraFields
246 ' />' +nl+
247 '</Separator>'),
248
249 ('Transform {' +nl+
250 ' translation %s' +nl+
251 ' rotation %s %s' +nl+
252 ' children Viewpoint {' +nl+
253 ' position 0 0 0 # camera position is expressed by translation' +nl+
254 ' orientation %s' +nl+
255 '%s' + // ExtraFields
256 ' }' +nl+
257 '}',
258
259 '<Transform' +nl+
260 ' translation="%s"' +nl+
261 ' rotation="%s %s">' +nl+
262 ' <!-- the camera position is already expressed by the translation above -->' +nl+
263 ' <Viewpoint' +nl+
264 ' position="0 0 0"' +nl+
265 ' orientation="%s"' +nl+
266 '%s' + // ExtraFields
267 ' />' +nl+
268 '</Transform>')
269 );
270
271 var
272 RotationVectorForGravity: TVector3;
273 AngleForGravity: Single;
274 { Workarounding FPC 3.1.1 internal error 200211262 in x3dcamerautils.pas }
275 S1, S2, S3, S4: string;
276 ExtraFields: String;
277 begin
278 Result := Format(Comment[Xml], [ApplicationName,
279 Position.ToString,
280 Direction.ToString,
281 Up.ToString,
282 GravityUp.ToString ]);
283
284 { add centerOfRotation and fieldOfView to ExtraFields }
285 ExtraFields := '';
286 if Version = cvVrml2_X3d then
287 begin
288 if not CenterOfRotation.IsPerfectlyZero then
289 begin
290 if Xml then
291 ExtraFields := ExtraFields + Format(' centerOfRotation="%s"', [CenterOfRotation.ToRawString]) + NL
292 else
293 ExtraFields := ExtraFields + Format(' centerOfRotation %s', [CenterOfRotation.ToRawString]) + NL;
294 end;
295 if not SameValue(PerspectiveFieldOfView, DefaultPerspectiveFieldOfView, 0.001) then
296 begin
297 if Xml then
298 ExtraFields := ExtraFields + FormatDot(' fieldOfView="%f"', [PerspectiveFieldOfView]) + NL
299 else
300 ExtraFields := ExtraFields + FormatDot(' fieldOfView %f', [PerspectiveFieldOfView]) + NL;
301 end;
302 { As this is non-standard CGE field, it's especially important to
303 add it only when it's non-default. }
304 if AutoCenterOfRotation then
305 begin
306 if Xml then
307 ExtraFields := ExtraFields + ' autoCenterOfRotation="TRUE"' + NL
308 else
309 ExtraFields := ExtraFields + ' autoCenterOfRotation TRUE' + NL;
310 end;
311 end;
312
313 RotationVectorForGravity := TVector3.CrossProduct(DefaultX3DGravityUp, GravityUp);
314 if RotationVectorForGravity.IsZero then
315 begin
316 { Then GravityUp is parallel to DefaultX3DGravityUp, which means that it's
317 just the same. So we can use untranslated Viewpoint node. }
318 S1 := Position.ToRawString;
319 S2 := OrientationFromDirectionUp(Direction, Up).ToRawString;
320 Result := Result + Format(UntransformedViewpoint[Version, Xml], [S1, S2, ExtraFields]);
321 end else
322 begin
323 { Then we must transform Viewpoint node, in such way that
324 DefaultX3DGravityUp affected by this transformation will give
325 desired GravityUp. }
326 AngleForGravity := AngleRadBetweenVectors(DefaultX3DGravityUp, GravityUp);
327 S1 := Position.ToRawString;
328 S2 := RotationVectorForGravity.ToRawString;
329 S3 := FormatDot(FloatOutputFormat, [AngleForGravity]);
330 { We want such that
331 1. standard VRML/X3D dir/up vectors
332 2. rotated by orientation
333 3. rotated around RotationVectorForGravity
334 will give Camera.Direction/Up.
335 OrientationFromDirectionUp will calculate the orientation needed to
336 achieve given up/dir vectors. So I have to pass there
337 MatrixWalker.Direction/Up *already rotated negatively
338 around RotationVectorForGravity*. }
339 S4 := OrientationFromDirectionUp(
340 RotatePointAroundAxisRad(-AngleForGravity, Direction, RotationVectorForGravity),
341 RotatePointAroundAxisRad(-AngleForGravity, Up , RotationVectorForGravity)
342 ).ToRawString;
343 Result := Result + Format(TransformedViewpoint[Version, Xml], [S1, S2, S3, S4, ExtraFields]);
344 end;
345 end;
346
347 function TMakeX3DViewpoint.ToNode(
348 out ViewpointNode: TAbstractViewpointNode): TAbstractChildNode;
349 var
350 RotationVectorForGravity: TVector3;
351 AngleForGravity: Single;
352 Separator: TSeparatorNode_1;
353 Transform_1: TTransformNode_1;
354 Transform_2: TTransformNode;
355 Rotation, Orientation: TVector4;
356 begin
357 RotationVectorForGravity := TVector3.CrossProduct(DefaultX3DGravityUp, GravityUp);
358 if RotationVectorForGravity.IsZero then
359 begin
360 { Then GravityUp is parallel to DefaultX3DGravityUp, which means that it's
361 just the same. So we can use untranslated Viewpoint node. }
362 case Version of
363 cvVrml1_Inventor: ViewpointNode := TPerspectiveCameraNode_1.Create;
364 cvVrml2_X3d : ViewpointNode := TViewpointNode.Create;
365 {$ifndef COMPILER_CASE_ANALYSIS}
366 else raise EInternalError.Create('MakeCameraNode Version incorrect');
367 {$endif}
368 end;
369 ViewpointNode.Position := Position;
370 ViewpointNode.Orientation := OrientationFromDirectionUp(Direction, Up);
371 Result := ViewpointNode;
372 end else
373 begin
374 { Then we must transform Viewpoint node, in such way that
375 DefaultX3DGravityUp affected by this transformation will give
376 desired GravityUp. }
377 AngleForGravity := AngleRadBetweenVectors(DefaultX3DGravityUp, GravityUp);
378 Rotation := Vector4(RotationVectorForGravity, AngleForGravity);
379 { I want
380 1. standard VRML/X3D dir/up vectors
381 2. rotated by orientation
382 3. rotated around RotationVectorForGravity
383 will give MatrixWalker.Direction/Up.
384 OrientationFromDirectionUp will calculate the orientation needed to
385 achieve given up/dir vectors. So I have to pass there
386 MatrixWalker.Direction/Up *already rotated negatively
387 around RotationVectorForGravity*. }
388 Orientation := OrientationFromDirectionUp(
389 RotatePointAroundAxisRad(-AngleForGravity, Direction, RotationVectorForGravity),
390 RotatePointAroundAxisRad(-AngleForGravity, Up , RotationVectorForGravity));
391 case Version of
392 cvVrml1_Inventor:
393 begin
394 Transform_1 := TTransformNode_1.Create;
395 Transform_1.FdTranslation.Value := Position;
396 Transform_1.FdRotation.Value := Rotation;
397
398 ViewpointNode := TPerspectiveCameraNode_1.Create;
399 ViewpointNode.Position := TVector3.Zero;
400 ViewpointNode.Orientation := Orientation;
401
402 Separator := TSeparatorNode_1.Create;
403 Separator.VRML1ChildAdd(Transform_1);
404 Separator.VRML1ChildAdd(ViewpointNode);
405
406 Result := Separator;
407 end;
408
409 cvVrml2_X3d:
410 begin
411 Transform_2 := TTransformNode.Create;
412 Transform_2.Translation := Position;
413 Transform_2.Rotation := Rotation;
414
415 ViewpointNode := TViewpointNode.Create;
416 ViewpointNode.Position := TVector3.Zero;
417 ViewpointNode.Orientation := Orientation;
418
419 Transform_2.AddChildren(ViewpointNode);
420
421 Result := Transform_2;
422 end;
423 {$ifndef COMPILER_CASE_ANALYSIS}
424 else raise EInternalError.Create('MakeCameraNode Version incorrect');
425 {$endif}
426 end;
427 end;
428
429 { add CenterOfRotation and FieldOfView to ViewpointNode }
430 Assert(ViewpointNode <> nil);
431 ViewpointNode.CenterOfRotation := CenterOfRotation;
432 ViewpointNode.AutoCenterOfRotation := AutoCenterOfRotation;
433 if ViewpointNode is TViewpointNode then
434 TViewpointNode(ViewpointNode).FieldOfView := PerspectiveFieldOfView;
435 if ViewpointNode is TPerspectiveCameraNode_1 then
436 TPerspectiveCameraNode_1(ViewpointNode).HeightAngle := PerspectiveFieldOfView;
437 end;
438
439 function TMakeX3DViewpoint.ToNode: TAbstractChildNode;
440 var
441 IgnoredViewpointNode: TAbstractViewpointNode;
442 begin
443 Result := ToNode(IgnoredViewpointNode);
444 end;
445
446 { routines ------------------------------------------------------------------ }
447
448 function MakeCameraStr(const Version: TX3DCameraVersion;
449 const Xml: boolean;
450 const Position, Direction, Up, GravityUp: TVector3): string;
451 var
452 Make: TMakeX3DViewpoint;
453 begin
454 Make := TMakeX3DViewpoint.Create;
455 try
456 Make.Version := Version;
457 Make.Xml := Xml;
458 Make.Position := Position;
459 Make.Direction := Direction;
460 Make.Up := Up;
461 Make.GravityUp := GravityUp;
462 Result := Make.ToString;
463 finally FreeAndNil(Make) end;
464 end;
465
466 function MakeCameraNode(const Version: TX3DCameraVersion;
467 const BaseUrl: String;
468 const Position, Direction, Up, GravityUp: TVector3;
469 out ViewpointNode: TAbstractViewpointNode): TAbstractChildNode;
470 var
471 Make: TMakeX3DViewpoint;
472 begin
473 Make := TMakeX3DViewpoint.Create;
474 try
475 Make.Version := Version;
476 Make.Position := Position;
477 Make.Direction := Direction;
478 Make.Up := Up;
479 Make.GravityUp := GravityUp;
480 Result := Make.ToNode(ViewpointNode);
481 { BaseUrl on viewpoint node, or its transformation,
482 is completely meaningless. Which is why TMakeX3DViewpoint
483 doesn't even have BaseUrl property. }
484 Result.BaseUrl := BaseUrl;
485 finally FreeAndNil(Make) end;
486 end;
487
488 function MakeCameraNode(const Version: TX3DCameraVersion;
489 const BaseUrl: String;
490 const Position, Direction, Up, GravityUp: TVector3): TAbstractChildNode;
491 var
492 IgnoredViewpointNode: TAbstractViewpointNode;
493 begin
494 {$warnings off} // using deprecated in deprecated
495 Result := MakeCameraNode(Version, BaseUrl, Position, Direction, Up, GravityUp,
496 IgnoredViewpointNode);
497 {$warnings on}
498 end;
499
500 function CameraNodeForWholeScene(const Version: TX3DCameraVersion;
501 const BaseUrl: String;
502 const Box: TBox3D;
503 const WantedDirection, WantedUp: Integer;
504 const WantedDirectionPositive, WantedUpPositive: boolean): TAbstractChildNode;
505 var
506 Position, Direction, Up, GravityUp: TVector3;
507 ViewpointNode: TAbstractViewpointNode;
508 begin
509 CameraViewpointForWholeScene(Box, WantedDirection, WantedUp,
510 WantedDirectionPositive, WantedUpPositive, Position, Direction, Up, GravityUp);
511 {$warnings off} // TODO: fix using deprecated, actually CameraNodeForWholeScene should be reworked to be method of TMakeX3DViewpoint
512 Result := MakeCameraNode(Version, BaseUrl,
513 Position, Direction, Up, GravityUp, ViewpointNode);
514
515 // set useful CenterOfRotation or AutoCenterOfRotation
516 // option 1:
517 //ViewpointNode.AutoCenterOfRotation := false;
518 //ViewpointNode.CenterOfRotation := Box.Center;
519 // option 2:
520 // Better if scene may dynamically change to something drastically different.
521 ViewpointNode.AutoCenterOfRotation := true;
522 {$warnings on}
523 end;
524
525 function MakeCameraNavNode(const Version: TX3DCameraVersion;
526 const BaseUrl: String;
527 const NavigationType: string;
528 const WalkSpeed, VisibilityLimit: Single; const AvatarSize: TVector3;
529 const Headlight: boolean): TNavigationInfoNode;
530 var
531 NavigationNode: TNavigationInfoNode;
532 begin
533 case Version of
534 cvVrml2_X3d : NavigationNode := TNavigationInfoNode.Create('', BaseUrl);
535 else raise EInternalError.Create('MakeCameraNavNode Version incorrect');
536 end;
537 NavigationNode.FdType.Items.Clear;
538 NavigationNode.FdType.Items.Add(NavigationType);
539 NavigationNode.FdAvatarSize.Items.Clear;
540 NavigationNode.FdAvatarSize.Items.AddRange([AvatarSize.X, AvatarSize.Y, AvatarSize.Z]);
541 NavigationNode.FdHeadlight.Value := Headlight;
542 NavigationNode.FdSpeed.Value := WalkSpeed;
543 NavigationNode.FdVisibilityLimit.Value := VisibilityLimit;
544 Result := NavigationNode;
545 end;
546
547 end.