Fix physics

This commit is contained in:
schmelczerandras 2020-10-12 20:49:17 +02:00
commit f9f6825776
51 changed files with 820 additions and 529 deletions

3
.dockerignore Normal file
View file

@ -0,0 +1,3 @@
.dockerignore
Dockerfile
**/node_modules

View file

@ -1,17 +1,15 @@
FROM node:14.13.0-alpine3.10 as base FROM node:14.13.0-alpine3.10 as build
COPY . . COPY . .
RUN npm install && npm run initialize && npm run build RUN npm install && npm run initialize && npm run build
FROM node:14.13.0-alpine3.10 FROM node:14.13.0-alpine3.10
COPY backend/package.json . COPY backend/package.json .
RUN npm install --production RUN npm install --production
COPY --from=base backend/dist/main.js main.js COPY --from=build backend/dist/main.js main.js
EXPOSE 3000 EXPOSE 3000
CMD [ "node", "main.js" ] CMD [ "node", "main.js" ]

View file

@ -1,11 +0,0 @@
FROM node:14.13.0-alpine3.10
COPY package.json .
RUN npm install --production
COPY dist/main.js main.js
EXPOSE 3000
CMD [ "node", "main.js" ]

View file

@ -1,22 +0,0 @@
version: '3.8'
services:
decla-red-server:
init: true
image: schmelczera/decla-red-server
networks:
- network
deploy:
resources:
limits:
cpus: '1.0'
memory: 256M
reservations:
cpus: '0.25'
memory: 256M
restart_policy:
condition: on-failure
window: 30s
networks:
network:

View file

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

View file

