Improve gameplay

This commit is contained in:
schmelczerandras 2020-10-20 08:56:38 +02:00
commit 7c76b16d13
53 changed files with 1080 additions and 400 deletions

View file

@ -9,7 +9,7 @@ services:
http_port: 3000 http_port: 3000
instance_count: 1 instance_count: 1
instance_size_slug: basic-xxs instance_size_slug: basic-xxs
run_command: node main.js --name=Frankfurt --seed=102 run_command: ' node main.js --name=Frankfurt --seed=102'
name: decla-red-server name: decla-red-server
routes: routes:
- path: / - path: /

View file

@ -13,4 +13,6 @@ RUN npm install --production
COPY --from=build backend/dist/main.js main.js COPY --from=build backend/dist/main.js main.js
EXPOSE 3000 EXPOSE 3000
CMD [ "node", "main.js" ]
CMD ["--port=3000", "--name=Docker server", "--seed=500"]
ENTRYPOINT [ "node", "main.js" ]

View file

@ -29,7 +29,7 @@ export class GameServer {
io.on('connection', (socket: SocketIO.Socket) => { io.on('connection', (socket: SocketIO.Socket) => {
socket.on(TransportEvents.PlayerJoining, (playerInfo: PlayerInformation) => { socket.on(TransportEvents.PlayerJoining, (playerInfo: PlayerInformation) => {
const player = new Player(playerInfo, this.objects, socket); const player = new Player(playerInfo, this.players, this.objects, socket);
this.players.push(player); this.players.push(player);
socket.on(TransportEvents.PlayerToServer, (json: string) => { socket.on(TransportEvents.PlayerToServer, (json: string) => {
const command = deserialize(json); const command = deserialize(json);
@ -61,7 +61,7 @@ export class GameServer {
this.deltaTimes.sort((a, b) => a - b); this.deltaTimes.sort((a, b) => a - b);
console.log( console.log(
`Median physics time: ${this.deltaTimes[ `Median physics time: ${this.deltaTimes[
framesBetweenDeltaTimeCalculation Math.floor(framesBetweenDeltaTimeCalculation / 2)
].toFixed(2)} ms`, ].toFixed(2)} ms`,
); );
console.log( console.log(

View file

@ -1,5 +1,5 @@
import { vec2, vec3 } from 'gl-matrix'; import { vec2, vec3 } from 'gl-matrix';
import { Random, settings, PlanetBase } from 'shared'; import { Random, settings, PlanetBase, hsl } from 'shared';
import { LampPhysical } from '../objects/lamp-physical'; import { LampPhysical } from '../objects/lamp-physical';
import { PlanetPhysical } from '../objects/planet-physical'; import { PlanetPhysical } from '../objects/planet-physical';
import { PhysicalContainer } from '../physics/containers/physical-container'; import { PhysicalContainer } from '../physics/containers/physical-container';
@ -17,7 +17,7 @@ export const createWorld = (objectContainer: PhysicalContainer) => {
), ),
); );
for (let i = 0; i < worldSize / 400; i++) { for (let i = 0; i < 15; i++) {
console.log('planet', i); console.log('planet', i);
let position: vec2; let position: vec2;
@ -44,7 +44,7 @@ export const createWorld = (objectContainer: PhysicalContainer) => {
); );
} }
for (let i = 0; i < worldSize / 350; i++) { for (let i = 0; i < 15; i++) {
console.log('light', i); console.log('light', i);
let position: vec2; let position: vec2;
do { do {
@ -54,20 +54,17 @@ export const createWorld = (objectContainer: PhysicalContainer) => {
); );
} while ( } while (
evaluateSdf(position, objects) < 200 || evaluateSdf(position, objects) < 200 ||
lights.find((l) => l.distance(position) < 1800) lights.find((l) => l.distance(position) < 1500)
); );
lights.push( lights.push(
new LampPhysical( new LampPhysical(
position, position,
vec3.normalize( hsl(
vec3.create(), Random.getRandomInRange(0, 360),
vec3.fromValues( Random.getRandomInRange(50, 100),
Random.getRandomInRange(0.5, 1), Random.getRandomInRange(25, 50),
0,
Random.getRandomInRange(0.5, 1),
), ),
), Random.getRandomInRange(0.5, 2),
Random.getRandomInRange(0.25, 1),
), ),
); );
} }

View file

@ -30,10 +30,6 @@ export class CirclePhysical implements Circle, DynamicPhysical, ReactsToCollisio
this.recalculateBoundingBox(); this.recalculateBoundingBox();
} }
public calculateUpdates(): UpdateObjectMessage | null {
return null;
}
public get boundingBox(): BoundingBoxBase { public get boundingBox(): BoundingBoxBase {
return this._boundingBox; return this._boundingBox;
} }

View file

@ -9,23 +9,28 @@ import {
serializesTo, serializesTo,
settings, settings,
PlanetBase, PlanetBase,
CharacterTeam,
UpdateObjectMessage,
} from 'shared'; } from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box'; import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { StaticPhysical } from '../physics/physicals/static-physical'; import { StaticPhysical } from '../physics/physicals/static-physical';
import { UpdateGameObjectMessage } from '../update-game-object-message';
@serializesTo(PlanetBase) @serializesTo(PlanetBase)
export class PlanetPhysical extends PlanetBase implements StaticPhysical { export class PlanetPhysical extends PlanetBase implements StaticPhysical {
public readonly canCollide = true; public readonly canCollide = true;
public readonly canMove = false; public readonly canMove = false;
private center: vec2;
public static neutralPlanetCount = 0;
public static declaPlanetCount = 0;
public static redPlanetCount = 0;
private _boundingBox?: ImmutableBoundingBox; private _boundingBox?: ImmutableBoundingBox;
constructor(vertices: Array<vec2>) { constructor(vertices: Array<vec2>) {
super(id(), vertices); super(id(), vertices);
this.center = vertices.reduce((sum, v) => vec2.add(sum, sum, v), vec2.create()); PlanetPhysical.neutralPlanetCount++;
vec2.scale(this.center, this.center, 1 / vertices.length);
} }
public distance(target: vec2): number { public distance(target: vec2): number {
@ -62,6 +67,47 @@ export class PlanetPhysical extends PlanetBase implements StaticPhysical {
return sign * d; return sign * d;
} }
public calculateUpdates(): UpdateObjectMessage {
return new UpdateGameObjectMessage(this, ['ownership']);
}
public takeControl(team: CharacterTeam, deltaTime: number) {
const previousOwnership = this.ownership;
if (team === CharacterTeam.decla) {
this.ownership -= (0.5 / settings.takeControlTimeInSeconds) * deltaTime;
if (
previousOwnership >= 0.5 - settings.planetControlThreshold &&
this.ownership < 0.5 - settings.planetControlThreshold
) {
PlanetPhysical.declaPlanetCount++;
PlanetPhysical.neutralPlanetCount--;
} else if (
previousOwnership > 0.5 + settings.planetControlThreshold &&
previousOwnership <= 0.5 + settings.planetControlThreshold
) {
PlanetPhysical.redPlanetCount--;
PlanetPhysical.neutralPlanetCount++;
}
} else {
this.ownership += (0.5 / settings.takeControlTimeInSeconds) * deltaTime;
if (
previousOwnership < 0.5 + settings.planetControlThreshold &&
this.ownership >= 0.5 + settings.planetControlThreshold
) {
PlanetPhysical.redPlanetCount++;
PlanetPhysical.neutralPlanetCount--;
} else if (
previousOwnership <= 0.5 - settings.planetControlThreshold &&
previousOwnership > 0.5 + settings.planetControlThreshold
) {
PlanetPhysical.declaPlanetCount--;
PlanetPhysical.neutralPlanetCount++;
}
}
this.ownership = clamp01(this.ownership);
}
public get boundingBox(): ImmutableBoundingBox { public get boundingBox(): ImmutableBoundingBox {
if (!this._boundingBox) { if (!this._boundingBox) {
const { xMin, xMax, yMin, yMax } = this.vertices.reduce( const { xMin, xMax, yMin, yMax } = this.vertices.reduce(

View file

@ -9,6 +9,7 @@ import {
GameObject, GameObject,
Circle, Circle,
PlayerCharacterBase, PlayerCharacterBase,
CharacterTeam,
} from 'shared'; } from 'shared';
import { DynamicPhysical } from '../physics/physicals/dynamic-physical'; import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
import { CirclePhysical } from './circle-physical'; import { CirclePhysical } from './circle-physical';
@ -32,6 +33,8 @@ export class PlayerCharacterPhysical
private static readonly headRadius = 50; private static readonly headRadius = 50;
private static readonly feetRadius = 20; private static readonly feetRadius = 20;
private projectileStrength = settings.playerMaxStrength;
// offsets are meassured from (0, 0) // offsets are meassured from (0, 0)
private static readonly desiredHeadOffset = vec2.fromValues(0, 65); private static readonly desiredHeadOffset = vec2.fromValues(0, 65);
private static readonly desiredLeftFootOffset = vec2.fromValues(-20, 0); private static readonly desiredLeftFootOffset = vec2.fromValues(-20, 0);
@ -93,10 +96,11 @@ export class PlayerCharacterPhysical
constructor( constructor(
name: string, name: string,
public readonly colorIndex: number, public readonly colorIndex: number,
team: CharacterTeam,
private readonly container: PhysicalContainer, private readonly container: PhysicalContainer,
startPosition: vec2, startPosition: vec2,
) { ) {
super(id(), name, colorIndex); super(id(), name, colorIndex, team, settings.playerMaxHealth);
this.head = new CirclePhysical( this.head = new CirclePhysical(
vec2.add(vec2.create(), startPosition, PlayerCharacterPhysical.headOffset), vec2.add(vec2.create(), startPosition, PlayerCharacterPhysical.headOffset),
@ -129,7 +133,7 @@ export class PlayerCharacterPhysical
} }
public calculateUpdates(): UpdateObjectMessage { public calculateUpdates(): UpdateObjectMessage {
return new UpdateGameObjectMessage(this, ['head', 'leftFoot', 'rightFoot']); return new UpdateGameObjectMessage(this, ['head', 'leftFoot', 'rightFoot', 'health']);
} }
public handleMovementAction(c: MoveActionCommand) { public handleMovementAction(c: MoveActionCommand) {
@ -137,11 +141,43 @@ export class PlayerCharacterPhysical
} }
public onCollision(other: GameObject) { public onCollision(other: GameObject) {
if (other instanceof ProjectilePhysical) { if (other instanceof ProjectilePhysical && other.team !== this.team) {
other.destroy(); other.destroy();
this.health -= other.strength;
if (this.health <= 0) {
this.destroy(); this.destroy();
} }
} }
}
public shootTowards(position: vec2) {
if (!this.isAlive) {
return;
}
const start = vec2.clone(this.center);
const direction = vec2.subtract(vec2.create(), position, start);
vec2.normalize(direction, direction);
vec2.add(
start,
start,
vec2.scale(vec2.create(), direction, settings.projectileStartOffset),
);
const velocity = vec2.scale(direction, direction, settings.projectileSpeed);
vec2.add(velocity, velocity, this.velocity);
const strength = this.projectileStrength / 2;
this.projectileStrength -= strength;
const projectile = new ProjectilePhysical(
start,
20,
this.colorIndex,
strength,
this.team,
velocity,
this.container,
);
this.container.addObject(projectile);
}
public get boundingBox(): BoundingBoxBase { public get boundingBox(): BoundingBoxBase {
this.bound.center = this.head.center; this.bound.center = this.head.center;
@ -197,6 +233,13 @@ export class PlayerCharacterPhysical
this.currentPlanet = undefined; this.currentPlanet = undefined;
} }
this.projectileStrength = Math.min(
settings.playerMaxStrength,
this.projectileStrength + settings.playerStrengthRegenerationPerSeconds * deltaTime,
);
this.currentPlanet?.takeControl(this.team, deltaTime);
const intersectingWithForcefield = this.container.findIntersecting( const intersectingWithForcefield = this.container.findIntersecting(
getBoundingBoxOfCircle( getBoundingBoxOfCircle(
new Circle( new Circle(
@ -205,7 +248,13 @@ export class PlayerCharacterPhysical
), ),
), ),
); );
const actualGravity = forceAtPosition(this.center, intersectingWithForcefield); const feetCenter = vec2.add(
vec2.create(),
this.leftFoot.center,
this.rightFoot.center,
);
vec2.scale(feetCenter, feetCenter, 0.5);
const actualGravity = forceAtPosition(feetCenter, intersectingWithForcefield);
const direction = this.averageAndResetMovementActions(); const direction = this.averageAndResetMovementActions();
const movementForce = vec2.scale(direction, direction, settings.maxAcceleration); const movementForce = vec2.scale(direction, direction, settings.maxAcceleration);
@ -269,7 +318,7 @@ export class PlayerCharacterPhysical
private springMove(object: CirclePhysical, center: vec2, offset: vec2) { private springMove(object: CirclePhysical, center: vec2, offset: vec2) {
// todo: make time-independent // todo: make time-independent
const springConstant = 0.35; const springConstant = 0.55;
const desiredPosition = vec2.add(vec2.create(), center, offset); const desiredPosition = vec2.add(vec2.create(), center, offset);
vec2.rotate(desiredPosition, desiredPosition, center, this.direction); vec2.rotate(desiredPosition, desiredPosition, center, this.direction);

View file

@ -1,5 +1,12 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { id, settings, serializesTo, ProjectileBase, GameObject } from 'shared'; import {
id,
settings,
serializesTo,
ProjectileBase,
GameObject,
CharacterTeam,
} from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box'; import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { CirclePhysical } from './circle-physical'; import { CirclePhysical } from './circle-physical';
import { DynamicPhysical } from '../physics/physicals/dynamic-physical'; import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
@ -8,6 +15,7 @@ import { PlanetPhysical } from './planet-physical';
import { ReactsToCollision } from '../physics/physicals/reacts-to-collision'; import { ReactsToCollision } from '../physics/physicals/reacts-to-collision';
import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message'; import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message';
import { UpdateGameObjectMessage } from '../update-game-object-message'; import { UpdateGameObjectMessage } from '../update-game-object-message';
import { PlayerCharacterPhysical } from './player-character-physical';
@serializesTo(ProjectileBase) @serializesTo(ProjectileBase)
export class ProjectilePhysical export class ProjectilePhysical
@ -15,6 +23,7 @@ export class ProjectilePhysical
implements DynamicPhysical, ReactsToCollision { implements DynamicPhysical, ReactsToCollision {
public readonly canCollide = true; public readonly canCollide = true;
public readonly canMove = true; public readonly canMove = true;
private isDestroyed = false; private isDestroyed = false;
private bounceCount = 0; private bounceCount = 0;
private _boundingBox?: ImmutableBoundingBox; private _boundingBox?: ImmutableBoundingBox;
@ -24,15 +33,18 @@ export class ProjectilePhysical
constructor( constructor(
center: vec2, center: vec2,
radius: number, radius: number,
colorIndex: number,
public strength: number,
public team: CharacterTeam,
private velocity: vec2, private velocity: vec2,
readonly container: PhysicalContainer, readonly container: PhysicalContainer,
) { ) {
super(id(), center, radius); super(id(), center, radius, colorIndex, strength);
this.object = new CirclePhysical(center, radius, this, container, 0.9); this.object = new CirclePhysical(center, radius, this, container, 0.9);
} }
public calculateUpdates(): UpdateObjectMessage { public calculateUpdates(): UpdateObjectMessage {
return new UpdateGameObjectMessage(this, ['center']); return new UpdateGameObjectMessage(this, ['center', 'strength']);
} }
public get boundingBox(): ImmutableBoundingBox { public get boundingBox(): ImmutableBoundingBox {
@ -59,12 +71,20 @@ export class ProjectilePhysical
} }
public onCollision(other: GameObject) { public onCollision(other: GameObject) {
if (this.bounceCount++ === settings.projectileMaxBounceCount) { if (
!(other instanceof PlayerCharacterPhysical && other.team === this.team) &&
this.bounceCount++ === settings.projectileMaxBounceCount
) {
this.destroy(); this.destroy();
} }
} }
public step(deltaTime: number) { public step(deltaTime: number) {
if ((this.strength -= settings.projectileFadeSpeed * deltaTime) < 0) {
this.destroy();
return;
}
const gravity = vec2.create(); const gravity = vec2.create();
const intersecting = this.container.findIntersecting(this.boundingBox); const intersecting = this.container.findIntersecting(this.boundingBox);
intersecting.forEach((i) => { intersecting.forEach((i) => {

View file

@ -1,9 +1,6 @@
import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message';
import { PhysicalBase } from './physical-base'; import { PhysicalBase } from './physical-base';
export interface DynamicPhysical extends PhysicalBase { export interface DynamicPhysical extends PhysicalBase {
readonly canMove: true; readonly canMove: true;
step(deltaTimeInMilliseconds: number): void; step(deltaTimeInMilliseconds: number): void;
calculateUpdates(): UpdateObjectMessage | null;
} }

View file

@ -1,15 +0,0 @@
import { settings } from 'shared';
const colorUsage: Array<boolean> = new Array(settings.playerColors.length).fill(false);
export const requestColor = (): number => {
const index = colorUsage.findIndex((a) => !a);
if (index >= 0) {
colorUsage[index] = true;
}
return index + settings.playerColorIndexOffset;
};
export const freeColor = (index: number) => {
colorUsage[index - settings.playerColorIndexOffset] = false;
};

View file

@ -0,0 +1,22 @@
import { CharacterTeam, Random } from 'shared';
let declaCount = 0;
let redCount = 0;
export const requestTeam = (): { team: CharacterTeam; colorIndex: number } => {
if ((declaCount === redCount && Random.getRandom() > 0.5) || declaCount < redCount) {
declaCount++;
return { team: CharacterTeam.decla, colorIndex: 0 };
} else {
redCount++;
return { team: CharacterTeam.red, colorIndex: 1 };
}
};
export const freeTeam = (team: CharacterTeam) => {
if (team === CharacterTeam.decla) {
declaCount--;
} else {
redCount--;
}
};

View file

@ -12,30 +12,32 @@ import {
SetAspectRatioActionCommand, SetAspectRatioActionCommand,
calculateViewArea, calculateViewArea,
SecondaryActionCommand, SecondaryActionCommand,
PlayerDiedCommand,
settings, settings,
Circle, Circle,
PlayerInformation, PlayerInformation,
CharacterTeam,
UpdatePlanetOwnershipCommand,
GameObject,
Command,
UpdateObjectMessage,
} from 'shared'; } from 'shared';
import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds'; import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds';
import { ProjectilePhysical } from '../objects/projectile-physical';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box'; import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
import { PhysicalContainer } from '../physics/containers/physical-container'; import { PhysicalContainer } from '../physics/containers/physical-container';
import { getBoundingBoxOfCircle } from '../physics/functions/get-bounding-box-of-circle'; import { getBoundingBoxOfCircle } from '../physics/functions/get-bounding-box-of-circle';
import { isCircleIntersecting } from '../physics/functions/is-circle-intersecting'; import { isCircleIntersecting } from '../physics/functions/is-circle-intersecting';
import { requestColor, freeColor } from './player-color-service';
import { PlayerCharacterPhysical } from '../objects/player-character-physical'; import { PlayerCharacterPhysical } from '../objects/player-character-physical';
import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
import { Physical } from '../physics/physicals/physical'; import { Physical } from '../physics/physicals/physical';
import { freeTeam, requestTeam } from './player-team-service';
import { PlanetPhysical } from '../objects/planet-physical';
export class Player extends CommandReceiver { export class Player extends CommandReceiver {
private character: PlayerCharacterPhysical; private character?: PlayerCharacterPhysical | null;
private aspectRatio: number = 16 / 9; private aspectRatio: number = 16 / 9;
private isActive = true; private isActive = true;
private timeSinceLastProjectile = 0; private objectsPreviouslyInViewArea: Array<GameObject> = [];
private objectsPreviouslyInViewArea: Array<Physical> = [];
private objectsInViewArea: Array<Physical> = [];
private pingTime?: number; private pingTime?: number;
private _latency?: number; private _latency?: number;
@ -55,35 +57,20 @@ export class Player extends CommandReceiver {
[SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) => [SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) =>
(this.aspectRatio = v.aspectRatio), (this.aspectRatio = v.aspectRatio),
[MoveActionCommand.type]: (c: MoveActionCommand) => [MoveActionCommand.type]: (c: MoveActionCommand) =>
this.character.handleMovementAction(c), this.character?.handleMovementAction(c),
[SecondaryActionCommand.type]: (c: SecondaryActionCommand) => { [SecondaryActionCommand.type]: (c: SecondaryActionCommand) => {
if ( this.character?.shootTowards(c.position);
!this.character.isAlive ||
this.timeSinceLastProjectile < settings.projectileCreationInterval
) {
return;
}
const start = vec2.clone(this.character.center);
const direction = vec2.subtract(vec2.create(), c.position, start);
vec2.normalize(direction, direction);
vec2.add(
start,
start,
vec2.scale(vec2.create(), direction, settings.projectileStartOffset),
);
const velocity = vec2.scale(direction, direction, settings.projectileSpeed);
vec2.add(velocity, velocity, this.character.velocity);
const projectile = new ProjectilePhysical(start, 20, velocity, this.objects);
this.objects.addObject(projectile);
this.timeSinceLastProjectile = 0;
}, },
}; };
private findEmptyPositionForPlayer(): vec2 { private findEmptyPositionForPlayer(): vec2 {
let rotation = 0; let possibleCenter = this.players.find((p) => p.team === this.team)?.center;
let radius = 0; if (!possibleCenter) {
possibleCenter = vec2.create();
}
let rotation = Math.atan2(possibleCenter.y, possibleCenter.x);
let radius = vec2.length(possibleCenter);
for (;;) { for (;;) {
const playerPosition = vec2.fromValues( const playerPosition = vec2.fromValues(
radius * Math.cos(rotation), radius * Math.cos(rotation),
@ -106,27 +93,21 @@ export class Player extends CommandReceiver {
} }
} }
public readonly team: CharacterTeam;
private colorIndex: number;
constructor( constructor(
playerInfo: PlayerInformation, private readonly playerInfo: PlayerInformation,
private readonly players: Array<Player>,
private readonly objects: PhysicalContainer, private readonly objects: PhysicalContainer,
private readonly socket: SocketIO.Socket, private readonly socket: SocketIO.Socket,
) { ) {
super(); super();
const colorIndex = requestColor(); const { team, colorIndex } = requestTeam();
this.team = team;
this.colorIndex = colorIndex;
this.character = new PlayerCharacterPhysical( this.createCharacter();
playerInfo.name,
colorIndex,
objects,
this.findEmptyPositionForPlayer(),
);
this.objects.addObject(this.character);
socket.emit(
TransportEvents.ServerToPlayer,
serialize(new CreatePlayerCommand(this.character)),
);
socket.on( socket.on(
TransportEvents.Pong, TransportEvents.Pong,
@ -134,78 +115,99 @@ export class Player extends CommandReceiver {
); );
this.measureLatency(); this.measureLatency();
this.sendObjects(); this.step(0);
} }
private createCharacter() {
this.character = new PlayerCharacterPhysical(
this.playerInfo.name.slice(0, 20),
this.colorIndex,
this.team,
this.objects,
this.findEmptyPositionForPlayer(),
);
this.objects.addObject(this.character);
this.objectsPreviouslyInViewArea.push(this.character);
this.socket.emit(
TransportEvents.ServerToPlayer,
serialize(new CreatePlayerCommand(this.character)),
);
}
private center: vec2 = vec2.create();
private timeUntilRespawn = 0;
public step(deltaTime: number) { public step(deltaTime: number) {
this.sendObjects(); if (this.character) {
this.timeSinceLastProjectile += deltaTime; this.center = this.character?.center;
if (!this.character.isAlive) {
this.socket.emit(
TransportEvents.ServerToPlayer,
serialize(new PlayerDiedCommand(settings.playerDiedTimeout)),
);
this.character = null;
this.timeUntilRespawn = settings.playerDiedTimeout;
}
} else if ((this.timeUntilRespawn -= deltaTime) < 0) {
this.createCharacter();
} }
public sendObjects() { const viewArea = calculateViewArea(this.center, this.aspectRatio, 1.5);
const viewArea = calculateViewArea(this.character.center, this.aspectRatio, 1.5);
const bb = new BoundingBox(); const bb = new BoundingBox();
bb.topLeft = viewArea.topLeft; bb.topLeft = viewArea.topLeft;
bb.size = viewArea.size; bb.size = viewArea.size;
this.objectsInViewArea = this.objects.findIntersecting(bb); const objectsInViewArea = Array.from(
new Set(this.objects.findIntersecting(bb).map((o) => o.gameObject)),
);
const newlyIntersecting = this.objectsInViewArea.filter( const newlyIntersecting = objectsInViewArea.filter(
(o) => !this.objectsPreviouslyInViewArea.includes(o), (o) => !this.objectsPreviouslyInViewArea.includes(o),
); );
const noLongerIntersecting = this.objectsPreviouslyInViewArea.filter( const noLongerIntersecting = this.objectsPreviouslyInViewArea.filter(
(o) => !this.objectsInViewArea.includes(o), (o) => !objectsInViewArea.includes(o),
); );
this.objectsPreviouslyInViewArea = this.objectsInViewArea; this.objectsPreviouslyInViewArea = objectsInViewArea;
if (noLongerIntersecting.length > 0) { if (noLongerIntersecting.length > 0) {
this.socket.emit( this.sendToPlayer(new DeleteObjectsCommand(noLongerIntersecting.map((g) => g.id)));
TransportEvents.ServerToPlayer,
serialize(
new DeleteObjectsCommand([
...new Set(
noLongerIntersecting
.filter((p) => p.gameObject !== this.character)
.map((p) => p.gameObject.id),
),
]),
),
);
} }
if (newlyIntersecting.length > 0) { if (newlyIntersecting.length > 0) {
this.socket.emit( this.sendToPlayer(new CreateObjectsCommand(newlyIntersecting));
TransportEvents.ServerToPlayer, }
serialize(
new CreateObjectsCommand([ this.sendToPlayer(
...new Set( new UpdateObjectsCommand(
newlyIntersecting this.objectsPreviouslyInViewArea
.map((p) => p.gameObject) .map((g) => g.calculateUpdates())
.filter((g) => g !== this.character), .filter((u) => u) as Array<UpdateObjectMessage>,
), ),
]), );
this.sendToPlayer(
new UpdatePlanetOwnershipCommand(
PlanetPhysical.declaPlanetCount,
PlanetPhysical.redPlanetCount,
PlanetPhysical.neutralPlanetCount,
), ),
); );
} }
this.socket.emit( private sendToPlayer(command: Command) {
TransportEvents.ServerToPlayer, this.socket.emit(TransportEvents.ServerToPlayer, serialize(command));
serialize(
new UpdateObjectsCommand(
Array.from(new Set(this.objectsInViewArea))
.filter((p) => p.canMove)
.map((p) => (p as DynamicPhysical).calculateUpdates())
.filter((p) => p !== null) as any,
),
),
);
} }
public destroy() { public destroy() {
this.isActive = false; this.isActive = false;
freeColor(this.character.colorIndex); freeTeam(this.team);
if (this.character) {
this.character.destroy(); this.character.destroy();
} }
}
} }

View file

@ -45,7 +45,7 @@
"ts-loader": "^8.0.3", "ts-loader": "^8.0.3",
"sass": "^1.26.3", "sass": "^1.26.3",
"sass-loader": "^9.0.2", "sass-loader": "^9.0.2",
"sdf-2d": "^0.5.3", "sdf-2d": "^0.6.0",
"shared": "0.0.0", "shared": "0.0.0",
"socket.io-client": "^2.3.1", "socket.io-client": "^2.3.1",
"source-map-loader": "^1.1.0", "source-map-loader": "^1.1.0",

View file

@ -4,7 +4,8 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta <meta
name="viewport" name="viewport"
content="width=device-width,initial-scale=1,viewport-fit=cover" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,
user-scalable=0"
/> />
<meta name="theme-color" content="#b7455e" /> <meta name="theme-color" content="#b7455e" />
@ -15,10 +16,12 @@
</head> </head>
<body> <body>
<noscript>Javascript is required for this website.</noscript>
<canvas></canvas> <canvas></canvas>
<div id="overlay"></div> <div id="overlay"></div>
<article id="landing-ui"> <section id="landing-ui">
<h1>decla.<span class="red">red</span></h1> <h1>decla.<span class="red">red</span></h1>
<form id="join-game-form"> <form id="join-game-form">
<fieldset class="content"> <fieldset class="content">
@ -41,8 +44,28 @@
<button id="join-game" type="submit">Join</button> <button id="join-game" type="submit">Join</button>
</fieldset> </fieldset>
</form> </form>
</article> </section>
<noscript>Javascript is required for this website.</noscript> <img id="open-settings" class="icon" alt="open-settings" src="static/settings.svg" />
<section id="settings">
<h2>Settings</h2>
<input id="enable-relative-movement" checked type="checkbox" />
<label for="enable-relative-movement">Enable relative movement</label>
<button id="close-settings">Back</button>
</section>
<img
class="full-screen-controllers icon"
id="minimize"
alt="minimize-application"
src="static/minimize.svg"
/>
<img
class="full-screen-controllers icon"
id="maximize"
alt="maximize-application"
src="static/maximize.svg"
/>
</body> </body>
</html> </html>

View file

@ -14,6 +14,7 @@ import { PlanetView } from './scripts/objects/planet-view';
import './styles/main.scss'; import './styles/main.scss';
import { LandingPageBackground } from './scripts/landing-page-background'; import { LandingPageBackground } from './scripts/landing-page-background';
import { JoinFormHandler } from './scripts/join-form-handler'; import { JoinFormHandler } from './scripts/join-form-handler';
import { handleFullScreen } from './scripts/handle-full-screen';
import { Game } from './scripts/game'; import { Game } from './scripts/game';
import { PlayerCharacterView } from './scripts/objects/player-character-view'; import { PlayerCharacterView } from './scripts/objects/player-character-view';
@ -32,15 +33,28 @@ const main = async () => {
const serverContainer = document.querySelector('#server-container') as HTMLElement; const serverContainer = document.querySelector('#server-container') as HTMLElement;
const canvas = document.querySelector('canvas') as HTMLCanvasElement; const canvas = document.querySelector('canvas') as HTMLCanvasElement;
const overlay = document.querySelector('#overlay') as HTMLElement; const overlay = document.querySelector('#overlay') as HTMLElement;
const settings = document.querySelector('#settings') as HTMLElement;
const openSettings = document.querySelector('#open-settings') as HTMLElement;
const closeSettings = document.querySelector('#close-settings') as HTMLElement;
const minimize = document.querySelector('#minimize') as HTMLElement;
const maximize = document.querySelector('#maximize') as HTMLElement;
const enableRelativeMovementCheckbox = document.querySelector(
'#enable-relative-movement',
) as HTMLElement;
openSettings.addEventListener('click', () => (settings.style.visibility = 'visible'));
closeSettings.addEventListener('click', () => (settings.style.visibility = 'hidden'));
const background = new LandingPageBackground(canvas); const background = new LandingPageBackground(canvas);
const joinHandler = new JoinFormHandler(joinGameForm, serverContainer); const joinHandler = new JoinFormHandler(joinGameForm, serverContainer);
handleFullScreen(minimize, maximize);
const playerDecision = await joinHandler.getPlayerDecision(); const playerDecision = await joinHandler.getPlayerDecision();
landingUI.style.display = 'none'; landingUI.style.display = 'none';
background.destroy(); background.destroy();
await new Game(playerDecision, canvas, overlay).start();
new Game(playerDecision, canvas, overlay);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
alert(e); alert(e);

View file

@ -1,11 +1,13 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { import {
CircleLight, CircleLight,
ColorfulCircle,
compile, compile,
FilteringOptions, FilteringOptions,
Flashlight, Flashlight,
Renderer, Renderer,
renderNoise, renderNoise,
runAnimation,
WrapOptions, WrapOptions,
} from 'sdf-2d'; } from 'sdf-2d';
import { import {
@ -17,36 +19,41 @@ import {
SetAspectRatioActionCommand, SetAspectRatioActionCommand,
rgb, rgb,
PlayerInformation, PlayerInformation,
PlayerDiedCommand,
UpdatePlanetOwnershipCommand,
} from 'shared'; } from 'shared';
import io from 'socket.io-client'; import io from 'socket.io-client';
import { KeyboardListener } from './commands/generators/keyboard-listener'; import { KeyboardListener } from './commands/generators/keyboard-listener';
import { MouseListener } from './commands/generators/mouse-listener'; import { MouseListener } from './commands/generators/mouse-listener';
import { TouchListener } from './commands/generators/touch-listener'; import { TouchListener } from './commands/generators/touch-listener';
import { CommandReceiverSocket } from './commands/receivers/command-receiver-socket'; import { CommandReceiverSocket } from './commands/receivers/command-receiver-socket';
import { DeltaTimeCalculator } from './helper/delta-time-calculator';
import { PlayerDecision } from './join-form-handler'; import { PlayerDecision } from './join-form-handler';
import { GameObjectContainer } from './objects/game-object-container'; import { GameObjectContainer } from './objects/game-object-container';
import { BlobShape } from './shapes/blob-shape'; import { BlobShape } from './shapes/blob-shape';
import { Circle } from './shapes/circle'; import { PlanetShape } from './shapes/planet-shape';
import { Polygon } from './shapes/polygon';
export class Game { export class Game {
public readonly gameObjects = new GameObjectContainer(this); public readonly gameObjects = new GameObjectContainer(this);
private renderer!: Renderer; private renderer?: Renderer;
private socket!: SocketIOClient.Socket; private socket!: SocketIOClient.Socket;
private promises: Promise<[void, void]>; private deadTimeout = 0;
private deltaTimeCalculator = new DeltaTimeCalculator();
private declaPlanetCountElement = document.createElement('div');
private redPlanetCountElement = document.createElement('div');
private neutralPlanetCountElement = document.createElement('div');
constructor( constructor(
private readonly playerDecision: PlayerDecision, private readonly playerDecision: PlayerDecision,
private readonly canvas: HTMLCanvasElement, private readonly canvas: HTMLCanvasElement,
private readonly overlay: HTMLElement, private readonly overlay: HTMLElement,
) { ) {
this.promises = Promise.all([ this.start();
this.setupCommunication(playerDecision.server), const progressBar = document.createElement('div');
this.setupRenderer(), progressBar.className = 'planet-progress';
]); overlay.appendChild(progressBar);
progressBar.appendChild(this.declaPlanetCountElement);
progressBar.appendChild(this.neutralPlanetCountElement);
progressBar.appendChild(this.redPlanetCountElement);
} }
private async setupCommunication(serverUrl: string): Promise<void> { private async setupCommunication(serverUrl: string): Promise<void> {
@ -61,7 +68,26 @@ export class Game {
this.socket.on(TransportEvents.ServerToPlayer, (serialized: string) => { this.socket.on(TransportEvents.ServerToPlayer, (serialized: string) => {
const command = deserialize(serialized); const command = deserialize(serialized);
this.gameObjects.sendCommand(command); if (command instanceof PlayerDiedCommand) {
this.deadTimeout = command.timeout;
this.overlay.appendChild(this.announcmentText);
} else if (command instanceof UpdatePlanetOwnershipCommand) {
const all = command.declaCount + command.redCount + command.neutralCount;
this.declaPlanetCountElement.style.width = (command.declaCount / all) * 100 + '%';
this.neutralPlanetCountElement.style.width =
(command.neutralCount / all) * 100 + '%';
this.redPlanetCountElement.style.width = (command.redCount / all) * 100 + '%';
if (command.declaCount > all * 0.5) {
this.overlay.appendChild(this.announcmentText);
this.announcmentText.innerText = 'Decla team won 🎉';
}
if (command.redCount > all * 0.5) {
this.overlay.appendChild(this.announcmentText);
this.announcmentText.innerText = 'Red team won 🎉';
}
} else this.gameObjects.sendCommand(command);
}); });
this.socket.on(TransportEvents.Ping, () => { this.socket.on(TransportEvents.Ping, () => {
@ -82,14 +108,14 @@ export class Game {
); );
} }
private async setupRenderer(): Promise<void> { private async start(): Promise<void> {
const noiseTexture = await renderNoise([256, 256], 2, 1); const noiseTexture = await renderNoise([256, 256], 2, 1);
this.setupCommunication(this.playerDecision.server);
this.renderer = await compile( runAnimation(
this.canvas, this.canvas,
[ [
{ {
...Polygon.descriptor, ...PlanetShape.descriptor,
shaderCombinationSteps: [0, 1, 2, 3], shaderCombinationSteps: [0, 1, 2, 3],
}, },
{ {
@ -97,33 +123,27 @@ export class Game {
shaderCombinationSteps: [0, 1, 2, 8], shaderCombinationSteps: [0, 1, 2, 8],
}, },
{ {
...Circle.descriptor, ...ColorfulCircle.descriptor,
shaderCombinationSteps: [0, 2, 16], shaderCombinationSteps: [0, 2, 16],
}, },
{ {
...CircleLight.descriptor, ...CircleLight.descriptor,
shaderCombinationSteps: [0, 1, 2, 4, 8], shaderCombinationSteps: [0, 1, 2, 4, 8, 16],
}, },
{ {
...Flashlight.descriptor, ...Flashlight.descriptor,
shaderCombinationSteps: [0], shaderCombinationSteps: [0],
}, },
], ],
this.gameLoop.bind(this),
{ {
shadowTraceCount: 16, shadowTraceCount: 16,
paletteSize: 10, paletteSize: settings.palette.length,
//enableStopwatch: true, //enableStopwatch: true,
}, },
); {
this.renderer.setRuntimeSettings({
ambientLight: rgb(0.45, 0.4, 0.45), ambientLight: rgb(0.45, 0.4, 0.45),
colorPalette: [ colorPalette: settings.palette,
rgb(1, 1, 1),
rgb(0.4, 0.4, 0.4),
rgb(1, 1, 1),
...settings.playerColors,
],
enableHighDpiRendering: true, enableHighDpiRendering: true,
lightCutoffDistance: settings.lightCutoffDistance, lightCutoffDistance: settings.lightCutoffDistance,
textures: { textures: {
@ -136,16 +156,16 @@ export class Game {
}, },
}, },
}, },
}); },
} );
public async start(): Promise<void> {
await this.promises;
requestAnimationFrame(this.gameLoop.bind(this));
} }
public displayToWorldCoordinates(p: vec2): vec2 { public displayToWorldCoordinates(p: vec2): vec2 {
return this.renderer?.displayToWorldCoordinates(p); const result = this.renderer?.displayToWorldCoordinates(p);
if (!result) {
return vec2.create();
}
return result;
} }
public aspectRatioChanged(aspectRatio: number) { public aspectRatioChanged(aspectRatio: number) {
@ -155,14 +175,23 @@ export class Game {
); );
} }
private gameLoop(time: DOMHighResTimeStamp) { private announcmentText = document.createElement('h2');
const deltaTime = this.deltaTimeCalculator.getNextDeltaTimeInMilliseconds(time); private gameLoop(
renderer: Renderer,
currentTime: DOMHighResTimeStamp,
deltaTime: DOMHighResTimeStamp,
): boolean {
this.renderer = renderer;
if ((this.deadTimeout -= deltaTime / 1000) > 0) {
this.announcmentText.innerText = `Respawning in ${Math.floor(this.deadTimeout)} …`;
} else {
this.announcmentText.parentElement?.removeChild(this.announcmentText);
}
this.gameObjects.stepObjects(deltaTime); this.gameObjects.stepObjects(deltaTime);
this.gameObjects.drawObjects(this.renderer); this.gameObjects.drawObjects(this.renderer, this.overlay);
this.renderer.renderDrawables();
// this.overlay.innerText = prettyPrint(this.renderer.insights); return true;
requestAnimationFrame(this.gameLoop.bind(this));
} }
} }

View file

@ -0,0 +1,27 @@
export const handleFullScreen = (
minimizeButton: HTMLElement,
maximizeButton: HTMLElement,
) => {
if (!document.fullscreenEnabled) {
minimizeButton.style.visibility = 'hidden';
maximizeButton.style.visibility = 'hidden';
return;
}
let isInFullScreen = document.fullscreenElement !== null;
const showButtons = () => {
minimizeButton.style.visibility = isInFullScreen ? 'visible' : 'hidden';
maximizeButton.style.visibility = isInFullScreen ? 'hidden' : 'visible';
};
showButtons();
maximizeButton.addEventListener('click', () => document.body.requestFullscreen());
minimizeButton.addEventListener('click', () => document.exitFullscreen());
document.addEventListener('fullscreenchange', () => {
isInFullScreen = !isInFullScreen;
showButtons();
});
};

View file

@ -1,25 +0,0 @@
export class DeltaTimeCalculator {
private previousTime: DOMHighResTimeStamp | null = null;
constructor() {
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
}
public getNextDeltaTimeInMilliseconds(
currentTime: DOMHighResTimeStamp,
): DOMHighResTimeStamp {
if (this.previousTime === null) {
this.previousTime = currentTime;
}
const delta = currentTime - this.previousTime;
this.previousTime = currentTime;
return delta;
}
private handleVisibilityChange() {
if (!document.hidden) {
this.previousTime = null;
}
}
}

View file

@ -7,6 +7,7 @@ import {
NoisyPolygonFactory, NoisyPolygonFactory,
Renderer, Renderer,
renderNoise, renderNoise,
runAnimation,
WrapOptions, WrapOptions,
} from 'sdf-2d'; } from 'sdf-2d';
import { settings, rgb, PlanetBase, Random } from 'shared'; import { settings, rgb, PlanetBase, Random } from 'shared';
@ -18,17 +19,17 @@ const LangindPagePolygon = NoisyPolygonFactory(
); );
export class LandingPageBackground { export class LandingPageBackground {
private renderer!: Renderer; private isActive = true;
constructor(private readonly canvas: HTMLCanvasElement) { constructor(canvas: HTMLCanvasElement) {
this.start(); this.start(canvas);
} }
private async start(): Promise<void> { private async start(canvas: HTMLCanvasElement): Promise<void> {
const noiseTexture = await renderNoise([256, 256], 1.2, 2); const noiseTexture = await renderNoise([256, 256], 1.2, 2);
this.renderer = await compile( runAnimation(
this.canvas, canvas,
[ [
{ {
...LangindPagePolygon.descriptor, ...LangindPagePolygon.descriptor,
@ -39,13 +40,12 @@ export class LandingPageBackground {
shaderCombinationSteps: [0, 2], shaderCombinationSteps: [0, 2],
}, },
], ],
this.gameLoop.bind(this),
{ {
shadowTraceCount: 16, shadowTraceCount: 16,
paletteSize: 1, paletteSize: 1,
}, },
); {
this.renderer.setRuntimeSettings({
ambientLight: rgb(0, 0, 0), ambientLight: rgb(0, 0, 0),
lightCutoffDistance: settings.lightCutoffDistance, lightCutoffDistance: settings.lightCutoffDistance,
textures: { textures: {
@ -58,26 +58,18 @@ export class LandingPageBackground {
}, },
}, },
}, },
}); },
);
requestAnimationFrame(this.gameLoop.bind(this));
} }
public destroy() { private gameLoop(renderer: Renderer, time: DOMHighResTimeStamp, _: number): boolean {
this.renderer.destroy();
}
private gameLoop(time: DOMHighResTimeStamp) {
Random.seed = 42; Random.seed = 42;
this.renderer.setViewArea( renderer.setViewArea(vec2.fromValues(0, renderer.canvasSize.y), renderer.canvasSize);
vec2.fromValues(0, this.renderer.canvasSize.y),
this.renderer.canvasSize,
);
const topPlanetPosition = vec2.fromValues( const topPlanetPosition = vec2.fromValues(
0.7 * this.renderer.canvasSize.x, 0.7 * renderer.canvasSize.x,
0.7 * this.renderer.canvasSize.y, 0.7 * renderer.canvasSize.y,
); );
const topPlanet = new LangindPagePolygon( const topPlanet = new LangindPagePolygon(
@ -93,8 +85,8 @@ export class LandingPageBackground {
(topPlanet as any).randomOffset = 0.5 + time / 3500; (topPlanet as any).randomOffset = 0.5 + time / 3500;
const bottomPlanetPosition = vec2.fromValues( const bottomPlanetPosition = vec2.fromValues(
0.3 * this.renderer.canvasSize.x, 0.3 * renderer.canvasSize.x,
0.3 * this.renderer.canvasSize.y, 0.3 * renderer.canvasSize.y,
); );
const bottomPlanet = new LangindPagePolygon( const bottomPlanet = new LangindPagePolygon(
@ -118,11 +110,12 @@ export class LandingPageBackground {
const planetDirection = vec2.normalize(planetDistance, planetDistance); const planetDirection = vec2.normalize(planetDistance, planetDistance);
const planetAngle = Math.atan2(planetDirection.y, planetDirection.x); const planetAngle = Math.atan2(planetDirection.y, planetDirection.x);
this.renderer.addDrawable(topPlanet); renderer.addDrawable(topPlanet);
this.renderer.addDrawable(bottomPlanet); renderer.addDrawable(bottomPlanet);
this.renderer.addDrawable( renderer.addDrawable(
new CircleLight( new CircleLight(
this.calculateLightPosition( this.calculateLightPosition(
renderer,
planetAngle, planetAngle,
planetDistanceLength * 1.2, planetDistanceLength * 1.2,
-time / 3000, -time / 3000,
@ -132,9 +125,10 @@ export class LandingPageBackground {
), ),
); );
this.renderer.addDrawable( renderer.addDrawable(
new CircleLight( new CircleLight(
this.calculateLightPosition( this.calculateLightPosition(
renderer,
planetAngle, planetAngle,
planetDistanceLength * 1.2, planetDistanceLength * 1.2,
time / 2000 + Math.PI, time / 2000 + Math.PI,
@ -144,21 +138,28 @@ export class LandingPageBackground {
), ),
); );
this.renderer.renderDrawables(); return this.isActive;
requestAnimationFrame(this.gameLoop.bind(this));
} }
private calculateLightPosition(angle: number, length: number, t: number): vec2 { private calculateLightPosition(
renderer: Renderer,
angle: number,
length: number,
t: number,
): vec2 {
const lightPosition = vec2.fromValues( const lightPosition = vec2.fromValues(
length * Math.sin(t), length * Math.sin(t),
length * Math.sin(t) * Math.cos(t), length * Math.sin(t) * Math.cos(t),
); );
const canvasCenter = vec2.scale(vec2.create(), this.renderer.canvasSize, 0.5); const canvasCenter = vec2.scale(vec2.create(), renderer.canvasSize, 0.5);
vec2.add(lightPosition, lightPosition, canvasCenter); vec2.add(lightPosition, lightPosition, canvasCenter);
vec2.rotate(lightPosition, lightPosition, canvasCenter, angle); vec2.rotate(lightPosition, lightPosition, canvasCenter, angle);
return lightPosition; return lightPosition;
} }
public destroy() {
this.isActive = false;
}
} }

View file

@ -14,13 +14,11 @@ export class Camera extends GameObject implements ViewObject {
super(null); super(null);
} }
public update(updates: Array<UpdateMessage>) { public beforeDestroy(): void {}
throw new Error();
}
public step(deltaTimeInMilliseconds: number): void {} public step(deltaTimeInMilliseconds: number): void {}
public draw(renderer: Renderer) { public draw(renderer: Renderer, overlay: HTMLElement) {
const canvasAspectRatio = renderer.canvasSize.x / renderer.canvasSize.y; const canvasAspectRatio = renderer.canvasSize.x / renderer.canvasSize.y;
if (canvasAspectRatio !== this.aspectRatio) { if (canvasAspectRatio !== this.aspectRatio) {
this.aspectRatio = canvasAspectRatio; this.aspectRatio = canvasAspectRatio;

Some files were not shown because too many files have changed in this diff Show more