-
Notifications
You must be signed in to change notification settings - Fork 19
/
castle_model_viewer.dpr
4190 lines (3697 loc) · 153 KB
/
castle_model_viewer.dpr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Copyright 2002-2024 Michalis Kamburelis.
This file is part of "castle-model-viewer".
"castle-model-viewer" is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"castle-model-viewer" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with "castle-model-viewer"; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
----------------------------------------------------------------------------
}
{ Model viewer for all scene formats supported by Castle Game Engine
(glTF, X3D, Spine JSON, sprite sheets... ).
See https://castle-engine.io/creating_data_model_formats.php for a list of supported formats.
See https://castle-engine.io/castle-model-viewer for user documentation.
Note: If you want to learn how to use "Castle Game Engine",
the castle-model-viewer source code isn't the best place to study.
It's long and uses some obscure CGE features sometimes.
Look instead at Castle Game Engine examples and manual:
https://castle-engine.io/manual_intro.php .
}
program castle_model_viewer;
{$I v3dsceneconf.inc}
{$ifdef MSWINDOWS} {$apptype GUI} {$endif}
{ This adds icons and version info for Windows,
automatically created by "castle-engine compile". }
{$ifdef CASTLE_AUTO_GENERATED_RESOURCES} {$R castle-auto-generated-resources.res} {$endif}
{ Icon for Mac OS X. .res file managed by Lazarus. }
{$ifdef DARWIN}
{$R *.res}
{$endif}
{ Catch exceptions at loading and saving, and display them as nice messages to user.
This should be defined for users.
For debug purposes you may want to not define it.
Then our standard exception handler will show, with a useful backtrace. }
{$define CATCH_EXCEPTIONS}
uses SysUtils, Math, Classes,
{$ifndef VER3_0} OpenSSLSockets, {$endif}
{ CGE units }
CastleUtils, CastleVectors, CastleBoxes, CastleClassUtils,
CastleTriangles, CastleApplicationProperties, CastleParameters, CastleCameras,
CastleOpenDocument, CastleConfig, CastleStringUtils, CastleFilesUtils,
CastleTimeUtils, CastleLog, DateUtils, CastleFrustum,
CastleImages, CastleInternalCubeMaps, CastleInternalCompositeImage, CastleTransform, CastleSoundEngine,
CastleUIControls, CastleColors, CastleKeysMouse, CastleDownload, CastleUriUtils,
CastleProjection, CastleVideos, CastleTextureImages, CastleLoadGltf,
CastleWindow, CastleGLUtils, CastleMessages, CastleRenderPrimitives,
CastleWindowRecentFiles, CastleGLImages, CastleInternalGLCubeMaps, CastleComponentSerialize,
CastleControls, CastleGLShaders, CastleInternalControlsImages, CastleRenderContext,
X3DFields, CastleInternalShapeOctree, X3DNodes, X3DLoad, CastleScene,
CastleInternalBaseTriangleOctree, CastleFileFilters,
X3DLoadInternalUtils, CastleSceneCore, X3DCameraUtils,
CastleRenderOptions, CastleShapes, CastleViewport,
CastleInternalRenderer,
{ castle-model-viewer-specific units: }
V3DSceneTextureFilters, V3DSceneLights, V3DSceneRaytrace,
V3DSceneNavigationTypes, V3DSceneSceneChanges, V3DSceneBGColors, V3DSceneViewpoints,
V3DSceneWarnings, V3DSceneFillMode,
V3DSceneAntiAliasing, V3DSceneScreenShot, V3DSceneCaptions,
V3DSceneShadows, V3DSceneOctreeVisualize, V3DSceneMiscConfig, V3DSceneImages,
V3DSceneScreenEffects, V3DSceneSkeletonVisualize, V3DSceneViewports, V3DSceneVersion,
V3DSceneLightsEditor, V3DSceneWindow, V3DSceneStatus, V3DSceneNamedAnimations,
V3DSceneBoxes, V3DSceneInternalScenes, V3DSceneDialogBox, V3DSceneFonts;
var
ShowFrustum: boolean = false;
ShowFrustumAlwaysVisible: boolean = false;
MenuCollisions: TMenuItemChecked;
RecentMenu: TWindowRecentFiles;
{ Scene global variables.
Modified only by LoadSceneCore (and all using it Load*Scene* procedures)
and FreeScene.
Note that Window.Caption also should be modified only by those procedures.
Note that only one Scene object is created and present for the whole
lifetime of this program. When we load new scene (from "Open"
menu item) we DO NOT free and create new Scene object.
Instead we only free and create underlying root node (TCastleScene.Load).
This way we're preserving values of all RenderOptions.Xxx when opening new scene
from "Open" menu item. }
Scene: TCastleScene;
SceneBoundingBox: TBoundingBoxScene;
SceneDebugEdges: TDebugEdgesScene;
SceneUrl: String;
SelectedItem: PTriangle;
{ SelectedPoint* always lies on SelectedItem item,
and it's meaningless when SelectedItem = nil.
World is in world coords,
local in local shape (SelectedItem^.State.Transform) coords. }
SelectedPointWorld, SelectedPointLocal: TVector3;
{ SelectedShape is always SelectedItem^.Shape.
Except in GeometryChanged, when SelectedItem may be already freed,
and then SelectedShape variable is useful to compare with OnlyShapeChanged. }
SelectedShape: TShape;
{ Set to non-nil by CreateMainMenu. }
MenuSelectedOctreeStat: TMenuItem;
MenuSelectedInfo: TMenuItem;
MenuSelectedLightsInfo: TMenuItem;
MenuRemoveSelectedShape: TMenuItem;
MenuRemoveSelectedFace: TMenuItem;
MenuHideSelectedShape: TMenuItem;
MenuEditMaterial: TMenu;
MenuMergeCloseVertexes: TMenuItem;
MenuHeadlight, MenuGravity, MenuMouseLook: TMenuItemChecked;
MenuPreferGravityUpForRotations: TMenuItemChecked;
MenuPreferGravityUpForMoving: TMenuItemChecked;
MenuReopen: TMenuItem;
MenuNamedAnimations: TMenuItemChecked;
SceneWarnings: TSceneWarnings;
{ Does user want to process VRML/X3D events? Set by menu item.
When false, this also makes Time stopped (just like
AnimationTimePlaying = @false. IOW, always
Scene.TimePlaying := AnimationTimePlaying and ProcessEventsWanted.)
This is simpler for user --- ProcessEventsWanted=false is something
stricly "stronger" than AnimationTimePlaying=false. Actually, the engine
*could* do something otherwise, if we would allow Time to pass
with ProcessEventsWanted=false: time-dependent MovieTexture
would still play, as this is not using events (also precalculated
animation would play). }
ProcessEventsWanted: boolean = true;
{ If ButtonWarnings.GetExists is allowed. If false, then ButtonWarnings.Exists
should be false, regardless of warnings count. }
ButtonWarningsEnabled: boolean = true;
ButtonWarnings: TCastleButton;
{ ToolbarPanel is displayed if user wants to see the toolbar.
Otherwise we display ToolbarPanelShorter --- which only shows the warnings button,
see https://github.com/castle-engine/castle-model-viewer/issues/53 . }
ToolbarPanel, ToolbarPanelShorter,
ToolbarHorizGroup, ToolbarHorizGroupShorter: TCastleUserInterface;
ButtonCollisions: TCastleButton;
ButtonAnimations: TCastleButton;
ButtonPatreon: TCastleButton;
AnimationTimePlaying: boolean = true;
MenuAnimationTimePlaying: TMenuItemChecked;
ControlsOnScreenshot: boolean = false;
HideExtraScenesForScreenshot: boolean = false;
NavigationUi: TNavigationUi;
{ TEventsHandler -------------------------------------------------------------
TODO: Change TEventsHandler to "TViewMain = class(TCastleView)",
as is standard in CGE applications. }
type
{ Handle various events of the application. }
TEventsHandler = class(TComponent)
public
procedure OpenRecent(const Url: String);
procedure GeometryChanged(Scene: TCastleSceneCore;
const SomeLocalGeometryChanged: boolean;
OnlyShapeChanged: TShape);
procedure ViewpointsChanged(Sender: TObject);
procedure BoundViewpointChanged(Sender: TObject);
procedure BoundNavigationInfoChanged(Sender: TObject);
procedure PointingDeviceSensorsChange(Sender: TObject);
procedure HeadlightOnChanged(Sender: TObject);
procedure ClickButtonWarnings(Sender: TObject);
procedure ClickButtonPatreon(Sender: TObject);
procedure ClickNavigationTypeButton(Sender: TObject);
procedure ClickButtonOpen(Sender: TObject);
procedure ClickButtonCollisions(Sender: TObject);
procedure ClickButtonScreenshot(Sender: TObject);
procedure ClickButtonAnimations(Sender: TObject);
procedure OnWarningHandle(const Category, S: string);
procedure Press(const Sender: TCastleUserInterface;
const Event: TInputPressRelease; var Handled: boolean);
procedure MenuClick(const MenuItem: TMenuItem);
end;
var
EventsHandler: TEventsHandler;
{ Custom viewport class ------------------------------------------------ }
type
TV3DViewport = class(TV3DShadowsViewport)
protected
procedure RenderFromView3D(const Params: TRenderParams); override;
public
constructor Create(AOwner: TComponent); override;
procedure Resize; override;
procedure BeforeRender; override;
procedure Render; override;
function BaseLightsForRaytracer: TLightInstancesList;
procedure Update(const SecondsPassed: Single; var HandleInput: boolean); override;
end;
procedure ViewportProperties(Viewport: TCastleViewport);
begin
ViewportShadowsProperties(Viewport);
Viewport.BackgroundWireframe := FillModes[FillMode].BackgroundWireframe;
end;
constructor TV3DViewport.Create(AOwner: TComponent);
begin
inherited;
PreventInfiniteFallingDown := true;
end;
function TV3DViewport.BaseLightsForRaytracer: TLightInstancesList;
begin
Result := TLightInstancesList.Create;
InitializeGlobalLights(Result);
end;
procedure TV3DViewport.Update(const SecondsPassed: Single; var HandleInput: boolean);
begin
inherited;
{ Set Cursor = mcHand when we're over or keeping active
some pointing-device sensors. }
if (Scene <> nil) and
( ( (Scene.PointingDeviceSensors <> nil) and
(Scene.PointingDeviceSensors.EnabledCount <> 0)
) or
(Scene.PointingDeviceActiveSensors.Count <> 0)
) then
Cursor := mcHand
else
Cursor := mcDefault;
end;
procedure TV3DViewport.Resize;
begin
inherited;
// Call ResizeViewports to change size of all viewports, when container size changed
ResizeViewports(V3DSceneWindow.Window, MainViewport);
end;
{ Helper functions ----------------------------------------------------------- }
{ Show a multi-line message, allow to copy it to clipboard etc. }
procedure MessageReport(const S: string);
var
Answer: char;
begin
Answer := MessageChoice(Window, S,
['Copy To Clipboard (Ctrl + C)', 'Close (Enter)'],
[CtrlC, {CtrlW,} CharEnter], hpLeft, false, true);
if Answer = CtrlC then
Clipboard.AsText := S + NL;
end;
procedure UpdateSelectedEnabled;
begin
if MenuSelectedInfo <> nil then
MenuSelectedInfo.Enabled := SelectedItem <> nil;
if MenuSelectedOctreeStat <> nil then
MenuSelectedOctreeStat.Enabled := SelectedItem <> nil;
if MenuSelectedLightsInfo <> nil then
MenuSelectedLightsInfo.Enabled := SelectedItem <> nil;
if MenuRemoveSelectedShape <> nil then
MenuRemoveSelectedShape.Enabled := SelectedItem <> nil;
if MenuRemoveSelectedFace <> nil then
MenuRemoveSelectedFace.Enabled := SelectedItem <> nil;
if MenuHideSelectedShape <> nil then
MenuHideSelectedShape.Enabled := SelectedItem <> nil;
if MenuEditMaterial <> nil then
MenuEditMaterial.Enabled := SelectedItem <> nil;
if MenuMergeCloseVertexes <> nil then
MenuMergeCloseVertexes.Enabled := SelectedItem <> nil;
end;
{ Update menu items and buttons that reflect Camera properties }
procedure UpdateCameraUI;
var
WalkNav: TCastleWalkNavigation;
begin
UpdateCameraNavigationTypeUI;
WalkNav := WalkNavigation;
if MenuMouseLook <> nil then
MenuMouseLook.Checked := PersistentMouseLook;
if MenuGravity <> nil then
MenuGravity.Checked :=
(WalkNav <> nil) and WalkNav.Gravity;
if MenuPreferGravityUpForRotations <> nil then
MenuPreferGravityUpForRotations.Checked :=
(WalkNav <> nil) and WalkNav.PreferGravityUpForRotations;
if MenuPreferGravityUpForMoving <> nil then
MenuPreferGravityUpForMoving.Checked :=
(WalkNav <> nil) and WalkNav.PreferGravityUpForMoving;
end;
{ Return currently used collisions octree.
Note: When Scene.Collides = true, octree is always initialized
(SceneOctreeCreate is called, and corresponding SceneOctreeDestroy
was not).
Otherwise, when Scene.Collides = false, octree *may* be available
but doesn't have to. When setting Scene.Collides to false we do not
immediately destroy the octree (in case user will just go back
to Scene.Collides = true next), but it will be destroyed on next
rebuild of octree (when we will just destroy old and not recreate new).
}
function SceneOctreeCollisions: TBaseTrianglesOctree;
begin
if (Scene <> nil) and
(Scene.InternalOctreeCollisions <> nil) then
Result := Scene.InternalOctreeCollisions else
Result := nil;
end;
function SceneOctreeRendering: TShapeOctree;
begin
if (Scene <> nil) and
(Scene.InternalOctreeRendering <> nil) then
Result := Scene.InternalOctreeRendering else
Result := nil;
end;
procedure SceneOctreeCreate; forward;
procedure SetCollisions(const Value: boolean;
const NeedMenuUpdate: boolean = true);
begin
if Scene.Collides <> Value then
begin
Scene.Collides := Value;
ButtonCollisions.Pressed := Value;
if NeedMenuUpdate then
MenuCollisions.Checked := Value;
if Scene.Collides and (Scene.InternalOctreeCollisions = nil) then
SceneOctreeCreate;
end;
end;
procedure ToggleNamedAnimationsUi;
begin
NamedAnimationsUiExists := not NamedAnimationsUiExists;
MenuNamedAnimations.Checked := NamedAnimationsUiExists;
ButtonAnimations.Pressed := NamedAnimationsUiExists;
end;
function ViewpointNode: TAbstractViewpointNode; forward;
{ TExtendedStatusText -------------------------------------------------------- }
type
TExtendedStatusText = class(TStatusText)
protected
procedure CalculateText; override;
end;
procedure TExtendedStatusText.CalculateText;
const
HighlightBegin = '<font color="#ffffff">';
HighlightEnd = '</font>';
ValueColor = 'ffffff';
{ Describe pointing-device sensors (active and under the mouse). }
procedure DescribeSensors;
function DescribeSensor(Sensor: TX3DNode): string;
var
Description: string;
Anchor: TAnchorNode;
J: Integer;
begin
Result := Format('%s', [Sensor.NiceName]);
if Sensor is TAbstractPointingDeviceSensorNode then
begin
{ use description instead, if any provided }
Description := Trim(TAbstractPointingDeviceSensorNode(Sensor).Description);
if Description <> '' then
Result := Description;
end else
if Sensor is TAnchorNode then
begin
Anchor := TAnchorNode(Sensor);
{ use description instead, if any provided }
Description := Trim(Anchor.Description);
if Description <> '' then
Result := Description;
if Anchor.FdUrl.Count <> 0 then
begin
Result := Result + (' [' + UriDisplay(Anchor.FdUrl.Items[0]));
for J := 1 to Anchor.FdUrl.Count - 1 do
Result := Result + (', ' + UriDisplay(Anchor.FdUrl.Items[J]));
Result := Result + ']';
end;
end;
Result := SForCaption(Result);
end;
var
Over: TPointingDeviceSensorList;
Active: TX3DNodeList;
I: Integer;
S: string;
begin
if Scene.PointingDeviceOverItem <> nil then
Over := Scene.PointingDeviceSensors else
Over := nil;
Active := Scene.PointingDeviceActiveSensors;
if (Active.Count <> 0) or
((Over <> nil) and
(Over.Count <> 0)) then
begin
{ Display sensors active but not over.
We do not just list all active sensors in the 1st pass,
because we prefer to list active sensors in the (more stable) order
they have on Over list. See also g3l_stapes_dbg.wrl testcase. }
for I := 0 to Active.Count - 1 do
if (Over = nil) or
(Over.IndexOf(Active[I]) = -1) then
Text.Append(HighlightBegin + DescribeSensor(Active[I]) + HighlightEnd);
{ Display sensors over which the mouse hovers (and enabled).
Highlight active sensors on the list. }
if Over <> nil then
for I := 0 to Over.Count - 1 do
if Over.Enabled(I) then
begin
S := DescribeSensor(Over[I]);
if Active.IndexOf(Over[I]) <> -1 then
S := HighlightBegin + S + HighlightEnd;
Text.Append(S);
end;
{ Note that sensors that are "active and over" are undistinguishable
from "active and not over".
This means that a tiny bit of information is lost
(because you are not *always* over an active sensor, so this way
you don't know if you're over or not over an active sensor).
But it's not really useful information in practice, and hiding it
makes the sensors status look much cleaner. }
{ a blank line, separating from the rest of status, if needed }
if Text.Count <> 0 then
Text.Append('');
end;
end;
function CurrentAboveHeight(WalkNavigation: TCastleWalkNavigation): string;
begin
if SceneOctreeCollisions = nil then
Result := 'no collisions'
else
if not WalkNavigation.Gravity then
Result := 'no gravity'
else
if not WalkNavigation.IsAbove then
Result := 'no ground beneath'
else
Result := Format('%f', [WalkNavigation.AboveHeight]);
end;
var
s: string;
Statistics: TRenderStatistics;
Pos, Dir, Up: TVector3;
begin
inherited;
Statistics := MainViewport.Statistics;
DescribeSensors;
{ S := Format('Collision detection: %s', [ BoolToStrOO[Scene.Collides] ]);
if SceneOctreeCollisions = nil then
S := S + ' (octree resources released)';
Text.Append(S); }
MainViewport.Camera.GetWorldView(Pos, Dir, Up);
Text.Append(Format('Camera: pos <font color="#%s">%s</font>, dir <font color="#%s">%s</font>, up <font color="#%s">%s</font>',
[ ValueColor, Pos.ToString,
ValueColor, Dir.ToString,
ValueColor, Up.ToString ]));
if WalkNavigation <> nil then
begin
Text.Append(Format('Avatar height: <font color="#%s">%f</font> (last height above the ground: <font color="#%s">%s</font>)',
[ ValueColor, WalkNavigation.PreferredHeight,
ValueColor, CurrentAboveHeight(WalkNavigation) ]));
end;
{ if SceneLightsCount = 0 then
s := '(useless, scene has no lights)' else
s := BoolToStrOO[Scene.RenderOptions.UseSceneLights];
Text.Append(Format('Use scene lights: %s', [s])); }
Text.Append(Format('Rendered: <font color="#%s">%s</font>', [
ValueColor,
Statistics.ToString
]) + OctreeDisplayStatus);
if Scene.TimeAtLoad = 0.0 then
S := Format('World time: <font color="#%s">%d</font>',
[ValueColor, Trunc(Scene.Time)]) else
S := Format('World time: <font color="#%s">load time + %d</font>',
[ValueColor, Trunc(Scene.Time - Scene.TimeAtLoad)]);
if not AnimationTimePlaying then
S := S + ' (paused)';
if not ProcessEventsWanted then
S := S + (' (paused, not processing VRML/X3D events)');
Text.Append(S);
(*// nice to debug ShadowVolumeRenderer optimizations.
// Too cryptic to show normal users:)
S := Format('No shadow %d + zpass %d + zfail (no l cap) %d + zfail (l cap) %d = all %d',
[ MainViewport.ShadowVolumeRenderer.CountShadowsNotVisible,
MainViewport.ShadowVolumeRenderer.CountZPass,
MainViewport.ShadowVolumeRenderer.CountZFailNoLightCap,
MainViewport.ShadowVolumeRenderer.CountZFailAndLightCap,
MainViewport.ShadowVolumeRenderer.CountCasters ]);
Text.Append(S);
*)
{
Text.Append(Format('Projection: near %f far %f', [
MainViewport.Camera.EffectiveProjectionNear,
MainViewport.Camera.EffectiveProjectionFar
]));
}
end;
{ TCastleWindow callbacks --------------------------------------------------------- }
{ Update SceneBoundingBox look. }
procedure SceneBoundingBoxUpdate(const RenderingCamera: TRenderingCamera);
begin
SceneBoundingBox.Exists :=
(RenderingCamera.Target = rtScreen) and
(not HideExtraScenesForScreenshot) and
ShowBBox;
if SceneBoundingBox.Exists then
begin
{ Use Scene.RenderOptions.LineWidth for our visualizations as well }
SceneBoundingBox.RenderOptions.LineWidth := Scene.RenderOptions.LineWidth;
SceneBoundingBox.UpdateBox(Scene.BoundingBox);
end;
end;
var
HasWalkFrustum: Boolean; //< Secures from case when user never used Walk navigation, and so WalkFrustum is undefined
WalkFrustum: TFrustum;
{ Render visualization of various stuff, like octree and such. }
procedure RenderVisualizations(const RenderingCamera: TRenderingCamera);
procedure RenderFrustum(const AlwaysVisible: boolean);
var
FrustumPoints: TFrustumPoints;
SavedDepthTest: Boolean;
Mesh: TCastleRenderUnlitMesh;
begin
if not HasWalkFrustum then
Exit;
if AlwaysVisible then
begin
SavedDepthTest := RenderContext.DepthTest;
RenderContext.DepthTest := false;
end;
try
WalkFrustum.CalculatePoints(FrustumPoints);
Mesh := TCastleRenderUnlitMesh.Create(true);
try
Mesh.ModelViewProjection := RenderContext.ProjectionMatrix * RenderingCamera.CurrentMatrix;
Mesh.SetVertexes(@FrustumPoints, High(FrustumPoints) + 1, false);
Mesh.SetIndexes(@FrustumPointsLinesIndexes, (High(FrustumPointsLinesIndexes) + 1) * 2);
Mesh.Render(pmLines);
finally FreeAndNil(Mesh) end;
finally
if AlwaysVisible then
RenderContext.DepthTest := SavedDepthTest;
end;
end;
procedure RenderSelected(const Box: TBox3D; const Triangle: TTriangle3; const Point: TVector3);
var
SavedDepthTest, SavedCullFace: Boolean;
ModelViewProjection: TMatrix4;
Mesh: TCastleRenderUnlitMesh;
SavedLineWidth, SavedPointSize: Single;
begin
SavedDepthTest := RenderContext.DepthTest;
SavedCullFace := RenderContext.CullFace;
SavedLineWidth := RenderContext.LineWidth;
SavedPointSize := RenderContext.PointSize;
RenderContext.DepthTest := false; // draw stuff visible through other geometry here
RenderContext.CullFace := true; // note: it doesn't matter for lines, but matters for triangles below
RenderContext.LineWidth := 2.0;
RenderContext.PointSize := 5.0;
ModelViewProjection := RenderContext.ProjectionMatrix * RenderingCamera.CurrentMatrix;
// draw red selection corner markers
glDrawCornerMarkers(Box, Vector4(0.5, 0.3, 0.3, 1), ModelViewProjection);
Mesh := TCastleRenderUnlitMesh.Create(true);
try
Mesh.ModelViewProjection := ModelViewProjection;
RenderContext.BlendingEnable(bsSrcAlpha, bdOneMinusSrcAlpha);
Mesh.Color := Vector4(0.5, 0.3, 0.3, 0.5); // draw face back in red
Mesh.SetVertexes([
Vector4(Triangle.Data[0], 1),
Vector4(Triangle.Data[2], 1),
Vector4(Triangle.Data[1], 1)
], false);
Mesh.Render(pmTriangles);
Mesh.Color := Vector4(0.4, 0.4, 1, 0.4); // draw face front in blue
Mesh.SetVertexes([
Vector4(Triangle.Data[0], 1),
Vector4(Triangle.Data[1], 1),
Vector4(Triangle.Data[2], 1)
], false);
Mesh.Render(pmTriangles);
RenderContext.BlendingDisable;
// draw face outline in white
Mesh.Color := White;
Mesh.Render(pmLineLoop); // note: we use vertexes set previously
// draw hit point
Mesh.SetVertexes([Vector4(Point, 1)], false);
Mesh.Render(pmPoints);
finally FreeAndNil(Mesh) end;
{ Draw blue corner markers, these overwrite the red markers, but only when in front.
So corners in front are blue, those behind are red.
Gives depth impression and is generally visible against various geometry. }
glDrawCornerMarkers(Box, Vector4(0.2, 0.2, 1, 1), ModelViewProjection);
RenderContext.DepthTest := SavedDepthTest;
RenderContext.CullFace := SavedCullFace;
RenderContext.LineWidth := SavedLineWidth;
RenderContext.PointSize := SavedPointSize;
end;
begin
{ Save WalkFrustum for future RenderFrustum rendering. }
if (RenderingCamera.Target = rtScreen) and (WalkNavigation <> nil) then
begin
HasWalkFrustum := true;
WalkFrustum := MainViewport.Camera.Frustum;
end;
if (RenderingCamera.Target = rtScreen) and (not HideExtraScenesForScreenshot) then
begin
{ Visualization below depends on depth test enabled }
RenderContext.DepthTest := true;
{ Use Scene.RenderOptions.LineWidth for our visualizations as well }
RenderContext.LineWidth := Scene.RenderOptions.LineWidth;
OctreeDisplay(Scene, RenderContext.ProjectionMatrix * RenderingCamera.CurrentMatrix);
{ Note that there is no sense in showing WalkFrustum if WalkNavigation <> nil
since then the WalkFrustum matches currently used frustum. }
if ShowFrustum and (WalkNavigation = nil) then
RenderFrustum(ShowFrustumAlwaysVisible);
if SelectedItem <> nil then
{ Note that this assumes that Scene transformation is identity.
We only transform selected stuff into scene coordinate-system. }
RenderSelected(
TShape(SelectedItem^.Shape).BoundingBox,
SelectedItem^.World.Triangle,
SelectedPointWorld
);
end;
end;
procedure TV3DViewport.RenderFromView3D(const Params: TRenderParams);
begin
SceneBoundingBoxUpdate(Params.RenderingCamera);
Scene.Visible := FillMode <> fmSilhouetteBorderEdges;
SceneDebugEdges.Exists := FillMode = fmSilhouetteBorderEdges;
if SceneDebugEdges.Exists then
SceneDebugEdges.UpdateEdges(Scene);
inherited;
{ Draw visualizations after viewport contents, this is important for
"selected" visualization that doesn't use depth test and assumes it is
just drawn on top of everything. }
RenderVisualizations(Params.RenderingCamera);
end;
procedure TV3DViewport.BeforeRender;
begin
{ Make sure to call ViewportProperties before inherited. }
ViewportProperties(Self);
inherited;
end;
procedure TV3DViewport.Render;
begin
{ Make sure to call ViewportProperties before inherited. }
ViewportProperties(Self);
inherited;
end;
const
SNavigationClassWalkNeeded =
'You must be in "Walk", "Fly" or "None" navigation types to use this function.';
SOnlyWhenOctreeAvailable = 'This is not possible when octree is not generated. Turn on "Navigation -> Collision Detection" to make it available.';
procedure SetViewpointForWholeScene(
const WantedDirection, WantedUp: Integer;
const WantedDirectionPositive, WantedUpPositive: boolean);
var
Position, Direction, Up, GravityUp: TVector3;
begin
CameraViewpointForWholeScene(Scene.BoundingBox, WantedDirection, WantedUp,
WantedDirectionPositive, WantedUpPositive,
Position, Direction, Up, GravityUp);
MainViewport.Camera.AnimateTo(Position, Direction, Up, CameraTransitionTime);
MainViewport.Camera.GravityUp := GravityUp;
end;
procedure SetViewpointTop;
begin
SetViewpointForWholeScene(1, 2, false, false);
end;
procedure SetViewpointBottom;
begin
SetViewpointForWholeScene(1, 2, true , false);
end;
procedure SetViewpointFront;
begin
SetViewpointForWholeScene(2, 1, false, true);
end;
procedure SetViewpointBack;
begin
SetViewpointForWholeScene(2, 1, true , true);
end;
procedure SetViewpointRight;
begin
SetViewpointForWholeScene(0, 1, false, true);
end;
procedure SetViewpointLeft;
begin
SetViewpointForWholeScene(0, 1, true , true);
end;
procedure TEventsHandler.Press(const Sender: TCastleUserInterface;
const Event: TInputPressRelease; var Handled: boolean);
begin
{ Although some of these shortcuts are also assigned to menu items,
catching them here is more reliable -- allows to handle also Ctrl+number
combinations, and capture both numpad and non-numpad versions. }
if Event.IsKey(key7) or Event.IsKey(keyNumPad7) then
begin
if Event.ModifiersDown = [] then
SetViewpointTop
else
if Event.ModifiersDown = [mkCtrl] then
SetViewpointBottom;
end;
if Event.IsKey(key1) or Event.IsKey(keyNumPad1) then
begin
if Event.ModifiersDown = [] then
SetViewpointFront
else
if Event.ModifiersDown = [mkCtrl] then
SetViewpointBack;
end;
if Event.IsKey(key3) or Event.IsKey(keyNumPad3) then
begin
if Event.ModifiersDown = [] then
SetViewpointRight
else
if Event.ModifiersDown = [mkCtrl] then
SetViewpointLeft;
end;
{ Support selecting item by ctrl + right button click. }
if Event.IsMouseButton(buttonRight) and
(mkCtrl in Window.Container.Pressed.Modifiers) then
begin
SelectedItem := Scene.PointingDeviceOverItem;
SelectedPointWorld := Scene.PointingDeviceOverPoint;
{ calculate SelectedPointLocal }
if SelectedItem <> nil then
begin
SelectedShape := TShape(SelectedItem^.Shape);
try
SelectedPointLocal :=
SelectedItem^.State.Transformation.InverseTransform.MultPoint(SelectedPointWorld);
except
on ETransformedResultInvalid do
SelectedItem := nil;
end;
end;
UpdateSelectedEnabled;
Window.Invalidate;
end;
end;
procedure TEventsHandler.PointingDeviceSensorsChange(Sender: TObject);
begin
{ Our status text displays current sensors (under the mouse,
and currently active (if any)), so we have to redisplay. }
Window.Invalidate;
end;
{ Setting viewpoint ---------------------------------------------------------- }
function NavigationNode: TNavigationInfoNode;
begin
if Scene <> nil then
Result := Scene.NavigationInfoStack.Top else
Result := nil;
end;
function ViewpointNode: TAbstractViewpointNode;
begin
if Scene <> nil then
Result := Scene.ViewpointStack.Top else
Result := nil;
end;
procedure TEventsHandler.ViewpointsChanged(Sender: TObject);
begin
Viewpoints.Recalculate(Scene);
end;
procedure TEventsHandler.BoundViewpointChanged(Sender: TObject);
var
V: TAbstractViewpointNode;
begin
V := Scene.ViewpointStack.Top;
Viewpoints.BoundViewpoint := Viewpoints.ItemOf(V);
end;
procedure TEventsHandler.BoundNavigationInfoChanged(Sender: TObject);
begin
UpdateCameraUI;
end;
procedure TEventsHandler.HeadlightOnChanged(Sender: TObject);
begin
if MenuHeadlight <> nil then
MenuHeadlight.Checked := Scene.HeadLightOn;
end;
{ Scene operations ---------------------------------------------------------- }
{ Call when ButtonWarningsEnabled or SceneWarnings.Count changes
or when window sizes change. }
procedure UpdateButtonWarnings;
begin
ButtonWarnings.Caption := Format('%d warnings', [SceneWarnings.Count]);
ButtonWarnings.Exists := ButtonWarningsEnabled and (SceneWarnings.Count <> 0);
{ When window is closed, width/height may be incorrect (even negative,
because of WindowDefaultSize). Do not call EventResize then.
May happen when you used --write, and some warning occurs. }
if not Window.Closed then
Window.Container.EventResize; { update ButtonWarnings.Left }
end;
procedure TEventsHandler.OnWarningHandle(const Category, S: string);
begin
{ It is possible that SceneWarnings = nil now,
in case on macOS we use
".../castle-model-viewer .../dynamic_world.x3dv --screenshot 0 output_2d_screenshot.png"
and get warning
"Freeing form failed with EAccessViolation, this is unfortunately possible on macOS with Carbon widgetset".
The ButtonWarnings is invalid (already freed) at this point too. }
if SceneWarnings <> nil then
begin
if Category <> '' then
SceneWarnings.Add(Category + ': ' + S)
else
SceneWarnings.Add(S);
UpdateButtonWarnings;
end;
if Window <> nil then
Window.Invalidate;
end;
procedure SceneOctreeCreate;
begin
{ Do not create octrees when Scene.Collides = false. This makes
setting Scene.Collides to false an optimization: octree doesn't have to
be recomputed when animation frame changes, or new scene is loaded etc. }
if Scene.Collides then
Scene.PreciseCollisions := true;
end;
procedure SceneOctreeFree;
begin
if Scene <> nil then
begin
{ Since we destroy our PTriangles, make sure Scene
doesn't hold a reference to it.
Note: PointingDeviceClear will automatically update current cursor
(by calling OnPointingDeviceSensorsChange that leads to our method). }
Scene.PointingDeviceClear;
Scene.PreciseCollisions := false;
end;
end;
procedure Unselect;
begin
SelectedItem := nil;
SelectedShape := nil;
UpdateSelectedEnabled;
end;
{ Frees (and sets to some null values) "scene global variables". }
procedure FreeScene;
begin
SceneOctreeFree;
// Scene.Close;
Viewpoints.Recalculate(nil);
RefreshNamedAnimationsUi(Window, nil, ToolbarPanel.EffectiveHeight);
SceneUrl := '';
if MenuReopen <> nil then
MenuReopen.Enabled := false;
Unselect;
end;
procedure LoadClearScene; forward;
type
TLoadSceneOption = (lsoCommandLineCustomization);
TLoadSceneOptions = set of TLoadSceneOption;
{ Set proper Camera.ProjectionNear and Navigation.Radius based on predicted
bounding box we need to display.
Navigation may be @nil.
CGE since commit 050dc126a4f0ac0a0211d929f1e1f8d7f96a88f9 no longer does it
automatically based on box. }
procedure UpdateRadiusProjectionNear(const Camera: TCastleCamera;
const Navigation: TCastleNavigation;
const Box: TBox3D);
const
WorldBoxSizeToRadius = 0.005;
var
Radius: Single;
begin
Radius := Box.AverageSize(false, 1.0) * WorldBoxSizeToRadius;
{ Make Radius at most DefaultCameraRadius?
Commented out, not necessary and could be troublesome -- we want the autocalculate