@ -1,45 +1,127 @@
import { vec2, vec3 } from 'gl-matrix'; import { vec2, vec3 } from 'gl-matrix';
import { Random } from 'shared'; import { last, Random, settings } from 'shared';
import { LampPhysical } from '../objects/lamp-physical'; 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 { PhysicalContainer } from '../physics/containers/physical-container';
import { Physical } from '../physics/physical';
export const createDungeon = (objects: PhysicalContainer) => { export const createDungeon = (objectContainer: PhysicalContainer) => {
let previousRadius = 350; const width = 100000;
let previousEnd = vec2.create(); 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) { for (let i = 0; i < 400; i++) {
const deltaHeight = (Random.getRandom() - 0.5) * 500; let position: vec2;
const height = previousEnd.y + deltaHeight;
const currentEnd = vec2.fromValues(i, height);
const currentToRadius = Random.getRandom() * 300 + 150;
const tunnel = new TunnelPhysical( do {
previousEnd, position = vec2.fromValues(
currentEnd, Random.getRandomInRange(-width / 2, width / 2),
previousRadius, Random.getRandomInRange(0, height),
currentToRadius, );
} while (
calculateDistanceField(position) < 600 ||
calculateDistanceField(position) > 2000
); );
objects.addObject(tunnel); objects.push(
createBlob(
position,
Random.getRandomInRange(200, 2000),
Random.getRandomInRange(100, 500),
Random.getRandomInRange(10, 40),
),
);
}
if (++tunnelsCountSinceLastLight > 3 && Random.getRandom() > 0.7) { let tryCount = 0;
objects.addObject( 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( new LampPhysical(
currentEnd, position,
vec3.normalize( vec3.normalize(
vec3.create(), vec3.create(),
vec3.fromValues(Random.getRandom(), 0, Random.getRandom()), vec3.fromValues(
Random.getRandomInRange(0.5, 1),
0,
Random.getRandomInRange(0.5, 1),
), ),
0.5, ),
Random.getRandomInRange(0.75, 1.5),
), ),
); );
tunnelsCountSinceLastLight = 0;
} }
previousEnd = currentEnd; [...objects, ...lights].forEach((o) => objectContainer.addObject(o));
previousRadius = currentToRadius; };
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 { import {
id, id,
CharacterBase, CharacterBase,
StepCommand,
settings, settings,
CommandExecutors,
MoveActionCommand, MoveActionCommand,
serializesTo, serializesTo,
clamp, clamp,
last, last,
Circle,
} from 'shared'; } from 'shared';
import { DynamicPhysical } from '../physics/conatiners/dynamic-physical';
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 { Physical } from '../physics/physical';
import { PhysicalContainer } from '../physics/containers/physical-container'; import { PhysicalContainer } from '../physics/containers/physical-container';
import { Spring } from './spring'; import { Spring } from './spring';
@serializesTo(CharacterBase) @serializesTo(CharacterBase)
export class CharacterPhysical extends CharacterBase implements Physical { export class CharacterPhysical extends CharacterBase implements DynamicPhysical {
public readonly canCollide = true; public readonly canCollide = true;
public readonly isInverted = false;
public readonly canMove = true; public readonly canMove = true;
private jumpEnergyLeft = settings.defaultJumpEnergy; private jumpEnergyLeft = settings.defaultJumpEnergy;
@ -32,17 +29,19 @@ export class CharacterPhysical extends CharacterBase implements Physical {
private movementActions: Array<MoveActionCommand> = []; private movementActions: Array<MoveActionCommand> = [];
private lastMovementAction: MoveActionCommand = new MoveActionCommand(vec2.create()); private lastMovementAction: MoveActionCommand = new MoveActionCommand(vec2.create());
protected commandExecutors: CommandExecutors = { public handleMovementAction(c: MoveActionCommand) {
[StepCommand.type]: this.step.bind(this), this.movementActions.push(c);
[MoveActionCommand.type]: (c: MoveActionCommand) => this.movementActions.push(c), }
};
private static readonly headOffset = vec2.fromValues(0, 40); private static readonly headOffset = vec2.fromValues(0, 40);
private static readonly leftFootOffset = vec2.fromValues(-20, -35); private static readonly leftFootOffset = vec2.fromValues(-20, -35);
private static readonly rightFootOffset = vec2.fromValues(20, -35); private static readonly rightFootOffset = vec2.fromValues(20, -35);
constructor(private readonly container: PhysicalContainer) { constructor(
super(id()); public readonly colorIndex: number,
private readonly container: PhysicalContainer,
) {
super(id(), colorIndex);
this.head = new CirclePhysical( this.head = new CirclePhysical(
vec2.clone(CharacterPhysical.headOffset), vec2.clone(CharacterPhysical.headOffset),
50, 50,
@ -76,7 +75,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return this._boundingBox; return this._boundingBox;
} }
public get gameObject(): CharacterPhysical { public get gameObject(): this {
return this; return this;
} }
@ -84,6 +83,10 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return this.head.center; return this.head.center;
} }
public get velocity(): vec2 {
return this.head.velocity;
}
public distance(target: vec2): number { public distance(target: vec2): number {
return ( return (
Math.min( Math.min(
@ -113,11 +116,11 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return direction; return direction;
} }
public step(c: StepCommand) { public step(deltaTimeInMiliseconds: number) {
const deltaTime = c.deltaTimeInMiliseconds / 1000; const deltaTime = deltaTimeInMiliseconds / 1000;
const direction = this.sumAndResetMovementActions(); 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 += isAirborne ? -deltaTime : deltaTime;
this.jumpEnergyLeft = clamp(this.jumpEnergyLeft, 0, settings.defaultJumpEnergy); this.jumpEnergyLeft = clamp(this.jumpEnergyLeft, 0, settings.defaultJumpEnergy);
@ -129,52 +132,80 @@ export class CharacterPhysical extends CharacterBase implements Physical {
vec2.fromValues(xMax, yMax), 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( Spring.step(
this.leftFoot, this.leftFoot,
this.rightFoot, this.rightFoot,
vec2.distance(CharacterPhysical.leftFootOffset, CharacterPhysical.rightFootOffset), vec2.distance(CharacterPhysical.leftFootOffset, CharacterPhysical.rightFootOffset),
100, 300,
deltaTime, deltaTime,
); );
this.head.applyForce(movementForce, deltaTime); this.applyForce(this.head, movementForce, deltaTime);
this.leftFoot.applyForce(movementForce, deltaTime); this.applyForce(this.leftFoot, movementForce, deltaTime);
this.rightFoot.applyForce(movementForce, deltaTime); this.applyForce(this.rightFoot, movementForce, deltaTime);
this.head.applyForce(settings.gravitationalForce, deltaTime); if (feetAirborne) {
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime); this.applyForce(this.head, settings.gravitationalForce, deltaTime);
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime); }
this.applyForce(this.leftFoot, settings.gravitationalForce, deltaTime);
this.applyForce(this.rightFoot, settings.gravitationalForce, deltaTime);
this.head.step(deltaTime); this.head.step2(deltaTime);
this.leftFoot.step(deltaTime); this.leftFoot.step2(deltaTime);
this.rightFoot.step(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() { public destroy() {

View file

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

View file

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

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, protected _yMax: number = 0,
) {} ) {}
[key: number]: number | undefined;
public get 0(): number { public get 0(): number {
return this._xMin; 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'; import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
export class BoundingBoxList { 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); this.objects.push(object);
} }
public remove(object: Physical) { public remove(object: DynamicPhysical) {
this.objects.splice( this.objects.splice(
this.objects.findIndex((i) => i === object), this.objects.findIndex((i) => i === object),
1, 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)); return this.objects.filter((b) => b.boundingBox.intersects(boundingBox));
} }
} }

View file

@ -1,15 +1,15 @@
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base'; 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 // source: https://github.com/ubilabs/kd-tree-javascript/blob/master/kdTree.js
class Node { class Node {
public left?: Node = null; public left: Node | null = null;
public right?: Node = null; public right: Node | null = null;
constructor(public object: StaticPhysical, public parent: Node) {} constructor(public object: StaticPhysical, public parent: Node | null) {}
} }
export class BoundingBoxTree { export class BoundingBoxTree {
root?: Node; root?: Node | null;
constructor(objects: Array<StaticPhysical> = []) { constructor(objects: Array<StaticPhysical> = []) {
this.build(objects); this.build(objects);
@ -22,8 +22,8 @@ export class BoundingBoxTree {
private buildRecursive( private buildRecursive(
objects: Array<StaticPhysical>, objects: Array<StaticPhysical>,
depth: number, depth: number,
parent: Node, parent: Node | null,
): Node { ): Node | null {
if (objects.length === 0) { if (objects.length === 0) {
return null; return null;
} }
@ -34,7 +34,7 @@ export class BoundingBoxTree {
const dimension = depth % 4; 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); const median = Math.floor(objects.length / 2);
@ -54,7 +54,9 @@ export class BoundingBoxTree {
const node = new Node(object, insertPosition); const node = new Node(object, insertPosition);
const dimension = depth % 4; const dimension = depth % 4;
if (object.boundingBox[dimension] < insertPosition.object.boundingBox[dimension]) { if (
object.boundingBox[dimension]! < insertPosition.object.boundingBox[dimension]!
) {
insertPosition.left = node; insertPosition.left = node;
} else { } else {
insertPosition.right = node; insertPosition.right = node;
@ -63,14 +65,14 @@ export class BoundingBoxTree {
} }
public findIntersecting(boundingBox: BoundingBoxBase): Array<StaticPhysical> { 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)); const results = maybeResults.filter((b) => b.boundingBox.intersects(boundingBox));
return results; return results;
} }
private findMaybeIntersecting( private findMaybeIntersecting(
boundingBox: BoundingBoxBase, boundingBox: BoundingBoxBase,
node: Node, node: Node | null,
depth: number, depth: number,
): Array<StaticPhysical> { ): Array<StaticPhysical> {
if (node === null) { if (node === null) {
@ -102,17 +104,17 @@ export class BoundingBoxTree {
private findParent( private findParent(
object: StaticPhysical, object: StaticPhysical,
node: Node, node: Node | null | undefined,
depth: number, depth: number,
parent: Node, parent: Node | null,
): [Node, number] { ): [Node | null, number] {
if (node === null) { if (!node) {
return [parent, depth - 1]; return [parent, depth - 1];
} }
const dimension = depth % 4; 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); 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 { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
import { BoundingBoxList } from './bounding-box-list'; import { BoundingBoxList } from './bounding-box-list';
import { BoundingBoxTree } from './bounding-box-tree'; import { BoundingBoxTree } from './bounding-box-tree';
import { Command } from 'shared';
import { Physical } from '../physical'; import { Physical } from '../physical';
import { StaticPhysical } from './static-physical-object'; import { StaticPhysical } from './static-physical';
import { DynamicPhysical } from './dynamic-physical';
export class PhysicalContainer { export class PhysicalContainer {
private isTreeInitialized = false; private isTreeInitialized = false;
@ -13,27 +13,12 @@ export class PhysicalContainer {
private staticBoundingBoxes = new BoundingBoxTree(); private staticBoundingBoxes = new BoundingBoxTree();
private dynamicBoundingBoxes = new BoundingBoxList(); private dynamicBoundingBoxes = new BoundingBoxList();
protected objects: Map<Id, GameObject> = new Map();
private objectsGroupedByAbilities: Map<string, Array<GameObject>> = new Map();
public initialize() { public initialize() {
this.staticBoundingBoxes.build(this.staticBoundingBoxesWaitList); this.staticBoundingBoxes.build(this.staticBoundingBoxesWaitList);
this.isTreeInitialized = true; this.isTreeInitialized = true;
} }
public addObject(object: Physical) { public addObject(physical: 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) {
if (physical.canMove) { if (physical.canMove) {
this.dynamicBoundingBoxes.insert(physical); this.dynamicBoundingBoxes.insert(physical);
} else { } else {
@ -45,39 +30,12 @@ export class PhysicalContainer {
} }
} }
public removeObject(object: Physical) { public removeObject(object: DynamicPhysical) {
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,
);
}
}
this.dynamicBoundingBoxes.remove(object); this.dynamicBoundingBoxes.remove(object);
} }
public sendCommand(e: Command) { public stepObjects(deltaTimeInMilliseconds: number) {
if (!this.objectsGroupedByAbilities.has(e.type)) { this.dynamicBoundingBoxes.forEach((o) => o.step(deltaTimeInMilliseconds));
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 findIntersecting(box: BoundingBoxBase): Array<Physical> { public findIntersecting(box: BoundingBoxBase): Array<Physical> {

View file

@ -0,0 +1,6 @@
import { Physical } from '../physical';
import { ImmutableBoundingBox } from '../bounding-boxes/immutable-bounding-box';
export interface StaticPhysical extends Physical {
readonly boundingBox: ImmutableBoundingBox;
}

View file

@ -1,5 +1,5 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { rotate90Deg, settings } from 'shared'; import { Circle, rotate90Deg } from 'shared';
import { CirclePhysical } from '../objects/circle-physical'; import { CirclePhysical } from '../objects/circle-physical';
import { Physical } from './physical'; import { Physical } from './physical';
@ -13,71 +13,48 @@ export const moveCircle = (
normal?: vec2; normal?: vec2;
tangent?: vec2; tangent?: vec2;
} => { } => {
const nextCircle = new Circle(vec2.clone(circle.center), circle.radius);
vec2.add(nextCircle.center, nextCircle.center, delta);
possibleIntersectors = possibleIntersectors.filter(
(b) => b.gameObject !== circle.gameObject && b.canCollide,
);
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); circle.center = vec2.add(circle.center, circle.center, delta);
const intersecting = possibleIntersectors.filter(
(b) =>
b.gameObject !== circle.gameObject && circle.areIntersecting(b) && b.canCollide,
);
if (intersecting.length === 0) {
return { return {
realDelta: delta, realDelta: delta,
hitSurface: false, 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 vec2.normalize(normal, normal);
.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);
const distancesOfIntersectingPoints = distancesOfPoints.filter( const rotatedNormal = rotate90Deg(normal);
(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);
return { return {
realDelta: delta, realDelta: delta,
hitSurface: true, hitSurface: true,
normal: approxNormal, normal,
tangent: rotate90Deg(approxNormal), 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'; import { BoundingBoxBase } from './bounding-boxes/bounding-box-base';
export interface Physical { export interface Physical {
readonly isInverted: boolean;
readonly canCollide: boolean; readonly canCollide: boolean;
readonly canMove: boolean; readonly canMove: boolean;
readonly boundingBox: BoundingBoxBase; readonly boundingBox: BoundingBoxBase;

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