-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathbehavior.ts
More file actions
490 lines (412 loc) · 15.2 KB
/
behavior.ts
File metadata and controls
490 lines (412 loc) · 15.2 KB
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
import { distance2BetweenPoints } from '@kitware/vtk.js/Common/Core/Math';
import macro from '@kitware/vtk.js/macros';
import type { Vector3 } from '@kitware/vtk.js/types';
import vtkRenderer from '@kitware/vtk.js/Rendering/Core/Renderer';
import { WidgetAction } from '@/src/vtk/ToolWidgetUtils/types';
import { computeWorldCoords } from '@/src/vtk/ToolWidgetUtils/utils';
type Position3d = { x: number; y: number; z: number };
type vtkMouseEvent = {
position: Position3d;
pokedRenderer: vtkRenderer;
};
const FINISHABLE_DISTANCE = 10;
const FINISHABLE_DISTANCE_SQUARED = FINISHABLE_DISTANCE ** 2;
const DOUBLE_CLICK_TIMEOUT = 300; // milliseconds
const DOUBLE_CLICK_SLIP_DISTANCE_MAX = 10; // pixels
const DOUBLE_CLICK_SLIP_DISTANCE_MAX_SQUARED =
DOUBLE_CLICK_SLIP_DISTANCE_MAX ** 2;
export default function widgetBehavior(publicAPI: any, model: any) {
model.classHierarchy.push('vtkPolygonWidgetBehavior');
const anotherWidgetHasFocus = () =>
model._widgetManager
.getWidgets()
.some((w: any) => w !== publicAPI && w.hasFocus());
const setDragging = (isDragging: boolean) => {
model._dragging = isDragging;
publicAPI.invokeDraggingEvent({
dragging: isDragging,
});
};
// overUnselectedHandle is true if mouse is over handle that was created before a mouse move event.
// That happens if creating new handle and immediately dragging.
// Then widgetManager.getSelections() still points to the last actor
// after the mouse button is released. In this widgets case, the last actor is part of the LineGlyphRepresentation.
// overUnselectedHandle tracks if the mouse is over the new handle so we
// don't create a another handle when clicking after without mouse move.
// A mouse move event sets overUnselectedHandle to false as we can then rely on widgetManager.getSelections().
let overUnselectedHandle = false;
let freeHanding = false;
// Check if mouse is over line segment between handles
const checkOverSegment = () => {
// overSegment guards against clicking anywhere in view
const selections = model._widgetManager.getSelections();
const overSegment =
selections?.[0]?.getProperties().prop ===
model.representations[1].getActors()[0]; // line representation is second representation
return overSegment && !overUnselectedHandle;
};
// Check if mouse is over fill representation (for hover but not interaction)
const checkOverFill = () => {
const selections = model._widgetManager.getSelections();
return (
model.representations[2] &&
selections?.[0]?.getProperties().prop ===
model.representations[2].getActors()[0]
);
};
// support setting per-view widget manipulators
macro.setGet(publicAPI, model, ['manipulator']);
// events to emit
macro.event(publicAPI, model, 'RightClickEvent');
macro.event(publicAPI, model, 'PlacedEvent');
macro.event(publicAPI, model, 'HoverEvent');
macro.event(publicAPI, model, 'DraggingEvent');
publicAPI.resetInteractions = () => {
model._interactor.cancelAnimation(publicAPI, true);
};
// --------------------------------------------------------------------------
// Interactor events
// --------------------------------------------------------------------------
const reset = () => {
publicAPI.loseFocus();
model.widgetState.clearHandles();
};
const removeLastHandle = () => {
const handles = model.widgetState.getHandles();
if (handles.length > 0) {
model.widgetState.removeHandle(handles.length - 1);
if (handles.length === 0) {
reset();
}
}
};
const finishPlacing = () => {
model.widgetState.setPlacing(false);
publicAPI.loseFocus();
// Tool Component listens for 'placed' event
publicAPI.invokePlacedEvent();
};
function isFinishable() {
const handles = model.widgetState.getHandles();
const moveHandle = model.widgetState.getMoveHandle();
if (model.activeState === moveHandle && handles.length >= 3) {
// Check moveHandle distance to first handle
const moveCoords = model._apiSpecificRenderWindow.worldToDisplay(
...moveHandle.getOrigin(),
model._renderer
);
const firstCoords = model._apiSpecificRenderWindow.worldToDisplay(
...handles[0].getOrigin(),
model._renderer
);
if (!moveCoords || !firstCoords) return false;
const cssPixelDistance =
FINISHABLE_DISTANCE_SQUARED *
model._apiSpecificRenderWindow.getComputedDevicePixelRatio();
const distance = distance2BetweenPoints(firstCoords, moveCoords);
return distance < cssPixelDistance;
}
return false;
}
const getWorldCoords = computeWorldCoords(model);
// returns macro.EVENT_ABORT if dragging handle or finishing
// to indicate event should be consumed.
function updateActiveStateHandle(callData: any) {
const worldCoords = getWorldCoords(callData);
if (
worldCoords?.length &&
(model.activeState === model.widgetState.getMoveHandle() ||
model._dragging)
) {
model.activeState.setOrigin(worldCoords);
model.widgetState.setFinishable(isFinishable());
if (model.widgetState.getFinishable())
// snap to first point
model.activeState.setOrigin(
model.widgetState.getHandles()[0].getOrigin()
);
publicAPI.invokeInteractionEvent();
return macro.EVENT_ABORT;
}
return macro.VOID;
}
function addHandle() {
const moveHandle = model.widgetState.getMoveHandle();
const newHandle = model.widgetState.addHandle();
newHandle.setOrigin(moveHandle.getOrigin());
}
// --------------------------------------------------------------------------
// Left press: Select handle to drag / Add new handle
// --------------------------------------------------------------------------
publicAPI.handleLeftButtonPress = (event: vtkMouseEvent) => {
if (!model.manipulator) {
return macro.VOID;
}
const activeWidget = model._widgetManager.getActiveWidget();
// If not placing and hovering over another widget, don't consume event.
if (
!model.widgetState.getPlacing() &&
activeWidget &&
activeWidget !== publicAPI
) {
return macro.VOID;
}
// Ignore clicks on this widget's segment or fill
if (checkOverSegment() || checkOverFill()) {
return macro.VOID;
}
// Drop point?
const manipulator =
model.activeState?.getManipulator?.() ?? model.manipulator;
if (model.widgetState.getPlacing() && manipulator) {
// Dropping first point?
if (model.widgetState.getHandles().length === 0) {
model._widgetManager.grabFocus(publicAPI);
}
updateActiveStateHandle(event);
if (model.widgetState.getFinishable()) {
finishPlacing();
// Don't add another point, just return
return macro.EVENT_ABORT;
}
addHandle();
publicAPI.invokeStartInteractionEvent();
freeHanding = true;
return macro.EVENT_ABORT;
}
if (
model.activeState?.getActive() &&
model.activeState?.setOrigin &&
model.pickable &&
model.dragable
) {
setDragging(true);
model._apiSpecificRenderWindow.setCursor('grabbing');
model._interactor.requestAnimation(publicAPI);
publicAPI.invokeStartInteractionEvent();
return macro.EVENT_ABORT;
}
return macro.VOID;
};
// --------------------------------------------------------------------------
// Mouse move: Drag selected handle / Handle follow the mouse
// --------------------------------------------------------------------------
publicAPI.handleMouseMove = (event: vtkMouseEvent) => {
if (
model.pickable &&
model.dragable &&
model.activeState &&
updateActiveStateHandle(event) === macro.EVENT_ABORT // side effect!
) {
if (freeHanding) {
addHandle();
}
return macro.EVENT_ABORT; // consume event
}
// widgetManager.getSelections() updates on mouse move and not animating.
// (Widget triggers animation when dragging.)
// So we can rely on getSelections() to be up to date now
overUnselectedHandle = false;
if (anotherWidgetHasFocus()) {
publicAPI.invokeHoverEvent({
...event,
hovering: false,
});
return macro.VOID;
}
publicAPI.invokeHoverEvent({
...event,
hovering: !!model.activeState || checkOverFill(),
});
return macro.VOID;
};
// --------------------------------------------------------------------------
// Left release: Finish drag
// --------------------------------------------------------------------------
// Detect double click by diffing these.
let lastReleaseTime = 0;
let lastReleasePosition: Vector3 | undefined;
function isDoubleClick(event: vtkMouseEvent) {
const currentTime = Date.now();
const currentDisplayPos = [
event.position.x,
event.position.y,
event.position.z,
] as Vector3;
const elapsed = currentTime - lastReleaseTime;
const distance = lastReleasePosition
? distance2BetweenPoints(
[event.position.x, event.position.y, event.position.z],
lastReleasePosition
)
: Number.POSITIVE_INFINITY;
const doubleClicked =
elapsed < DOUBLE_CLICK_TIMEOUT &&
distance < DOUBLE_CLICK_SLIP_DISTANCE_MAX_SQUARED;
lastReleaseTime = currentTime;
lastReleasePosition = currentDisplayPos;
return doubleClicked;
}
publicAPI.handleLeftButtonRelease = (event: vtkMouseEvent) => {
if (
!model.activeState ||
!model.activeState.getActive() ||
!model.pickable
) {
return macro.VOID;
}
freeHanding = false;
if (model._dragging) {
model._apiSpecificRenderWindow.setCursor('pointer');
model._interactor.cancelAnimation(publicAPI);
setDragging(false);
model._widgetManager.enablePicking();
// So a following left click without moving the mouse can immediately grab the handle,
// we don't call model.widgetState.deactivate() here.
publicAPI.invokeEndInteractionEvent();
return macro.EVENT_ABORT;
}
// If not placing (and not dragging) don't consume event
// so camera control widgets can react.
if (!model.widgetState.getPlacing()) {
return macro.VOID;
}
if (model.widgetState.getFinishable()) {
finishPlacing();
} else if (isDoubleClick(event)) {
// try to finish placing
const handles = model.widgetState.getHandles();
// Need 3 handles to finish. Double click created 2 handles, 1 extra.
if (handles.length >= 4) {
removeLastHandle();
finishPlacing();
}
}
if (
(model.hasFocus && !model.activeState) ||
(model.activeState && !model.activeState.getActive())
) {
model._widgetManager.enablePicking();
model._interactor.render();
}
publicAPI.invokeEndInteractionEvent();
return macro.EVENT_ABORT;
};
// --------------------------------------------------------------------------
// Escape key: clear handles
// --------------------------------------------------------------------------
publicAPI.handleKeyDown = ({ key }: any) => {
if (model.widgetState.getPlacing() && key === 'Escape') {
reset();
return macro.EVENT_ABORT;
}
if (model.widgetState.getPlacing() && key === 'Enter') {
if (model.widgetState.getHandles().length >= 3) {
finishPlacing();
}
return macro.EVENT_ABORT;
}
return macro.VOID;
};
// Called when mouse moves off handle.
publicAPI.deactivateAllHandles = () => {
model.widgetState.deactivate();
// Context menu should only show if hovering over the tool.
// Stops right clicking anywhere showing context menu.
model.activeState = null;
};
// --------------------------------------------------------------------------
// Right press: Remove last handle / Pop context menu
// --------------------------------------------------------------------------
const makeWidgetActions = (eventData: any) => {
const widgetActions: Array<WidgetAction> = [];
const { activeState } = model;
const overSegment = checkOverSegment();
if (overSegment) {
// Allow inserting ponts when over a segment
widgetActions.push({
name: 'Add Point',
func: () => {
const insertIndex = activeState.getIndex() + 1;
const newHandle = model.widgetState.addHandle({ insertIndex });
const coords = getWorldCoords(eventData);
if (!coords) throw new Error('No world coords');
newHandle.setOrigin(coords);
// enable dragging immediately
publicAPI.activateHandle({
selectedState: newHandle,
representation: model.representations[0].getActors()[0], // first actor is GlyphMapper for handles
});
},
});
} else if (!overSegment && model.widgetState.getHandles().length > 2) {
// if hovering on handle and we will still have at least 2 points after removing handle
widgetActions.push({
name: 'Delete Point',
func: () => {
model.widgetState.removeHandle(activeState.getIndex());
},
});
}
return widgetActions;
};
publicAPI.handleRightButtonPress = (eventData: any) => {
// When placing, handle right-click regardless of what widget manager picked
if (model.widgetState.getPlacing()) {
removeLastHandle();
return macro.EVENT_ABORT;
}
if (!model.activeState) {
return macro.VOID;
}
if (anotherWidgetHasFocus()) {
return macro.VOID;
}
const eventWithWidgetAction = {
...eventData,
widgetActions: makeWidgetActions(eventData),
};
publicAPI.invokeRightClickEvent(eventWithWidgetAction);
return macro.EVENT_ABORT;
};
// --------------------------------------------------------------------------
// Focused means PolygonWidget is in initial drawing/placing mode.
// After first point dropped, make moveHandle follow mouse.
// --------------------------------------------------------------------------
publicAPI.grabFocus = () => {
if (!model.hasFocus) {
model.activeState = model.widgetState.getMoveHandle();
model.activeState.activate();
model.activeState.setVisible(true);
model._interactor.requestAnimation(publicAPI);
publicAPI.invokeStartInteractionEvent();
}
model.hasFocus = true;
};
// Called after we are finished/placed.
publicAPI.loseFocus = () => {
const hadFocus = model.hasFocus;
if (hadFocus) {
model._interactor.cancelAnimation(publicAPI);
publicAPI.invokeEndInteractionEvent();
}
model.widgetState.deactivate();
model.widgetState.getMoveHandle().deactivate();
model.widgetState.getMoveHandle().setVisible(false);
model.widgetState.getMoveHandle().setOrigin(null);
model.activeState = null;
model.hasFocus = false;
if (hadFocus) {
model._widgetManager.releaseFocus();
// Deactivate all widgets so stale activeStates don't persist
// (user may right-click again without moving mouse)
model._widgetManager
.getWidgets()
.forEach((w: any) => w.deactivateAllHandles());
}
model._widgetManager.enablePicking();
};
publicAPI.delete = macro.chain(() => {
publicAPI.resetInteractions();
}, publicAPI.delete);
}