Fix physics

This commit is contained in:
schmelczerandras 2020-10-12 20:49:17 +02:00
parent 37954e2ef1
commit f9f6825776
51 changed files with 832 additions and 541 deletions

View file

@ -7,7 +7,6 @@ import {
Random,
TransportEvents,
deserialize,
StepCommand,
settings,
} from 'shared';
import './index.html';
@ -25,9 +24,6 @@ Random.seed = 42;
const objects = new PhysicalContainer();
createDungeon(objects);
createDungeon(objects);
createDungeon(objects);
createDungeon(objects);
objects.initialize();
@ -88,8 +84,7 @@ let deltas: Array<number> = [];
const handlePhysics = () => {
const delta = deltaTimeCalculator.getNextDeltaTimeInMilliseconds();
deltas.push(delta);
const step = new StepCommand(delta);
if (deltas.length > 100) {
if (deltas.length > 1000) {
deltas.sort((a, b) => a - b);
console.log(`Median physics time: ${deltas[50].toFixed(2)} ms`);
console.log(
@ -99,17 +94,8 @@ const handlePhysics = () => {
console.log(players.map((p) => p.latency));
}
if (deltas.length > 100) {
deltas.sort((a, b) => a - b);
console.log(`Median physics time: ${deltas[50].toFixed(2)} ms`);
console.log(
`Memory used: ${(process.memoryUsage().rss / 1024 / 1024).toFixed(2)} MB`,
);
deltas = [];
}
objects.sendCommand(step);
players.forEach((p) => p.sendCommand(step));
objects.stepObjects(delta);
players.forEach((p) => p.sendObjects());
const physicsDelta = deltaTimeCalculator.getDeltaTimeInMilliseconds();
deltas.push(physicsDelta);

View file

@ -1,45 +1,127 @@
import { vec2, vec3 } from 'gl-matrix';
import { Random } from 'shared';
import { last, Random, settings } from 'shared';
import { LampPhysical } from '../objects/lamp-physical';
import { TunnelPhysical } from '../objects/tunnel-physical';
import { StonePhysical } from '../objects/stone-physical';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { Physical } from '../physics/physical';
export const createDungeon = (objects: PhysicalContainer) => {
let previousRadius = 350;
let previousEnd = vec2.create();
export const createDungeon = (objectContainer: PhysicalContainer) => {
const width = 100000;
const height = 10000;
const objects: Array<Physical> = [];
const lights: Array<Physical> = [];
let tunnelsCountSinceLastLight = 0;
let previousEnd = vec2.fromValues(-width / 2, 0);
while (previousEnd.x < width / 2) {
const { stone, end } = createFloorElement(previousEnd);
objects.push(stone);
previousEnd = end;
}
const calculateDistanceField = (target: vec2): number =>
objects.reduce((min, i) => (min = Math.min(min, i.distance(target))), 1000);
for (let i = 0; i < 50000; i += 500) {
const deltaHeight = (Random.getRandom() - 0.5) * 500;
const height = previousEnd.y + deltaHeight;
const currentEnd = vec2.fromValues(i, height);
const currentToRadius = Random.getRandom() * 300 + 150;
for (let i = 0; i < 400; i++) {
let position: vec2;
const tunnel = new TunnelPhysical(
previousEnd,
currentEnd,
previousRadius,
currentToRadius,
do {
position = vec2.fromValues(
Random.getRandomInRange(-width / 2, width / 2),
Random.getRandomInRange(0, height),
);
} while (
calculateDistanceField(position) < 600 ||
calculateDistanceField(position) > 2000
);
objects.addObject(tunnel);
if (++tunnelsCountSinceLastLight > 3 && Random.getRandom() > 0.7) {
objects.addObject(
new LampPhysical(
currentEnd,
vec3.normalize(
vec3.create(),
vec3.fromValues(Random.getRandom(), 0, Random.getRandom()),
),
0.5,
),
);
tunnelsCountSinceLastLight = 0;
}
previousEnd = currentEnd;
previousRadius = currentToRadius;
objects.push(
createBlob(
position,
Random.getRandomInRange(200, 2000),
Random.getRandomInRange(100, 500),
Random.getRandomInRange(10, 40),
),
);
}
let tryCount = 0;
lightGeneration: for (let i = 0; i < 300; i++) {
console.log(i);
let position: vec2;
do {
position = vec2.fromValues(
Random.getRandomInRange(-width / 2, width / 2),
Random.getRandomInRange(-1000, height),
);
if (tryCount++ > 1e4) {
break lightGeneration;
}
} while (
calculateDistanceField(position) < 200 ||
lights.find((l) => l.distance(position) < 1200)
);
lights.push(
new LampPhysical(
position,
vec3.normalize(
vec3.create(),
vec3.fromValues(
Random.getRandomInRange(0.5, 1),
0,
Random.getRandomInRange(0.5, 1),
),
),
Random.getRandomInRange(0.75, 1.5),
),
);
}
[...objects, ...lights].forEach((o) => objectContainer.addObject(o));
};
const createBlob = (
center: vec2,
width: number,
height: number,
randomness: number,
): StonePhysical => {
const vertices = [];
for (let i = 0; i < settings.polygonEdgeCount; i++) {
vertices.push(
vec2.fromValues(
center.x +
(width / 2) * Math.cos((i / settings.polygonEdgeCount) * -Math.PI * 2) +
Random.getRandomInRange(-randomness, randomness),
center.y +
(height / 2) * Math.sin((i / settings.polygonEdgeCount) * -Math.PI * 2) +
Random.getRandomInRange(-randomness, randomness),
),
);
}
return new StonePhysical(vertices);
};
const createFloorElement = (
start: vec2,
): {
stone: StonePhysical;
end: vec2;
} => {
const vertices: Array<vec2> = [vec2.fromValues(start.x, -10000), start];
let previousX = start.x;
let previousY = start.y;
for (let i = 0; i < settings.polygonEdgeCount - 3; i++) {
previousX += Random.getRandomInRange(200, 800);
previousY += Random.getRandomInRange(-100, 100);
vertices.push(vec2.fromValues(previousX, previousY));
}
const end = last(vertices)!;
vertices.push(vec2.fromValues(end.x, -10000));
return {
stone: new StonePhysical(vertices),
end,
};
};

View file

@ -2,25 +2,22 @@ import { vec2 } from 'gl-matrix';
import {
id,
CharacterBase,
StepCommand,
settings,
CommandExecutors,
MoveActionCommand,
serializesTo,
clamp,
last,
Circle,
} from 'shared';
import { DynamicPhysical } from '../physics/conatiners/dynamic-physical';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { CirclePhysical } from './circle-physical';
import { Physical } from '../physics/physical';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { Spring } from './spring';
@serializesTo(CharacterBase)
export class CharacterPhysical extends CharacterBase implements Physical {
export class CharacterPhysical extends CharacterBase implements DynamicPhysical {
public readonly canCollide = true;
public readonly isInverted = false;
public readonly canMove = true;
private jumpEnergyLeft = settings.defaultJumpEnergy;
@ -32,17 +29,19 @@ export class CharacterPhysical extends CharacterBase implements Physical {
private movementActions: Array<MoveActionCommand> = [];
private lastMovementAction: MoveActionCommand = new MoveActionCommand(vec2.create());
protected commandExecutors: CommandExecutors = {
[StepCommand.type]: this.step.bind(this),
[MoveActionCommand.type]: (c: MoveActionCommand) => this.movementActions.push(c),
};
public handleMovementAction(c: MoveActionCommand) {
this.movementActions.push(c);
}
private static readonly headOffset = vec2.fromValues(0, 40);
private static readonly leftFootOffset = vec2.fromValues(-20, -35);
private static readonly rightFootOffset = vec2.fromValues(20, -35);
constructor(private readonly container: PhysicalContainer) {
super(id());
constructor(
public readonly colorIndex: number,
private readonly container: PhysicalContainer,
) {
super(id(), colorIndex);
this.head = new CirclePhysical(
vec2.clone(CharacterPhysical.headOffset),
50,
@ -76,7 +75,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return this._boundingBox;
}
public get gameObject(): CharacterPhysical {
public get gameObject(): this {
return this;
}
@ -84,6 +83,10 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return this.head.center;
}
public get velocity(): vec2 {
return this.head.velocity;
}
public distance(target: vec2): number {
return (
Math.min(
@ -113,11 +116,11 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return direction;
}
public step(c: StepCommand) {
const deltaTime = c.deltaTimeInMiliseconds / 1000;
public step(deltaTimeInMiliseconds: number) {
const deltaTime = deltaTimeInMiliseconds / 1000;
const direction = this.sumAndResetMovementActions();
const isAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne;
const feetAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne;
const isAirborne = feetAirborne && this.head.isAirborne;
this.jumpEnergyLeft += isAirborne ? -deltaTime : deltaTime;
this.jumpEnergyLeft = clamp(this.jumpEnergyLeft, 0, settings.defaultJumpEnergy);
@ -129,52 +132,80 @@ export class CharacterPhysical extends CharacterBase implements Physical {
vec2.fromValues(xMax, yMax),
);
const sumBody = vec2.add(vec2.create(), this.head.center, this.leftFoot.center);
vec2.add(sumBody, sumBody, this.rightFoot.center);
vec2.scale(sumBody, sumBody, 1 / 3);
const headPosition = vec2.add(vec2.create(), sumBody, CharacterPhysical.headOffset);
Spring.step(new Circle(headPosition, 0), this.head, 0, 30, deltaTime);
const footDistance = vec2.distance(
CharacterPhysical.headOffset,
CharacterPhysical.leftFootOffset,
);
Spring.step(
new Circle(this.head.center, this.head.radius),
this.leftFoot,
footDistance,
25,
deltaTime,
);
Spring.step(
new Circle(this.head.center, this.head.radius),
this.rightFoot,
footDistance,
25,
deltaTime,
);
Spring.step(
this.leftFoot,
this.rightFoot,
vec2.distance(CharacterPhysical.leftFootOffset, CharacterPhysical.rightFootOffset),
100,
300,
deltaTime,
);
this.head.applyForce(movementForce, deltaTime);
this.leftFoot.applyForce(movementForce, deltaTime);
this.rightFoot.applyForce(movementForce, deltaTime);
this.applyForce(this.head, movementForce, deltaTime);
this.applyForce(this.leftFoot, movementForce, deltaTime);
this.applyForce(this.rightFoot, movementForce, deltaTime);
this.head.applyForce(settings.gravitationalForce, deltaTime);
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
if (feetAirborne) {
this.applyForce(this.head, settings.gravitationalForce, deltaTime);
}
this.applyForce(this.leftFoot, settings.gravitationalForce, deltaTime);
this.applyForce(this.rightFoot, settings.gravitationalForce, deltaTime);
this.head.step(deltaTime);
this.leftFoot.step(deltaTime);
this.rightFoot.step(deltaTime);
this.head.step2(deltaTime);
this.leftFoot.step2(deltaTime);
this.rightFoot.step2(deltaTime);
let sumBody = vec2.add(vec2.create(), this.head.center, this.leftFoot.center);
vec2.add(sumBody, sumBody, this.rightFoot.center);
vec2.scale(sumBody, sumBody, 1 / 3);
const headPosition = vec2.add(vec2.create(), sumBody, CharacterPhysical.headOffset);
const headDelta = vec2.subtract(headPosition, headPosition, this.head.center);
vec2.scale(headDelta, headDelta, 0.5);
this.head.tryMove(headDelta);
sumBody = vec2.add(vec2.create(), this.head.center, this.leftFoot.center);
vec2.add(sumBody, sumBody, this.rightFoot.center);
vec2.scale(sumBody, sumBody, 1 / 3);
const leftFootPosition = vec2.add(
vec2.create(),
sumBody,
CharacterPhysical.leftFootOffset,
);
const leftFootDelta = vec2.subtract(
leftFootPosition,
leftFootPosition,
this.leftFoot.center,
);
vec2.scale(leftFootDelta, leftFootDelta, 1);
this.leftFoot.tryMove(leftFootDelta);
const rightFootPosition = vec2.add(
vec2.create(),
sumBody,
CharacterPhysical.rightFootOffset,
);
const rightFootDelta = vec2.subtract(
rightFootPosition,
rightFootPosition,
this.rightFoot.center,
);
vec2.scale(rightFootDelta, rightFootDelta, 1);
this.rightFoot.tryMove(rightFootDelta);
}
public applyForce(circle: CirclePhysical, force: vec2, timeInSeconds: number) {
vec2.add(
circle.velocity,
circle.velocity,
vec2.scale(vec2.create(), force, timeInSeconds),
);
vec2.set(
circle.velocity,
clamp(circle.velocity.x, -settings.maxVelocityX, settings.maxVelocityX),
clamp(circle.velocity.y, -settings.maxVelocityY, settings.maxVelocityY),
);
}
public destroy() {

View file

@ -1,20 +1,20 @@
import { vec2 } from 'gl-matrix';
import { Circle, clamp, GameObject, serializesTo, settings } from 'shared';
import { Circle, GameObject, serializesTo, settings } from 'shared';
import { Physical } from '../physics/physical';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
import { BoundingBoxBase } from '../physics/bounding-boxes/bounding-box-base';
import { moveCircle } from '../physics/move-circle';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { DynamicPhysical } from '../physics/conatiners/dynamic-physical';
@serializesTo(Circle)
export class CirclePhysical implements Circle, Physical {
readonly isInverted = false;
export class CirclePhysical implements Circle, DynamicPhysical {
readonly canCollide = true;
readonly canMove = true;
private _isAirborne = true;
private velocity = vec2.create();
public velocity = vec2.create();
public get isAirborne(): boolean {
return this._isAirborne;
@ -27,6 +27,7 @@ export class CirclePhysical implements Circle, Physical {
private _radius: number,
public owner: GameObject,
private readonly container: PhysicalContainer,
private restitution = 0,
) {
this._boundingBox = new BoundingBox();
this.recalculateBoundingBox();
@ -74,19 +75,6 @@ export class CirclePhysical implements Circle, Physical {
return other.distance(this.center) < -this.radius;
}
public getPerimeterPoints(count: number): Array<vec2> {
const result: Array<vec2> = [];
for (let i = 0; i < count; i++) {
result.push(
vec2.fromValues(
Math.cos((2 * Math.PI * i) / count) * this.radius + this.center.x,
Math.sin((2 * Math.PI * i) / count) * this.radius + this.center.y,
),
);
}
return result;
}
private recalculateBoundingBox() {
this._boundingBox.xMin = this.center.x - this._radius;
this._boundingBox.xMax = this.center.x + this._radius;
@ -100,48 +88,75 @@ export class CirclePhysical implements Circle, Physical {
this.velocity,
vec2.scale(vec2.create(), force, timeInSeconds),
);
vec2.set(
this.velocity,
clamp(this.velocity.x, -settings.maxVelocityX, settings.maxVelocityX),
clamp(this.velocity.y, -settings.maxVelocityY, settings.maxVelocityY),
);
}
public resetVelocity() {
this.velocity = vec2.create();
}
public step(deltaTime: number) {}
public step(deltaTimeInSeconds: number): boolean {
public step2(deltaTimeInSeconds: number): boolean {
vec2.scale(
this.velocity,
this.velocity,
Math.pow(settings.velocityAttenuation, deltaTimeInSeconds),
);
const distance = vec2.scale(vec2.create(), this.velocity, deltaTimeInSeconds);
const delta = vec2.scale(vec2.create(), this.velocity, deltaTimeInSeconds);
const distanceLength = vec2.length(distance);
const stepCount = Math.ceil(distanceLength / settings.physicsMaxStep);
vec2.scale(distance, distance, 1 / stepCount);
const stepCount = Math.ceil(vec2.length(delta) / settings.physicsMaxStep);
vec2.scale(delta, delta, 1 / stepCount);
let wasHit = false;
for (let i = 0; i < stepCount; i++) {
const { tangent, hitSurface } = moveCircle(
this,
vec2.clone(distance),
this.container.findIntersecting(this.boundingBox),
const distance = vec2.scale(
vec2.create(),
this.velocity,
deltaTimeInSeconds / stepCount,
);
this.radius += vec2.length(distance);
const intersecting = this.container.findIntersecting(this.boundingBox);
this.radius -= vec2.length(distance);
const { normal, hitSurface } = moveCircle(this, vec2.clone(distance), intersecting);
if (hitSurface) {
vec2.scale(this.velocity, tangent!, vec2.dot(tangent!, this.velocity));
if (
vec2.length(this.velocity) <
settings.frictionMinVelocity * deltaTimeInSeconds
) {
this.velocity = vec2.create();
}
vec2.subtract(
this.velocity,
this.velocity,
vec2.scale(
normal!,
normal!,
(1 + this.restitution) * vec2.dot(normal!, this.velocity),
),
);
wasHit = true;
}
}
this._isAirborne = !wasHit;
return wasHit;
}
public tryMove(delta: vec2) {
const stepCount = Math.ceil(vec2.length(delta) / settings.physicsMaxStep);
vec2.scale(delta, delta, 1 / stepCount);
let wasHit = false;
for (let i = 0; i < stepCount; i++) {
this.radius += vec2.length(delta);
const intersecting = this.container.findIntersecting(this.boundingBox);
this.radius -= vec2.length(delta);
const { normal, hitSurface } = moveCircle(this, vec2.clone(delta), intersecting);
if (hitSurface) {
vec2.subtract(
delta,
delta,
vec2.scale(normal!, normal!, vec2.dot(normal!, delta)),
);
wasHit = true;
}
}

View file

@ -2,13 +2,11 @@ import { vec2, vec3 } from 'gl-matrix';
import { LampBase, settings, id, serializesTo } from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { Physical } from '../physics/physical';
import { StaticPhysical } from '../physics/containers/static-physical';
@serializesTo(LampBase)
export class LampPhysical extends LampBase implements Physical {
export class LampPhysical extends LampBase implements StaticPhysical {
public readonly canCollide = false;
public readonly isInverted = false;
public readonly canMove = false;
constructor(center: vec2, color: vec3, lightness: number) {
@ -30,12 +28,11 @@ export class LampPhysical extends LampBase implements Physical {
return this._boundingBox;
}
public get gameObject(): LampPhysical {
public get gameObject(): this {
return this;
}
// todo
public distance(_: vec2): number {
return 0;
public distance(target: vec2): number {
return vec2.distance(this.center, target);
}
}

View file

@ -0,0 +1,67 @@
import { vec2 } from 'gl-matrix';
import {
id,
settings,
serializesTo,
ProjectileBase,
GameObject,
rotate90Deg,
} from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { CirclePhysical } from './circle-physical';
import { DynamicPhysical } from '../physics/conatiners/dynamic-physical';
import { PhysicalContainer } from '../physics/containers/physical-container';
@serializesTo(ProjectileBase)
export class ProjectilePhysical extends ProjectileBase implements DynamicPhysical {
public readonly canCollide = true;
public readonly canMove = true;
public object: CirclePhysical;
constructor(
center: vec2,
radius: number,
private velocity: vec2,
readonly container: PhysicalContainer,
) {
super(id(), center, radius);
this.object = new CirclePhysical(center, radius, this, container, 0.9);
}
private _boundingBox?: ImmutableBoundingBox;
public get boundingBox(): ImmutableBoundingBox {
if (!this._boundingBox) {
this._boundingBox = (this.object as CirclePhysical).boundingBox;
}
return this._boundingBox;
}
public get gameObject(): this {
return this;
}
public distance(target: vec2): number {
return this.object.distance(target);
}
public onCollision(normal: vec2, other: GameObject) {
const tangent = rotate90Deg(normal);
vec2.scale(this.velocity, tangent, vec2.dot(tangent, this.velocity));
}
public step(deltaTimeInMiliseconds: number) {
const deltaTime = deltaTimeInMiliseconds / 1000;
vec2.add(
this.velocity,
this.velocity,
vec2.scale(vec2.create(), settings.gravitationalForce, deltaTime),
);
this.object.velocity = this.velocity;
this.object.step2(deltaTime);
}
}

View file

@ -0,0 +1,78 @@
import { vec2 } from 'gl-matrix';
import { clamp01, id, serializesTo, StoneBase } from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { StaticPhysical } from '../physics/containers/static-physical';
@serializesTo(StoneBase)
export class StonePhysical extends StoneBase implements StaticPhysical {
public readonly canCollide = true;
public readonly canMove = false;
private _boundingBox?: ImmutableBoundingBox;
constructor(vertices: Array<vec2>) {
super(id(), vertices);
}
public distance(target: vec2): number {
const startEnd = this.vertices[0];
let vb = startEnd;
let d = vec2.squaredDistance(target, vb);
let sign = 1;
for (let i = 1; i <= this.vertices.length; i++) {
const va = vb;
vb = i === this.vertices.length ? startEnd : this.vertices[i];
const targetFromDelta = vec2.subtract(vec2.create(), target, va);
const toFromDelta = vec2.subtract(vec2.create(), vb, va);
const h = clamp01(
vec2.dot(targetFromDelta, toFromDelta) / vec2.squaredLength(toFromDelta),
);
const ds = vec2.fromValues(
vec2.dist(targetFromDelta, vec2.scale(vec2.create(), toFromDelta, h)),
toFromDelta.x * targetFromDelta.y - toFromDelta.y * targetFromDelta.x,
);
if (
(target.y >= va.y && target.y < vb.y && ds.y > 0) ||
(target.y < va.y && target.y >= vb.y && ds.y <= 0)
) {
sign *= -1;
}
d = Math.min(d, ds.x);
}
return sign * d;
}
public get boundingBox(): ImmutableBoundingBox {
if (!this._boundingBox) {
const { xMin, xMax, yMin, yMax } = this.vertices.reduce(
(extremities, vertex) => ({
xMin: Math.min(extremities.xMin, vertex.x),
xMax: Math.max(extremities.xMax, vertex.x),
yMin: Math.min(extremities.yMin, vertex.y),
yMax: Math.max(extremities.yMax, vertex.y),
}),
{
xMin: Infinity,
xMax: -Infinity,
yMin: Infinity,
yMax: -Infinity,
},
);
this._boundingBox = new ImmutableBoundingBox(xMin, xMax, yMin, yMax);
}
return this._boundingBox;
}
public get gameObject(): this {
return this;
}
}

View file

@ -1,48 +0,0 @@
import { vec2 } from 'gl-matrix';
import { clamp01, mix, TunnelBase, id, serializesTo } from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { StaticPhysical } from '../physics/containers/static-physical-object';
@serializesTo(TunnelBase)
export class TunnelPhysical extends TunnelBase implements StaticPhysical {
public readonly canCollide = true;
public readonly isInverted = true;
public readonly canMove = false;
private _boundingBox?: ImmutableBoundingBox;
constructor(from: vec2, to: vec2, fromRadius: number, toRadius: number) {
super(id(), from, to, fromRadius, toRadius);
}
public distance(target: vec2): number {
const toFromDelta = vec2.subtract(vec2.create(), this.to, this.from);
const targetFromDelta = vec2.subtract(vec2.create(), target, this.from);
const h = clamp01(
vec2.dot(targetFromDelta, toFromDelta) / vec2.dot(toFromDelta, toFromDelta),
);
return (
vec2.distance(targetFromDelta, vec2.scale(vec2.create(), toFromDelta, h)) -
mix(this.fromRadius, this.toRadius, h)
);
}
public get boundingBox(): ImmutableBoundingBox {
if (!this._boundingBox) {
const xMin = Math.min(this.from.x - this.fromRadius, this.to.x - this.toRadius);
const yMin = Math.min(this.from.y - this.fromRadius, this.to.y - this.toRadius);
const xMax = Math.max(this.from.x + this.fromRadius, this.to.x + this.toRadius);
const yMax = Math.max(this.from.y + this.fromRadius, this.to.y + this.toRadius);
this._boundingBox = new ImmutableBoundingBox(xMin, xMax, yMin, yMax);
}
return this._boundingBox;
}
public get gameObject(): TunnelPhysical {
return this;
}
}

View file

@ -8,6 +8,8 @@ export class BoundingBoxBase {
protected _yMax: number = 0,
) {}
[key: number]: number | undefined;
public get 0(): number {
return this._xMin;
}

View file

@ -1,21 +1,25 @@
import { Physical } from '../physical';
import { DynamicPhysical } from '../dynamic-physical';
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
export class BoundingBoxList {
constructor(private objects: Array<Physical> = []) {}
constructor(private objects: Array<DynamicPhysical> = []) {}
public insert(object: Physical) {
public insert(object: DynamicPhysical) {
this.objects.push(object);
}
public remove(object: Physical) {
public remove(object: DynamicPhysical) {
this.objects.splice(
this.objects.findIndex((i) => i === object),
1,
);
}
public findIntersecting(boundingBox: BoundingBoxBase): Array<Physical> {
public forEach(func: (object: DynamicPhysical) => unknown) {
this.objects.forEach(func);
}
public findIntersecting(boundingBox: BoundingBoxBase): Array<DynamicPhysical> {
return this.objects.filter((b) => b.boundingBox.intersects(boundingBox));
}
}

View file

@ -1,15 +1,15 @@
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
import { StaticPhysical } from './static-physical-object';
import { StaticPhysical } from './static-physical';
// source: https://github.com/ubilabs/kd-tree-javascript/blob/master/kdTree.js
class Node {
public left?: Node = null;
public right?: Node = null;
constructor(public object: StaticPhysical, public parent: Node) {}
public left: Node | null = null;
public right: Node | null = null;
constructor(public object: StaticPhysical, public parent: Node | null) {}
}
export class BoundingBoxTree {
root?: Node;
root?: Node | null;
constructor(objects: Array<StaticPhysical> = []) {
this.build(objects);
@ -22,8 +22,8 @@ export class BoundingBoxTree {
private buildRecursive(
objects: Array<StaticPhysical>,
depth: number,
parent: Node,
): Node {
parent: Node | null,
): Node | null {
if (objects.length === 0) {
return null;
}
@ -34,7 +34,7 @@ export class BoundingBoxTree {
const dimension = depth % 4;
objects.sort((a, b) => a.boundingBox[dimension] - b.boundingBox[dimension]);
objects.sort((a, b) => a.boundingBox[dimension]! - b.boundingBox[dimension]!);
const median = Math.floor(objects.length / 2);
@ -54,7 +54,9 @@ export class BoundingBoxTree {
const node = new Node(object, insertPosition);
const dimension = depth % 4;
if (object.boundingBox[dimension] < insertPosition.object.boundingBox[dimension]) {
if (
object.boundingBox[dimension]! < insertPosition.object.boundingBox[dimension]!
) {
insertPosition.left = node;
} else {
insertPosition.right = node;
@ -63,14 +65,14 @@ export class BoundingBoxTree {
}
public findIntersecting(boundingBox: BoundingBoxBase): Array<StaticPhysical> {
const maybeResults = this.findMaybeIntersecting(boundingBox, this.root, 0);
const maybeResults = this.findMaybeIntersecting(boundingBox, this.root!, 0);
const results = maybeResults.filter((b) => b.boundingBox.intersects(boundingBox));
return results;
}
private findMaybeIntersecting(
boundingBox: BoundingBoxBase,
node: Node,
node: Node | null,
depth: number,
): Array<StaticPhysical> {
if (node === null) {
@ -102,17 +104,17 @@ export class BoundingBoxTree {
private findParent(
object: StaticPhysical,
node: Node,
node: Node | null | undefined,
depth: number,
parent: Node,
): [Node, number] {
if (node === null) {
parent: Node | null,
): [Node | null, number] {
if (!node) {
return [parent, depth - 1];
}
const dimension = depth % 4;
if (object.boundingBox[dimension] < node.object.boundingBox[dimension]) {
if (object.boundingBox[dimension]! < node.object.boundingBox[dimension]!) {
return this.findParent(object, node.left, depth + 1, node);
}

View file

@ -0,0 +1,5 @@
import { Physical } from '../physical';
export interface DynamicPhysical extends Physical {
step(deltaTimeInMilliseconds: number): void;
}

View file

@ -1,11 +1,11 @@
import { GameObject, Id } from 'shared';
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
import { BoundingBoxList } from './bounding-box-list';
import { BoundingBoxTree } from './bounding-box-tree';
import { Command } from 'shared';
import { Physical } from '../physical';
import { StaticPhysical } from './static-physical-object';
import { StaticPhysical } from './static-physical';
import { DynamicPhysical } from './dynamic-physical';
export class PhysicalContainer {
private isTreeInitialized = false;
@ -13,27 +13,12 @@ export class PhysicalContainer {
private staticBoundingBoxes = new BoundingBoxTree();
private dynamicBoundingBoxes = new BoundingBoxList();
protected objects: Map<Id, GameObject> = new Map();
private objectsGroupedByAbilities: Map<string, Array<GameObject>> = new Map();
public initialize() {
this.staticBoundingBoxes.build(this.staticBoundingBoxesWaitList);
this.isTreeInitialized = true;
}
public addObject(object: Physical) {
this.objects.set(object.gameObject.id, object.gameObject);
for (const command of this.objectsGroupedByAbilities.keys()) {
if (object.gameObject.reactsToCommand(command)) {
this.objectsGroupedByAbilities.get(command).push(object.gameObject);
}
}
this.addPhysical(object);
}
public addPhysical(physical: Physical) {
public addObject(physical: Physical) {
if (physical.canMove) {
this.dynamicBoundingBoxes.insert(physical);
} else {
@ -45,39 +30,12 @@ export class PhysicalContainer {
}
}
public removeObject(object: Physical) {
this.objects.delete(object.gameObject.id);
for (const command of this.objectsGroupedByAbilities.keys()) {
if (object.gameObject.reactsToCommand(command)) {
const array = this.objectsGroupedByAbilities.get(command);
array.splice(
array.findIndex((i) => i.id == object.gameObject.id),
1,
);
}
}
public removeObject(object: DynamicPhysical) {
this.dynamicBoundingBoxes.remove(object);
}
public sendCommand(e: Command) {
if (!this.objectsGroupedByAbilities.has(e.type)) {
this.createGroupForCommand(e.type);
}
this.objectsGroupedByAbilities.get(e.type).forEach((o, _) => o.sendCommand(e));
}
private createGroupForCommand(commandType: string) {
const objectsReactingToCommand = [];
this.objects.forEach((o, _) => {
if (o.reactsToCommand(commandType)) {
objectsReactingToCommand.push(o);
}
});
this.objectsGroupedByAbilities.set(commandType, objectsReactingToCommand);
public stepObjects(deltaTimeInMilliseconds: number) {
this.dynamicBoundingBoxes.forEach((o) => o.step(deltaTimeInMilliseconds));
}
public findIntersecting(box: BoundingBoxBase): Array<Physical> {

View file

@ -1,5 +1,5 @@
import { vec2 } from 'gl-matrix';
import { rotate90Deg, settings } from 'shared';
import { Circle, rotate90Deg } from 'shared';
import { CirclePhysical } from '../objects/circle-physical';
import { Physical } from './physical';
@ -13,71 +13,48 @@ export const moveCircle = (
normal?: vec2;
tangent?: vec2;
} => {
circle.center = vec2.add(circle.center, circle.center, delta);
const nextCircle = new Circle(vec2.clone(circle.center), circle.radius);
vec2.add(nextCircle.center, nextCircle.center, delta);
const intersecting = possibleIntersectors.filter(
(b) =>
b.gameObject !== circle.gameObject && circle.areIntersecting(b) && b.canCollide,
possibleIntersectors = possibleIntersectors.filter(
(b) => b.gameObject !== circle.gameObject && b.canCollide,
);
if (intersecting.length === 0) {
const getSdfAtPoint = (point: vec2): number => {
return possibleIntersectors
.filter((i) => i.canCollide)
.reduce((min, i) => (min = Math.min(min, i.distance(point))), 1000);
};
const sdfAtCenter = getSdfAtPoint(nextCircle.center);
if (sdfAtCenter > nextCircle.radius) {
circle.center = vec2.add(circle.center, circle.center, delta);
return {
realDelta: delta,
hitSurface: false,
};
}
const points = circle.getPerimeterPoints(settings.hitDetectionCirclePointCount);
const dx =
getSdfAtPoint(vec2.add(vec2.create(), nextCircle.center, vec2.fromValues(1, 0))) -
sdfAtCenter;
const dy =
getSdfAtPoint(vec2.add(vec2.create(), nextCircle.center, vec2.fromValues(0, 1))) -
sdfAtCenter;
const normal = vec2.fromValues(dx, dy);
const distancesOfPoints = points
.map((point) => ({
point,
closest: intersecting
.map((i) => ({
inverted: i.isInverted,
distance: i.distance(point),
}))
.sort((a, b) => a.distance - b.distance)[0],
}))
.filter((i) => i.closest);
vec2.normalize(normal, normal);
const distancesOfIntersectingPoints = distancesOfPoints.filter(
(d) =>
(d.closest.distance > 0 && d.closest.inverted) ||
(d.closest.distance < 0 && !d.closest.inverted),
);
if (distancesOfIntersectingPoints.length === 0) {
return {
realDelta: delta,
hitSurface: false,
};
}
const deltas = distancesOfIntersectingPoints.map((pointDistance) => {
vec2.subtract(pointDistance.point, circle.center, pointDistance.point);
vec2.normalize(pointDistance.point, pointDistance.point);
vec2.scale(
pointDistance.point,
pointDistance.point,
(pointDistance.closest.inverted ? 1 : -1) * pointDistance.closest.distance,
);
return pointDistance.point;
});
const approxNormal = deltas.reduce(
(sum, current) => vec2.add(sum, sum, current),
vec2.create(),
);
vec2.scale(approxNormal, approxNormal, 1 / deltas.length);
circle.center = vec2.add(circle.center, circle.center, approxNormal);
vec2.normalize(approxNormal, approxNormal);
const rotatedNormal = rotate90Deg(normal);
return {
realDelta: delta,
hitSurface: true,
normal: approxNormal,
tangent: rotate90Deg(approxNormal),
normal,
tangent:
vec2.dot(rotatedNormal, delta) < 0
? vec2.scale(rotatedNormal, rotatedNormal, -1)
: rotatedNormal,
};
};

View file

@ -3,7 +3,6 @@ import { GameObject } from 'shared';
import { BoundingBoxBase } from './bounding-boxes/bounding-box-base';
export interface Physical {
readonly isInverted: boolean;
readonly canCollide: boolean;
readonly canMove: boolean;
readonly boundingBox: BoundingBoxBase;

View file

@ -0,0 +1,15 @@
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

@ -1,3 +1,4 @@
import { vec2 } from 'gl-matrix';
import {
CommandExecutors,
CommandReceiver,
@ -8,16 +9,19 @@ import {
serialize,
TransportEvents,
UpdateObjectsCommand,
StepCommand,
SetAspectRatioActionCommand,
calculateViewArea,
SecondaryActionCommand,
settings,
} from 'shared';
import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds';
import { CharacterPhysical } from '../objects/character-physical';
import { ProjectilePhysical } from '../objects/projectile-physical';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { Physical } from '../physics/physical';
import { requestColor, freeColor } from './player-color-service';
export class Player extends CommandReceiver {
private character: CharacterPhysical;
@ -42,10 +46,24 @@ export class Player extends CommandReceiver {
}
protected commandExecutors: CommandExecutors = {
[StepCommand.type]: this.sendObjects.bind(this),
[SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) =>
(this.aspectRatio = v.aspectRatio),
[MoveActionCommand.type]: (c: MoveActionCommand) => this.character.sendCommand(c),
[MoveActionCommand.type]: (c: MoveActionCommand) =>
this.character.handleMovementAction(c),
[SecondaryActionCommand.type]: (c: SecondaryActionCommand) => {
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);
},
};
constructor(
@ -53,7 +71,8 @@ export class Player extends CommandReceiver {
private readonly socket: SocketIO.Socket,
) {
super();
this.character = new CharacterPhysical(objects);
const colorIndex = requestColor();
this.character = new CharacterPhysical(colorIndex, objects);
this.objectsPreviouslyInViewArea.push(this.character);
this.objectsInViewArea.push(this.character);
@ -70,7 +89,6 @@ export class Player extends CommandReceiver {
);
this.measureLatency();
this.sendObjects();
}
@ -89,6 +107,7 @@ export class Player extends CommandReceiver {
const noLongerIntersecting = this.objectsPreviouslyInViewArea.filter(
(o) => !this.objectsInViewArea.includes(o),
);
this.objectsPreviouslyInViewArea = this.objectsInViewArea;
if (noLongerIntersecting.length > 0) {
@ -113,7 +132,7 @@ export class Player extends CommandReceiver {
);
}
this.socket.emit(
this.socket.volatile.emit(
TransportEvents.ServerToPlayer,
serialize(
new UpdateObjectsCommand([
@ -127,6 +146,7 @@ export class Player extends CommandReceiver {
public destroy() {
this.isActive = false;
freeColor(this.character.colorIndex);
this.character.destroy();
this.objects.removeObject(this.character);
}