-
-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathscreen.ts
More file actions
1236 lines (1082 loc) · 39.4 KB
/
Copy pathscreen.ts
File metadata and controls
1236 lines (1082 loc) · 39.4 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
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
import { vec, Vector } from './math/vector';
import { Logger } from './util/log';
import type { Camera } from './camera';
import type { BrowserEvents } from './util/browser';
import { BoundingBox } from './collision/index';
import type { ExcaliburGraphicsContext } from './graphics/context/excalibur-graphics-context';
import { getPosition } from './util/util';
import { ExcaliburGraphicsContextWebGL } from './graphics/context/excalibur-graphics-context-webgl';
import { ExcaliburGraphicsContext2DCanvas } from './graphics/context/excalibur-graphics-context-2d-canvas';
import { EventEmitter } from './event-emitter';
/**
* Enum representing the different display modes available to Excalibur.
*/
export enum DisplayMode {
/**
* Default, use a specified resolution for the game. Like 800x600 pixels for example.
*/
Fixed = 'Fixed',
/**
* Fit the aspect ratio given by the game resolution within the container at all times will fill any gaps with canvas.
* The displayed area outside the aspect ratio is not guaranteed to be on the screen, only the {@apilink Screen.contentArea}
* is guaranteed to be on screen.
*/
FitContainerAndFill = 'FitContainerAndFill',
/**
* Fit the aspect ratio given by the game resolution the screen at all times will fill the screen.
* This displayed area outside the aspect ratio is not guaranteed to be on the screen, only the {@apilink Screen.contentArea}
* is guaranteed to be on screen.
*/
FitScreenAndFill = 'FitScreenAndFill',
/**
* Fit the viewport to the parent element maintaining aspect ratio given by the game resolution, but zooms in to avoid the black bars
* (letterbox) that would otherwise be present in {@apilink FitContainer}.
*
* **warning** This will clip some drawable area from the user because of the zoom,
* use {@apilink Screen.contentArea} to know the safe to draw area.
*/
FitContainerAndZoom = 'FitContainerAndZoom',
/**
* Fit the viewport to the device screen maintaining aspect ratio given by the game resolution, but zooms in to avoid the black bars
* (letterbox) that would otherwise be present in {@apilink FitScreen}.
*
* **warning** This will clip some drawable area from the user because of the zoom,
* use {@apilink Screen.contentArea} to know the safe to draw area.
*/
FitScreenAndZoom = 'FitScreenAndZoom',
/**
* Fit to screen using as much space as possible while maintaining aspect ratio and resolution.
* This is not the same as {@apilink Screen.enterFullscreen} but behaves in a similar way maintaining aspect ratio.
*
* You may want to center your game here is an example
* ```html
* <!-- html -->
* <body>
* <main>
* <canvas id="game"></canvas>
* </main>
* </body>
* ```
*
* ```css
* // css
* main {
* display: flex;
* align-items: center;
* justify-content: center;
* height: 100%;
* width: 100%;
* }
* ```
*/
FitScreen = 'FitScreen',
/**
* Fill the entire screen's css width/height for the game resolution dynamically. This means the resolution of the game will
* change dynamically as the window is resized. This is not the same as {@apilink Screen.enterFullscreen}
*/
FillScreen = 'FillScreen',
/**
* Fit to parent element width/height using as much space as possible while maintaining aspect ratio and resolution.
*/
FitContainer = 'FitContainer',
/**
* Use the parent DOM container's css width/height for the game resolution dynamically
*/
FillContainer = 'FillContainer'
}
/**
* Convenience class for quick resolutions
* Mostly sourced from https://emulation.gametechwiki.com/index.php/Resolution
*/
export class Resolution {
/* istanbul ignore next */
public static get SVGA(): Resolution {
return { width: 800, height: 600 };
}
/* istanbul ignore next */
public static get Standard(): Resolution {
return { width: 1920, height: 1080 };
}
/* istanbul ignore next */
public static get Atari2600(): Resolution {
return { width: 160, height: 192 };
}
/* istanbul ignore next */
public static get GameBoy(): Resolution {
return { width: 160, height: 144 };
}
/* istanbul ignore next */
public static get GameBoyAdvance(): Resolution {
return { width: 240, height: 160 };
}
/* istanbul ignore next */
public static get NintendoDS(): Resolution {
return { width: 256, height: 192 };
}
/* istanbul ignore next */
public static get NES(): Resolution {
return { width: 256, height: 224 };
}
/* istanbul ignore next */
public static get SNES(): Resolution {
return { width: 256, height: 244 };
}
}
export type ViewportUnit = 'pixel' | 'percent';
export interface Resolution {
width: number;
height: number;
}
export interface ViewportDimension {
widthUnit?: ViewportUnit;
heightUnit?: ViewportUnit;
width: number;
height: number;
}
export interface ScreenOptions {
/**
* Canvas element to build a screen on
*/
canvas: HTMLCanvasElement;
/**
* Graphics context for the screen
*/
context: ExcaliburGraphicsContext;
/**
* Browser abstraction
*/
browser: BrowserEvents;
/**
* Optionally set antialiasing, defaults to true. If set to true, images will be smoothed
*/
antialiasing?: boolean;
/**
* Optionally set the image rendering CSS hint on the canvas element, default is auto
*/
canvasImageRendering?: 'auto' | 'pixelated';
/**
* Optionally override the pixel ratio to use for the screen, otherwise calculated automatically from the browser
*/
pixelRatio?: number;
/**
* Optionally specify the actual pixel resolution in width/height pixels (also known as logical resolution), by default the
* resolution will be the same as the viewport. Resolution will be overridden by {@apilink DisplayMode.FillContainer} and
* {@apilink DisplayMode.FillScreen}.
*/
resolution?: Resolution;
/**
* Visual viewport size in css pixel, if resolution is not specified it will be the same as the viewport
*/
viewport: ViewportDimension;
/**
* Set the display mode of the screen, by default DisplayMode.Fixed.
*/
displayMode?: DisplayMode;
}
/**
* Fires when the screen resizes, useful if you have logic that needs to be aware of resolution/viewport constraints
*/
export interface ScreenResizeEvent {
/**
* Current viewport in css pixels of the screen
*/
viewport: ViewportDimension;
/**
* Current resolution in world pixels of the screen
*/
resolution: Resolution;
}
/**
* Fires when the pixel ratio changes, useful to know if you've moved to a hidpi screen or back
*/
export interface PixelRatioChangeEvent {
/**
* Current pixel ratio of the screen
*/
pixelRatio: number;
}
/**
* Fires when the browser fullscreen api is successfully engaged or disengaged
*/
export interface FullScreenChangeEvent {
/**
* Current fullscreen state
*/
fullscreen: boolean;
}
/**
* Built in events supported by all entities
*/
export interface ScreenEvents {
/**
* Fires when the screen resizes, useful if you have logic that needs to be aware of resolution/viewport constraints
*/
resize: ScreenResizeEvent;
/**
* Fires when the pixel ratio changes, useful to know if you've moved to a hidpi screen or back
*/
pixelratio: PixelRatioChangeEvent;
/**
* Fires when the browser fullscreen api is successfully engaged or disengaged
*/
fullscreen: FullScreenChangeEvent;
}
export const ScreenEvents = {
ScreenResize: 'resize',
PixelRatioChange: 'pixelratio',
FullScreenChange: 'fullscreen'
} as const;
/**
* The Screen handles all aspects of interacting with the screen for Excalibur.
*/
export class Screen {
public graphicsContext: ExcaliburGraphicsContext;
/**
* Listen to screen events {@apilink ScreenEvents}
*/
public events = new EventEmitter<ScreenEvents>();
private _canvas: HTMLCanvasElement;
private _antialiasing: boolean = true;
private _canvasImageRendering: 'auto' | 'pixelated' = 'auto';
private _contentResolution: Resolution;
private _browser: BrowserEvents;
private _camera: Camera;
private _resolution: Resolution;
private _resolutionStack: Resolution[] = [];
private _viewport: ViewportDimension;
private _viewportStack: ViewportDimension[] = [];
private _pixelRatioOverride: number | null = null;
private _displayMode: DisplayMode;
private _isFullscreen = false;
private _mediaQueryList: MediaQueryList;
private _isDisposed = false;
private _logger = Logger.getInstance();
private _resizeObserver: ResizeObserver;
constructor(options: ScreenOptions) {
this.viewport = options.viewport;
this.resolution = options.resolution ?? { ...this.viewport };
this._contentResolution = this.resolution;
this._displayMode = options.displayMode ?? DisplayMode.Fixed;
this._canvas = options.canvas;
this.graphicsContext = options.context;
this._antialiasing = options.antialiasing ?? this._antialiasing;
this._canvasImageRendering = options.canvasImageRendering ?? this._canvasImageRendering;
this._browser = options.browser;
this._pixelRatioOverride = options.pixelRatio;
this._applyDisplayMode();
this._listenForPixelRatio();
this._canvas.addEventListener('fullscreenchange', this._fullscreenChangeHandler);
this.applyResolutionAndViewport();
}
private _listenForPixelRatio() {
if (this._mediaQueryList && !this._mediaQueryList.addEventListener) {
// Safari <=13.1 workaround, remove any existing handlers
this._mediaQueryList.removeListener(this._pixelRatioChangeHandler);
}
this._mediaQueryList = this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
// Safari <=13.1 workaround
if (this._mediaQueryList.addEventListener) {
this._mediaQueryList.addEventListener('change', this._pixelRatioChangeHandler, { once: true });
} else {
this._mediaQueryList.addListener(this._pixelRatioChangeHandler);
}
}
public dispose(): void {
if (!this._isDisposed) {
// Clean up handlers
this._isDisposed = true;
this.events.clear();
this._browser.window.off('resize', this._resizeHandler);
this._browser.window.clear();
if (this._resizeObserver) {
this._resizeObserver.disconnect();
}
if (!(this.parent instanceof Window)) {
this.parent.removeEventListener('resize', this._resizeHandler);
}
// Safari <=13.1 workaround
if (this._mediaQueryList.removeEventListener) {
this._mediaQueryList.removeEventListener('change', this._pixelRatioChangeHandler);
} else {
this._mediaQueryList.removeListener(this._pixelRatioChangeHandler);
}
this._canvas.removeEventListener('fullscreenchange', this._fullscreenChangeHandler);
this._canvas = null;
}
}
private _fullscreenChangeHandler = () => {
if (this._isDisposed) {
return;
}
this._isFullscreen = !this._isFullscreen;
this._logger.debug('Fullscreen Change', this._isFullscreen);
this.events.emit('fullscreen', {
fullscreen: this.isFullscreen
} satisfies FullScreenChangeEvent);
};
private _pixelRatioChangeHandler = () => {
if (this._isDisposed) {
return;
}
this._logger.debug('Pixel Ratio Change', window.devicePixelRatio);
this._listenForPixelRatio();
this._devicePixelRatio = this._calculateDevicePixelRatio();
this.applyResolutionAndViewport();
this.events.emit('pixelratio', {
pixelRatio: this.pixelRatio
} satisfies PixelRatioChangeEvent);
};
private _resizeHandler = () => {
if (this._isDisposed) {
return;
}
const parent = this.parent;
this._logger.debug('View port resized');
this._setResolutionAndViewportByDisplayMode(parent);
this.applyResolutionAndViewport();
// Emit resize event
this.events.emit('resize', {
resolution: this.resolution,
viewport: this.viewport
} satisfies ScreenResizeEvent);
};
private _calculateDevicePixelRatio() {
if (window.devicePixelRatio < 1) {
return 1;
}
const devicePixelRatio = window.devicePixelRatio || 1;
return devicePixelRatio;
}
// Asking the window.devicePixelRatio is expensive we do it once
private _devicePixelRatio = this._calculateDevicePixelRatio();
/**
* Returns the computed pixel ratio, first using any override, then the device pixel ratio
*/
public get pixelRatio(): number {
if (this._pixelRatioOverride) {
return this._pixelRatioOverride;
}
return this._devicePixelRatio;
}
/**
* This calculates the ratio between excalibur pixels and the HTML pixels.
*
* This is useful for scaling HTML UI so that it matches your game.
*/
public get worldToPagePixelRatio(): number {
if (this._canvas) {
const pageOrigin = this.worldToPageCoordinates(Vector.Zero);
const pageDistance = this.worldToPageCoordinates(vec(1, 0)).sub(pageOrigin);
const pixelConversion = pageDistance.x;
return pixelConversion;
} else {
return 1;
}
}
/**
* Get or set the pixel ratio override
*
* You will need to call applyResolutionAndViewport() affect change on the screen
*/
public get pixelRatioOverride(): number | undefined {
return this._pixelRatioOverride;
}
public set pixelRatioOverride(value: number | undefined) {
this._pixelRatioOverride = value;
}
public get isHiDpi() {
return this.pixelRatio !== 1;
}
public get displayMode(): DisplayMode {
return this._displayMode;
}
public get canvas(): HTMLCanvasElement {
return this._canvas;
}
public get parent(): HTMLElement | Window {
switch (this.displayMode) {
case DisplayMode.FillContainer:
case DisplayMode.FitContainer:
case DisplayMode.FitContainerAndFill:
case DisplayMode.FitContainerAndZoom:
return this.canvas.parentElement || document.body;
default:
return window;
}
}
public get resolution(): Resolution {
return this._resolution;
}
public set resolution(resolution: Resolution) {
this._resolution = resolution;
}
/**
* Returns screen dimensions in pixels or percentage
*/
public get viewport(): ViewportDimension {
if (this._viewport) {
return this._viewport;
}
return this._resolution;
}
public set viewport(viewport: ViewportDimension) {
this._viewport = viewport;
}
public get aspectRatio() {
return this._resolution.width / this._resolution.height;
}
public get scaledWidth() {
return this._resolution.width * this.pixelRatio;
}
public get scaledHeight() {
return this._resolution.height * this.pixelRatio;
}
public setCurrentCamera(camera: Camera) {
this._camera = camera;
}
public pushResolutionAndViewport() {
this._resolutionStack.push(this.resolution);
this._viewportStack.push(this.viewport);
this.resolution = { ...this.resolution };
this.viewport = { ...this.viewport };
}
public peekViewport(): ViewportDimension {
return this._viewportStack[this._viewportStack.length - 1];
}
public peekResolution(): Resolution {
return this._resolutionStack[this._resolutionStack.length - 1];
}
public popResolutionAndViewport() {
if (this._resolutionStack.length && this._viewportStack.length) {
this.resolution = this._resolutionStack.pop();
this.viewport = this._viewportStack.pop();
}
}
public applyResolutionAndViewport() {
if (this.graphicsContext instanceof ExcaliburGraphicsContextWebGL) {
const scaledResolutionSupported = this.graphicsContext.checkIfResolutionSupported({
width: this.scaledWidth,
height: this.scaledHeight
});
if (!scaledResolutionSupported) {
this._logger.warnOnce(
`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) and pixel ratio (${this.pixelRatio})` +
' are too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly.' +
' Try reducing the resolution or disabling Hi DPI scaling to avoid this' +
' (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).'
);
// Attempt to recover if the user hasn't configured a specific ratio for up scaling
if (!this.pixelRatioOverride) {
let currentPixelRatio = Math.max(1, this.pixelRatio - 0.5);
let newResolutionSupported = false;
while (currentPixelRatio > 1 && !newResolutionSupported) {
currentPixelRatio = Math.max(1, currentPixelRatio - 0.5);
const width = this._resolution.width * currentPixelRatio;
const height = this._resolution.height * currentPixelRatio;
newResolutionSupported = this.graphicsContext.checkIfResolutionSupported({ width, height });
}
this.pixelRatioOverride = currentPixelRatio;
this._logger.warnOnce(
'Scaled resolution too big attempted recovery!' +
` Pixel ratio was automatically reduced to (${this.pixelRatio}) to avoid 4k texture limit.` +
' Setting `ex.Engine({pixelRatio: ...}) will override any automatic recalculation, do so at your own risk.` ' +
' (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).'
);
}
}
}
this._canvas.width = this.scaledWidth;
this._canvas.height = this.scaledHeight;
if (this._canvasImageRendering === 'auto') {
this._canvas.style.imageRendering = 'auto';
} else {
this._canvas.style.imageRendering = 'pixelated';
// Fall back to 'crisp-edges' if 'pixelated' is not supported
// Currently for firefox https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering
if (this._canvas.style.imageRendering === '') {
this._canvas.style.imageRendering = 'crisp-edges';
}
}
const widthUnit = this.viewport.widthUnit === 'percent' ? '%' : 'px';
const heightUnit = this.viewport.heightUnit === 'percent' ? '%' : 'px';
this._canvas.style.width = this.viewport.width + widthUnit;
this._canvas.style.height = this.viewport.height + heightUnit;
// After messing with the canvas width/height the graphics context is invalidated and needs to have some properties reset
this.graphicsContext.updateViewport(this.resolution);
this.graphicsContext.resetTransform();
this.graphicsContext.smoothing = this._antialiasing;
if (this.graphicsContext instanceof ExcaliburGraphicsContext2DCanvas) {
this.graphicsContext.scale(this.pixelRatio, this.pixelRatio);
}
// Add the excalibur world pixel to page pixel
document.documentElement.style.setProperty('--ex-pixel-ratio', this.worldToPagePixelRatio.toString());
}
/**
* Get or set screen antialiasing,
*
* If true smoothing is applied
*/
public get antialiasing() {
return this._antialiasing;
}
/**
* Get or set screen antialiasing
*/
public set antialiasing(isSmooth: boolean) {
this._antialiasing = isSmooth;
this.graphicsContext.smoothing = this._antialiasing;
}
/**
* Returns true if excalibur is fullscreen using the browser fullscreen api
* @deprecated use isFullscreen()
*/
public get isFullScreen() {
return this._isFullscreen;
}
/**
* Returns true if excalibur is fullscreen using the browser fullscreen api
*/
public get isFullscreen() {
return this._isFullscreen;
}
/**
* Requests to go fullscreen using the browser fullscreen api, requires user interaction to be successful.
* For example, wire this to a user click handler.
*
* Optionally specify a target element id to go fullscreen, by default the game canvas is used
* @param elementId
* @deprecated use enterFullscreen(...)
*/
public goFullScreen(elementId?: string): Promise<void> {
return this.enterFullscreen(elementId);
}
/**
* Requests to enter fullscreen using the browser fullscreen api, requires user interaction to be successful.
* For example, wire this to a user click handler.
*
* Optionally specify a target element id to go fullscreen, by default the game canvas is used
* @param elementId
*/
public enterFullscreen(elementId?: string): Promise<void> {
if (elementId) {
const maybeElement = document.getElementById(elementId);
// workaround for safari partial support
if (maybeElement?.requestFullscreen || (maybeElement as any)?.webkitRequestFullscreen) {
if (!maybeElement.getAttribute('ex-fullscreen-listener')) {
maybeElement.setAttribute('ex-fullscreen-listener', 'true');
maybeElement.addEventListener('fullscreenchange', this._fullscreenChangeHandler);
}
if (maybeElement.requestFullscreen) {
return maybeElement.requestFullscreen() ?? Promise.resolve();
} else if ((maybeElement as any).webkitRequestFullscreen) {
return (maybeElement as any).webkitRequestFullscreen() ?? Promise.resolve();
}
}
}
if (this._canvas?.requestFullscreen) {
return this._canvas?.requestFullscreen() ?? Promise.resolve();
} else if ((this._canvas as any).webkitRequestFullscreen) {
return (this._canvas as any).webkitRequestFullscreen() ?? Promise.resolve();
}
this._logger.warnOnce('Could not go fullscreen, is this an iPhone? Currently Apple does not support fullscreen on iPhones');
return Promise.resolve();
}
/**
* Requests to exit fullscreen using the browser fullscreen api
* @deprecated use exitFullscreen()
*/
public exitFullScreen(): Promise<void> {
return this.exitFullscreen();
}
public exitFullscreen(): Promise<void> {
return document.exitFullscreen();
}
private _viewportToPixels(viewport: ViewportDimension) {
return {
width: viewport.widthUnit === 'percent' ? this.canvas.offsetWidth : viewport.width,
height: viewport.heightUnit === 'percent' ? this.canvas.offsetHeight : viewport.height
} satisfies ViewportDimension;
}
/**
* Takes a coordinate in normal html page space, for example from a pointer move event, and translates it to
* Excalibur screen space.
*
* Excalibur screen space starts at the top left (0, 0) corner of the viewport, and extends to the
* bottom right corner (resolutionX, resolutionY). When using *AndFill suffixed display modes screen space
* (0, 0) is the top left of the safe content area bounding box not the viewport.
* @param point
*/
public pageToScreenCoordinates(point: Vector): Vector {
let newX = point.x;
let newY = point.y;
if (!this._isFullscreen) {
newX -= getPosition(this._canvas).x;
newY -= getPosition(this._canvas).y;
}
const viewport = this._viewportToPixels(this.viewport);
// if fullscreen api on it centers with black bars
// we need to adjust the screen to world coordinates in this case
if (this._isFullscreen) {
if (window.innerWidth / this.aspectRatio < window.innerHeight) {
const screenHeight = window.innerWidth / this.aspectRatio;
const screenMarginY = (window.innerHeight - screenHeight) / 2;
newY = ((newY - screenMarginY) / screenHeight) * viewport.height;
newX = (newX / window.innerWidth) * viewport.width;
} else {
const screenWidth = window.innerHeight * this.aspectRatio;
const screenMarginX = (window.innerWidth - screenWidth) / 2;
newX = ((newX - screenMarginX) / screenWidth) * viewport.width;
newY = (newY / window.innerHeight) * viewport.height;
}
}
newX = (newX / viewport.width) * this.resolution.width;
newY = (newY / viewport.height) * this.resolution.height;
// offset by content area
newX = newX - this.contentArea.left;
newY = newY - this.contentArea.top;
return new Vector(newX, newY);
}
/**
* Takes a coordinate in Excalibur screen space, and translates it to normal html page space. For example,
* this is where html elements might live if you want to position them relative to Excalibur.
*
* Excalibur screen space starts at the top left (0, 0) corner of the viewport, and extends to the
* bottom right corner (resolutionX, resolutionY)
* @param point
*/
public screenToPageCoordinates(point: Vector): Vector {
let newX = point.x;
let newY = point.y;
// no need to offset by content area, drawing is already offset by this
const viewport = this._viewportToPixels(this.viewport);
newX = (newX / this.resolution.width) * viewport.width;
newY = (newY / this.resolution.height) * viewport.height;
if (this._isFullscreen) {
if (window.innerWidth / this.aspectRatio < window.innerHeight) {
const screenHeight = window.innerWidth / this.aspectRatio;
const screenMarginY = (window.innerHeight - screenHeight) / 2;
newY = (newY / viewport.height) * screenHeight + screenMarginY;
newX = (newX / viewport.width) * window.innerWidth;
} else {
const screenWidth = window.innerHeight * this.aspectRatio;
const screenMarginX = (window.innerWidth - screenWidth) / 2;
newX = (newX / viewport.width) * screenWidth + screenMarginX;
newY = (newY / viewport.height) * window.innerHeight;
}
}
if (!this._isFullscreen) {
newX += getPosition(this._canvas).x;
newY += getPosition(this._canvas).y;
}
return new Vector(newX, newY);
}
/**
* Takes a coordinate in Excalibur screen space, and translates it to Excalibur world space.
*
* World space is where {@apilink Entity | `entities`} in Excalibur live by default {@apilink CoordPlane.World}
* and extends infinitely out relative from the {@apilink Camera}.
* @param point Screen coordinate to convert
*/
public screenToWorldCoordinates(point: Vector): Vector {
// offset by content area
point = point.add(vec(this.contentArea.left, this.contentArea.top));
// the only difference between screen & world is the camera transform
if (this._camera) {
return this._camera.inverse.multiply(point);
}
// fallback to center screen camera
return point.sub(vec(this.resolution.width / 2, this.resolution.height / 2));
}
/**
* Takes a coordinate in Excalibur world space, and translates it to Excalibur screen space.
*
* Screen space is where {@apilink ScreenElement | `screen elements`} and {@apilink Entity | `entities`} with {@apilink CoordPlane.Screen} live.
* @param point World coordinate to convert
*/
public worldToScreenCoordinates(point: Vector): Vector {
if (this._camera) {
return this._camera.transform.multiply(point);
}
// fallback to center screen camera
return point.add(vec(this.resolution.width / 2, this.resolution.height / 2));
}
public pageToWorldCoordinates(point: Vector): Vector {
const screen = this.pageToScreenCoordinates(point);
return this.screenToWorldCoordinates(screen);
}
public worldToPageCoordinates(point: Vector): Vector {
const screen = this.worldToScreenCoordinates(point);
return this.screenToPageCoordinates(screen);
}
/**
* Returns a BoundingBox of the top left corner of the screen
* and the bottom right corner of the screen.
*
* World bounds are in world coordinates, useful for culling objects offscreen that are in world space
*/
public getWorldBounds(): BoundingBox {
const bounds = BoundingBox.fromDimension(this.resolution.width, this.resolution.height, Vector.Half)
.scale(vec(1 / this._camera.zoom, 1 / this._camera.zoom))
.rotate(this._camera.rotation)
.translate(this._camera.drawPos);
return bounds;
}
/**
* Returns a BoundingBox of the top left corner of the screen and the bottom right corner of the screen.
*
* Screen bounds are in screen coordinates, useful for culling objects offscreen that are in screen space
*/
public getScreenBounds(): BoundingBox {
const bounds = BoundingBox.fromDimension(this.resolution.width, this.resolution.height, Vector.Zero, Vector.Zero);
return bounds;
}
/**
* The width of the game canvas in pixels (physical width component of the
* resolution of the canvas element)
*/
public get canvasWidth(): number {
return this.canvas.width;
}
/**
* Returns half width of the game canvas in pixels (half physical width component)
*/
public get halfCanvasWidth(): number {
return this.canvas.width / 2;
}
/**
* The height of the game canvas in pixels, (physical height component of
* the resolution of the canvas element)
*/
public get canvasHeight(): number {
return this.canvas.height;
}
/**
* Returns half height of the game canvas in pixels (half physical height component)
*/
public get halfCanvasHeight(): number {
return this.canvas.height / 2;
}
/**
* Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get drawWidth(): number {
if (this._camera) {
return this.resolution.width / this._camera.zoom;
}
return this.resolution.width;
}
/**
* Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get width(): number {
if (this._camera) {
return this.resolution.width / this._camera.zoom;
}
return this.resolution.width;
}
/**
* Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get halfDrawWidth(): number {
return this.drawWidth / 2;
}
/**
* Returns the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get drawHeight(): number {
if (this._camera) {
return this.resolution.height / this._camera.zoom;
}
return this.resolution.height;
}
public get height(): number {
if (this._camera) {
return this.resolution.height / this._camera.zoom;
}
return this.resolution.height;
}
/**
* Returns half the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get halfDrawHeight(): number {
return this.drawHeight / 2;
}
/**
* Returns screen center coordinates including zoom and device pixel ratio.
*/
public get center(): Vector {
return vec(this.halfDrawWidth, this.halfDrawHeight);
}
/**
* Returns the content area in screen space where it is safe to place content
*/
public get contentArea(): BoundingBox {
return this._contentArea;
}
/**
* Returns the unsafe area in screen space, this is the full screen and some space may not be onscreen.
*/
public get unsafeArea(): BoundingBox {
return this._unsafeArea;
}
private _contentArea: BoundingBox = new BoundingBox();
private _unsafeArea: BoundingBox = new BoundingBox();
private _computeFit() {
document.body.style.margin = '0px';
document.body.style.overflow = 'hidden';
const aspect = this.aspectRatio;
let adjustedWidth = 0;
let adjustedHeight = 0;
if (window.innerWidth / aspect < window.innerHeight) {
adjustedWidth = window.innerWidth;
adjustedHeight = window.innerWidth / aspect;
} else {
adjustedWidth = window.innerHeight * aspect;
adjustedHeight = window.innerHeight;
}
this.viewport = {
width: adjustedWidth,
height: adjustedHeight
};
this._contentArea = BoundingBox.fromDimension(this.resolution.width, this.resolution.height, Vector.Zero);
this._unsafeArea = BoundingBox.fromDimension(this.resolution.width, this.resolution.height, Vector.Zero);
this.events.emit('resize', {
resolution: this.resolution,
viewport: this.viewport
} satisfies ScreenResizeEvent);
}
private _computeFitScreenAndFill() {
document.body.style.margin = '0px';
document.body.style.overflow = 'hidden';
const vw = window.innerWidth;
const vh = window.innerHeight;
this._computeFitAndFill(vw, vh);
this.events.emit('resize', {
resolution: this.resolution,
viewport: this.viewport
} satisfies ScreenResizeEvent);
}
private _computeFitContainerAndFill() {
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
this._computeFitAndFill(this.canvas.offsetWidth, this.canvas.offsetHeight, {
width: 100,
widthUnit: 'percent',
height: 100,
heightUnit: 'percent'
});
this.events.emit('resize', {
resolution: this.resolution,
viewport: this.viewport
} satisfies ScreenResizeEvent);
}
private _computeFitAndFill(vw: number, vh: number, viewport?: ViewportDimension) {
this.viewport = viewport ?? {