humus-old/client/index.js
2019-03-30 05:08:58 -05:00

157 lines
4.0 KiB
JavaScript

import {create as createClient} from '@avocado/client';
import {EntityList} from '@avocado/entity';
import {ActionRegistry} from '@avocado/input';
import {Stage} from '@avocado/graphics';
import {Vector} from '@avocado/math';
import {World} from '@avocado/physics/matter/world';
import {StateSynchronizer} from '@avocado/state';
import {Room, RoomView} from '@avocado/topdown';
import {clearAnimation, setAnimation} from '@avocado/timing';
// DOM.
const appNode = document.querySelector('.app');
// Graphics stage.
const stage = new Stage([640, 360]);
stage.scale = [2, 2];
stage.addToDom(appNode);
stage.element.addEventListener('blur', () => {
stage.sepia();
});
stage.element.addEventListener('focus', () => {
stage.removeAllFilters();
});
// Create room.
const room = new Room();
room.world = new World();
const roomView = new RoomView(room, stage.renderer);
stage.addChild(roomView);
// Synchronize state.
const stateSynchronizer = new StateSynchronizer({
room,
});
// Handle "own" entity.
let selfEntity;
function hasSelfEntity() {
return selfEntity && 'string' !== typeof selfEntity;
}
room.on('entityAdded', (entity) => {
entity.removeTrait('controllable');
// Set self entity.
if ('string' === typeof selfEntity) {
if (entity === room.findEntity(selfEntity)) {
selfEntity = entity;
// Only self entity should be controllable.
entity.addTrait('controllable');
}
}
});
// Accept input.
const canvasNode = document.querySelector('.app canvas');
const actionRegistry = new ActionRegistry();
actionRegistry.mapKeysToActions({
'w': 'MoveUp',
'a': 'MoveLeft',
's': 'MoveDown',
'd': 'MoveRight',
});
actionRegistry.listen(canvasNode);
// Mouse/touch movement.
function createMoveToNormal(position) {
if (!selfEntity) {
return;
}
const entityPosition = selfEntity.position;
const magnitude = Vector.magnitude(position, entityPosition);
if (magnitude < 8) {
return;
}
const diff = Vector.sub(position, entityPosition);
return Vector.normalize(diff);
}
let pointingAt = [-1, -1];
function isPointingAtAnything() {
return -1 !== pointingAt[0] && -1 !== pointingAt[1];
}
stage.on('pointerDown', (event) => {
pointingAt = event.position;
});
stage.on('pointerMove', (event) => {
if (!isPointingAtAnything()) {
return;
}
pointingAt = event.position;
});
stage.on('pointerUp', (event) => {
pointingAt = [-1, -1];
});
let actionState = actionRegistry.state;
// Create the socket connection.
const socket = createClient(window.location.href);
// Input messages.
const messageHandle = setInterval(() => {
// Mouse/touch movement.
do {
if (isPointingAtAnything()) {
const normal = createMoveToNormal(pointingAt);
if (normal) {
actionRegistry.state = actionRegistry.state.set('MoveTo', normal);
break;
}
}
actionRegistry.state = actionRegistry.state.delete('MoveTo');
} while (false);
if (actionState !== actionRegistry.state) {
actionState = actionRegistry.state;
socket.send({
type: 'input',
payload: actionState.toJS()
});
}
}, 1000 / 60);
// Prediction.
let lastTime = performance.now();
const predictionHandle = setInterval(() => {
const now = performance.now();
const elapsed = (now - lastTime) / 1000;
lastTime = now;
if (hasSelfEntity()) {
selfEntity.inputState = actionState.toJS();
}
room.tick(elapsed);
}, 1000 / 80);
// State updates.
let dirty = false;
function onMessage({type, payload}) {
switch (type) {
case 'state-update':
if (payload.selfEntity) {
selfEntity = payload.selfEntity;
}
stateSynchronizer.acceptStateChange(payload);
dirty = true;
break;
default:
}
}
socket.on('message', onMessage);
// Render.
function render() {
stage.tick();
if (!dirty) {
return;
}
stage.render();
dirty = false;
}
const renderHandle = setAnimation(render);
// Hot reloading.
if (module.hot) {
module.hot.accept((error) => {
console.error(error);
});
module.hot.dispose(() => {
clearAnimation(renderHandle);
room.destroy();
stage.destroy();
});
}