astra
This commit is contained in:
parent
c074bc2645
commit
244620105a
21 changed files with 2080 additions and 518 deletions
|
|
@ -15,7 +15,7 @@ import '../static/favicons/favicon-32x32.png';
|
|||
import '../static/favicons/favicon.ico';
|
||||
import ResizeObserver from 'resize-observer-polyfill';
|
||||
import { LandingPageBackground } from './scripts/landing-page-background';
|
||||
import { JoinFormHandler } from './scripts/join-form-handler';
|
||||
import { JoinFormHandler, PlayerDecision } from './scripts/join-form-handler';
|
||||
import { handleFullScreen } from './scripts/helper/handle-full-screen';
|
||||
import { Game } from './scripts/game';
|
||||
import { initializeOptions } from './scripts/options-handler';
|
||||
|
|
@ -25,6 +25,7 @@ import { CharacterView } from './scripts/objects/types/character-view';
|
|||
import { LampView } from './scripts/objects/types/lamp-view';
|
||||
import { PlanetView } from './scripts/objects/types/planet-view';
|
||||
import { ProjectileView } from './scripts/objects/types/projectile-view';
|
||||
import { loadStoredValue, saveStoredValue } from './scripts/helper/storage';
|
||||
|
||||
glMatrix.setMatrixArrayType(Array);
|
||||
|
||||
|
|
@ -88,9 +89,9 @@ const applyServerContainerShadows = () => {
|
|||
const main = async () => {
|
||||
let game: Game | undefined;
|
||||
|
||||
const storedUserName = localStorage.getItem('userName');
|
||||
if (storedUserName) {
|
||||
nameInput.value = JSON.parse(storedUserName);
|
||||
const storedUserName = loadStoredValue('userName');
|
||||
if (typeof storedUserName === 'string') {
|
||||
nameInput.value = storedUserName;
|
||||
}
|
||||
|
||||
const firstClickListener = () => {
|
||||
|
|
@ -138,12 +139,17 @@ const main = async () => {
|
|||
const background = new LandingPageBackground(canvas);
|
||||
const joinHandler = new JoinFormHandler(joinGameForm, serverContainer);
|
||||
|
||||
await background.renderer;
|
||||
setVisible(spinner, false);
|
||||
let playerDecision: PlayerDecision;
|
||||
try {
|
||||
await background.renderer;
|
||||
setVisible(spinner, false);
|
||||
playerDecision = await joinHandler.getPlayerDecision();
|
||||
} finally {
|
||||
background.destroy();
|
||||
joinHandler.destroy();
|
||||
}
|
||||
|
||||
const playerDecision = await joinHandler.getPlayerDecision();
|
||||
|
||||
localStorage.setItem('userName', JSON.stringify(playerDecision.name));
|
||||
saveStoredValue('userName', playerDecision.name);
|
||||
|
||||
if (!history.state) {
|
||||
history.pushState(true, '');
|
||||
|
|
@ -151,7 +157,6 @@ const main = async () => {
|
|||
|
||||
setDisplayed(landingUI, null);
|
||||
setVisible(spinner, true);
|
||||
background.destroy();
|
||||
game = new Game(playerDecision, canvas, overlay);
|
||||
const gameOver = game.start();
|
||||
await game.started;
|
||||
|
|
@ -168,6 +173,7 @@ const main = async () => {
|
|||
main().catch((error) => {
|
||||
console.error(error);
|
||||
setVisible(spinner, false);
|
||||
setDisplayed(landingUI, 'flex');
|
||||
joinNotice.innerText = 'Something went wrong. Please reload the page.';
|
||||
setDisplayed(joinNotice, 'block');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -22,6 +22,11 @@ export class CommandSocket {
|
|||
this.commandQueue.push(command);
|
||||
}
|
||||
|
||||
public reset() {
|
||||
this.commandQueue = [];
|
||||
this.lastSendMs = -Infinity;
|
||||
}
|
||||
|
||||
public sendQueuedCommands() {
|
||||
// socket.io-client would buffer emits made while disconnected and flush them before the re-join.
|
||||
if (!this.socket.connected) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,18 @@ import { vec2 } from 'gl-matrix';
|
|||
import type { Command } from 'shared';
|
||||
import { InputGenerator } from './input-generator';
|
||||
|
||||
const movementKeys = new Set([
|
||||
'KeyW',
|
||||
'KeyA',
|
||||
'KeyS',
|
||||
'KeyD',
|
||||
'ArrowUp',
|
||||
'ArrowLeft',
|
||||
'ArrowDown',
|
||||
'ArrowRight',
|
||||
]);
|
||||
const leapKeys = new Set(['Space', 'ShiftLeft', 'ShiftRight']);
|
||||
|
||||
export class KeyboardListener extends InputGenerator {
|
||||
private keysDown: Set<string> = new Set();
|
||||
|
||||
|
|
@ -14,18 +26,23 @@ export class KeyboardListener extends InputGenerator {
|
|||
|
||||
private keyDownListener = (event: KeyboardEvent) => {
|
||||
const key = event.code;
|
||||
if (!movementKeys.has(key) && !leapKeys.has(key)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
if (this.keysDown.has(key)) {
|
||||
return;
|
||||
}
|
||||
this.keysDown.add(key);
|
||||
if (key === 'Space' || key === 'ShiftLeft' || key === 'ShiftRight') {
|
||||
if (leapKeys.has(key)) {
|
||||
this.sendLeap();
|
||||
} else {
|
||||
this.sendMovement();
|
||||
}
|
||||
this.sendMovement();
|
||||
};
|
||||
|
||||
private keyUpListener = (event: KeyboardEvent) => {
|
||||
if (this.keysDown.delete(event.code)) {
|
||||
if (this.keysDown.delete(event.code) && movementKeys.has(event.code)) {
|
||||
this.sendMovement();
|
||||
}
|
||||
};
|
||||
|
|
@ -35,6 +52,12 @@ export class KeyboardListener extends InputGenerator {
|
|||
this.sendMovement();
|
||||
};
|
||||
|
||||
public resendMovement() {
|
||||
if ([...this.keysDown].some((key) => movementKeys.has(key))) {
|
||||
this.sendMovement();
|
||||
}
|
||||
}
|
||||
|
||||
private sendMovement() {
|
||||
const down = (...codes: Array<string>) =>
|
||||
codes.some((c) => this.keysDown.has(c)) ? 1 : 0;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ export class MouseListener extends InputGenerator {
|
|||
|
||||
private mouseDownListener = (event: MouseEvent) => {
|
||||
if (event.button === 0) {
|
||||
this.mouseMoveListener(event);
|
||||
this.primaryDownAt = performance.now();
|
||||
ChargeIndicator.begin(event.clientX, event.clientY, true);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,12 +21,13 @@ export class TouchListener extends InputGenerator {
|
|||
|
||||
private isJoystickActive = false;
|
||||
private touchStartPosition = vec2.create();
|
||||
private movement = vec2.create();
|
||||
private primaryDownAt: number | null = null;
|
||||
private gestureTouchId: number | null = null;
|
||||
|
||||
private fireDownAt: number | null = null;
|
||||
private fireTouchId: number | null = null;
|
||||
private fireButtonCenter = vec2.create();
|
||||
private fireAim: vec2 | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly target: HTMLElement,
|
||||
|
|
@ -46,6 +47,7 @@ export class TouchListener extends InputGenerator {
|
|||
this.fireButton.addEventListener('touchstart', this.fireButtonDownListener);
|
||||
this.fireButton.addEventListener('touchmove', this.fireButtonMoveListener);
|
||||
this.fireButton.addEventListener('touchend', this.fireButtonUpListener);
|
||||
this.fireButton.addEventListener('touchcancel', this.fireButtonCancelListener);
|
||||
|
||||
this.leapButton.className = 'touch-button leap';
|
||||
this.leapButton.addEventListener('touchstart', this.leapButtonListener);
|
||||
|
|
@ -54,11 +56,12 @@ export class TouchListener extends InputGenerator {
|
|||
target.addEventListener('touchmove', this.touchMoveListener);
|
||||
target.addEventListener('touchend', this.touchEndListener);
|
||||
target.addEventListener('touchcancel', this.touchCancelListener);
|
||||
window.addEventListener('blur', this.cancelTouches);
|
||||
}
|
||||
|
||||
private findGestureTouch(list: TouchList): Touch | undefined {
|
||||
private findTouch(list: TouchList, id: number | null): Touch | undefined {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (list[i].identifier === this.gestureTouchId) {
|
||||
if (list[i].identifier === id) {
|
||||
return list[i];
|
||||
}
|
||||
}
|
||||
|
|
@ -78,7 +81,7 @@ export class TouchListener extends InputGenerator {
|
|||
),
|
||||
0,
|
||||
);
|
||||
} else {
|
||||
} else if (this.gestureTouchId === null) {
|
||||
this.gestureTouchId = touch.identifier;
|
||||
vec2.set(this.touchStartPosition, touch.clientX, touch.clientY);
|
||||
this.primaryDownAt = performance.now();
|
||||
|
|
@ -89,7 +92,7 @@ export class TouchListener extends InputGenerator {
|
|||
private touchMoveListener = (event: TouchEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
const touch = this.findGestureTouch(event.touches);
|
||||
const touch = this.findTouch(event.touches, this.gestureTouchId);
|
||||
if (!touch) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -117,16 +120,17 @@ export class TouchListener extends InputGenerator {
|
|||
|
||||
if (deltaLength > deadZone) {
|
||||
vec2.set(delta, delta[0], -delta[1]);
|
||||
this.sendMove(vec2.normalize(delta, delta));
|
||||
vec2.normalize(this.movement, delta);
|
||||
} else {
|
||||
this.sendMove(vec2.create());
|
||||
vec2.zero(this.movement);
|
||||
}
|
||||
this.sendMove(vec2.clone(this.movement));
|
||||
};
|
||||
|
||||
private touchEndListener = (event: TouchEvent) => {
|
||||
event.preventDefault();
|
||||
|
||||
const touch = this.findGestureTouch(event.changedTouches);
|
||||
const touch = this.findTouch(event.changedTouches, this.gestureTouchId);
|
||||
if (!touch) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -147,7 +151,7 @@ export class TouchListener extends InputGenerator {
|
|||
};
|
||||
|
||||
private touchCancelListener = (event: TouchEvent) => {
|
||||
if (!this.findGestureTouch(event.changedTouches)) {
|
||||
if (!this.findTouch(event.changedTouches, this.gestureTouchId)) {
|
||||
return;
|
||||
}
|
||||
this.gestureTouchId = null;
|
||||
|
|
@ -161,7 +165,30 @@ export class TouchListener extends InputGenerator {
|
|||
private releaseJoystick() {
|
||||
this.isJoystickActive = false;
|
||||
this.joystick.remove();
|
||||
this.sendMove(vec2.create());
|
||||
vec2.zero(this.movement);
|
||||
this.sendMove(vec2.clone(this.movement));
|
||||
}
|
||||
|
||||
public resendMovement() {
|
||||
if (this.isJoystickActive) {
|
||||
this.sendMove(vec2.clone(this.movement));
|
||||
}
|
||||
}
|
||||
|
||||
private cancelTouches = () => {
|
||||
this.gestureTouchId = null;
|
||||
this.primaryDownAt = null;
|
||||
this.cancelFire();
|
||||
if (this.isJoystickActive) {
|
||||
this.releaseJoystick();
|
||||
}
|
||||
};
|
||||
|
||||
private cancelFire() {
|
||||
this.fireTouchId = null;
|
||||
this.fireDownAt = null;
|
||||
this.fireAimLine.style.opacity = '0';
|
||||
ChargeIndicator.end();
|
||||
}
|
||||
|
||||
private swallowTouch(event: TouchEvent) {
|
||||
|
|
@ -176,6 +203,11 @@ export class TouchListener extends InputGenerator {
|
|||
|
||||
private fireButtonDownListener = (event: TouchEvent) => {
|
||||
this.swallowTouch(event);
|
||||
const touch = event.changedTouches[0];
|
||||
if (this.fireTouchId !== null || !touch) {
|
||||
return;
|
||||
}
|
||||
this.fireTouchId = touch.identifier;
|
||||
this.fireDownAt = performance.now();
|
||||
const rect = this.fireButton.getBoundingClientRect();
|
||||
vec2.set(
|
||||
|
|
@ -183,18 +215,16 @@ export class TouchListener extends InputGenerator {
|
|||
rect.left + rect.width / 2,
|
||||
rect.top + rect.height / 2,
|
||||
);
|
||||
this.fireAim = null;
|
||||
ChargeIndicator.begin(this.fireButtonCenter[0], this.fireButtonCenter[1]);
|
||||
};
|
||||
|
||||
private fireButtonMoveListener = (event: TouchEvent) => {
|
||||
this.swallowTouch(event);
|
||||
const touch = event.targetTouches[0] ?? event.changedTouches[0];
|
||||
const touch = this.findTouch(event.touches, this.fireTouchId);
|
||||
if (this.fireDownAt === null || !touch) {
|
||||
return;
|
||||
}
|
||||
const aim = this.aimFromTouch(touch);
|
||||
this.fireAim = aim;
|
||||
if (aim) {
|
||||
this.fireAimLine.style.opacity = '1';
|
||||
this.fireAimLine.style.transform = `translateY(-50%) rotate(${Math.atan2(-aim[1], aim[0])}rad)`;
|
||||
|
|
@ -215,22 +245,21 @@ export class TouchListener extends InputGenerator {
|
|||
|
||||
private fireButtonUpListener = (event: TouchEvent) => {
|
||||
this.swallowTouch(event);
|
||||
ChargeIndicator.end();
|
||||
this.fireAimLine.style.opacity = '0';
|
||||
if (this.fireDownAt === null) {
|
||||
const touch = this.findTouch(event.changedTouches, this.fireTouchId);
|
||||
if (this.fireDownAt === null || !touch) {
|
||||
return;
|
||||
}
|
||||
|
||||
const charge = chargeHeldSince(this.fireDownAt);
|
||||
this.fireDownAt = null;
|
||||
const aim = this.aimFromTouch(touch);
|
||||
this.cancelFire();
|
||||
|
||||
const character = this.game.gameObjects.localPlayer;
|
||||
if (!character) {
|
||||
return;
|
||||
}
|
||||
|
||||
const direction = this.fireAim ?? character.facingDirection;
|
||||
this.fireAim = null;
|
||||
const direction = aim ?? character.facingDirection;
|
||||
this.sendPrimary(
|
||||
vec2.scaleAndAdd(
|
||||
vec2.create(),
|
||||
|
|
@ -242,10 +271,20 @@ export class TouchListener extends InputGenerator {
|
|||
);
|
||||
};
|
||||
|
||||
private fireButtonCancelListener = (event: TouchEvent) => {
|
||||
this.swallowTouch(event);
|
||||
if (this.findTouch(event.changedTouches, this.fireTouchId)) {
|
||||
this.cancelFire();
|
||||
}
|
||||
};
|
||||
|
||||
public update() {
|
||||
if (!this.fireButton.parentElement) {
|
||||
this.overlay.append(this.fireButton, this.leapButton);
|
||||
}
|
||||
if (this.isJoystickActive && !this.joystick.parentElement) {
|
||||
this.overlay.appendChild(this.joystick);
|
||||
}
|
||||
|
||||
const character = this.game.gameObjects.localPlayer;
|
||||
if (character) {
|
||||
|
|
@ -261,13 +300,16 @@ export class TouchListener extends InputGenerator {
|
|||
this.target.removeEventListener('touchmove', this.touchMoveListener);
|
||||
this.target.removeEventListener('touchend', this.touchEndListener);
|
||||
this.target.removeEventListener('touchcancel', this.touchCancelListener);
|
||||
window.removeEventListener('blur', this.cancelTouches);
|
||||
|
||||
this.fireButton.removeEventListener('touchstart', this.fireButtonDownListener);
|
||||
this.fireButton.removeEventListener('touchmove', this.fireButtonMoveListener);
|
||||
this.fireButton.removeEventListener('touchend', this.fireButtonUpListener);
|
||||
this.fireButton.removeEventListener('touchcancel', this.fireButtonCancelListener);
|
||||
this.leapButton.removeEventListener('touchstart', this.leapButtonListener);
|
||||
|
||||
this.fireButton.remove();
|
||||
this.leapButton.remove();
|
||||
this.joystick.remove();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,8 +59,6 @@ export class Game extends CommandReceiver {
|
|||
private resolveStarted!: () => void;
|
||||
private isBetweenGames = false;
|
||||
private isActive = true;
|
||||
private isEnding = false;
|
||||
private timeScaling = 1;
|
||||
|
||||
private readonly keyboardListener: KeyboardListener;
|
||||
private readonly mouseListener: MouseListener;
|
||||
|
|
@ -92,7 +90,7 @@ export class Game extends CommandReceiver {
|
|||
c.lastLeapClientTimeMs,
|
||||
c.ackAgeMs,
|
||||
),
|
||||
[GameEndCommand.name]: () => (this.isEnding = true),
|
||||
[GameEndCommand.name]: () => (localCharacterPredictor.enabled = false),
|
||||
[UpdateMinimap.name]: (c: UpdateMinimap) => (this.lastMinimap = c),
|
||||
[GameStartCommand.name]: () => this.initialize(),
|
||||
};
|
||||
|
|
@ -125,6 +123,7 @@ export class Game extends CommandReceiver {
|
|||
this.socket?.close();
|
||||
serverTimeline.reset();
|
||||
localCharacterPredictor.reset();
|
||||
localCharacterPredictor.enabled = true;
|
||||
ScreenShake.reset();
|
||||
this.gameObjects.reset();
|
||||
this.gameObjects = new GameObjectContainer(this);
|
||||
|
|
@ -132,10 +131,8 @@ export class Game extends CommandReceiver {
|
|||
this.keystoneArrow = undefined;
|
||||
this.connectionBanner = undefined;
|
||||
this.lastMinimap = undefined;
|
||||
this.isEnding = false;
|
||||
this.lastAnnouncementText = '';
|
||||
this.announcementText.innerText = '';
|
||||
this.timeScaling = 1;
|
||||
this.overlay.append(
|
||||
this.scoreboard.element,
|
||||
this.minimap.element,
|
||||
|
|
@ -172,6 +169,7 @@ export class Game extends CommandReceiver {
|
|||
serverTimeline.reset();
|
||||
localCharacterPredictor.reset();
|
||||
this.gameObjects.reset();
|
||||
this.socketReceiver.reset();
|
||||
this.socket.emit(TransportEvents.PlayerJoining, {
|
||||
...this.playerDecision,
|
||||
reconnectToken: this.reconnectToken,
|
||||
|
|
@ -220,49 +218,64 @@ export class Game extends CommandReceiver {
|
|||
}
|
||||
|
||||
public async start(): Promise<void> {
|
||||
this.initialize();
|
||||
this.resolveStarted();
|
||||
const noiseTexture = await renderNoise([256, 256], 2, 1);
|
||||
setFrameTimeMs(0);
|
||||
try {
|
||||
this.initialize();
|
||||
this.resolveStarted();
|
||||
let renderError: unknown;
|
||||
const noiseTexture = await renderNoise([256, 256], 2, 1);
|
||||
|
||||
await runAnimation(
|
||||
this.canvas,
|
||||
[
|
||||
PlanetShape.descriptor,
|
||||
CharacterShape.descriptor,
|
||||
{
|
||||
...CircleLight.descriptor,
|
||||
shaderCombinationSteps: [0, 1, 2, 4, 8, 16],
|
||||
await runAnimation(
|
||||
this.canvas,
|
||||
[
|
||||
PlanetShape.descriptor,
|
||||
CharacterShape.descriptor,
|
||||
{
|
||||
...CircleLight.descriptor,
|
||||
shaderCombinationSteps: [0, 1, 2, 4, 8, 16],
|
||||
},
|
||||
],
|
||||
(renderer, currentTime, deltaTime) => {
|
||||
try {
|
||||
return this.gameLoop(renderer, currentTime, deltaTime);
|
||||
} catch (error) {
|
||||
renderError = error;
|
||||
return false;
|
||||
}
|
||||
},
|
||||
],
|
||||
this.gameLoop.bind(this),
|
||||
{
|
||||
shadowTraceCount: 16,
|
||||
paletteSize: settings.paletteDim.length,
|
||||
colorPalette: settings.paletteDim,
|
||||
enableHighDpiRendering: true,
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
lightOverlapReduction: settings.lightOverlapReduction,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
{
|
||||
shadowTraceCount: 16,
|
||||
paletteSize: settings.paletteDim.length,
|
||||
colorPalette: settings.paletteDim,
|
||||
enableHighDpiRendering: true,
|
||||
lightCutoffDistance: settings.lightCutoffDistance,
|
||||
lightOverlapReduction: settings.lightOverlapReduction,
|
||||
textures: {
|
||||
noiseTexture: {
|
||||
source: noiseTexture,
|
||||
overrides: {
|
||||
maxFilter: FilteringOptions.LINEAR,
|
||||
wrapS: WrapOptions.MIRRORED_REPEAT,
|
||||
wrapT: WrapOptions.MIRRORED_REPEAT,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
this.socket.close();
|
||||
this.gameObjects.reset();
|
||||
this.overlay.innerHTML = '';
|
||||
this.hideConnectionBanner();
|
||||
FeedbackHud.reset();
|
||||
this.keyboardListener.destroy();
|
||||
this.mouseListener.destroy();
|
||||
this.touchListener.destroy();
|
||||
);
|
||||
if (renderError) {
|
||||
throw renderError;
|
||||
}
|
||||
} finally {
|
||||
this.resolveStarted();
|
||||
this.socket?.close();
|
||||
this.gameObjects.reset();
|
||||
this.overlay.innerHTML = '';
|
||||
this.hideConnectionBanner();
|
||||
FeedbackHud.reset();
|
||||
this.keyboardListener.destroy();
|
||||
this.mouseListener.destroy();
|
||||
this.touchListener.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
public static rejectionText(reason: JoinRejectionReason): string {
|
||||
|
|
@ -307,6 +320,11 @@ export class Game extends CommandReceiver {
|
|||
this.isActive = false;
|
||||
}
|
||||
|
||||
public resendMovement() {
|
||||
this.keyboardListener.resendMovement();
|
||||
this.touchListener.resendMovement();
|
||||
}
|
||||
|
||||
private gameLoop(
|
||||
renderer: Renderer,
|
||||
currentTime: DOMHighResTimeStamp,
|
||||
|
|
@ -333,11 +351,6 @@ export class Game extends CommandReceiver {
|
|||
this.lastAnnouncementText = '';
|
||||
}
|
||||
|
||||
if (this.isEnding) {
|
||||
this.timeScaling *= Math.pow(settings.endGameDeltaScaling, deltaTime);
|
||||
deltaTime /= this.timeScaling;
|
||||
}
|
||||
|
||||
this.gameObjects.step(deltaTime);
|
||||
this.gameObjects.render(renderer, this.overlay, shouldChangeLayout);
|
||||
this.touchListener.update();
|
||||
|
|
|
|||
|
|
@ -18,32 +18,25 @@ export const handleFullScreen = (
|
|||
};
|
||||
|
||||
showButtons();
|
||||
|
||||
let currentWindowHeight = innerHeight;
|
||||
|
||||
const followToggle = () => {
|
||||
SoundHandler.play(Sounds.click);
|
||||
showButtons();
|
||||
currentWindowHeight = innerHeight;
|
||||
};
|
||||
document.addEventListener('fullscreenchange', showButtons);
|
||||
|
||||
const triggerToggle = async () => {
|
||||
await (isInFullScreen()
|
||||
? document.exitFullscreen()
|
||||
: document.body.requestFullscreen());
|
||||
followToggle();
|
||||
try {
|
||||
await (isInFullScreen()
|
||||
? document.exitFullscreen()
|
||||
: document.body.requestFullscreen());
|
||||
SoundHandler.play(Sounds.click);
|
||||
} catch {
|
||||
// The browser may deny fullscreen (for example, when embedded).
|
||||
}
|
||||
};
|
||||
|
||||
addEventListener('keydown', (e) => {
|
||||
if (e.key === 'F11') {
|
||||
triggerToggle();
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
addEventListener('resize', () => {
|
||||
if (isInFullScreen() && currentWindowHeight > innerHeight) {
|
||||
followToggle();
|
||||
if (!e.repeat) {
|
||||
void triggerToggle();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -28,7 +28,10 @@ export class LinearInterpolator {
|
|||
const newest = this.frames.length > 0 ? this.frames[this.frames.length - 1] : null;
|
||||
const wasCoasting = this.isCoasting;
|
||||
|
||||
if (newest && time <= newest.time) {
|
||||
if (newest && time < newest.time) {
|
||||
return;
|
||||
}
|
||||
if (newest && time === newest.time) {
|
||||
this.frames[this.frames.length - 1] = {
|
||||
time: newest.time,
|
||||
value,
|
||||
|
|
|
|||
|
|
@ -9,11 +9,16 @@ import {
|
|||
} from 'shared';
|
||||
import { PlanetView } from '../../objects/types/planet-view';
|
||||
|
||||
export type PlanetSnapshot = Pick<
|
||||
PlanetView,
|
||||
'id' | 'vertices' | 'snapshotRotation' | 'snapshotRotationSpeed'
|
||||
>;
|
||||
|
||||
// Planets only, re-seeded from the newest snapshot every frame; never dispatches collisions.
|
||||
export class ClientCharacterWorld implements CharacterWorld {
|
||||
private surfaces: Array<PlanetBase> = [];
|
||||
|
||||
public sync(planets: Array<PlanetView>) {
|
||||
public sync(planets: Array<PlanetSnapshot>) {
|
||||
this.surfaces = planets
|
||||
.map((planet) => {
|
||||
const surface = new PlanetBase(planet.id, planet.vertices);
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
feetRadius,
|
||||
headRadius,
|
||||
} from 'shared';
|
||||
import { ClientCharacterWorld } from './client-character-world';
|
||||
import { ClientCharacterWorld, PlanetSnapshot } from './client-character-world';
|
||||
import type { PlanetView } from '../../objects/types/planet-view';
|
||||
import { InputHistory } from './input-history';
|
||||
|
||||
|
|
@ -25,6 +25,18 @@ export const setFrameTimeMs = (timeMs: number): void => {
|
|||
export const clientTimeMs = (): number => frameTimeMs;
|
||||
|
||||
const maxReplayMs = 400;
|
||||
const correctionSeconds = 0.08;
|
||||
const snapDistance = 1500;
|
||||
|
||||
interface ReplaySnapshot {
|
||||
pose: { head: Circle; leftFoot: Circle; rightFoot: Circle };
|
||||
movement: CharacterMovementSnapshot;
|
||||
anchorMs: number;
|
||||
leapAckMs: number;
|
||||
strength: number;
|
||||
planets: Array<PlanetSnapshot>;
|
||||
horizonState?: CharacterMovementState;
|
||||
}
|
||||
|
||||
const upwards = vec2.fromValues(0, 1);
|
||||
|
||||
|
|
@ -37,6 +49,7 @@ const makeBody = (center: vec2, radius: number, normal: vec2): PhysicsBody => ({
|
|||
});
|
||||
|
||||
export class LocalCharacterPredictor {
|
||||
public enabled = true;
|
||||
private readonly inputHistory = new InputHistory();
|
||||
private readonly world = new ClientCharacterWorld();
|
||||
|
||||
|
|
@ -48,6 +61,9 @@ export class LocalCharacterPredictor {
|
|||
private currentStrength = settings.playerMaxStrength;
|
||||
|
||||
private alive = true;
|
||||
private previousSnapshot?: ReplaySnapshot;
|
||||
private lastUpdateMs?: number;
|
||||
private readonly correction = vec2.create();
|
||||
|
||||
private renderHead = new Circle(vec2.create(), headRadius);
|
||||
private renderLeftFoot = new Circle(vec2.create(), feetRadius);
|
||||
|
|
@ -75,10 +91,7 @@ export class LocalCharacterPredictor {
|
|||
lastLeapClientTimeMs: number,
|
||||
ackAgeMs = 0,
|
||||
): void {
|
||||
const anchor = clientTimeMs + Math.max(0, ackAgeMs);
|
||||
if (this.replayAnchorMs === undefined || anchor > this.replayAnchorMs) {
|
||||
this.replayAnchorMs = anchor;
|
||||
}
|
||||
this.replayAnchorMs = clientTimeMs + Math.max(0, ackAgeMs);
|
||||
this.movement = movement;
|
||||
this.lastLeapAckMs = lastLeapClientTimeMs;
|
||||
}
|
||||
|
|
@ -114,6 +127,9 @@ export class LocalCharacterPredictor {
|
|||
this.movement = undefined;
|
||||
this.currentStrength = settings.playerMaxStrength;
|
||||
this.alive = true;
|
||||
this.previousSnapshot = undefined;
|
||||
this.lastUpdateMs = undefined;
|
||||
vec2.zero(this.correction);
|
||||
}
|
||||
|
||||
public get canPredict(): boolean {
|
||||
|
|
@ -132,29 +148,77 @@ export class LocalCharacterPredictor {
|
|||
}
|
||||
|
||||
public update(planets: Array<PlanetView>): boolean {
|
||||
if (!this.alive || !this.canPredict || this.isAnimatingInOrOut) {
|
||||
if (!this.enabled || !this.alive || !this.canPredict || this.isAnimatingInOrOut) {
|
||||
this.previousSnapshot = undefined;
|
||||
this.lastUpdateMs = undefined;
|
||||
vec2.zero(this.correction);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.world.sync(planets);
|
||||
const predicted = this.simulate();
|
||||
const now = clientTimeMs();
|
||||
const deltaSeconds =
|
||||
this.lastUpdateMs === undefined ? 0 : (now - this.lastUpdateMs) / 1000;
|
||||
vec2.scale(
|
||||
this.correction,
|
||||
this.correction,
|
||||
Math.exp(-deltaSeconds / correctionSeconds),
|
||||
);
|
||||
const snapshot: ReplaySnapshot =
|
||||
this.previousSnapshot && this.previousSnapshot.pose === this.authoritative
|
||||
? this.previousSnapshot
|
||||
: {
|
||||
pose: this.authoritative!,
|
||||
movement: this.movement!,
|
||||
anchorMs: this.replayAnchorMs!,
|
||||
leapAckMs: this.lastLeapAckMs,
|
||||
strength: this.currentStrength,
|
||||
planets: planets.map(
|
||||
({ id, vertices, snapshotRotation, snapshotRotationSpeed }) => ({
|
||||
id,
|
||||
vertices,
|
||||
snapshotRotation,
|
||||
snapshotRotationSpeed,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const predicted = this.simulate(snapshot);
|
||||
|
||||
vec2.copy(this.renderHead.center, predicted.head.center);
|
||||
this.renderHead.radius = predicted.head.radius;
|
||||
vec2.copy(this.renderLeftFoot.center, predicted.leftFoot.center);
|
||||
this.renderLeftFoot.radius = predicted.leftFoot.radius;
|
||||
vec2.copy(this.renderRightFoot.center, predicted.rightFoot.center);
|
||||
this.renderRightFoot.radius = predicted.rightFoot.radius;
|
||||
if (this.previousSnapshot && this.previousSnapshot.pose !== snapshot.pose) {
|
||||
// Compare both snapshots at the same instant: smooth only the correction,
|
||||
// leaving fresh input and ordinary movement immediate.
|
||||
const previous = this.simulate(this.previousSnapshot);
|
||||
vec2.add(
|
||||
this.correction,
|
||||
this.correction,
|
||||
vec2.subtract(vec2.create(), previous.head.center, predicted.head.center),
|
||||
);
|
||||
if (vec2.length(this.correction) > snapDistance) {
|
||||
vec2.zero(this.correction);
|
||||
}
|
||||
}
|
||||
for (const [render, body] of [
|
||||
[this.renderHead, predicted.head],
|
||||
[this.renderLeftFoot, predicted.leftFoot],
|
||||
[this.renderRightFoot, predicted.rightFoot],
|
||||
]) {
|
||||
vec2.add(render.center, body.center, this.correction);
|
||||
render.radius = body.radius;
|
||||
}
|
||||
this.previousSnapshot = snapshot;
|
||||
this.lastUpdateMs = now;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private simulate(): CharacterMovementState {
|
||||
const auth = this.authoritative!;
|
||||
const movement = this.movement!;
|
||||
private simulate(snapshot: ReplaySnapshot): CharacterMovementState {
|
||||
if (snapshot.horizonState) {
|
||||
return snapshot.horizonState;
|
||||
}
|
||||
this.world.sync(snapshot.planets);
|
||||
const { pose: auth, movement } = snapshot;
|
||||
const now = clientTimeMs();
|
||||
const startMs = Math.max(this.replayAnchorMs!, now - maxReplayMs);
|
||||
const windowMs = Math.max(0, now - startMs);
|
||||
const startMs = snapshot.anchorMs;
|
||||
const windowMs = Math.min(maxReplayMs, Math.max(0, now - startMs));
|
||||
const steps = Math.floor(windowMs / stepMs);
|
||||
const partialStep = (windowMs - steps * stepMs) / stepMs;
|
||||
|
||||
|
|
@ -176,39 +240,32 @@ export class LocalCharacterPredictor {
|
|||
bodyVelocity: vec2.fromValues(movement.bodyVelocity[0], movement.bodyVelocity[1]),
|
||||
};
|
||||
|
||||
const cooldownMs = settings.leapCooldownSeconds * 1000;
|
||||
let availableStrength = this.currentStrength;
|
||||
let lastLeapMs = -Infinity;
|
||||
let availableStrength = snapshot.strength;
|
||||
let cooldown = movement.leapCooldownRemaining ?? 0;
|
||||
|
||||
let t = startMs;
|
||||
for (let i = 0; i < steps; i++) {
|
||||
const input = this.inputHistory.directionAt(t);
|
||||
this.world.advance(stepSeconds);
|
||||
tickPlanetDetachment(state, stepSeconds);
|
||||
stepCharacterMovement(state, this.world, input, stepSeconds);
|
||||
|
||||
for (let i = 0; i < steps + (partialStep > 0 ? 1 : 0); i++) {
|
||||
const fraction = i < steps ? 1 : partialStep;
|
||||
const from =
|
||||
fraction < 1
|
||||
? [state.head, state.leftFoot, state.rightFoot].map((body) =>
|
||||
vec2.clone(body.center),
|
||||
)
|
||||
: undefined;
|
||||
for (const leapMs of this.leapHistory) {
|
||||
if (
|
||||
leapMs >= t &&
|
||||
leapMs < t + stepMs &&
|
||||
leapMs > this.lastLeapAckMs &&
|
||||
leapMs < t + stepMs * fraction &&
|
||||
leapMs > snapshot.leapAckMs &&
|
||||
state.currentPlanet &&
|
||||
leapMs - lastLeapMs >= cooldownMs &&
|
||||
cooldown <= 0 &&
|
||||
availableStrength >= settings.leapStrengthCost
|
||||
) {
|
||||
applyLeapImpulse(state, this.inputHistory.directionAt(leapMs));
|
||||
availableStrength -= settings.leapStrengthCost;
|
||||
lastLeapMs = leapMs;
|
||||
cooldown = settings.leapCooldownSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
t += stepMs;
|
||||
}
|
||||
|
||||
if (partialStep > 0) {
|
||||
const from = [state.head, state.leftFoot, state.rightFoot].map((b) =>
|
||||
vec2.clone(b.center),
|
||||
);
|
||||
this.world.advance(stepSeconds);
|
||||
tickPlanetDetachment(state, stepSeconds);
|
||||
stepCharacterMovement(
|
||||
|
|
@ -217,11 +274,22 @@ export class LocalCharacterPredictor {
|
|||
this.inputHistory.directionAt(t),
|
||||
stepSeconds,
|
||||
);
|
||||
[state.head, state.leftFoot, state.rightFoot].forEach((body, i) =>
|
||||
vec2.lerp(body.center, from[i], body.center, partialStep),
|
||||
cooldown = Math.max(0, cooldown - stepSeconds);
|
||||
availableStrength = Math.min(
|
||||
settings.playerMaxStrength,
|
||||
availableStrength + settings.playerStrengthRegenerationPerSeconds * stepSeconds,
|
||||
);
|
||||
if (from) {
|
||||
[state.head, state.leftFoot, state.rightFoot].forEach((body, index) =>
|
||||
vec2.lerp(body.center, from[index], body.center, fraction),
|
||||
);
|
||||
}
|
||||
t += stepMs;
|
||||
}
|
||||
|
||||
if (windowMs === maxReplayMs) {
|
||||
snapshot.horizonState = state;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const resyncSeconds = 0.3;
|
|||
class ServerTimeline {
|
||||
private cursor?: number;
|
||||
private newestSnapshotTime?: number;
|
||||
private sinceNewestSnapshot = 0;
|
||||
private newestReceivedAtMs = 0;
|
||||
public snapshotTime = 0;
|
||||
|
||||
public get renderTime(): number {
|
||||
|
|
@ -20,7 +20,7 @@ class ServerTimeline {
|
|||
this.snapshotTime = timestamp;
|
||||
if (this.newestSnapshotTime === undefined || timestamp > this.newestSnapshotTime) {
|
||||
this.newestSnapshotTime = timestamp;
|
||||
this.sinceNewestSnapshot = 0;
|
||||
this.newestReceivedAtMs = performance.now();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -29,10 +29,9 @@ class ServerTimeline {
|
|||
return;
|
||||
}
|
||||
|
||||
this.sinceNewestSnapshot += deltaTimeInSeconds;
|
||||
const target =
|
||||
this.newestSnapshotTime +
|
||||
this.sinceNewestSnapshot -
|
||||
(performance.now() - this.newestReceivedAtMs) / 1000 -
|
||||
settings.interpolationDelaySeconds;
|
||||
|
||||
if (this.cursor === undefined || Math.abs(target - this.cursor) > resyncSeconds) {
|
||||
|
|
@ -40,18 +39,16 @@ class ServerTimeline {
|
|||
return;
|
||||
}
|
||||
|
||||
const rate = clamp(
|
||||
1 + (target - this.cursor) * rateGain,
|
||||
1 - maxRateAdjustment,
|
||||
1 + maxRateAdjustment,
|
||||
);
|
||||
this.cursor += deltaTimeInSeconds * rate;
|
||||
this.cursor += deltaTimeInSeconds;
|
||||
this.cursor +=
|
||||
deltaTimeInSeconds *
|
||||
clamp((target - this.cursor) * rateGain, -maxRateAdjustment, maxRateAdjustment);
|
||||
}
|
||||
|
||||
public reset() {
|
||||
this.cursor = undefined;
|
||||
this.newestSnapshotTime = undefined;
|
||||
this.sinceNewestSnapshot = 0;
|
||||
this.newestReceivedAtMs = 0;
|
||||
this.snapshotTime = 0;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
16
frontend/src/scripts/helper/storage.ts
Normal file
16
frontend/src/scripts/helper/storage.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
export function loadStoredValue(key: string): unknown {
|
||||
try {
|
||||
const stored = localStorage.getItem(key);
|
||||
return stored === null ? undefined : JSON.parse(stored);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveStoredValue(key: string, value: unknown): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// Preferences still apply for this visit when browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
|
@ -16,12 +16,8 @@ export class JoinFormHandler {
|
|||
private readonly decision: Promise<PlayerDecision>;
|
||||
private readonly pollServersTimer: ReturnType<typeof setInterval>;
|
||||
private servers: Array<ServerChooserOption> = [];
|
||||
|
||||
private keyUpListener = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !this.joinButton.disabled) {
|
||||
this.form.requestSubmit();
|
||||
}
|
||||
};
|
||||
private readonly pendingRequests = new Map<string, AbortController>();
|
||||
private destroyed = false;
|
||||
|
||||
constructor(
|
||||
private readonly form: HTMLFormElement,
|
||||
|
|
@ -33,14 +29,16 @@ export class JoinFormHandler {
|
|||
this.decision = new Promise((resolve) => {
|
||||
form.onsubmit = (e) => {
|
||||
e.preventDefault();
|
||||
if (this.joinButton.disabled) {
|
||||
return;
|
||||
}
|
||||
SoundHandler.play(Sounds.click);
|
||||
const data = new FormData(form);
|
||||
this.destroy();
|
||||
resolve({ name: String(data.get('name')), server: String(data.get('server')) });
|
||||
};
|
||||
});
|
||||
this.decision.then(() => this.destroy());
|
||||
|
||||
addEventListener('keyup', this.keyUpListener);
|
||||
this.pollServersTimer = setInterval(() => this.loadServers(), pollInterval);
|
||||
this.loadServers();
|
||||
}
|
||||
|
|
@ -49,49 +47,60 @@ export class JoinFormHandler {
|
|||
return this.decision;
|
||||
}
|
||||
|
||||
private destroy() {
|
||||
removeEventListener('keyup', this.keyUpListener);
|
||||
public destroy() {
|
||||
this.destroyed = true;
|
||||
this.form.onsubmit = null;
|
||||
clearInterval(this.pollServersTimer);
|
||||
this.pendingRequests.forEach((controller) => controller.abort());
|
||||
this.servers.forEach((s) => s.destroy());
|
||||
}
|
||||
|
||||
private loadServers() {
|
||||
servers
|
||||
.filter((url) => !this.servers.some((s) => s.url === url))
|
||||
.forEach(async (url) => {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), pollInterval * 0.8);
|
||||
for (const url of servers) {
|
||||
if (!this.pendingRequests.has(url) && !this.servers.some((s) => s.url === url)) {
|
||||
void this.loadServer(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let content: ServerInformation;
|
||||
try {
|
||||
const response = await fetch(url + serverInformationEndpoint, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
content = await response.json();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.servers.some((s) => s.url === url)) {
|
||||
const server = new ServerChooserOption(
|
||||
content,
|
||||
url,
|
||||
(s) => this.removeServer(s),
|
||||
this.servers.length === 0,
|
||||
);
|
||||
this.servers.push(server);
|
||||
this.joinButton.disabled = false;
|
||||
this.container.appendChild(server.element);
|
||||
}
|
||||
private async loadServer(url: string) {
|
||||
const controller = new AbortController();
|
||||
this.pendingRequests.set(url, controller);
|
||||
const timeout = setTimeout(() => controller.abort(), pollInterval * 0.8);
|
||||
try {
|
||||
const response = await fetch(url + serverInformationEndpoint, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
const content: ServerInformation = await response.json();
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
const server = new ServerChooserOption(
|
||||
content,
|
||||
url,
|
||||
(s) => this.removeServer(s),
|
||||
this.servers.length === 0,
|
||||
);
|
||||
this.servers.push(server);
|
||||
this.joinButton.disabled = false;
|
||||
this.container.appendChild(server.element);
|
||||
} catch {
|
||||
// Unavailable servers are retried on the next poll.
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
this.pendingRequests.delete(url);
|
||||
}
|
||||
}
|
||||
|
||||
private removeServer(server: ServerChooserOption) {
|
||||
this.servers = this.servers.filter((s) => s !== server);
|
||||
this.joinButton.disabled = this.servers.length === 0;
|
||||
if (this.servers.length && !this.servers.some((s) => s.input.checked)) {
|
||||
this.servers[0].input.checked = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -107,9 +116,11 @@ const roundCompletionTexts = [
|
|||
|
||||
class ServerChooserOption {
|
||||
public readonly element = document.createElement('div');
|
||||
public readonly input = document.createElement('input');
|
||||
private readonly serverNameElement = document.createElement('span');
|
||||
private readonly completionElement = document.createElement('span');
|
||||
private readonly socket: Socket;
|
||||
private readonly reconnectFailedListener = () => this.destroy();
|
||||
|
||||
constructor(
|
||||
private readonly content: ServerInformation,
|
||||
|
|
@ -117,7 +128,7 @@ class ServerChooserOption {
|
|||
private readonly onDestroy: (v: ServerChooserOption) => unknown,
|
||||
isFirst: boolean,
|
||||
) {
|
||||
const input = document.createElement('input');
|
||||
const input = this.input;
|
||||
input.required = true;
|
||||
input.type = 'radio';
|
||||
input.id = input.value = url;
|
||||
|
|
@ -144,7 +155,7 @@ class ServerChooserOption {
|
|||
parser,
|
||||
} as any);
|
||||
|
||||
this.socket.io.on('reconnect_failed', () => this.destroy());
|
||||
this.socket.io.on('reconnect_failed', this.reconnectFailedListener);
|
||||
this.socket.on('connect', () =>
|
||||
this.socket.emit(TransportEvents.SubscribeForServerInfoUpdates),
|
||||
);
|
||||
|
|
@ -159,6 +170,7 @@ class ServerChooserOption {
|
|||
}
|
||||
|
||||
public destroy() {
|
||||
this.socket.io.off('reconnect_failed', this.reconnectFailedListener);
|
||||
this.socket.close();
|
||||
this.element.remove();
|
||||
this.onDestroy(this);
|
||||
|
|
|
|||
|
|
@ -27,14 +27,16 @@ export class LandingPageBackground {
|
|||
};
|
||||
|
||||
constructor(canvas: HTMLCanvasElement) {
|
||||
this.renderer = new Promise((r) => (this.resolveRenderer = r));
|
||||
this.start(canvas);
|
||||
this.renderer = new Promise((resolve, reject) => {
|
||||
this.resolveRenderer = resolve;
|
||||
void this.start(canvas).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
private async start(canvas: HTMLCanvasElement): Promise<void> {
|
||||
const noiseTexture = await renderNoise([256, 256], 1.2, 2);
|
||||
|
||||
runAnimation(
|
||||
await runAnimation(
|
||||
canvas,
|
||||
[
|
||||
{ ...PlanetShape.descriptor, shaderCombinationSteps: [0, 1, 2] },
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import {
|
|||
DeleteObjectsCommand,
|
||||
Id,
|
||||
PropertyUpdatesForObjects,
|
||||
RemoteCall,
|
||||
RemoteCallsForObjects,
|
||||
settings,
|
||||
UpdatePropertyCommand,
|
||||
} from 'shared';
|
||||
import { FeedbackHud } from '../feedback-hud';
|
||||
|
|
@ -34,6 +34,8 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
private deleteAt = new Map<Id, number>();
|
||||
private awaitingCreateStamp: Array<Id> = [];
|
||||
private awaitingDeleteStamp: Array<Id> = [];
|
||||
private remoteCalls: Array<{ object: View; calls: Array<RemoteCall>; at?: number }> =
|
||||
[];
|
||||
|
||||
protected commandExecutors: CommandExecutors = {
|
||||
[CreatePlayerCommand.name]: (c: CreatePlayerCommand) => {
|
||||
|
|
@ -41,6 +43,7 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
this.player.isMainCharacter = true;
|
||||
this.addObject(this.player);
|
||||
localCharacterPredictor.reset();
|
||||
this.game.resendMovement();
|
||||
FeedbackHud.hideElimination();
|
||||
this.wasLocalPlayerAlive = true;
|
||||
},
|
||||
|
|
@ -52,9 +55,14 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
}),
|
||||
|
||||
[RemoteCallsForObjects.name]: (c: RemoteCallsForObjects) =>
|
||||
c.callsForObjects.forEach((c) =>
|
||||
this.objects.get(c.id)?.processRemoteCalls(c.calls),
|
||||
),
|
||||
c.callsForObjects.forEach(({ id, calls }) => {
|
||||
const object = this.objects.get(id);
|
||||
if (object === this.player) {
|
||||
object?.processRemoteCalls(calls);
|
||||
} else if (object) {
|
||||
this.remoteCalls.push({ object, calls });
|
||||
}
|
||||
}),
|
||||
|
||||
[PropertyUpdatesForObjects.name]: (c: PropertyUpdatesForObjects) => {
|
||||
serverTimeline.onSnapshot(c.timestamp);
|
||||
|
|
@ -72,7 +80,7 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
c.ids.forEach((id: Id) => this.awaitingDeleteStamp.push(id)),
|
||||
};
|
||||
|
||||
constructor(game: Game) {
|
||||
constructor(private readonly game: Game) {
|
||||
super();
|
||||
this.camera = new Camera(game);
|
||||
}
|
||||
|
|
@ -86,6 +94,7 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
this.deleteAt.clear();
|
||||
this.awaitingCreateStamp = [];
|
||||
this.awaitingDeleteStamp = [];
|
||||
this.remoteCalls = [];
|
||||
this.wasLocalPlayerAlive = false;
|
||||
}
|
||||
|
||||
|
|
@ -96,6 +105,16 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
public step(deltaTimeInSeconds: number) {
|
||||
this.stampPending(serverTimeline.snapshotTime);
|
||||
this.retireDueObjects();
|
||||
this.remoteCalls = this.remoteCalls.filter(({ object, calls, at }) => {
|
||||
if (this.objects.get(object.id) !== object) {
|
||||
return false;
|
||||
}
|
||||
if (at !== undefined && at <= serverTimeline.renderTime) {
|
||||
object.processRemoteCalls(calls);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.objects.forEach((o) => o.step(deltaTimeInSeconds));
|
||||
|
||||
const player = this.localPlayer;
|
||||
|
|
@ -107,15 +126,13 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
|
||||
if (player) {
|
||||
localCharacterPredictor.setAlive(alive);
|
||||
localCharacterPredictor.setStrength(
|
||||
player.strengthFraction * settings.playerMaxStrength,
|
||||
);
|
||||
localCharacterPredictor.setStrength(player.snapshotStrength);
|
||||
if (localCharacterPredictor.update(this.planets)) {
|
||||
player.head = localCharacterPredictor.head;
|
||||
player.leftFoot = localCharacterPredictor.leftFoot;
|
||||
player.rightFoot = localCharacterPredictor.rightFoot;
|
||||
}
|
||||
this.camera.follow(player.position, deltaTimeInSeconds);
|
||||
this.camera.follow(player.position);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -144,11 +161,14 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
this.deleteAt.set(id, timestamp);
|
||||
}
|
||||
this.awaitingDeleteStamp = [];
|
||||
for (const call of this.remoteCalls) {
|
||||
call.at ??= timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
private retireDueObjects() {
|
||||
const renderTime = serverTimeline.renderTime;
|
||||
for (const [id, at] of [...this.deleteAt]) {
|
||||
for (const [id, at] of this.deleteAt) {
|
||||
if (renderTime >= at) {
|
||||
this.deleteObject(id);
|
||||
}
|
||||
|
|
@ -172,6 +192,12 @@ export class GameObjectContainer extends CommandReceiver {
|
|||
}
|
||||
|
||||
private addObject(object: View) {
|
||||
// An object can re-enter the interest area before its delayed deletion is drawn.
|
||||
// Retire the old view and its pending deletion before installing the replacement.
|
||||
if (this.objects.has(object.id)) {
|
||||
this.deleteObject(object.id);
|
||||
}
|
||||
this.awaitingDeleteStamp = this.awaitingDeleteStamp.filter((id) => id !== object.id);
|
||||
this.objects.set(object.id, object);
|
||||
if (object instanceof PlanetView) {
|
||||
this.planets.push(object);
|
||||
|
|
|
|||
|
|
@ -1,28 +1,17 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { Renderer } from 'sdf-2d';
|
||||
import { calculateViewArea, followVec2, mixRgb, settings } from 'shared';
|
||||
import { calculateViewArea, mixRgb, settings } from 'shared';
|
||||
import type { Game } from '../../game';
|
||||
import { ScreenShake } from '../../screen-shake';
|
||||
|
||||
const followSeconds = 0.08;
|
||||
const snapDistance = 1500;
|
||||
|
||||
export class Camera {
|
||||
public readonly center: vec2 = vec2.create();
|
||||
private readonly previousTarget = vec2.create();
|
||||
private aspectRatio?: number;
|
||||
|
||||
constructor(private readonly game: Game) {}
|
||||
|
||||
public follow(target: vec2, deltaTimeInSeconds: number) {
|
||||
followVec2(
|
||||
this.center,
|
||||
target,
|
||||
this.previousTarget,
|
||||
deltaTimeInSeconds,
|
||||
followSeconds,
|
||||
snapDistance,
|
||||
);
|
||||
public follow(target: vec2) {
|
||||
vec2.copy(this.center, target);
|
||||
}
|
||||
|
||||
public draw(renderer: Renderer) {
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ const deathIcon =
|
|||
|
||||
export class CharacterView extends CharacterBase implements View {
|
||||
public isMainCharacter = false;
|
||||
public snapshotStrength = settings.playerMaxStrength;
|
||||
|
||||
private readonly shape: CharacterShape;
|
||||
private readonly muzzleFlash: CircleLight;
|
||||
|
|
@ -144,6 +145,7 @@ export class CharacterView extends CharacterBase implements View {
|
|||
} else if (propertyKey === 'rightFoot') {
|
||||
this.rightFootInterpolator.addFrame(propertyValue, rateOfChange);
|
||||
} else if (propertyKey === 'strength') {
|
||||
this.snapshotStrength = propertyValue;
|
||||
this.strengthInterpolator.addFrame(propertyValue, rateOfChange);
|
||||
}
|
||||
}
|
||||
|
|
@ -225,7 +227,6 @@ export class CharacterView extends CharacterBase implements View {
|
|||
0,
|
||||
this.muzzleFlashIntensity - deltaTimeInSeconds / muzzleFlashDecaySeconds,
|
||||
);
|
||||
this.muzzleFlash.center = this.head.center;
|
||||
this.muzzleFlash.intensity = this.muzzleFlashIntensity;
|
||||
}
|
||||
|
||||
|
|
@ -241,7 +242,6 @@ export class CharacterView extends CharacterBase implements View {
|
|||
0,
|
||||
this.deathBurstIntensity - deltaTimeInSeconds / deathBurstDecaySeconds,
|
||||
);
|
||||
this.deathBurst.center = this.bodyCenter;
|
||||
this.deathBurst.intensity =
|
||||
deathBurstMaxIntensity * this.deathBurstIntensity * this.deathBurstIntensity;
|
||||
}
|
||||
|
|
@ -284,9 +284,11 @@ export class CharacterView extends CharacterBase implements View {
|
|||
renderer.addDrawable(this.shape);
|
||||
|
||||
if (this.muzzleFlashIntensity > 0) {
|
||||
this.muzzleFlash.center = this.head.center;
|
||||
renderer.addDrawable(this.muzzleFlash);
|
||||
}
|
||||
if (this.deathBurstIntensity > 0) {
|
||||
this.deathBurst.center = this.bodyCenter;
|
||||
renderer.addDrawable(this.deathBurst);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,11 +8,13 @@ import {
|
|||
UpdatePropertyCommand,
|
||||
} from 'shared';
|
||||
import { Vec2Interpolator } from '../../helper/interpolators/vec2-interpolator';
|
||||
import { LinearInterpolator } from '../../helper/interpolators/linear-interpolator';
|
||||
import { View } from '../view';
|
||||
|
||||
export class ProjectileView extends ProjectileBase implements View {
|
||||
private readonly light: CircleLight;
|
||||
private readonly centerInterpolator: Vec2Interpolator;
|
||||
private readonly strengthInterpolator: LinearInterpolator;
|
||||
|
||||
constructor(
|
||||
id: Id,
|
||||
|
|
@ -28,15 +30,23 @@ export class ProjectileView extends ProjectileBase implements View {
|
|||
0,
|
||||
);
|
||||
this.centerInterpolator = new Vec2Interpolator(center);
|
||||
this.strengthInterpolator = new LinearInterpolator(strength);
|
||||
}
|
||||
|
||||
public updateProperty({ propertyValue, rateOfChange }: UpdatePropertyCommand) {
|
||||
this.centerInterpolator.addFrame(propertyValue, rateOfChange);
|
||||
public updateProperty({
|
||||
propertyKey,
|
||||
propertyValue,
|
||||
rateOfChange,
|
||||
}: UpdatePropertyCommand) {
|
||||
if (propertyKey === 'center') {
|
||||
this.centerInterpolator.addFrame(propertyValue, rateOfChange);
|
||||
} else if (propertyKey === 'strength') {
|
||||
this.strengthInterpolator.addFrame(propertyValue, rateOfChange);
|
||||
}
|
||||
}
|
||||
|
||||
public step(deltaTimeInSeconds: number) {
|
||||
super.step(deltaTimeInSeconds);
|
||||
|
||||
this.strength = Math.max(0, this.strengthInterpolator.getValue(deltaTimeInSeconds));
|
||||
this.center = this.centerInterpolator.getValue(deltaTimeInSeconds);
|
||||
this.light.center = this.center;
|
||||
this.light.intensity = Math.min(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { SoundHandler, Sounds } from './sound-handler';
|
||||
import { VibrationHandler } from './vibration-handler';
|
||||
import { loadStoredValue, saveStoredValue } from './helper/storage';
|
||||
|
||||
export interface Options {
|
||||
vibrationEnabled: boolean;
|
||||
|
|
@ -13,14 +14,17 @@ export const options: Options = {
|
|||
musicEnabled: true,
|
||||
};
|
||||
|
||||
const save = () => localStorage.setItem('options', JSON.stringify(options));
|
||||
|
||||
export const initializeOptions = (
|
||||
inputElements: Record<keyof Options, HTMLInputElement>,
|
||||
) => {
|
||||
const stored = localStorage.getItem('options');
|
||||
if (stored) {
|
||||
Object.assign(options, JSON.parse(stored));
|
||||
const stored = loadStoredValue('options');
|
||||
if (stored && typeof stored === 'object') {
|
||||
for (const key of Object.keys(inputElements) as Array<keyof Options>) {
|
||||
const value = (stored as Partial<Options>)[key];
|
||||
if (typeof value === 'boolean') {
|
||||
options[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (options.musicEnabled) {
|
||||
|
|
@ -51,7 +55,7 @@ export const initializeOptions = (
|
|||
}
|
||||
|
||||
SoundHandler.play(Sounds.click);
|
||||
save();
|
||||
saveStoredValue('options', options);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ let initialized = false;
|
|||
async function initializeSound(src: string): Promise<HTMLAudioElement> {
|
||||
const snd = new Audio(src);
|
||||
snd.muted = true;
|
||||
await snd.play();
|
||||
await snd.play().catch(() => undefined);
|
||||
snd.pause();
|
||||
snd.muted = false;
|
||||
snd.currentTime = 0;
|
||||
|
|
@ -27,20 +27,22 @@ async function initialize(
|
|||
onPlayKeypress: () => unknown = () => null,
|
||||
onPauseKeypress: () => unknown = () => null,
|
||||
) {
|
||||
ambient.muted = true;
|
||||
ambient.volume = 0.5;
|
||||
ambient.loop = true;
|
||||
// Unlock every audio element during the initiating click, before awaiting any one.
|
||||
const ambientReady = ambient.play().catch(() => undefined);
|
||||
const [hit, shoot, click] = await Promise.all(
|
||||
[hitSound, shootSound, clickSound].map(initializeSound),
|
||||
);
|
||||
sounds = { hit, shoot, click };
|
||||
|
||||
await ambient.play();
|
||||
ambient.muted = true;
|
||||
await ambientReady;
|
||||
initialized = true;
|
||||
ambient.onpause = onPauseKeypress;
|
||||
ambient.onplay = onPlayKeypress;
|
||||
|
||||
ambient.muted = false;
|
||||
ambient.volume = 0.5;
|
||||
ambient.loop = true;
|
||||
|
||||
if (!isAmbientPlaying) {
|
||||
ambient.pause();
|
||||
|
|
@ -66,7 +68,7 @@ function play(snd: Sound, volume = 1, playbackRate = 1) {
|
|||
function playAmbient() {
|
||||
isAmbientPlaying = true;
|
||||
if (initialized) {
|
||||
ambient.play();
|
||||
void ambient.play().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue