/
ViewTool.ts
4549 lines (3844 loc) · 181 KB
/
ViewTool.ts
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 (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Tools
*/
import { BeDuration, BeTimePoint } from "@itwin/core-bentley";
import {
Angle, AngleSweep, Arc3d, AxisOrder, ClipUtilities, Constant, CurveLocationDetail, Geometry, LineString3d, Matrix3d, Plane3dByOriginAndUnitNormal,
Point2d, Point3d, Range2d, Range3d, Ray3d, Transform, Vector2d, Vector3d, XAndY, YawPitchRollAngles,
} from "@itwin/core-geometry";
import { Cartographic, ColorDef, Frustum, LinePixels, NpcCenter } from "@itwin/core-common";
import {
DialogItem, DialogProperty, DialogPropertySyncItem, PropertyDescriptionHelper,
} from "@itwin/appui-abstract";
import { AccuDraw, AccuDrawHintBuilder } from "../AccuDraw";
import { BingLocationProvider } from "../BingLocation";
import { CoordSystem } from "../CoordSystem";
import { IModelApp } from "../IModelApp";
import { LengthDescription } from "../properties/LengthDescription";
import { GraphicType } from "../render/GraphicBuilder";
import { Pixel } from "../render/Pixel";
import { StandardViewId } from "../StandardView";
import { Animator, MarginOptions, OnViewExtentsError, ViewChangeOptions } from "../ViewAnimation";
import { DecorateContext } from "../ViewContext";
import {
eyeToCartographicOnGlobeFromGcs, GlobalLocation, queryTerrainElevationOffset, rangeToCartographicArea, viewGlobalLocation,
ViewGlobalLocationConstants,
} from "../ViewGlobalLocation";
import { DepthPointSource, ScreenViewport, Viewport } from "../Viewport";
import { ViewPose } from "../ViewPose";
import { ViewRect } from "../common/ViewRect";
import { ViewState3d } from "../ViewState";
import { ViewStatus } from "../ViewStatus";
import { EditManipulator } from "./EditManipulator";
import { PrimitiveTool } from "./PrimitiveTool";
import {
BeButton, BeButtonEvent, BeModifierKeys, BeTouchEvent, BeWheelEvent, CoordSource, CoreTools, EventHandled, InputSource, InteractiveTool,
} from "./Tool";
import { ToolAssistance, ToolAssistanceImage, ToolAssistanceInputMethod, ToolAssistanceInstruction, ToolAssistanceSection } from "./ToolAssistance";
import { ToolSettings } from "./ToolSettings";
// cspell:ignore wasd, arrowright, arrowleft, pagedown, pageup, arrowup, arrowdown
/* eslint-disable no-restricted-syntax */
/** @internal */
const enum ViewHandleWeight {
Thin = 1,
Normal = 2,
Bold = 3,
VeryBold = 4,
FatDot = 8,
}
/** @internal */
export enum ViewHandleType {
None = 0,
Rotate = 1,
TargetCenter = 1 << 1,
Pan = 1 << 2,
Scroll = 1 << 3,
Zoom = 1 << 4,
Walk = 1 << 5,
Fly = 1 << 6,
Look = 1 << 7,
LookAndMove = 1 << 8,
}
/** @internal */
const enum ViewManipPriority {
Low = 1,
Normal = 10,
Medium = 100,
High = 1000,
}
const enum NavigateMode { Pan = 0, Look = 1, Travel = 2 }
/* eslint-enable no-restricted-syntax */
// dampen an inertia vector according to tool settings
const inertialDampen = (pt: Vector3d) => {
pt.scaleInPlace(Geometry.clamp(ToolSettings.viewingInertia.damping, .75, .999));
};
/** An InteractiveTool that manipulates a view.
* @public
* @extensions
*/
export abstract class ViewTool extends InteractiveTool {
public static translate(val: string) { return CoreTools.translate(`View.${val}`); }
public inDynamicUpdate = false;
public beginDynamicUpdate() { this.inDynamicUpdate = true; }
public endDynamicUpdate() { this.inDynamicUpdate = false; }
public override async run(..._args: any[]): Promise<boolean> {
const toolAdmin = IModelApp.toolAdmin;
if (undefined !== this.viewport && this.viewport === toolAdmin.markupView) {
IModelApp.notifications.outputPromptByKey("iModelJs:Viewing.NotDuringMarkup");
return false;
}
if (!await toolAdmin.onInstallTool(this))
return false;
await toolAdmin.startViewTool(this);
await toolAdmin.onPostInstallTool(this);
return true;
}
public constructor(public viewport?: ScreenViewport) {
super();
}
public override async onResetButtonUp(_ev: BeButtonEvent) {
await this.exitTool();
return EventHandled.Yes;
}
/** Do not override. */
public async exitTool() { return IModelApp.toolAdmin.exitViewTool(); }
public static showPrompt(prompt: string) {
IModelApp.notifications.outputPrompt(ViewTool.translate(prompt));
}
}
/** @internal */
export abstract class ViewingToolHandle {
protected readonly _lastPtNpc = new Point3d();
protected _depthPoint?: Point3d;
constructor(public viewTool: ViewManip) {
this._depthPoint = undefined;
}
public onReinitialize(): void { }
public onCleanup(): void { }
public focusOut(): void { }
public motion(_ev: BeButtonEvent): boolean { return false; }
public checkOneShot(): boolean { return true; }
public getHandleCursor(): string { return "default"; }
public abstract doManipulation(ev: BeButtonEvent, inDynamics: boolean): boolean;
public abstract firstPoint(ev: BeButtonEvent): boolean;
public abstract testHandleForHit(ptScreen: Point3d, out: { distance: number, priority: ViewManipPriority }): boolean;
public abstract get handleType(): ViewHandleType;
public focusIn(): void { IModelApp.toolAdmin.setCursor(this.getHandleCursor()); }
public drawHandle(_context: DecorateContext, _hasFocus: boolean): void { }
public onWheel(_ev: BeWheelEvent): boolean { return false; }
public onTouchStart(_ev: BeTouchEvent): boolean { return false; }
public onTouchEnd(_ev: BeTouchEvent): boolean { return false; }
public async onTouchComplete(_ev: BeTouchEvent): Promise<boolean> { return false; }
public async onTouchCancel(_ev: BeTouchEvent): Promise<boolean> { return false; }
public onTouchMove(_ev: BeTouchEvent): boolean { return false; }
public onTouchMoveStart(_ev: BeTouchEvent, _startEv: BeTouchEvent): boolean { return false; }
public onTouchTap(_ev: BeTouchEvent): boolean { return false; }
public onKeyTransition(_wentDown: boolean, _keyEvent: KeyboardEvent): boolean { return false; }
public onModifierKeyTransition(_wentDown: boolean, _modifier: BeModifierKeys, _event: KeyboardEvent): boolean { return false; }
public needDepthPoint(_ev: BeButtonEvent, _isPreview: boolean): boolean { return false; }
public adjustDepthPoint(isValid: boolean, _vp: Viewport, _plane: Plane3dByOriginAndUnitNormal, source: DepthPointSource): boolean {
switch (source) {
case DepthPointSource.Geometry:
case DepthPointSource.Model:
case DepthPointSource.BackgroundMap:
case DepthPointSource.GroundPlane:
case DepthPointSource.Grid:
case DepthPointSource.Map:
return isValid; // Sources with visible geometry/graphics are considered valid by default...
default:
return false; // Sources without visible geometry/graphics are NOT considered valid by default...
}
}
protected pickDepthPoint(ev: BeButtonEvent) {
this._depthPoint = this.viewTool.pickDepthPoint(ev);
}
// if we have a valid depth point, set the focus distance to
protected changeFocusFromDepthPoint() {
if (undefined !== this._depthPoint) {
const view = this.viewTool.viewport!.view;
if (view.is3d() && view.isCameraOn)
view.changeFocusFromPoint(this._depthPoint); // set the focus distance to the depth point
}
}
}
/** @internal */
export class ViewHandleArray {
public handles: ViewingToolHandle[] = [];
public focus = -1;
public focusDrag = false;
public hitHandleIndex = 0;
constructor(public viewTool: ViewManip) { }
public empty() {
this.focus = -1;
this.focusDrag = false;
this.hitHandleIndex = -1; // setting to -1 will result in onReinitialize getting called before testHit which sets the hit index
this.handles.length = 0;
}
public get count(): number { return this.handles.length; }
public get hitHandle(): ViewingToolHandle | undefined { return this.getByIndex(this.hitHandleIndex); }
public get focusHandle(): ViewingToolHandle | undefined { return this.getByIndex(this.focus); }
public add(handle: ViewingToolHandle): void { this.handles.push(handle); }
public getByIndex(index: number): ViewingToolHandle | undefined { return (index >= 0 && index < this.count) ? this.handles[index] : undefined; }
public focusHitHandle(): void { this.setFocus(this.hitHandleIndex); }
public testHit(ptScreen: Point3d, forced = ViewHandleType.None): boolean {
this.hitHandleIndex = -1;
const data = { distance: 0.0, priority: ViewManipPriority.Normal };
let minDistance = 0.0;
let minDistValid = false;
let highestPriority = ViewManipPriority.Low;
let nearestHitHandle: ViewingToolHandle | undefined;
for (let i = 0; i < this.count; i++) {
data.priority = ViewManipPriority.Normal;
const handle = this.handles[i];
if (forced) {
if (handle.handleType === forced) {
this.hitHandleIndex = i;
return true;
}
} else if (handle.testHandleForHit(ptScreen, data)) {
if (data.priority >= highestPriority) {
if (data.priority > highestPriority)
minDistValid = false;
highestPriority = data.priority;
if (!minDistValid || (data.distance < minDistance)) {
minDistValid = true;
minDistance = data.distance;
nearestHitHandle = handle;
this.hitHandleIndex = i;
}
}
}
}
return undefined !== nearestHitHandle;
}
public drawHandles(context: DecorateContext): void {
if (0 === this.count)
return;
// all handle objects must draw themselves
for (let i = 0; i < this.count; ++i) {
if (i !== this.hitHandleIndex) {
const handle = this.handles[i];
handle.drawHandle(context, this.focus === i);
}
}
// draw the hit handle last
if (-1 !== this.hitHandleIndex) {
const handle = this.handles[this.hitHandleIndex];
handle.drawHandle(context, this.focus === this.hitHandleIndex);
}
}
public setFocus(index: number): void {
if (this.focus === index && (this.focusDrag === this.viewTool.inHandleModify))
return;
let focusHandle: ViewingToolHandle | undefined;
if (this.focus >= 0) {
focusHandle = this.getByIndex(this.focus);
if (focusHandle)
focusHandle.focusOut();
}
if (index >= 0) {
focusHandle = this.getByIndex(index);
if (focusHandle)
focusHandle.focusIn();
}
this.focus = index;
this.focusDrag = this.viewTool.inHandleModify;
const vp = this.viewTool.viewport;
if (undefined !== vp)
vp.invalidateDecorations();
}
public onReinitialize(): void { this.handles.forEach((handle) => handle.onReinitialize()); }
public onCleanup(): void { this.handles.forEach((handle) => handle.onCleanup()); }
public motion(ev: BeButtonEvent): void { this.handles.forEach((handle) => handle.motion(ev)); }
public onWheel(ev: BeWheelEvent): boolean {
let preventDefault = false;
this.handles.forEach((handle) => {
if (handle.onWheel(ev))
preventDefault = true;
});
return preventDefault;
}
/** determine whether a handle of a specific type exists */
public hasHandle(handleType: ViewHandleType): boolean { return this.handles.some((handle) => handle.handleType === handleType); }
}
/** Base class for tools that manipulate the frustum of a Viewport.
* @public
* @extensions
*/
export abstract class ViewManip extends ViewTool {
/** @internal */
public viewHandles: ViewHandleArray;
public frustumValid = false; // unused
public readonly targetCenterWorld = new Point3d();
public inHandleModify = false;
public isDragging = false;
public targetCenterValid = false;
public targetCenterLocked = false;
public nPts = 0;
/** @internal */
public forcedHandle = ViewHandleType.None;
/** @internal */
protected _depthPreview?: { testPoint: Point3d, pickRadius: number, plane: Plane3dByOriginAndUnitNormal, source: DepthPointSource, isDefaultDepth: boolean, sourceId?: string };
/** @internal */
protected _startPose?: ViewPose;
constructor(viewport: ScreenViewport | undefined, public handleMask: number, public oneShot: boolean, public isDraggingRequired: boolean = false) {
super(viewport);
this.viewHandles = new ViewHandleArray(this);
this.changeViewport(viewport);
}
public override decorate(context: DecorateContext): void {
this.viewHandles.drawHandles(context);
this.previewDepthPoint(context);
}
/** @internal */
public previewDepthPoint(context: DecorateContext): void {
if (undefined === this._depthPreview)
return;
const cursorVp = IModelApp.toolAdmin.cursorView;
if (cursorVp !== context.viewport)
return;
let origin = this._depthPreview.plane.getOriginRef();
let normal = this._depthPreview.plane.getNormalRef();
if (this._depthPreview.isDefaultDepth) {
origin = cursorVp.worldToView(origin);
origin.z = 0.0;
cursorVp.viewToWorld(origin, origin); // Avoid getting clipped out in z...
normal = context.viewport.view.getZVector(); // Always draw circle for invalid depth point oriented to view...
}
const pixelSize = context.viewport.getPixelSizeAtPoint(origin);
const skew = context.viewport.view.getAspectRatioSkew();
const radius = this._depthPreview.pickRadius * pixelSize;
const rMatrix = Matrix3d.createRigidHeadsUp(normal);
const ellipse = Arc3d.createScaledXYColumns(origin, rMatrix, radius, radius / skew, AngleSweep.create360());
const colorBase = (this._depthPreview.isDefaultDepth ? ColorDef.red : (DepthPointSource.Geometry === this._depthPreview.source ? ColorDef.green : context.viewport.hilite.color));
const colorLine = EditManipulator.HandleUtils.adjustForBackgroundColor(colorBase, cursorVp).withTransparency(50);
const colorFill = colorLine.withTransparency(200);
const builder = context.createGraphicBuilder(GraphicType.WorldOverlay);
builder.setSymbology(colorLine, colorFill, 1, this._depthPreview.isDefaultDepth ? LinePixels.Code2 : LinePixels.Solid);
builder.addArc(ellipse, true, true);
builder.addArc(ellipse, false, false);
context.addDecorationFromBuilder(builder);
ViewTargetCenter.drawCross(context, origin, this._depthPreview.pickRadius * 0.5, false);
}
/** @internal */
public getDepthPointGeometryId(): string | undefined {
if (undefined === this._depthPreview)
return undefined;
return (DepthPointSource.Geometry === this._depthPreview.source ? this._depthPreview.sourceId : undefined);
}
/** @internal */
public clearDepthPoint(): boolean {
if (undefined === this._depthPreview)
return false;
this._depthPreview = undefined;
return true;
}
/** @internal */
public pickDepthPoint(ev: BeButtonEvent, isPreview: boolean = false): Point3d | undefined {
if (!isPreview && ev.viewport && undefined !== this.getDepthPointGeometryId())
ev.viewport.flashedId = undefined;
this.clearDepthPoint();
if (isPreview && this.inDynamicUpdate)
return undefined;
const vp = ev.viewport;
if (undefined === vp || undefined === this.viewHandles.hitHandle || !this.viewHandles.hitHandle.needDepthPoint(ev, isPreview))
return undefined;
const pickRadiusPixels = vp.pixelsFromInches(ToolSettings.viewToolPickRadiusInches);
const result = vp.pickDepthPoint(ev.rawPoint, pickRadiusPixels);
let isValidDepth = false;
switch (result.source) {
case DepthPointSource.Geometry:
case DepthPointSource.Model:
case DepthPointSource.Map:
isValidDepth = true;
break;
case DepthPointSource.BackgroundMap:
case DepthPointSource.GroundPlane:
case DepthPointSource.Grid:
case DepthPointSource.ACS:
case DepthPointSource.TargetPoint:
const npcPt = vp.worldToNpc(result.plane.getOriginRef());
isValidDepth = !(npcPt.z < 0.0 || npcPt.z > 1.0);
break;
}
// Allow handle to reject depth depending on source and to set a default depth point when invalid...
isValidDepth = this.viewHandles.hitHandle.adjustDepthPoint(isValidDepth, vp, result.plane, result.source);
if (isPreview)
this._depthPreview = { testPoint: ev.rawPoint, pickRadius: pickRadiusPixels, plane: result.plane, source: result.source, isDefaultDepth: !isValidDepth, sourceId: result.sourceId };
return (isValidDepth || isPreview ? result.plane.getOriginRef() : undefined);
}
public override async onReinitialize() {
if (undefined !== this.viewport) {
this.viewport.synchWithView(); // make sure we store any changes in view undo buffer.
this.viewHandles.setFocus(-1);
}
this.nPts = 0;
this.inHandleModify = false;
this.inDynamicUpdate = false;
this._startPose = undefined;
this.viewHandles.onReinitialize();
}
public override async onDataButtonDown(ev: BeButtonEvent): Promise<EventHandled> {
// Tool was started in "drag required" mode, don't advance tool state and wait to see if we get the start drag event.
if ((0 === this.nPts && this.isDraggingRequired && !this.isDragging) || undefined === ev.viewport)
return EventHandled.No;
switch (this.nPts) {
case 0:
this.changeViewport(ev.viewport);
if (this.processFirstPoint(ev))
this.nPts = 1;
break;
case 1:
this.nPts = 2;
break;
}
if (this.nPts > 1) {
this.inDynamicUpdate = false;
if (this.processPoint(ev, false) && this.oneShot)
await this.exitTool();
else
await this.onReinitialize();
}
return EventHandled.Yes;
}
public override async onDataButtonUp(_ev: BeButtonEvent): Promise<EventHandled> {
if (this.nPts <= 1 && this.isDraggingRequired && !this.isDragging && this.oneShot)
await this.exitTool();
return EventHandled.No;
}
public override async onMouseWheel(inputEv: BeWheelEvent): Promise<EventHandled> {
const ev = inputEv.clone();
if (this.viewHandles.onWheel(ev)) // notify handles that wheel has rolled.
return EventHandled.Yes;
await IModelApp.toolAdmin.processWheelEvent(ev, false);
return EventHandled.Yes;
}
/** @internal */
public async startHandleDrag(ev: BeButtonEvent, forcedHandle?: ViewHandleType): Promise<EventHandled> {
if (this.inHandleModify)
return EventHandled.No; // If already changing the view reject the request...
if (undefined !== forcedHandle) {
if (!this.viewHandles.hasHandle(forcedHandle))
return EventHandled.No; // If requested handle isn't present reject the request...
this.forcedHandle = forcedHandle;
}
this.receivedDownEvent = true; // Request up events even though we may not have gotten the down event...
this.isDragging = true;
if (0 === this.nPts)
await this.onDataButtonDown(ev);
return EventHandled.Yes;
}
public override async onMouseStartDrag(ev: BeButtonEvent): Promise<EventHandled> {
if (BeButton.Data !== ev.button)
return EventHandled.No;
return this.startHandleDrag(ev);
}
public override async onMouseEndDrag(ev: BeButtonEvent): Promise<EventHandled> {
// NOTE: To support startHandleDrag being called by IdleTool for middle button drag, check inHandleModify and not the button type...
if (!this.inHandleModify)
return EventHandled.No;
this.isDragging = false;
return (0 === this.nPts) ? EventHandled.Yes : this.onDataButtonDown(ev);
}
public override async onMouseMotion(ev: BeButtonEvent) {
if (0 === this.nPts && this.viewHandles.testHit(ev.viewPoint))
this.viewHandles.focusHitHandle();
if (0 !== this.nPts)
this.processPoint(ev, true);
this.viewHandles.motion(ev);
const prevSourceId = this.getDepthPointGeometryId();
const showDepthChanged = (undefined !== this.pickDepthPoint(ev, true) || this.clearDepthPoint());
if (ev.viewport && (showDepthChanged || prevSourceId)) {
const currSourceId = this.getDepthPointGeometryId();
if (currSourceId !== prevSourceId)
ev.viewport.flashedId = currSourceId;
ev.viewport.invalidateDecorations();
}
}
public override async onTouchStart(ev: BeTouchEvent): Promise<void> {
if (0 === this.nPts && this.viewHandles.testHit(ev.viewPoint))
this.viewHandles.focusHitHandle();
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle)
focusHandle.onTouchStart(ev);
}
public override async onTouchEnd(ev: BeTouchEvent): Promise<void> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle)
focusHandle.onTouchEnd(ev);
}
public override async onTouchComplete(ev: BeTouchEvent): Promise<void> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle && await focusHandle.onTouchComplete(ev))
return;
if (this.inHandleModify)
return IModelApp.toolAdmin.convertTouchEndToButtonUp(ev);
}
public override async onTouchCancel(ev: BeTouchEvent): Promise<void> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle && await focusHandle.onTouchCancel(ev))
return;
if (this.inHandleModify)
return IModelApp.toolAdmin.convertTouchEndToButtonUp(ev, BeButton.Reset);
}
public override async onTouchMove(ev: BeTouchEvent): Promise<void> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle && focusHandle.onTouchMove(ev))
return;
if (this.inHandleModify)
return IModelApp.toolAdmin.convertTouchMoveToMotion(ev);
}
public override async onTouchMoveStart(ev: BeTouchEvent, startEv: BeTouchEvent): Promise<EventHandled> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle && focusHandle.onTouchMoveStart(ev, startEv))
return EventHandled.Yes;
if (!this.inHandleModify && startEv.isSingleTouch)
await IModelApp.toolAdmin.convertTouchMoveStartToButtonDownAndMotion(startEv, ev);
return this.inHandleModify ? EventHandled.Yes : EventHandled.No;
}
public override async onTouchTap(ev: BeTouchEvent): Promise<EventHandled> {
const focusHandle = this.viewHandles.focusHandle;
if (undefined !== focusHandle && focusHandle.onTouchTap(ev))
return EventHandled.Yes;
return ev.isSingleTap ? EventHandled.Yes : EventHandled.No; // Prevent IdleTool from converting single tap into data button down/up...
}
public override async onKeyTransition(wentDown: boolean, keyEvent: KeyboardEvent): Promise<EventHandled> {
const focusHandle = this.viewHandles.focusHandle;
return (undefined !== focusHandle && focusHandle.onKeyTransition(wentDown, keyEvent) ? EventHandled.Yes : EventHandled.No);
}
public override async onModifierKeyTransition(wentDown: boolean, modifier: BeModifierKeys, event: KeyboardEvent): Promise<EventHandled> {
const focusHandle = this.viewHandles.focusHandle;
return (undefined !== focusHandle && focusHandle.onModifierKeyTransition(wentDown, modifier, event) ? EventHandled.Yes : EventHandled.No);
}
public override async onPostInstall() {
await super.onPostInstall();
await this.onReinitialize(); // Call onReinitialize now that tool is installed.
}
/** @beta */
public provideToolAssistance(mainInstrKey: string, additionalInstr?: ToolAssistanceInstruction[]): void {
const mainInstruction = ToolAssistance.createInstruction(this.iconSpec, ViewTool.translate(mainInstrKey));
const mouseInstructions: ToolAssistanceInstruction[] = [];
const touchInstructions: ToolAssistanceInstruction[] = [];
const acceptMsg = CoreTools.translate("ElementSet.Inputs.AcceptPoint");
const rejectMsg = CoreTools.translate("ElementSet.Inputs.Exit");
touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.OneTouchDrag, acceptMsg, false, ToolAssistanceInputMethod.Touch));
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.LeftClick, acceptMsg, false, ToolAssistanceInputMethod.Mouse));
touchInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.TwoTouchTap, rejectMsg, false, ToolAssistanceInputMethod.Touch));
mouseInstructions.push(ToolAssistance.createInstruction(ToolAssistanceImage.RightClick, rejectMsg, false, ToolAssistanceInputMethod.Mouse));
if (undefined !== additionalInstr) {
for (const instr of additionalInstr) {
if (ToolAssistanceInputMethod.Touch === instr.inputMethod)
touchInstructions.push(instr);
else
mouseInstructions.push(instr);
}
}
const sections: ToolAssistanceSection[] = [];
sections.push(ToolAssistance.createSection(mouseInstructions, ToolAssistance.inputsLabel));
sections.push(ToolAssistance.createSection(touchInstructions, ToolAssistance.inputsLabel));
const instructions = ToolAssistance.createInstructions(mainInstruction, sections);
IModelApp.notifications.setToolAssistance(instructions);
}
public override async onCleanup() {
let restorePrevious = false;
if (this.inDynamicUpdate) {
this.endDynamicUpdate();
restorePrevious = true;
}
const vp = this.viewport;
if (undefined !== vp) {
if (restorePrevious && this._startPose) {
vp.view.applyPose(this._startPose);
vp.animateFrustumChange();
} else {
vp.synchWithView();
}
vp.invalidateDecorations();
}
this.viewHandles.onCleanup();
this.viewHandles.empty();
}
/**
* Set the center of rotation for rotate handle.
* @param pt the new target point in world coordinates
* @param lockTarget consider the target point locked for this tool instance
* @param saveTarget save this target point for use between tool instances
*/
public setTargetCenterWorld(pt: Point3d, lockTarget: boolean, saveTarget: boolean) {
this.targetCenterWorld.setFrom(pt);
this.targetCenterValid = true;
this.targetCenterLocked = lockTarget;
if (!this.viewport)
return;
if (!this.viewport.view.allow3dManipulations())
this.targetCenterWorld.z = 0.0;
this.viewport.viewCmdTargetCenter = (saveTarget ? pt : undefined);
}
public updateTargetCenter(): void {
const vp = this.viewport;
if (!vp)
return;
if (this.targetCenterValid) {
if (this.inHandleModify)
return;
if (IModelApp.tentativePoint.isActive) {
let tentPt = IModelApp.tentativePoint.getPoint();
if (!IModelApp.tentativePoint.isSnapped) {
if (undefined === this._depthPreview && this.targetCenterLocked) {
const ev = new BeButtonEvent();
IModelApp.toolAdmin.fillEventFromCursorLocation(ev);
this.targetCenterLocked = false; // Depth preview won't be active (or requested) if target is currently locked...
this.pickDepthPoint(ev, true);
}
if (undefined !== this._depthPreview && !this._depthPreview.isDefaultDepth)
tentPt = this._depthPreview.plane.getOriginRef(); // Prefer valid depth preview point to unsnapped tentative location...
}
this.setTargetCenterWorld(tentPt, true, false);
IModelApp.tentativePoint.clear(true); // Clear tentative, there won't be a datapoint to accept...
}
return;
}
if (IModelApp.tentativePoint.isActive)
return this.setTargetCenterWorld(IModelApp.tentativePoint.getPoint(), true, false);
if (vp.viewCmdTargetCenter && this.isPointVisible(vp.viewCmdTargetCenter))
return this.setTargetCenterWorld(vp.viewCmdTargetCenter, true, true);
return this.setTargetCenterWorld(ViewManip.getDefaultTargetPointWorld(vp), false, false);
}
public processFirstPoint(ev: BeButtonEvent) {
const forcedHandle = this.forcedHandle;
this.forcedHandle = ViewHandleType.None;
if (this.viewHandles.testHit(ev.viewPoint, forcedHandle)) {
this.inHandleModify = true;
this.viewHandles.focusHitHandle();
const handle = this.viewHandles.hitHandle;
if (undefined !== handle && !handle.firstPoint(ev))
return false;
}
this._startPose = this.viewport ? this.viewport.view.savePose() : undefined;
return true;
}
public processPoint(ev: BeButtonEvent, inDynamics: boolean) {
const hitHandle = this.viewHandles.hitHandle;
if (undefined === hitHandle)
return true;
const doUpdate = hitHandle.doManipulation(ev, inDynamics);
return inDynamics || (doUpdate && hitHandle.checkOneShot());
}
public lensAngleMatches(angle: Angle, tolerance: number): boolean {
const cameraView = this.viewport!.view;
return !cameraView.is3d() ? false : Math.abs(cameraView.calcLensAngle().radians - angle.radians) < tolerance;
}
public get isZUp() {
const view = this.viewport!.view;
const viewX = view.getXVector();
const viewY = view.getXVector();
const zVec = Vector3d.unitZ();
return (Math.abs(zVec.dotProduct(viewY)) > 0.99 && Math.abs(zVec.dotProduct(viewX)) < 0.01);
}
public static getFocusPlaneNpc(vp: Viewport): number {
const pt = vp.worldToNpc(vp.view.getTargetPoint());
return (pt.z < 0.0 || pt.z > 1.0) ? 0.5 : pt.z;
}
public static getDefaultTargetPointWorld(vp: Viewport): Point3d {
if (!vp.view.allow3dManipulations())
return vp.npcToWorld(NpcCenter);
const targetPoint = vp.view.getTargetPoint();
const targetPointNpc = vp.worldToNpc(targetPoint);
if (targetPointNpc.z < 0.0 || targetPointNpc.z > 1.0) {
targetPointNpc.z = 0.5;
vp.npcToWorld(targetPointNpc, targetPoint);
}
return targetPoint;
}
/** Determine whether the supplied point is visible in this Viewport. */
public isPointVisible(testPt: Point3d): boolean {
const vp = this.viewport;
if (!vp)
return false;
return vp.isPointVisibleXY(testPt);
}
/** @internal */
public static computeFitRange(viewport: ScreenViewport): Range3d {
const range = viewport.computeViewRange();
const clip = (viewport.viewFlags.clipVolume ? viewport.view.getViewClip() : undefined);
if (undefined !== clip) {
const clipRange = ClipUtilities.rangeOfClipperIntersectionWithRange(clip, range);
if (!clipRange.isNull)
range.setFrom(clipRange);
}
return range;
}
public static fitView(viewport: ScreenViewport, animateFrustumChange: boolean, options?: ViewChangeOptions & MarginOptions) {
const range = this.computeFitRange(viewport);
const aspect = viewport.viewRect.aspect;
viewport.view.lookAtVolume(range, aspect, options);
viewport.synchWithView({ animateFrustumChange });
viewport.viewCmdTargetCenter = undefined;
}
/** @internal */
public static fitViewWithGlobeAnimation(viewport: ScreenViewport, animateFrustumChange: boolean, options?: ViewChangeOptions & MarginOptions) {
const range = this.computeFitRange(viewport);
if (viewport.view.isSpatialView() && animateFrustumChange && (viewport.viewingGlobe || !viewport.view.getIsViewingProject())) {
const cartographicCenter = viewport.view.rootToCartographic(range.center);
if (undefined !== cartographicCenter) {
const cartographicArea = rangeToCartographicArea(viewport.view, range);
(async () => {
await viewport.animateFlyoverToGlobalLocation({ center: cartographicCenter, area: cartographicArea }); // NOTE: Turns on camera...which is why we checked that it was already on...
viewport.viewCmdTargetCenter = undefined;
})().catch(() => { });
return;
}
}
const aspect = viewport.viewRect.aspect;
viewport.view.lookAtVolume(range, aspect, options);
viewport.synchWithView({ animateFrustumChange });
viewport.viewCmdTargetCenter = undefined;
}
public static async zoomToAlwaysDrawnExclusive(viewport: ScreenViewport, options?: ViewChangeOptions & MarginOptions): Promise<boolean> {
if (!viewport.isAlwaysDrawnExclusive || undefined === viewport.alwaysDrawn || 0 === viewport.alwaysDrawn.size)
return false;
await viewport.zoomToElements(viewport.alwaysDrawn, options);
return true;
}
public setCameraLensAngle(lensAngle: Angle, retainEyePoint: boolean): ViewStatus {
const vp = this.viewport;
if (!vp)
return ViewStatus.InvalidViewport;
const view = vp.view;
if (!view.is3d() || !view.allow3dManipulations())
return ViewStatus.InvalidViewport;
const result = (retainEyePoint && view.isCameraOn) ?
view.lookAt({ eyePoint: view.getEyePoint(), targetPoint: view.getTargetPoint(), upVector: view.getYVector(), lensAngle }) :
vp.turnCameraOn(lensAngle);
if (result !== ViewStatus.Success)
return result;
vp.setupFromView();
return ViewStatus.Success;
}
public enforceZUp(pivotPoint: Point3d) {
const vp = this.viewport;
if (!vp || this.isZUp)
return false;
const viewY = vp.view.getYVector();
const rotMatrix = Matrix3d.createRotationVectorToVector(viewY, Vector3d.unitZ());
if (!rotMatrix)
return false;
const transform = Transform.createFixedPointAndMatrix(pivotPoint, rotMatrix);
const frust = vp.getWorldFrustum();
frust.multiply(transform);
vp.setupViewFromFrustum(frust);
return true;
}
public changeViewport(vp?: ScreenViewport): void {
if (vp === this.viewport && 0 !== this.viewHandles.count) // If viewport isn't really changing do nothing...
return;
if (this.viewport)
this.viewport.invalidateDecorations(); // Remove decorations from current viewport...
this.viewport = vp;
this.targetCenterValid = false;
if (this.handleMask & (ViewHandleType.Rotate | ViewHandleType.TargetCenter))
this.updateTargetCenter();
this.viewHandles.empty();
if (this.handleMask & ViewHandleType.Rotate)
this.viewHandles.add(new ViewRotate(this));
if (this.handleMask & ViewHandleType.TargetCenter)
this.viewHandles.add(new ViewTargetCenter(this));
if (this.handleMask & ViewHandleType.Pan)
this.viewHandles.add(new ViewPan(this));
if (this.handleMask & ViewHandleType.Scroll)
this.viewHandles.add(new ViewScroll(this));
if (this.handleMask & ViewHandleType.Zoom)
this.viewHandles.add(new ViewZoom(this));
if (this.handleMask & ViewHandleType.Walk)
this.viewHandles.add(new ViewWalk(this));
if (this.handleMask & ViewHandleType.Fly)
this.viewHandles.add(new ViewFly(this));
if (this.handleMask & ViewHandleType.Look)
this.viewHandles.add(new ViewLook(this));
if (this.handleMask & ViewHandleType.LookAndMove)
this.viewHandles.add(new ViewLookAndMove(this));
}
}
/** ViewingToolHandle for modifying the view's target point for operations like rotate */
class ViewTargetCenter extends ViewingToolHandle {
public get handleType() { return ViewHandleType.TargetCenter; }
public override checkOneShot(): boolean { return false; } // Don't exit tool after moving target in single-shot mode...
public firstPoint(ev: BeButtonEvent) {
if (undefined === ev.viewport)
return false;
ev.viewport.viewCmdTargetCenter = undefined; // Clear current saved target, must accept a new location with ctrl...
return true;
}
public testHandleForHit(ptScreen: Point3d, out: { distance: number, priority: ViewManipPriority }): boolean {
if (this.viewTool.isDraggingRequired)
return false; // Target center handle is not movable in this mode, but it's still nice to display the point we're rotating about...
const targetPt = this.viewTool.viewport!.worldToView(this.viewTool.targetCenterWorld);
const distance = targetPt.distanceXY(ptScreen);
const locateThreshold = this.viewTool.viewport!.pixelsFromInches(0.15);
if (distance > locateThreshold)
return false;
out.distance = distance;
out.priority = ViewManipPriority.High;
return true;
}
/** @internal */
public static drawCross(context: DecorateContext, worldPoint: Point3d, sizePixels: number, hasFocus: boolean): void {
const crossSize = Math.floor(sizePixels) + 0.5;
const outlineSize = crossSize + 1;
const position = context.viewport.worldToView(worldPoint);
position.x = Math.floor(position.x) + 0.5;
position.y = Math.floor(position.y) + 0.5;
const drawDecoration = (ctx: CanvasRenderingContext2D) => {
ctx.beginPath();
ctx.strokeStyle = "rgba(0,0,0,.5)";
ctx.lineWidth = hasFocus ? 5 : 3;
ctx.moveTo(-outlineSize, 0);
ctx.lineTo(outlineSize, 0);
ctx.moveTo(0, -outlineSize);
ctx.lineTo(0, outlineSize);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = "white";
ctx.lineWidth = hasFocus ? 3 : 1;
ctx.shadowColor = "black";
ctx.shadowBlur = hasFocus ? 7 : 5;
ctx.moveTo(-crossSize, 0);
ctx.lineTo(crossSize, 0);
ctx.moveTo(0, -crossSize);
ctx.lineTo(0, crossSize);
ctx.stroke();
};
context.addCanvasDecoration({ position, drawDecoration });
}
public override drawHandle(context: DecorateContext, hasFocus: boolean): void {
if (context.viewport !== this.viewTool.viewport)
return;
if (!this.viewTool.targetCenterLocked && !this.viewTool.inHandleModify)
return; // Don't display default target center, will be updated to use pick point on element...
if (hasFocus && this.viewTool.inHandleModify)
return; // Cross display handled by preview depth point...
let sizeInches = 0.2;
if (!hasFocus && this.viewTool.inHandleModify) {
const hitHandle = this.viewTool.viewHandles.hitHandle;
if (undefined !== hitHandle && ViewHandleType.Rotate !== hitHandle.handleType)
return; // Only display when modifying another handle if that handle is rotate (not pan)...
sizeInches = 0.1; // Display small target when dragging...
}
const crossSize = context.viewport.pixelsFromInches(sizeInches);
ViewTargetCenter.drawCross(context, this.viewTool.targetCenterWorld, crossSize, hasFocus);
}
public doManipulation(ev: BeButtonEvent, inDynamics: boolean) {
if (inDynamics || ev.viewport !== this.viewTool.viewport)
return false;
this.pickDepthPoint(ev);
this.viewTool.setTargetCenterWorld(undefined !== this._depthPoint ? this._depthPoint : ev.point, true, ev.isControlKey); // Lock target for just this tool instance, only save if control is down...
return false; // false means don't do screen update
}