-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCameraService.ts
More file actions
417 lines (367 loc) · 13.9 KB
/
CameraService.ts
File metadata and controls
417 lines (367 loc) · 13.9 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
import intersects from "intersects";
import { Graph } from "../../graph";
import { Emitter } from "../../utils/Emitter";
import { clamp } from "../../utils/functions/clamp";
import { TRect } from "../../utils/types/shapes";
import { ECameraScaleLevel } from "./cameraScaleEnums";
export { ECameraScaleLevel } from "./cameraScaleEnums";
export { defaultGetCameraBlockScaleLevel } from "./defaultGetCameraBlockScaleLevel";
export type TCameraState = {
x: number;
y: number;
width: number;
height: number;
scale: number;
scaleMin: number;
scaleMax: number;
relativeX: number;
relativeY: number;
relativeWidth: number;
relativeHeight: number;
/**
* Insets of visible viewport inside the canvas area (in screen space, pixels)
* Use these to specify drawers/side panels overlaying the canvas. All values are >= 0.
*/
viewportInsets: {
left: number;
right: number;
top: number;
bottom: number;
};
/**
* Auto-panning mode enabled state
* When enabled, the camera will automatically pan when the mouse is near the viewport edges
*/
autoPanningEnabled: boolean;
};
export type { TGetCameraBlockScaleLevel } from "./defaultGetCameraBlockScaleLevel";
export const getInitCameraState = (): TCameraState => {
return {
/**
* Viewport of camera in canvas space
* x,y - center of camera(may be negative)
* width, height - size of viewport, equals to canvas w/h
* */
x: 0,
y: 0,
width: 0,
height: 0,
/**
* Viewport of camera in camera space
* relativeX, relativeY - center of camera
* relativeWidth, relativeHeight - size of viewport
*
* In easy words, it's a scale-aware viewport
*/
relativeX: 0,
relativeY: 0,
relativeWidth: 0,
relativeHeight: 0,
scale: 0.5,
scaleMax: 1,
scaleMin: 0.01,
viewportInsets: { left: 0, right: 0, top: 0, bottom: 0 },
autoPanningEnabled: false,
};
};
export type ICamera = Interface<CameraService>;
export class CameraService extends Emitter {
constructor(
protected graph: Graph,
protected state: TCameraState = getInitCameraState()
) {
super();
}
public resize(newState: Partial<TCameraState>) {
const diffX = newState.width - this.state.width;
const diffY = newState.height - this.state.height;
this.set(newState);
this.move(diffX, diffY);
}
public set(newState: Partial<TCameraState>) {
this.graph.executеDefaultEventAction("camera-change", Object.assign({}, this.state, newState), () => {
this.state = Object.assign(this.state, newState);
this.updateRelative();
});
}
private updateRelative() {
// Relative coordinates are based on full canvas viewport (ignore insets)
this.state.relativeX = this.getRelative(this.state.x) | 0;
this.state.relativeY = this.getRelative(this.state.y) | 0;
this.state.relativeWidth = this.getRelative(this.state.width) | 0;
this.state.relativeHeight = this.getRelative(this.state.height) | 0;
}
public getCameraRect(): TRect {
const { x, y, width, height } = this.state;
return { x, y, width, height };
}
/**
* Returns the visible camera rect in screen space that accounts for the viewport insets.
* @returns {TRect} Visible rectangle inside the canvas after applying insets
*/
public getVisibleCameraRect(): TRect {
const { x, y, width, height, viewportInsets } = this.state;
const visibleWidth = Math.max(0, width - viewportInsets.left - viewportInsets.right);
const visibleHeight = Math.max(0, height - viewportInsets.top - viewportInsets.bottom);
return {
x: x + viewportInsets.left,
y: y + viewportInsets.top,
width: visibleWidth,
height: visibleHeight,
};
}
/**
* Returns camera viewport rectangle in camera-relative space.
* By default returns full canvas-relative viewport (ignores insets).
* When options.respectInsets is true, returns viewport of the visible area (with insets applied).
* @param {Object} [options]
* @param {boolean} [options.respectInsets]
* @returns {TRect} Relative viewport rectangle
*/
public getRelativeViewportRect(options?: { respectInsets?: boolean }): TRect {
const useVisible = Boolean(options?.respectInsets);
if (!useVisible) {
return {
x: this.getRelative(this.state.x) | 0,
y: this.getRelative(this.state.y) | 0,
width: this.getRelative(this.state.width) | 0,
height: this.getRelative(this.state.height) | 0,
};
}
const insets = this.state.viewportInsets;
const visibleWidth = Math.max(0, this.state.width - insets.left - insets.right);
const visibleHeight = Math.max(0, this.state.height - insets.top - insets.bottom);
return {
x: this.getRelative(this.state.x + insets.left) | 0,
y: this.getRelative(this.state.y + insets.top) | 0,
width: this.getRelative(visibleWidth) | 0,
height: this.getRelative(visibleHeight) | 0,
};
}
public getCameraScale() {
return this.state.scale;
}
/**
* Qualitative zoom tier for blocks. Delegates to `settings.getCameraBlockScaleLevel` (always set; defaults to
* the exported `defaultGetCameraBlockScaleLevel` strategy).
* @param cameraScale Optional scale override; defaults to current camera scale
*/
public getCameraBlockScaleLevel(cameraScale = this.getCameraScale()): ECameraScaleLevel {
return this.graph.rootStore.settings.$settings.value.getCameraBlockScaleLevel(this.graph, {
...this.state,
scale: cameraScale,
});
}
public getCameraState(): TCameraState {
return this.state;
}
public move(dx = 0, dy = 0) {
const x = (this.state.x + dx) | 0;
const y = (this.state.y + dy) | 0;
this.set({
x,
y,
});
}
/**
* Limits the effect of camera scale on visual details to preserve their visibility.
* Prevents important details from becoming too large or too small during zoom.
* Converts absolute value to camera space with optional clamping.
* @param {number} value Absolute value in screen space
* @param {number} [max] Maximum allowed value
* @returns {number} Scale-compensated value in camera space
*/
public limitScaleEffect(value: number, max?: number): number {
const result = this.getRelative(value);
if (max !== undefined) {
return clamp(result, value, max);
}
return result;
}
/**
* Converts a value from absolute (screen space) to relative (camera space).
* @param {number} n Absolute value
* @param {number} [scale=this.state.scale] Scale to use for conversion
* @returns {number} Relative value
*/
public getRelative(n: number, scale: number = this.state.scale): number {
return n / scale;
}
public getRelativeXY(x: number, y: number) {
return [(x - this.state.x) / this.state.scale, (y - this.state.y) / this.state.scale];
}
/**
* Converts relative coordinate to absolute (screen space).
* Inverse of getRelative.
* @param {number} n Relative coordinate
* @param {number} [scale=this.state.scale] Scale to use for conversion
* @returns {number} Absolute coordinate in screen space
*/
public getAbsolute(n: number, scale: number = this.state.scale): number {
return n * scale;
}
/**
* Converts relative coordinates to absolute (screen space).
* Inverse of getRelativeXY.
* @param {number} x Relative x
* @param {number} y Relative y
* @returns {number[]} Absolute [x, y] in screen space
*/
public getAbsoluteXY(x: number, y: number) {
return [x * this.state.scale + this.state.x, y * this.state.scale + this.state.y];
}
/**
* Zoom to a screen point.
* @param {number} x Screen x where zoom anchors
* @param {number} y Screen y where zoom anchors
* @param {number} scale Target scale value
* @returns {void}
*/
public zoom(x: number, y: number, scale: number) {
const normalizedScale = clamp(scale, this.state.scaleMin, this.state.scaleMax);
const dx = this.getRelative(x - this.state.x);
const dy = this.getRelative(y - this.state.y);
const dxInNextScale = this.getRelative(x - this.state.x, normalizedScale);
const dyInNextScale = this.getRelative(y - this.state.y, normalizedScale);
const nextX = this.state.x + (dxInNextScale - dx) * normalizedScale;
const nextY = this.state.y + (dyInNextScale - dy) * normalizedScale;
this.set({
scale: normalizedScale,
x: nextX,
y: nextY,
});
}
public getScaleRelativeDimensionsBySide(
size: number,
axis: "width" | "height",
options?: { respectInsets?: boolean }
) {
const useVisible = Boolean(options?.respectInsets);
const insets = this.state.viewportInsets;
let viewportSize: number;
if (axis === "width") {
viewportSize = useVisible ? Math.max(0, this.state.width - insets.left - insets.right) : this.state.width;
} else {
viewportSize = useVisible ? Math.max(0, this.state.height - insets.top - insets.bottom) : this.state.height;
}
return clamp(Number(viewportSize / size), this.state.scaleMin, this.state.scaleMax);
}
public getScaleRelativeDimensions(width: number, height: number, options?: { respectInsets?: boolean }) {
return Math.min(
this.getScaleRelativeDimensionsBySide(width, "width", options),
this.getScaleRelativeDimensionsBySide(height, "height", options)
);
}
public getXYRelativeCenterDimensions(dimensions: TRect, scale: number, options?: { respectInsets?: boolean }) {
const useVisible = Boolean(options?.respectInsets);
const insets = this.state.viewportInsets;
const centerX = useVisible
? insets.left + Math.max(0, this.state.width - insets.left - insets.right) / 2
: this.state.width / 2;
const centerY = useVisible
? insets.top + Math.max(0, this.state.height - insets.top - insets.bottom) / 2
: this.state.height / 2;
const x = 0 - dimensions.x * scale - (dimensions.width / 2) * scale + centerX;
const y = 0 - dimensions.y * scale - (dimensions.height / 2) * scale + centerY;
return { x, y };
}
public isRectVisible(x: number, y: number, w: number, h: number) {
// Shift by relative viewport origin (full viewport, without insets). Insets are irrelevant for visibility.
return intersects.boxBox(
x + this.state.relativeX,
y + this.state.relativeY,
w,
h,
0,
0,
this.state.relativeWidth,
this.state.relativeHeight
);
}
public isLineVisible(x1: number, y1: number, x2: number, y2: number) {
// because the camera coordinates are inverted
return intersects.lineBox(
-x1,
-y1,
-x2,
-y2,
this.state.relativeX - this.state.relativeWidth,
this.state.relativeY - this.state.relativeHeight,
this.state.relativeWidth,
this.state.relativeHeight
);
}
public applyToPoint(x: number, y: number): [number, number] {
return [(this.getRelative(x) - this.state.relativeX) | 0, (this.getRelative(y) - this.state.relativeY) | 0];
}
public applyToRect(...arg: number[]): number[];
public applyToRect(x: number, y: number, w: number, h: number): number[] {
return this.applyToPoint(x, y).concat(Math.floor(this.getRelative(w)), Math.floor(this.getRelative(h)));
}
/**
* Update viewport insets (screen-space paddings inside canvas) and optionally keep the
* world point under the visible center unchanged.
* @param {Object} insets Partial insets to update
* @param {number} [insets.left]
* @param {number} [insets.right]
* @param {number} [insets.top]
* @param {number} [insets.bottom]
* @param {string} [maintain=center] Preserve visual anchor; allowed values: center or none. "center" keeps the
* same world point under visible center
* @returns {void}
*/
public setViewportInsets(insets: Partial<TCameraState["viewportInsets"]>, params?: { maintain?: "center" }): void {
const currentInsets = this.state.viewportInsets;
const nextInsets = {
left: insets.left ?? currentInsets.left,
right: insets.right ?? currentInsets.right,
top: insets.top ?? currentInsets.top,
bottom: insets.bottom ?? currentInsets.bottom,
};
if (params?.maintain === "center") {
const oldVisibleWidth = Math.max(0, this.state.width - currentInsets.left - currentInsets.right);
const oldVisibleHeight = Math.max(0, this.state.height - currentInsets.top - currentInsets.bottom);
const oldCenterX = currentInsets.left + oldVisibleWidth / 2;
const oldCenterY = currentInsets.top + oldVisibleHeight / 2;
const [anchorWorldX, anchorWorldY] = this.getRelativeXY(oldCenterX, oldCenterY);
const newVisibleWidth = Math.max(0, this.state.width - nextInsets.left - nextInsets.right);
const newVisibleHeight = Math.max(0, this.state.height - nextInsets.top - nextInsets.bottom);
const newCenterX = nextInsets.left + newVisibleWidth / 2;
const newCenterY = nextInsets.top + newVisibleHeight / 2;
const nextX = newCenterX - anchorWorldX * this.state.scale;
const nextY = newCenterY - anchorWorldY * this.state.scale;
this.set({ viewportInsets: nextInsets, x: nextX, y: nextY });
return;
}
this.set({ viewportInsets: nextInsets });
}
/**
* Returns current viewport insets.
* @returns {{left: number, right: number, top: number, bottom: number}} Current insets of visible viewport
*/
public getViewportInsets(): TCameraState["viewportInsets"] {
return this.state.viewportInsets;
}
/**
* Enable auto-panning mode.
* When enabled, the camera will automatically pan when the mouse is near the viewport edges.
* @returns {void}
*/
public enableAutoPanning(): void {
this.set({ autoPanningEnabled: true });
}
/**
* Disable auto-panning mode.
* @returns {void}
*/
public disableAutoPanning(): void {
this.set({ autoPanningEnabled: false });
}
/**
* Check if auto-panning mode is enabled.
* @returns {boolean} True if auto-panning is enabled
*/
public isAutoPanningEnabled(): boolean {
return this.state.autoPanningEnabled;
}
}