Debian Codegraph @

tools/castle-editor/code/designvisualizetransform.pas

raw
1 {
2 Copyright 2020-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 { Visualize TCastleTransform selection and dragging to transform (TVisualizeTransform). }
17 unit DesignVisualizeTransform;
18
19 interface
20
21 uses Classes, SysUtils, Contnrs, Generics.Collections,
22 CastleColors, CastleVectors, CastleVectorsInternalSingle, CastleTransform,
23 CastleDebugTransform, CastleScene, CastleCameras, CastleTriangles, CastleUtils,
24 CastleClassUtils;
25
26 type
27 { Visualize TCastleTransform hover.
28 This is really just a thin wrapper around TDebugTransformBox in this case. }
29 TVisualizeTransformHover = class(TComponent)
30 strict private
31 FParent: TCastleTransform;
32 FParentObserver: TFreeNotificationObserver;
33 Box: TDebugTransformBox;
34 procedure ParentFreeNotification(const Sender: TFreeNotificationObserver);
35 procedure SetParent(const AValue: TCastleTransform);
36 public
37 constructor Create(AOwner: TComponent); override;
38 destructor Destroy; override;
39 { Currently visualized TCastleTransform instance as "we are hovering over it,
40 and clicking will select it". }
41 property Parent: TCastleTransform read FParent write SetParent;
42 end;
43
44 TVisualizeOperation = (voSelect, voTranslate, voRotate, voScale);
45
46 TDebugTransformBoxList = specialize TObjectList<TDebugTransformBox>;
47
48 { Visualize TCastleTransform selection and dragging to transform. }
49 TVisualizeTransformSelected = class(TComponent)
50 strict private
51 type
52 TGizmoScene = class(TCastleScene)
53 strict private
54 {.$define DEBUG_GIZMO_PICK}
55 {$ifdef DEBUG_GIZMO_PICK}
56 VisualizePick: TCastleScene;
57 {$endif DEBUG_GIZMO_PICK}
58 GizmoDragging: Boolean;
59 DraggingCoord: Integer;
60 LastPick: TVector3;
61 LastPickAngle: Single;
62 GizmoScalingAssumeScale: Boolean;
63 GizmoScalingAssumeScaleValue: TVector3;
64 InsideInternalCameraChanged: Boolean;
65 LastIsProjectionOrthographic: Boolean;
66
67 { Point on axis closest to given pick.
68 Axis may be -1 to indicate we drag on all axes with the same amount
69 or -2 to indicate we drag X and Y axes for 2D. }
70 function PointOnAxis(out Intersection: TVector3;
71 const Pick: TRayCollisionNode; const Axis: Integer): Boolean;
72
73 { Angle in radians on a plane lying at given Coord
74 (e.g. plane "Z = 0" when Coord = 2).
75 The angle is measured using ArcTan2 on the given plane.
76 Angle is in radians, from -Pi to Pi.
77
78 It is not defined here where's the Angle = 0 exactly, as users
79 of this routine in practice always want to subtract 2 values of such
80 angle, so it doesn't matter "where is Angle = 0". }
81 function AngleOnPlane(out Angle: Single;
82 const Pick: TRayCollisionNode; const Coord: T3DAxis): Boolean;
83
84 procedure DoParentModified;
85 procedure DoGizmoStopDrag;
86 procedure UpdateSize;
87 protected
88 procedure ChangeWorld(const Value: TCastleAbstractRootTransform); override;
89 function LocalRayCollision(const RayOrigin, RayDirection: TVector3;
90 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision; override;
91 public
92 Operation: TVisualizeOperation;
93 OnParentModified: TNotifyEvent;
94 OnGizmoStopDrag: TNotifyEvent;
95 constructor Create(AOwner: TComponent); override;
96 procedure InternalCameraChanged; override;
97 function PointingDevicePress(const Pick: TRayCollisionNode;
98 const Distance: Single): Boolean; override;
99 function PointingDeviceMove(const Pick: TRayCollisionNode;
100 const Distance: Single): Boolean; override;
101 function PointingDeviceRelease(const Pick: TRayCollisionNode;
102 const Distance: Single; const CancelAction: Boolean): Boolean; override;
103 procedure LocalRender(const Params: TRenderParams); override;
104 end;
105
106 var
107 FOperation: TVisualizeOperation;
108 FParent: TCastleTransform;
109 FParentObserver: TFreeNotificationObserver;
110 FPickable: Boolean;
111 Boxes: TDebugTransformBoxList;
112 Gizmo: array [TVisualizeOperation] of TGizmoScene;
113 procedure SetOperation(const AValue: TVisualizeOperation);
114 procedure SetParent(const AValue: TCastleTransform);
115 procedure SetPickable(const Value: Boolean);
116 procedure GizmoHasModifiedParent(Sender: TObject);
117 procedure GizmoStopDrag(Sender: TObject);
118 procedure ParentFreeNotification(const Sender: TFreeNotificationObserver);
119 procedure CreateMoreBoxes;
120 public
121 OnParentModified: TNotifyEvent;
122 OnGizmoStopDrag: TNotifyEvent;
123 constructor Create(AOwner: TComponent); override;
124 destructor Destroy; override;
125
126 { Currently visualized TCastleTransform instance for potential move/rotate/scale
127 (depending on Operation).
128 @nil to not visualize anything.
129
130 TODO: ideally we'd like to remove it at one point, and gizmos to transform
131 should work on multi-selection too. }
132 property Parent: TCastleTransform read FParent write SetParent;
133
134 property Pickable: Boolean read FPickable write SetPickable;
135 property Operation: TVisualizeOperation read FOperation write SetOperation
136 default voSelect;
137
138 { Visualize selected parents reflecting the given list.
139 Selected may be nil (equivalent to empty list).
140 Only TCastleTransform descendants on Selected are taken into account here. }
141 procedure SetSelectedParents(const Selected: TComponentList);
142 end;
143
144 var
145 ColorHover, ColorSelected, ColorHoverAndSelected: TCastleColor;
146
147 implementation
148
149 uses Math,
150 ProjectUtils,
151 CastleLog, CastleShapes, CastleViewport, CastleProjection,
152 CastleQuaternions, X3DNodes, CastleGLUtils, CastleRenderContext,
153 CastleControl, CastleKeysMouse, CastleRenderOptions;
154
155 { TVisualizeTransformHover ------------------------------------------------------ }
156
157 constructor TVisualizeTransformHover.Create(AOwner: TComponent);
158 begin
159 inherited Create(AOwner);
160
161 FParentObserver := TFreeNotificationObserver.Create(Self);
162 FParentObserver.OnFreeNotification := {$ifdef FPC}@{$endif} ParentFreeNotification;
163
164 Box := TDebugTransformBox.Create(Self);
165 Box.BoxColor := ColorOpacity(ColorHover, 0.25);
166 Box.Exists := true;
167 end;
168
169 destructor TVisualizeTransformHover.Destroy;
170 begin
171 inherited;
172 end;
173
174 procedure TVisualizeTransformHover.SetParent(const AValue: TCastleTransform);
175 begin
176 if FParent = AValue then Exit;
177
178 FParent := AValue;
179 FParentObserver.Observed := AValue;
180 Box.Parent := FParent;
181 end;
182
183 procedure TVisualizeTransformHover.ParentFreeNotification(const Sender: TFreeNotificationObserver);
184 begin
185 Parent := nil;
186 end;
187
188 { TVisualizeTransformSelected.TGizmoScene -------------------------------------------- }
189
190 function TVisualizeTransformSelected.TGizmoScene.PointOnAxis(
191 out Intersection: TVector3; const Pick: TRayCollisionNode;
192 const Axis: Integer): Boolean;
193
194 (*
195 var
196 Axis1, Axis2: Integer;
197 begin
198 Result := Pick.Triangle <> nil; // otherwise Pick.Point undefined
199
200 Intersection := Pick.Point;
201
202 // leave only Intersection[Axis] non-zero
203 if Axis >= 0 then
204 begin
205 RestOf3DCoords(Axis, Axis1, Axis2);
206 Intersection[Axis1] := 0;
207 Intersection[Axis2] := 0;
208 end;
209 end;
210 *)
211
212 var
213 IntersectionScalar: Single;
214 IntersectionOneAxis: TVector3;
215 begin
216 if Axis = -1 then
217 begin
218 (*
219 Result := Pick.Triangle <> nil; // otherwise Pick.Point undefined
220 if Result then
221 begin
222 Intersection := Pick.Point;
223 IntersectionScalar := Approximate3DScale(Intersection);
224 Intersection := Vector3(IntersectionScalar, IntersectionScalar, IntersectionScalar);
225 end;
226 *)
227
228 Result := true;
229 IntersectionScalar := Sqrt(PointToLineDistanceSqr(TVector3.Zero, Pick.RayOrigin, Pick.RayDirection));
230 Intersection := Vector3(IntersectionScalar, IntersectionScalar, IntersectionScalar);
231 end else
232 if Axis = -2 then
233 begin
234 Intersection := Vector3(0, 0, 0);
235 Result := false;
236 if PointOnLineClosestToLine(IntersectionOneAxis,
237 TVector3.Zero, TVector3.One[0],
238 Pick.RayOrigin, Pick.RayDirection) then
239 begin
240 Intersection := IntersectionOneAxis;
241 Result := true;
242 end;
243
244 if PointOnLineClosestToLine(IntersectionOneAxis,
245 TVector3.Zero, TVector3.One[1],
246 Pick.RayOrigin, Pick.RayDirection) then
247 begin
248 Intersection := Intersection + IntersectionOneAxis;
249 Result := true;
250 end;
251 end else
252 begin
253 Result := PointOnLineClosestToLine(Intersection,
254 TVector3.Zero, TVector3.One[Axis],
255 Pick.RayOrigin, Pick.RayDirection);
256
257 {$ifdef DEBUG_GIZMO_PICK}
258 VisualizePick.Exists := Result;
259 if Result then
260 begin
261 // Intersection is in Parent coordinate space, i.e. ignores our gizmo scale
262 VisualizePick.Translation := OutsideToLocal(Intersection);
263 WritelnLog('VisualizePick with %s', [Intersection.ToString]);
264 WritelnLog('Line 1: %s %s, line 2 %s %s', [
265 TVector3.Zero.ToString,
266 TVector3.One[Axis].ToString,
267 Pick.RayOrigin.ToString,
268 Pick.RayDirection.ToString
269 ]);
270 end;
271 {$endif DEBUG_GIZMO_PICK}
272 end;
273 end;
274
275 function TVisualizeTransformSelected.TGizmoScene.AngleOnPlane(out Angle: Single;
276 const Pick: TRayCollisionNode; const Coord: T3DAxis): Boolean;
277 var
278 C1, C2: T3DAxis;
279 PointProjected: TVector2;
280 Intersection: TVector3;
281 begin
282 if not TrySimplePlaneRayIntersection(Intersection, Coord, 0, Pick.RayOrigin, Pick.RayDirection) then
283 Exit(false);
284 { Use RestOf3DCoordsCycle, in the lopping order X-Y-Z.
285 This results in consistent ArcTan2 results, that makes rotating around
286 any coord in TVisualizeTransformSelected.TGizmoScene.PointingDeviceMove
287 have the same behavior (no need to invert angle sign for Y coord,
288 as with RestOf3DCoords). }
289 RestOf3DCoordsCycle(Coord, C1, C2);
290 PointProjected.X := Intersection[C1];
291 PointProjected.Y := Intersection[C2];
292 Angle := ArcTan2(PointProjected.Y, PointProjected.X);
293 Result := true;
294 end;
295
296 procedure TVisualizeTransformSelected.TGizmoScene.DoParentModified;
297 begin
298 if Assigned(OnParentModified) then
299 OnParentModified(Self);
300 end;
301
302 procedure TVisualizeTransformSelected.TGizmoScene.DoGizmoStopDrag;
303 begin
304 if Assigned(OnGizmoStopDrag) then
305 OnGizmoStopDrag(Self);
306 end;
307
308 procedure TVisualizeTransformSelected.TGizmoScene.ChangeWorld(
309 const Value: TCastleAbstractRootTransform);
310 begin
311 if Value <> World then
312 begin
313 inherited;
314 GizmoDragging := false;
315 end;
316 end;
317
318 constructor TVisualizeTransformSelected.TGizmoScene.Create(AOwner: TComponent);
319 {$ifdef DEBUG_GIZMO_PICK}
320 var
321 SphereGeometry: TSphereNode;
322 SphereShape: TShapeNode;
323 SphereMat: TMaterialNode;
324 SphereAppearance: TAppearanceNode;
325 SphereRoot: TX3DRootNode;
326 {$endif DEBUG_GIZMO_PICK}
327 begin
328 inherited Create(AOwner);
329 InternalExistsOnlyInMeaningfulParents := true;
330 RenderLayer := rlFront;
331
332 {$ifdef DEBUG_GIZMO_PICK}
333 VisualizePick := TCastleScene.Create(Self);
334
335 SphereGeometry := TSphereNode.CreateWithShape(SphereShape);
336 SphereGeometry.Radius := 0.1;
337
338 SphereMat := TMaterialNode.Create;
339 SphereMat.DiffuseColor := RedRGB;
340
341 SphereAppearance := TAppearanceNode.Create;
342 SphereAppearance.Material := SphereMat;
343
344 SphereShape.Appearance := SphereAppearance;
345
346 SphereRoot := TX3DRootNode.Create;
347 SphereRoot.AddChildren(SphereShape);
348
349 VisualizePick.Load(SphereRoot, true);
350 VisualizePick.Exists := false;
351 Add(VisualizePick);
352 {$endif DEBUG_GIZMO_PICK}
353 end;
354
355 procedure TVisualizeTransformSelected.TGizmoScene.InternalCameraChanged;
356 begin
357 inherited;
358 { UpdateSize changes our transformation, and ChangedTransform in turn
359 calls InternalCameraChanged, which means we can get into infinite
360 recursion. Use InsideInternalCameraChanged to prevent it. }
361 if InsideInternalCameraChanged then Exit;
362 InsideInternalCameraChanged := true;
363 UpdateSize;
364 InsideInternalCameraChanged := false;
365 end;
366
367 procedure TVisualizeTransformSelected.TGizmoScene.UpdateSize;
368
369 function Projected(const V, X, Y: TVector3): TVector2;
370 begin
371 Result.X := TVector3.DotProduct(V, X);
372 Result.Y := TVector3.DotProduct(V, Y);
373 end;
374
375 var
376 OldScale: TVector3;
377
378 { Surround calls to WorldTransform in this, to account for
379 GizmoScalingAssumeScale[Value]. }
380 procedure BeginWorldTransform;
381 begin
382 if GizmoScalingAssumeScale then
383 begin
384 OldScale := Parent.Scale;
385 Parent.Scale := GizmoScalingAssumeScaleValue;
386 end;
387 end;
388
389 procedure EndWorldTransform;
390 begin
391 if GizmoScalingAssumeScale then
392 Parent.Scale := OldScale;
393 end;
394
395 function GetPerspectiveGizmoScale(const Camera: TCastleCamera; const BaseGizmoScale: Single): Single;
396 const
397 AssumeNear = 1.0;
398 var
399 // ViewProjectionMatrix: TMatrix4;
400 ZeroProjected, OneProjected: TVector2;
401 OneDistance: Single;
402 CameraPos, CameraDir, CameraUp: TVector3; //< camera vectors in world-coordinates
403 ZeroWorld, OneWorld, OneProjected3, ZeroProjected3, CameraSide: TVector3;
404 CameraNearPlane: TVector4;
405 SceneSizeMultiplier: Single;
406 begin
407 { In theory, any value of SceneSizeMultiplier is OK,
408 and it could be always 1.0.
409 But on large scenes, this makes huge precision problems with calculation
410 below, as OneWorld will be very close to ZeroWorld and then OneDistance is tiny.
411 So we use to calculate in larger coordinates, and then scale it back to achieve the same.
412 Testcase: gizmo_flickering_bug . }
413 SceneSizeMultiplier := World.BoundingBox.AverageSize(false, 1.0);
414
415 Camera.GetWorldView(CameraPos, CameraDir, CameraUp);
416
417 BeginWorldTransform;
418
419 { Map two points from gizmo local transformation,
420 to determine correct gizmo scale.
421 These points reflect the parent translation and scale.
422
423 Note that we know that gizmo itself has never any translation,
424 but it may have a scale.
425 }
426 Scale := Vector3(1, 1, 1); // assume gizmo scale = 1, will be changed later
427 ZeroWorld := LocalToWorld(TVector3.Zero);
428 { Note: We use CameraUp, not Camera.GravityUp, to work sensibly even
429 when looking at world at a direction similar to +Y. }
430 OneWorld := LocalToWorld(WorldToLocalDirection(CameraUp).AdjustToLength(SceneSizeMultiplier));
431
432 EndWorldTransform;
433
434 (* TODO: why this fails:
435 ViewProjectionMatrix := Camera.ProjectionMatrix * Camera.Matrix;
436 ZeroProjected := (ViewProjectionMatrix * Vector4(ZeroWorld, 1)).XY;
437 OneProjected := (ViewProjectionMatrix * Vector4(OneWorld, 1)).XY;
438 *)
439
440 CameraNearPlane := Vector4(
441 CameraDir,
442 { plane equation should yield 0 when used with point in front of camera }
443 - TVector3.DotProduct(
444 CameraPos + CameraDir * AssumeNear * SceneSizeMultiplier,
445 CameraDir
446 )
447 );
448 if not TryPlaneLineIntersection(OneProjected3, CameraNearPlane, CameraPos, OneWorld - CameraPos) then
449 Exit(1.0); // no valid value can be calculated
450 if not TryPlaneLineIntersection(ZeroProjected3, CameraNearPlane, CameraPos, ZeroWorld - CameraPos) then
451 Exit(1.0); // no valid value can be calculated
452
453 CameraSide := TVector3.CrossProduct(CameraDir, CameraUp);
454 ZeroProjected := Projected(ZeroProjected3, CameraSide, CameraUp);
455 OneProjected := Projected(OneProjected3, CameraSide, CameraUp);
456
457 // get the distance, on screen in pixels, of a 1 unit in 3D around gizmo
458 OneDistance := PointsDistance(ZeroProjected, OneProjected);
459
460 if IsZero(OneDistance) then
461 Result := SceneSizeMultiplier
462 else
463 { Multiply by SceneSizeMultiplier 2x because
464 1. it increases OneWorld
465 2. it increases camera near (at AssumeNear) }
466 Result := Sqr(SceneSizeMultiplier) * BaseGizmoScale / OneDistance;
467 end;
468
469 const
470 BaseGizmoScaleOrtho = 0.3 * 0.5;
471 BaseGizmoScalePerspective = 0.25 * 0.5;
472 var
473 Camera: TCastleCamera;
474 GizmoScale, ScaleUniform: Single;
475 begin
476 { Adjust scale to take the same space on screen. }
477 if HasWorldTransform and
478 (World <> nil) and
479 (World.MainCamera <> nil) then
480 begin
481 Camera := World.MainCamera;
482
483 if Camera.ProjectionType = ptOrthographic then
484 begin
485 { We just want gizmo is about 15% of effective height }
486 GizmoScale := BaseGizmoScaleOrtho * Camera.Orthographic.EffectiveRect.Height;
487 ScaleUniform := Parent.WorldToLocalDistance(GizmoScale);
488 end else
489 begin
490 GizmoScale := BaseGizmoScalePerspective {TODO:* Camera.Perspective.EffectiveFieldOfViewVertical};
491 ScaleUniform := GetPerspectiveGizmoScale(Camera, GizmoScale);
492 end;
493
494 Scale := Vector3(ScaleUniform, ScaleUniform, ScaleUniform);
495 end;
496 end;
497
498 (*
499 // Not needed now
500 function TVisualizeTransformSelected.TGizmoScene.Dragging: boolean;
501 begin
502 Result := (inherited Dragging) or GizmoDragging;
503 end;
504 *)
505
506 function TVisualizeTransformSelected.TGizmoScene.PointingDevicePress(
507 const Pick: TRayCollisionNode; const Distance: Single): Boolean;
508 var
509 AppearanceName: String;
510 CanDrag: Boolean;
511
512 function IsOrthographicTranslation: Boolean;
513 begin
514 Result := (
515 (Operation = voTranslate)
516 and HasWorldTransform
517 and (World <> nil)
518 and (World.MainCamera <> nil)
519 and (World.MainCamera.ProjectionType = ptOrthographic)
520 // TODO: should check world-space direction
521 and (TVector3.Equals(World.MainCamera.Direction, Vector3(0, 0, -1)))
522 );
523 end;
524
525 begin
526 Result := inherited;
527 if Result then Exit;
528
529 { When importing glTF, Blender material name -> X3D Appearance name. }
530 if (Pick.Triangle <> nil) and
531 (Pick.Triangle^.ShapeNode <> nil) and
532 (Pick.Triangle^.ShapeNode.Appearance <> nil) then
533 begin
534 AppearanceName := Pick.Triangle^.ShapeNode.Appearance.X3DName;
535 case AppearanceName of
536 'MaterialX': DraggingCoord := 0;
537 'MaterialY': DraggingCoord := 1;
538 'MaterialZ':
539 begin
540 { In 2D mode dragging Z axis means translate in X and Y. }
541 if IsOrthographicTranslation then
542 DraggingCoord := -2
543 else
544 DraggingCoord := 2;
545 end;
546 'MaterialCenter':
547 begin
548 { In 2D mode dragging center square means translate in X and Y. }
549 if IsOrthographicTranslation then
550 DraggingCoord := -2
551 else if (Operation = voScale) then
552 DraggingCoord := -1;
553 end;
554 else Exit;
555 end;
556
557 if Operation = voRotate then
558 CanDrag := AngleOnPlane(LastPickAngle, Pick, DraggingCoord)
559 else
560 CanDrag := PointOnAxis(LastPick, Pick, DraggingCoord);
561
562 if CanDrag then
563 begin
564 if Operation = voScale then
565 begin
566 { In CameraChanged, we adjust gizmo scale to make it fit within
567 the screen nicely. This way, we actually "nullify" the effect
568 of parent's scale on gizmo size.
569
570 But this has to be disabled within the dragging when scaling,
571 to enable scaling gizmo get smaller/larger as we drag.
572
573 During a single drag, we behave like Scale is constant.
574 Gizmo will be correctly scaled when you release. }
575 GizmoScalingAssumeScale := true;
576 GizmoScalingAssumeScaleValue := Parent.Scale;
577 end;
578 GizmoDragging := true;
579 // keep tracking pointing device events, by TCastleViewport.CapturePointingDevice mechanism
580 Result := true;
581 end;
582 end;
583 end;
584
585 function TVisualizeTransformSelected.TGizmoScene.PointingDeviceMove(
586 const Pick: TRayCollisionNode; const Distance: Single): Boolean;
587 var
588 NewPick, Diff: TVector3;
589 NewPickAngle, DiffAngle: Single;
590 I: Integer;
591 DragSuccess: Boolean;
592 begin
593 Result := inherited;
594 if Result then Exit;
595
596 if GizmoDragging then
597 begin
598 if Operation = voRotate then
599 DragSuccess := AngleOnPlane(NewPickAngle, Pick, DraggingCoord)
600 else
601 DragSuccess := PointOnAxis(NewPick, Pick, DraggingCoord);
602 if DragSuccess then
603 begin
604 {$ifdef DEBUG_GIZMO_PICK}
605 if TCastleControl.MainControl.Pressed[keyShift] then
606 {$endif DEBUG_GIZMO_PICK}
607 case Operation of
608 voTranslate:
609 begin
610 Diff := NewPick - LastPick;
611 { Our gizmo display and interaction is affected by existing
612 Parent.Rotation although the Parent.Translation
613 is applied before rotation technically.
614 So we need to manually multiply Diff by curent rotation. }
615 Diff := RotatePointAroundAxis(Parent.Rotation, Diff);
616 if DraggingCoord >= 0 then
617 { We need to apply only scale in 1 axis,
618 https://forum.castle-engine.io/t/creating-a-non-linear-strategic-adventure/403/22 }
619 Diff := Diff * Parent.Scale[DraggingCoord]
620 else
621 Diff := Diff * Parent.Scale;
622 Parent.Translation := Parent.Translation + Diff;
623 end;
624 voRotate:
625 begin
626 DiffAngle := NewPickAngle - LastPickAngle;
627 Parent.Rotation := (
628 QuatFromAxisAngle(Parent.Rotation) *
629 QuatFromAxisAngle(TVector3.One[DraggingCoord], DiffAngle)).
630 ToAxisAngle;
631 end;
632 voScale:
633 begin
634 for I := 0 to 2 do
635 if IsZero(LastPick[I]) then
636 Diff.Data[I] := 1
637 else
638 Diff.Data[I] := NewPick[I] / LastPick[I];
639 Parent.Scale := Parent.Scale * Diff;
640 end;
641 voSelect:
642 raise EInternalError.Create('TGizmoScene shall never be created with voSelect, ');
643 end;
644
645 { No point in updating LastPick or LastPickAngle:
646 it remains the same, as it is expressed
647 in local coordinate system, which we just changed by changing
648 Parent.Translation. }
649
650 // update our gizmo size, as we moved ourselves
651 UpdateSize;
652 DoParentModified;
653 end;
654 end;
655 end;
656
657 function TVisualizeTransformSelected.TGizmoScene.PointingDeviceRelease(
658 const Pick: TRayCollisionNode; const Distance: Single;
659 const CancelAction: Boolean): Boolean;
660 begin
661 Result := inherited;
662 if Result then Exit;
663
664 GizmoDragging := false;
665
666 if GizmoScalingAssumeScale then
667 begin
668 GizmoScalingAssumeScale := false;
669 UpdateSize;
670 end;
671 DoGizmoStopDrag;
672 end;
673
674 procedure TVisualizeTransformSelected.TGizmoScene.LocalRender(const Params: TRenderParams);
675 var
676 GizmoRendered: Boolean;
677 begin
678 { Similar to TInternalCastleEditorGizmo.LocalRender, do not render when gizmo
679 is over the rendering camera (happens when moving/rotating/scaling
680 the camera that is aligned to view). }
681 LastIsProjectionOrthographic :=
682 (Params.RenderingCamera.Camera <> nil) and
683 (Params.RenderingCamera.Camera.ProjectionType = ptOrthographic);
684 GizmoRendered := TInternalCastleEditorGizmo.ShouldGizmoBeRendered(
685 LastIsProjectionOrthographic,
686 Params.Transformation^.Transform.MultPoint(TVector3.Zero),
687 Params.RenderingCamera.View.Translation
688 );
689 if not GizmoRendered then
690 Exit; // do not show gizmo
691 inherited;
692 end;
693
694 function TVisualizeTransformSelected.TGizmoScene.LocalRayCollision(
695 const RayOrigin, RayDirection: TVector3;
696 const TrianglesToIgnoreFunc: TTriangleIgnoreFunc): TRayCollision;
697 var
698 GizmoRendered: Boolean;
699 begin
700 { Similar to TInternalCastleEditorGizmo.LocalRayCollision, do not collide
701 when gizmo is also hidden. }
702 GizmoRendered := TInternalCastleEditorGizmo.ShouldGizmoBeRendered(
703 LastIsProjectionOrthographic,
704 TVector3.Zero, RayOrigin);
705 if not GizmoRendered then
706 Exit(nil); // do not pick with gizmo with raycast
707
708 Result := inherited;
709
710 { Hack to make picking of the gizmo work even when gizmo is obscured
711 by other TCastleTransform (including bbox of Parent, which is what
712 we actually want to transform).
713 Hacking Distance to be smallest possible means that it "wins"
714 when TCastleTransform.LocalRayCollision desides which collision
715 is first along the ray. }
716 if Result <> nil then
717 Result.Distance := 0;
718 end;
719
720 { TVisualizeTransformSelected ------------------------------------------------------ }
721
722 constructor TVisualizeTransformSelected.Create(AOwner: TComponent);
723
724 function CreateGizmoScene: TGizmoScene;
725 begin
726 Result := TGizmoScene.Create(Self);
727 Result.Collides := false;
728 Result.Pickable := FPickable;
729 Result.CastShadows := false;
730 Result.InternalExcludeFromParentBoundingVolume := true;
731 {$warnings off} // TODO: Change this to Result.PreciseCollisions := true, once tested it equally performs
732 Result.Spatial := [ssDynamicCollisions];
733 {$warnings on}
734 Result.SetTransient;
735 Result.OnParentModified := @GizmoHasModifiedParent;
736 Result.OnGizmoStopDrag := @GizmoStopDrag;
737 end;
738
739 begin
740 inherited;
741 FPickable := true;
742
743 FParentObserver := TFreeNotificationObserver.Create(Self);
744 FParentObserver.OnFreeNotification := {$ifdef FPC}@{$endif} ParentFreeNotification;
745
746 Boxes := TDebugTransformBoxList.Create(true);
747 CreateMoreBoxes;
748
749 // Gizmo[voSelect] remains nil
750 Gizmo[voTranslate] := CreateGizmoScene;
751 Gizmo[voTranslate].Load(InternalCastleDesignData + 'gizmos/transform/translate_final.x3dv');
752 Gizmo[voTranslate].Operation := voTranslate;
753 Gizmo[voRotate] := CreateGizmoScene;
754 Gizmo[voRotate].Load(InternalCastleDesignData + 'gizmos/transform/rotate_final.x3dv');
755 Gizmo[voRotate].Operation := voRotate;
756 Gizmo[voScale] := CreateGizmoScene;
757 Gizmo[voScale].Load(InternalCastleDesignData + 'gizmos/transform/scale_final.x3dv');
758 Gizmo[voScale].Operation := voScale;
759 end;
760
761 destructor TVisualizeTransformSelected.Destroy;
762 begin
763 inherited;
764 end;
765
766 procedure TVisualizeTransformSelected.CreateMoreBoxes;
767 const
768 IncreaseBoxes = 8;
769 var
770 C, I: Integer;
771 begin
772 C := Boxes.Count;
773 Boxes.Count := Boxes.Count + IncreaseBoxes;
774 for I := C to Boxes.Count - 1 do
775 begin
776 Boxes[I] := TDebugTransformBox.Create(Self);
777 Boxes[I].BoxColor := ColorOpacity(ColorSelected, 0.5);
778 Boxes[I].Exists := true;
779 end;
780 end;
781
782 procedure TVisualizeTransformSelected.SetSelectedParents(const Selected: TComponentList);
783 var
784 NextBox, I: Integer;
785 begin
786 NextBox := 0;
787 if Selected <> nil then
788 for I := 0 to Selected.Count - 1 do
789 if Selected[I] is TCastleTransform then
790 begin
791 if NextBox >= Boxes.Count then
792 CreateMoreBoxes;
793 Assert(NextBox < Boxes.Count);
794 Boxes[NextBox].Parent := TCastleTransform(Selected[I]);
795 Inc(NextBox);
796 end;
797
798 { Note: each TDebugTransformBox already observes its Parent,
799 and sets own Parent=nil if the parent is freed.
800 So there's no need to worry about it here anymore. }
801
802 { Detach remaining Boxes from any parent, to not show them }
803 for I := NextBox to Boxes.Count - 1 do
804 Boxes[I].Parent := nil;
805 end;
806
807 procedure TVisualizeTransformSelected.SetParent(const AValue: TCastleTransform);
808 begin
809 if FParent = AValue then Exit;
810
811 if FParent <> nil then
812 begin
813 if Gizmo[Operation] <> nil then
814 FParent.Remove(Gizmo[Operation]);
815 end;
816
817 FParent := AValue;
818 FParentObserver.Observed := AValue;
819
820 if FParent <> nil then
821 begin
822 if Gizmo[Operation] <> nil then
823 FParent.Add(Gizmo[Operation]);
824 end;
825 end;
826
827 procedure TVisualizeTransformSelected.ParentFreeNotification(const Sender: TFreeNotificationObserver);
828 begin
829 Parent := nil;
830 end;
831
832 procedure TVisualizeTransformSelected.SetPickable(const Value: Boolean);
833 var
834 VisualizeOperation: TVisualizeOperation;
835 begin
836 if FPickable <> Value then
837 begin
838 FPickable := Value;
839 for VisualizeOperation in TVisualizeOperation do
840 if Gizmo[VisualizeOperation] <> nil then // Gizmo[voSelect] is nil now, nothing to show
841 Gizmo[VisualizeOperation].Pickable := Value;
842 end;
843 end;
844
845 procedure TVisualizeTransformSelected.GizmoHasModifiedParent(Sender: TObject);
846 begin
847 if Assigned(OnParentModified) then
848 OnParentModified(Self);
849 end;
850
851 procedure TVisualizeTransformSelected.GizmoStopDrag(Sender: TObject);
852 begin
853 if Assigned(OnGizmoStopDrag) then
854 OnGizmoStopDrag(Self);
855 end;
856
857 procedure TVisualizeTransformSelected.SetOperation(const AValue: TVisualizeOperation);
858 begin
859 if FOperation = AValue then Exit;
860
861 if (FParent <> nil) and (Gizmo[Operation] <> nil) then
862 FParent.Remove(Gizmo[Operation]);
863
864 FOperation := AValue;
865
866 if (FParent <> nil) and (Gizmo[Operation] <> nil) then
867 FParent.Add(Gizmo[Operation]);
868 end;
869
870 initialization
871 ColorHover := HexToColor('fffba0'); // desaturated yellow
872 ColorSelected := White;
873 ColorHoverAndSelected := Yellow;
874 end.