Compare commits

...

21 Commits

Author SHA1 Message Date
Oliver Zell
c6e23c5560 Merge branch 'master' into liquid-fun 2025-02-16 21:57:49 +01:00
Oliver Zell
9262dbdc0c fix: improve resolution for liquidfun examples 2025-02-16 18:49:12 +01:00
Oliver Zell
f5d5edcd40 performance: minor particle render improvement in testbed 2024-03-31 14:59:36 +02:00
Oliver Zell
7f5b6c934f refactor: remove default exports 2024-03-30 21:29:53 +01:00
Oliver Zell
66ed7231ef feat: render particles in testbed 2024-03-30 21:18:11 +01:00
Oliver Zell
589393aecc fix: fix liquid fun examples 2024-03-30 21:11:54 +01:00
Oliver Zell
3116852fb1 fix: fix build errors 2024-03-30 20:59:35 +01:00
Oliver Zell
9e2fba1aea Merge branch 'master' into liquid-fun 2024-03-30 19:58:51 +01:00
Oliver Zell
2195f6f305 Merge branch 'master' into liquid-fun 2022-05-21 17:55:16 +02:00
Oliver Zell
913a00cf28 add Particles and DamBreak example 2021-08-14 11:13:10 +02:00
Oliver Zell
c4b983df12 add ElasticParticles and RigidParticles example 2021-08-12 19:36:33 +02:00
Oliver Zell
5d902b0a38 render particles in testbed 2021-08-04 18:57:22 +02:00
Oliver Zell
b6c6a65246 simulate particle systems 2021-07-25 11:58:17 +02:00
Oliver Zell
c695cbe316 fix runtime errors during particleSystem initialization 2021-07-24 11:26:23 +02:00
Oliver Zell
b795bb9e0b add WaveMachine example 2021-07-24 10:56:38 +02:00
Oliver Zell
99604dd27c fix TS errors in ParticleSystem 2021-07-20 20:00:06 +02:00
Oliver Zell
477619638c add initial port of ParticleSystem from LiquidFun 2021-07-16 17:12:11 +02:00
Oliver Zell
2e33cc883e extend World by particle-systems 2021-06-27 17:31:00 +02:00
Oliver Zell
60784e20a8 add computeDistance method to shapes and fixture 2021-06-26 20:04:37 +02:00
Oliver Zell
6ec029ec2c add Particle and ParticleGroup from LiquidFun 2021-06-26 13:30:07 +02:00
Oliver Zell
6d77047aab add StackQueue and VoronoiDiagram from LiquidFun 2021-06-05 14:28:49 +02:00
32 changed files with 7753 additions and 15 deletions

52
example/DamBreak.ts Normal file
View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { World, Vec2, Chain, Box, Testbed } from "planck";
const testbed = Testbed.mount();
var world = new World({
gravity: new Vec2(0, -10),
});
testbed.x = 0;
testbed.y = 0;
testbed.width = 10;
testbed.height = 10;
testbed.ratio = 64;
testbed.start(world);
var ground = world.createBody();
var shape = new Chain([
new Vec2(-2, 0),
new Vec2(2, 0),
new Vec2(2, 4),
new Vec2(-2, 4)
], true);
ground.createFixture(shape, 0);
var particleSystem = world.createParticleSystem({
radius: 0.025,
dampingStrength: 0.2,
});
var group = particleSystem.createParticleGroup({
// flags: TestMain::GetParticleParameterValue(), // TODO
shape: new Box(0.8, 1.0, new Vec2(-1.2, 1.01), 0)
})
// if (pd.flags & b2_colorMixingParticle) { // TODO
// ColorParticleGroup(group, 0);
// }

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { World, Vec2, Circle, Polygon, Box, Testbed } from "planck";
// TODO export enums
const b2_springParticle = 1 << 3;
const b2_elasticParticle = 1 << 4;
const b2_solidParticleGroup = 1 << 0;
const testbed = Testbed.mount();
var world = new World({
gravity: new Vec2(0, -10),
});
testbed.x = 0;
testbed.y = 0;
testbed.width = 10;
testbed.height = 10;
testbed.ratio = 64;
testbed.start(world);
var ground = world.createBody();
{
const shape = new Polygon([
new Vec2(-4, -1),
new Vec2(4, -1),
new Vec2(4, 0),
new Vec2(-4, 0)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(-4, -0.1),
new Vec2(-2, -0.1),
new Vec2(-2, 2),
new Vec2(-4, 2)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(2, -0.1),
new Vec2(4, -0.1),
new Vec2(4, 2),
new Vec2(2, 2)
]);
ground.createFixture(shape, 0.0);
}
var particleSystem = world.createParticleSystem({
radius: 0.035,
});
particleSystem.createParticleGroup({
flags: b2_springParticle,
groupFlags: b2_solidParticleGroup,
shape: new Circle(new Vec2(0, 3), 0.5)
// color: (255, 0, 0, 255) // TODO
});
particleSystem.createParticleGroup({
flags: b2_elasticParticle,
groupFlags: b2_solidParticleGroup,
shape: new Circle(new Vec2(-1, 3), 0.5)
// color: (0, 255, 0, 255); // TODO
});
{
particleSystem.createParticleGroup({
flags: b2_elasticParticle,
groupFlags: b2_solidParticleGroup,
position: new Vec2(1, 4),
angle: -0.5,
angularVelocity: 2.0,
shape: new Box(1, 0.5)
// color: (0, 0, 255, 255); // TODO
});
}
{
const body = world.createDynamicBody();
const shape = new Circle(new Vec2(0,8), 0.5);
body.createFixture(shape, 0.5);
}

78
example/Particles.ts Normal file
View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { World, Vec2, Circle, Polygon, Testbed } from "planck";
const testbed = Testbed.mount();
var world = new World({
gravity: new Vec2(0, -10),
});
testbed.x = 0;
testbed.y = 0;
testbed.width = 10;
testbed.height = 10;
testbed.ratio = 64;
testbed.start(world);
var ground = world.createBody();
{
const shape = new Polygon([
new Vec2(-4, -1),
new Vec2(4, -1),
new Vec2(4, 0),
new Vec2(-4, 0)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(-4, -0.1),
new Vec2(-2, -0.1),
new Vec2(-2, 2),
new Vec2(-4, 3)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(2, -0.1),
new Vec2(4, -0.1),
new Vec2(4, 3),
new Vec2(2, 2)
]);
ground.createFixture(shape, 0.0);
}
var particleType = 0; // TestMain::GetParticleParameterValue(); // TODO
var particleSystem = world.createParticleSystem({
radius: 0.025,
dampingStrength: 0.2,
});
const group = particleSystem.createParticleGroup({
flags: particleType,
shape: new Circle(new Vec2(0, 3), 2)
});
// if (pd.flags & b2_colorMixingParticle) {
// ColorParticleGroup(group, 0); // TODO
// }
{
const body = world.createDynamicBody();
const shape = new Circle(new Vec2(0, 8), 0.5);
body.createFixture(shape, 0.5);
}

93
example/RigidParticles.ts Normal file
View File

@ -0,0 +1,93 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { World, Vec2, Circle, Polygon, Box, Testbed } from "planck";
// TODO export enums
const b2_rigidParticleGroup = 1 << 1;
const b2_solidParticleGroup = 1 << 0;
const testbed = Testbed.mount();
var world = new World({
gravity: new Vec2(0, -10),
});
testbed.x = 0;
testbed.y = 0;
testbed.width = 10;
testbed.height = 10;
testbed.ratio = 64;
testbed.start(world);
var ground = world.createBody();
{
const shape = new Polygon([
new Vec2(-4, -1),
new Vec2(4, -1),
new Vec2(4, 0),
new Vec2(-4, 0)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(-4, -0.1),
new Vec2(-2, -0.1),
new Vec2(-2, 2),
new Vec2(-4, 2)
]);
ground.createFixture(shape, 0.0);
}
{
const shape = new Polygon([
new Vec2(2, -0.1),
new Vec2(4, -0.1),
new Vec2(4, 2),
new Vec2(2, 2)
]);
ground.createFixture(shape, 0.0);
}
var particleSystem = world.createParticleSystem({
radius: 0.035,
});
particleSystem.createParticleGroup({
groupFlags: b2_rigidParticleGroup | b2_solidParticleGroup,
shape: new Circle(new Vec2(0, 3), 0.5)
// color: (255, 0, 0, 255) // TODO
});
particleSystem.createParticleGroup({
groupFlags: b2_rigidParticleGroup | b2_solidParticleGroup,
shape: new Circle(new Vec2(-1, 3), 0.5)
// color: (0, 255, 0, 255); // TODO
});
{
particleSystem.createParticleGroup({
groupFlags: b2_rigidParticleGroup | b2_solidParticleGroup,
position: new Vec2(1, 4),
angle: -0.5,
angularVelocity: 2.0,
shape: new Box(1, 0.5)
// color: (0, 0, 255, 255); // TODO
});
}
{
const body = world.createDynamicBody();
const shape = new Circle(new Vec2(0, 8), 0.5);
body.createFixture(shape, 0.5);
}

66
example/WaveMachine.ts Normal file
View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { World, Vec2, Box, RevoluteJoint, Testbed } from "planck";
const testbed = Testbed.mount();
var world = new World({
gravity: new Vec2(0, -10),
});
testbed.x = 0;
testbed.y = 0;
testbed.width = 10;
testbed.height = 10;
testbed.ratio = 64;
testbed.start(world);
var ground = world.createBody();
var body = world.createBody({
type: 'dynamic',
allowSleep: false,
position: new Vec2(0, 1)
});
body.createFixture(new Box(0.05, 1.00, new Vec2( 2, 0), 0), 5);
body.createFixture(new Box(0.05, 1.00, new Vec2(-2, 0), 0), 5);
body.createFixture(new Box(2.00, 0.05, new Vec2( 0, 1), 0), 5);
body.createFixture(new Box(2.00, 0.05, new Vec2( 0,-1), 0), 5);
var joint = world.createJoint(new RevoluteJoint({
bodyA: ground,
bodyB: body,
localAnchorA: new Vec2(0, 1),
localAnchorB: new Vec2(0, 0),
referenceAngle: 0,
motorSpeed: 0.05 * Math.PI,
maxMotorTorque: 1e7,
enableMotor: true,
}));
var particleSystem = world.createParticleSystem({
radius: 0.025,
dampingStrength: 0.2,
});
var box = new Box(0.9, 0.9, new Vec2(0, 1), 0);
var particleGroup = particleSystem.createParticleGroup({
shape: box,
});
testbed.step = (_, t) => {
var hz = 1; // TODO
joint.setMotorSpeed(0.05 * Math.cos(t / 1000 / hz) * Math.PI);
}

View File

@ -22,11 +22,13 @@
"ContinuousTest",
"ConvexHull",
"ConveyorBelt",
"DamBreak",
"DistanceTest",
"Dominos",
"DynamicTreeTest",
"EdgeShapes",
"EdgeTest",
"ElasticParticles",
"Gears",
"HeavyOnLight",
"HeavyOnLightTwo",
@ -35,6 +37,7 @@
"MobileBalanced",
"MotorJoint",
"OneSidedPlatform",
"Particles",
"Pinball",
"PolyCollision",
"PolyShapes",
@ -43,6 +46,7 @@
"Pyramid",
"RayCast",
"Revolute",
"RigidParticles",
"RopeJoint",
"SensorTest",
"ShapeCast",
@ -58,5 +62,6 @@
"VaryingFriction",
"VaryingRestitution",
"VerticalStack",
"WaveMachine",
"Web"
]

60
package-lock.json generated
View File

@ -17,6 +17,7 @@
"@typescript-eslint/parser": "^8.18.1",
"@vitest/coverage-v8": "^2.1.5",
"ajv": "^6.10.2",
"assemblyscript": "^0.19.23",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.4.2",
@ -2324,6 +2325,26 @@
"node": ">=0.10.0"
}
},
"node_modules/assemblyscript": {
"version": "0.19.23",
"resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.23.tgz",
"integrity": "sha512-fwOQNZVTMga5KRsfY80g7cpOl4PsFQczMwHzdtgoqLXaYhkhavufKb0sB0l3T1DUxpAufA0KNhlbpuuhZUwxMA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"binaryen": "102.0.0-nightly.20211028",
"long": "^5.2.0",
"source-map-support": "^0.5.20"
},
"bin": {
"asc": "bin/asc",
"asinit": "bin/asinit"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/assemblyscript"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@ -2352,6 +2373,16 @@
"node": ">=4"
}
},
"node_modules/binaryen": {
"version": "102.0.0-nightly.20211028",
"resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz",
"integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"wasm-opt": "bin/wasm-opt"
}
},
"node_modules/brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
@ -4233,6 +4264,12 @@
"node": ">=8"
}
},
"node_modules/long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==",
"dev": true
},
"node_modules/loupe": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz",
@ -8577,6 +8614,17 @@
"integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=",
"dev": true
},
"assemblyscript": {
"version": "0.19.23",
"resolved": "https://registry.npmjs.org/assemblyscript/-/assemblyscript-0.19.23.tgz",
"integrity": "sha512-fwOQNZVTMga5KRsfY80g7cpOl4PsFQczMwHzdtgoqLXaYhkhavufKb0sB0l3T1DUxpAufA0KNhlbpuuhZUwxMA==",
"dev": true,
"requires": {
"binaryen": "102.0.0-nightly.20211028",
"long": "^5.2.0",
"source-map-support": "^0.5.20"
}
},
"assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@ -8598,6 +8646,12 @@
"is-windows": "^1.0.0"
}
},
"binaryen": {
"version": "102.0.0-nightly.20211028",
"resolved": "https://registry.npmjs.org/binaryen/-/binaryen-102.0.0-nightly.20211028.tgz",
"integrity": "sha512-GCJBVB5exbxzzvyt8MGDv/MeUjs6gkXDvf4xOIItRBptYl0Tz5sm1o/uG95YK0L0VeG5ajDu3hRtkBP2kzqC5w==",
"dev": true
},
"brace-expansion": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
@ -9961,6 +10015,12 @@
}
}
},
"long": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==",
"dev": true
},
"loupe": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.2.tgz",

View File

@ -62,6 +62,7 @@
"@typescript-eslint/parser": "^8.18.1",
"@vitest/coverage-v8": "^2.1.5",
"ajv": "^6.10.2",
"assemblyscript": "^0.19.23",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.4.2",

View File

@ -129,6 +129,38 @@ export class Settings {
static baumgarte: number = 0.2;
static toiBaugarte: number = 0.75;
// Particle
/** A symbolic constant that stands for particle allocation error. */
static b2_invalidParticleIndex = -1;
static b2_maxParticleIndex = 0x7FFFFFFF;
/** The default distance between particles, multiplied by the particle diameter. */
static b2_particleStride = 0.75;
/** The minimum particle weight that produces pressure. */
static b2_minParticleWeight = 1.0;
/** The upper limit for particle pressure. */
static b2_maxParticlePressure = 0.25;
/** The upper limit for force between particles. */
static b2_maxParticleForce = 0.5;
/**
* The maximum distance between particles in a triad, multiplied by the
* particle diameter.
*/
static b2_maxTriadDistance = 2;
static b2_maxTriadDistanceSquared = (Settings.b2_maxTriadDistance * Settings.b2_maxTriadDistance)
/** The initial size of particle data buffers. */
static b2_minParticleSystemBufferCapacity = 256;
/** The time into the future that collisions against barrier particles will be detected. */
static b2_barrierCollisionTime = 2.5;
// Sleep
/**
@ -212,6 +244,36 @@ export class SettingsInternal {
static get toiBaugarte() {
return Settings.toiBaugarte;
}
static get b2_invalidParticleIndex() {
return Settings.b2_invalidParticleIndex;
}
static get b2_maxParticleIndex() {
return Settings.b2_maxParticleIndex;
}
static get b2_particleStride() {
return Settings.b2_particleStride;
}
static get b2_minParticleWeight() {
return Settings.b2_minParticleWeight;
}
static get b2_maxParticlePressure() {
return Settings.b2_maxParticlePressure;
}
static get b2_maxParticleForce() {
return Settings.b2_maxParticleForce;
}
static get b2_maxTriadDistance() {
return Settings.b2_maxTriadDistance;
}
static get b2_maxTriadDistanceSquared() {
return Settings.b2_maxTriadDistanceSquared;
}
static get b2_minParticleSystemBufferCapacity() {
return Settings.b2_minParticleSystemBufferCapacity;
}
static get b2_barrierCollisionTime() {
return Settings.b2_barrierCollisionTime;
}
static get timeToSleep() {
return Settings.timeToSleep;
}

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -11,7 +11,7 @@ import type { MassData } from "../dynamics/Body";
import { RayCastOutput, RayCastInput, AABBValue } from "./AABB";
import { DistanceProxy } from "./Distance";
import type { Transform, TransformValue } from "../common/Transform";
import type { Vec2Value } from "../common/Vec2";
import type { Vec2, Vec2Value } from "../common/Vec2";
import { Style } from "../util/Testbed";
// todo make shape an interface
@ -78,6 +78,17 @@ export abstract class Shape {
*/
abstract testPoint(xf: TransformValue, p: Vec2Value): boolean;
/**
* LIQUID_FUN:
*
* Compute the distance from the current shape to the specified point. This only works for convex shapes.
* @param xf the shape world transform.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @return returns the distance from the current shape.
*/
abstract computeDistance(xf: Transform, p: Vec2Value, normal: Vec2, childIndex: number): number;
/**
* Cast a ray against a child shape.
*

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -310,6 +310,22 @@ export class ChainShape extends Shape {
return false;
}
/**
* LIQUID_FUN:
*
* Compute the distance from the current shape to the specified point. This only works for convex shapes.
* @param xf the shape world transform.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @param childIndex The child shape index
* @return returns the distance from the current shape.
*/
computeDistance(xf: Transform, p: Vec2Value, normal: Vec2, childIndex: number) {
const edge = new EdgeShape();
this.getChildEdge(edge, childIndex);
return edge.computeDistance(xf, p, normal, 0);
}
/**
* Cast a ray against a child shape.
*

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -132,6 +132,24 @@ export class CircleShape extends Shape {
return matrix.distSqrVec2(p, center) <= this.m_radius * this.m_radius;
}
/**
* LIQUID_FUN:
*
* Compute the distance from the current shape to the specified point. This only works for convex shapes.
* @param transform the shape world transform.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @return returns the distance from the current shape.
*/
computeDistance(transform: Transform, p: Vec2Value, normal: Vec2, childIndex: number) {
const center = Vec2.add(transform.p, Rot.mulVec2(transform.q, this.m_p));
const d = Vec2.sub(p, center);
const d1 = d.length();
normal.setMul(1 / d1, d);
return d1 - this.m_radius;
}
/**
* Cast a ray against a child shape.
*

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -212,6 +212,36 @@ export class EdgeShape extends Shape {
return false;
}
/**
* LIQUID_FUN:
*
* Compute the distance from the current shape to the specified point. This only works for convex shapes.
* @param xf the shape world transform.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @return returns the distance from the current shape.
*/
computeDistance(xf: Transform, p: Vec2Value, normal: Vec2, childIndex: number) {
const v1 = Transform.mulVec2(xf, this.m_vertex1);
const v2 = Transform.mulVec2(xf, this.m_vertex2);
let d = Vec2.sub(p, v1);
const s = Vec2.sub(v2, v1);
const ds = Vec2.dot(d, s);
if (ds > 0) {
const s2 = Vec2.dot(s, s);
if (ds > s2) {
d = Vec2.sub(p, v2);
} else {
d.subMul(ds / s2, s);
}
}
const d1 = d.length();
normal.set(d1 > 0 ? Vec2.mul(1 / d1, d) : Vec2.zero()); // TODO remove unnecessary object creations (wait for final method signature)
return d1;
}
/**
* Cast a ray against a child shape.
*

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -312,6 +312,50 @@ export class PolygonShape extends Shape {
return true;
}
/**
* LIQUID_FUN:
*
* Compute the distance from the current shape to the specified point. This only works for convex shapes.
* @param xf the shape world transform.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @return returns the distance from the current shape.
*/
computeDistance(xf: Transform, p: Vec2Value, normal: Vec2, childIndex: number) {
const pLocal = Rot.mulTVec2(xf.q, Vec2.sub(p, xf.p));
let maxDistance = -Infinity;
let normalForMaxDistance = pLocal;
for (let i = 0; i < this.m_count; ++i) {
const dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i]));
if (dot > maxDistance) {
maxDistance = dot;
normalForMaxDistance = this.m_normals[i];
}
}
if (maxDistance > 0) {
let minDistance = normalForMaxDistance;
let minDistance2 = maxDistance * maxDistance;
for (let i = 0; i < this.m_count; ++i) {
const distance = Vec2.sub(pLocal, this.m_vertices[i]);
const distance2 = distance.lengthSquared();
if (minDistance2 > distance2) {
minDistance = distance;
minDistance2 = distance2;
}
}
normal.set(Rot.mulVec2(xf.q, minDistance));
normal.normalize();
return Math.sqrt(minDistance2);
}
else {
normal.set(Rot.mulVec2(xf.q, normalForMaxDistance));
return maxDistance;
}
}
/**
* Cast a ray against a child shape.
*

View File

@ -15,6 +15,12 @@ export const EPSILON = 1e-9;
/** @internal @deprecated */
export const isFinite = Number.isFinite;
/** @deprecated */
export function invSqrt(x: number): number {
// TODO:
return 1 / Math.sqrt(x);
};
/**
* @deprecated
* Next Largest Power of 2 Given a binary integer value x, the next largest
@ -90,6 +96,7 @@ export function random(min?: number, max?: number): number {
export const math = Object.create(Math);
math.EPSILON = EPSILON;
math.isFinite = isFinite;
math.invSqrt = invSqrt;
math.nextPowerOfTwo = nextPowerOfTwo;
math.isPowerOfTwo = isPowerOfTwo;
math.mod = mod;

View File

@ -39,7 +39,7 @@ export class Transform {
/** rotation */
q: Rot;
constructor(position?: Vec2Value, rotation?: number) {
constructor(position?: Vec2Value, rotation?: number | RotValue) {
if (_CONSTRUCTOR_FACTORY && !(this instanceof Transform)) {
return new Transform(position, rotation);
}
@ -48,8 +48,10 @@ export class Transform {
if (typeof position !== "undefined") {
this.p.setVec2(position);
}
if (typeof rotation !== "undefined") {
if (typeof rotation === "number") {
this.q.setAngle(rotation);
} else if (typeof rotation === "object") {
this.q.setRot(rotation)
}
}

View File

@ -208,6 +208,26 @@ export class Vec2 {
return this;
}
/**
* LIQUID_FUN:
* Set linear combination of u, v and w: `a * u + b * v + c * w`
*/
setCombine3(a: number, u: Vec2Value, b: number, v: Vec2Value, c: number, w: Vec2Value): Vec2 {
_ASSERT && console.assert(Number.isFinite(a));
_ASSERT && Vec2.assert(u);
_ASSERT && console.assert(Number.isFinite(b));
_ASSERT && Vec2.assert(v);
_ASSERT && console.assert(Number.isFinite(c));
_ASSERT && Vec2.assert(w);
const x = a * u.x + b * v.x + c * w.x;
const y = a * u.y + b * v.y + c * w.y;
// `this` may be `w`
this.x = x;
this.y = y;
return this;
}
setMul(a: number, v: Vec2Value): Vec2 {
if (_ASSERT) console.assert(Number.isFinite(a));
if (_ASSERT) Vec2.assert(v);
@ -533,6 +553,13 @@ export class Vec2 {
return Vec2.zero().setCombine(a, v, b, w);
}
/**
* LIQUID_FUN:
*/
static combine3(a: number, u: Vec2, b: number, v: Vec2, c: number, w: Vec2): Vec2 {
return Vec2.zero().setCombine3(a, u, b, v, c, w);
}
static sub(v: Vec2Value, w: Vec2Value): Vec2 {
if (_ASSERT) Vec2.assert(v);
if (_ASSERT) Vec2.assert(w);

View File

@ -0,0 +1,170 @@
/*
* Copyright (c) 2014 Google, Inc.
*
* This software is provided "as-is", without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
const _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
/**
* A simple array-like container, similar to std::vector.
* If we ever start using stl, we should replace this with std::vector.
*/
export class b2GrowableBuffer<T> {
data: T[] | null;
// count: number;
// capacity: number;
constructor(rhs?: b2GrowableBuffer<T>) {
this.data = [];
// this.count = 0;
// this.capacity = 0;
if(rhs) {
throw new Error("TODO"); // TODO
// // this.count = rhs.count;
// // this.capacity = rhs.capacity;
// if(rhs.data) {
// this.data = rhs.data.map(e => this.copy(e)); // TODO
// }
}
// #if defined(LIQUIDFUN_SIMD_NEON)
// // b2ParticleAssembly.neon.s assumes these values are at fixed offsets.
// // If this assert fails, be sure to update the assembly offsets!
// // ldr r3, [r9, #0] @ r3 = out = contacts.data
// // ldr r6, [r9, #8] @ r6 = contacts.capacity
// b2Assert((intptr_t)&data - (intptr_t)(this) == 0
// && (intptr_t)&capacity - (intptr_t)(this) == 8);
// #endif // defined(LIQUIDFUN_SIMD_NEON)
}
append(value: T): T {
this.data.push(value);
return value;
/* if (this.count >= this.capacity)
{
Grow();
}
return data[count++];*/
}
/* reserve(newCapacity: number) {
if (capacity >= newCapacity)
return;
// Reallocate and copy.
T* newData = (T*) allocator->Allocate(sizeof(T) * newCapacity);
if (data)
{
memcpy(newData, data, sizeof(T) * count);
allocator->Free(data, sizeof(T) * capacity);
}
// Update pointer and capacity.
capacity = newCapacity;
data = newData;
}*/
/* void Grow()
{
// Double the capacity.
int32 newCapacity = capacity ? 2 * capacity
: b2_minParticleSystemBufferCapacity;
b2Assert(newCapacity > capacity);
Reserve(newCapacity);
}*/
free() {
// if (this.data == null)
// return;
this.data = null;
// capacity = 0;
// this.count = 0;
}
/* void Shorten(const T* newEnd)
{
b2Assert(newEnd >= data);
count = (int32) (newEnd - data);
}*/
/* T& operator[](int i)
{
return data[i];
}*/
/* const T& operator[](int i) const
{
return data[i];
}*/
/* T* Data()
{
return data;
}*/
// TODO add to changelog (this method is new in JS)
getData() {
return this.data
}
begin() {
return 0; // TODO pretty useless
}
end() {
return this.data.length;
}
getCount() {
return this.data.length;
}
setCount(newCount: number) {
_ASSERT && console.assert(0 <= newCount && newCount <= this.data.length);
this.data.length = newCount;
}
removeIf(pred: (e: T) => boolean) {
this.data = this.data.filter(e => !pred(e)); // TODO mutate?
return this.data.length;
}
// TODO
// template<class BinaryPredicate>
// T* Unique(BinaryPredicate pred)
// {
// T* newEnd = std::unique(data, data + count, pred);
// Shorten(newEnd);
// return newEnd;
// }
unique(pred: (a: T, b: T) => boolean) {
if (this.data.length == 0) {
return 0;
}
let newLength = 1;
for (let i = 1; i < this.data.length; i++) {
if(!pred(this.data[newLength - 1], this.data[i])) {
this.data[newLength++] = this.data[i];
}
}
this.data.length = newLength;
return newLength;
}
}

View File

@ -0,0 +1,37 @@
import { Pool } from "../util/Pool";
/**
* TODO this is currently just an object pool imitating the b2SlabAllocator
* class
*
* TODO this currently leaks memory (because the objects never gets freed)
*/
export class b2SlabAllocator<T> {
private pool: Pool<T>;
private create: () => T;
private itemsPerSlab: number;
constructor(itemsPerSlab: number, create: () => T) {
this.itemsPerSlab = itemsPerSlab;
this.create = create;
this.pool = new Pool({
max: Infinity, // TODO
});
}
allocate() {
// TODO integrate itemsPerSlab directly into Pool
if (this.pool.size() == 0) {
for (let i = 0; i < this.itemsPerSlab; i++) {
this.pool.release(this.create());
}
}
return this.pool.allocate()
}
setItemsPerSlab(itemsPerSlab: number) {
this.itemsPerSlab = itemsPerSlab;
}
free(obj: T) {
this.pool.release(obj);
}
}

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -186,6 +186,8 @@ export class Body {
/** @internal */ m_invI: number;
/** @internal the body origin transform */
m_xf: Transform;
/** @internal LIQUID_FUN: the previous transform for particle simulation */
m_xf0: Transform;
/** @internal the swept motion for CCD */
m_sweep: Sweep;
// position and velocity correction
@ -253,6 +255,8 @@ export class Body {
this.m_xf = Transform.identity();
this.m_xf.p.setVec2(def.position);
this.m_xf.q.setAngle(def.angle);
// LIQUID_FUN:
this.m_xf0 = Transform.clone(this.m_xf); // TODO clone necessary?
// the swept motion for CCD
this.m_sweep = new Sweep();
@ -598,6 +602,8 @@ export class Body {
this.m_xf.setTransform(a as TransformValue);
}
// LIQUID_FUN:
this.m_xf0 = Transform.clone(this.m_xf); // TODO clone necessary?
this.m_sweep.setTransform(this.m_xf);
const broadPhase = this.m_world.m_broadPhase;

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -9,7 +9,7 @@
import * as matrix from "../common/Matrix";
import { options } from "../util/options";
import { Vec2Value } from "../common/Vec2";
import { Vec2, Vec2Value } from "../common/Vec2";
import { AABB, RayCastInput, RayCastOutput } from "../collision/AABB";
import { Shape, ShapeType } from "../collision/Shape";
import { Body, MassData } from "./Body";
@ -338,6 +338,19 @@ export class Fixture {
return this.m_shape.testPoint(this.m_body.getTransform(), p);
}
/**
* LIQUID_FUN:
*
* Compute the distance from this fixture to the specified point. This only works for convex shapes.
* @param p a point in world coordinates.
* @param normal returns the direction in which the distance increases.
* @return returns the distance from the current shape.
*/
// TODO remove normal as paramenter and return [distance: number, normal: Vec2] directly
computeDistance(p: Vec2Value, normal: Vec2, childIndex: number): number {
return this.m_shape.computeDistance(this.m_body.getTransform(), p, normal, childIndex);
}
/**
* Cast a ray against this shape.
*/

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -16,6 +16,7 @@ import { Joint } from "./Joint";
import { TimeOfImpact, TOIInput, TOIOutput, TOIOutputState } from "../collision/TimeOfImpact";
import { Distance, DistanceInput, DistanceOutput, SimplexCache } from "../collision/Distance";
import { World } from "./World";
import { Transform } from "../common/Transform";
import { Sweep } from "../common/Sweep";
@ -32,6 +33,8 @@ export class TimeStep {
inv_dt: number = 0;
velocityIterations: number = 0;
positionIterations: number = 0;
// LIQUID_FUN:
particleIterations: number = 0;
warmStarting: boolean = false;
blockSolve: boolean = true;
@ -153,6 +156,11 @@ export class Solver {
solveWorld(step: TimeStep): void {
const world = this.m_world;
// LIQUID_FUN: update previous transforms
for (let b = world.m_bodyList; b; b = b.m_next) {
b.m_xf0 = Transform.clone(b.m_xf); // TODO clone necessary?
}
// Clear all the island flags.
for (let b = world.m_bodyList; b; b = b.m_next) {
b.m_islandFlag = false;
@ -713,6 +721,8 @@ export class Solver {
s_subStep.dtRatio = 1.0;
s_subStep.positionIterations = 20;
s_subStep.velocityIterations = step.velocityIterations;
// LIQUID_FUN:
s_subStep.particleIterations = step.particleIterations;
s_subStep.warmStarting = false;
this.solveIslandTOI(s_subStep, bA, bB);

View File

@ -1,7 +1,7 @@
/*
* Planck.js
*
* Copyright (c) Erin Catto, Ali Shakiba
* Copyright (c) Erin Catto, Ali Shakiba, Google, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
@ -17,6 +17,9 @@ import { Contact } from "./Contact";
import { AABBValue, RayCastInput, RayCastOutput } from "../collision/AABB";
import { Fixture, FixtureProxy } from "./Fixture";
import { Manifold } from "../collision/Manifold";
import { b2CalculateParticleIterations } from "../particle/Particle";
import { b2ParticleSystem, b2ParticleSystemDef, ParticleAABBQueryCallback, ParticleRayCastCallback } from "../particle/ParticleSystem";
import { b2ParticleGroup } from "../particle/ParticleGroup";
/** @internal */ const _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
@ -114,6 +117,7 @@ export class World {
/** @internal */ m_bodyCount: number;
/** @internal */ m_jointList: Joint | null;
/** @internal */ m_jointCount: number;
/** @internal LIQUID_FUN: */ m_particleSystemList: b2ParticleSystem;
/** @internal */ m_stepComplete: boolean;
/** @internal */ m_allowSleep: boolean;
/** @internal */ m_gravity: Vec2;
@ -167,6 +171,9 @@ export class World {
this.m_jointList = null;
this.m_jointCount = 0;
// LIQUID_FUN:
this.m_particleSystemList = null;
this.m_stepComplete = true;
this.m_allowSleep = def.allowSleep;
@ -256,6 +263,19 @@ export class World {
return this.m_jointList;
}
/**
* LIQUID_FUN:
*
* Get the world particle-system list. With the returned particle-system, use
* {@link b2ParticleSystem.getNext} to get the next particle-system in the world
* list. A null particle-system indicates the end of the list.
*
* @return the head of the world particle-system list.
*/
getParticleSystemList(): b2ParticleSystem | null {
return this.m_particleSystemList;
}
/**
* Get the world contact list. With the returned contact, use Contact.getNext to
* get the next contact in the world list. A null contact indicates the end of
@ -406,6 +426,40 @@ export class World {
});
}
/**
* LIQUID_FUN:
*
* TODO
*/
// TODO is API change ok?
queryAABBParticles(
aabb: AABBValue,
callback: ParticleAABBQueryCallback,
shouldQueryParticleSystem = (particleSystem: b2ParticleSystem) => true
) {
for (let p = this.m_particleSystemList; p; p = p.getNext()) {
if (shouldQueryParticleSystem(p)) {
p.queryAABB(callback, aabb);
}
}
}
/**
* LIQUID_FUN:
*
* Query the world for all fixtures that potentially overlap the
* provided shape's AABB. Calls QueryAABB internally.
* @param callback a user implemented callback class.
* @param shape the query shape
* @param xf the transform of the AABB
*/
// TODO is this method used internally?
// queryShapeAABB(callback: b2QueryCallback, shape: Shape, xf: Transform): void { // TODO switch parameters?
// const aabb = new AABB();
// shape.computeAABB(aabb, xf, 0);
// this.queryAABB(aabb, callback);
// };
/**
* Ray-cast the world for all fixtures in the path of the ray. Your callback
* controls whether you get the closest point, any point, or n-points. The
@ -438,6 +492,24 @@ export class World {
return input.maxFraction;
});
}
/**
* LIQUID_FUN:
*
* TODO
*/
// TODO API change ok?
rayCastParticles(
point1: Vec2,
point2: Vec2,
callback: ParticleRayCastCallback,
shouldQueryParticleSystem = (particleSystem: b2ParticleSystem) => true
): void {
for (let p = this.m_particleSystemList; p; p = p.getNext()) {
if (shouldQueryParticleSystem(p)) {
p.rayCast(callback, point1, point2);
}
}
}
/**
* Get the number of broad-phase proxies.
@ -790,18 +862,82 @@ export class World {
this.publish("remove-joint", joint);
}
/**
* LIQUID_FUN:
*
* Create a particle system given a definition. No reference to the
* definition is retained.
*
* Warning: This function is locked during callbacks.
*/
createParticleSystem(def: b2ParticleSystemDef = {}): b2ParticleSystem | null {
_ASSERT && console.assert(this.isLocked() == false);
if (this.isLocked()) {
return null;
}
const p = new b2ParticleSystem(def, this);
// Add to world doubly linked list.
p.m_prev = null;
p.m_next = this.m_particleSystemList;
if (this.m_particleSystemList) {
this.m_particleSystemList.m_prev = p;
}
this.m_particleSystemList = p;
return p;
}
/**
* LIQUID_FUN:
*
* Destroy a particle system.
* Warning: This function is locked during callbacks.
*/
destroyParticleSystem(p: b2ParticleSystem): void {
_ASSERT && console.assert(this.m_particleSystemList != null);
_ASSERT && console.assert(this.isLocked() == false);
if (this.isLocked()) {
return;
}
// Remove world particleSystem list.
if (p.m_prev) {
p.m_prev.m_next = p.m_next;
}
if (p.m_next) {
p.m_next.m_prev = p.m_prev;
}
if (p == this.m_particleSystemList) {
this.m_particleSystemList = p.m_next;
}
// TODO if using WASM destroy particle-system
// TODO publish event
}
/** @internal */
s_step: TimeStep; // reuse
/**
* Take a time step. This performs collision detection, integration, and
* constraint solution.
*
* For the numerical stability of particles, minimize the following
* dimensionless gravity acceleration:
* gravity / particleRadius * (timeStep / particleIterations)^2
* b2CalculateParticleIterations() or
* CalculateReasonableParticleIterations() help to determine the optimal
* particleIterations.
*
* Broad-phase, narrow-phase, solve and solve time of impacts.
*
* @param timeStep Time step, this should not vary.
*/
step(timeStep: number, velocityIterations?: number, positionIterations?: number): void {
step(timeStep: number, velocityIterations?: number, positionIterations?: number, particleIterations = 1): void {
this.publish("pre-step", timeStep);
if ((velocityIterations | 0) !== velocityIterations) {
@ -823,6 +959,8 @@ export class World {
this.s_step.reset(timeStep);
this.s_step.velocityIterations = velocityIterations;
this.s_step.positionIterations = positionIterations;
// LIQUID_FUN:
this.s_step.particleIterations = particleIterations;
this.s_step.warmStarting = this.m_warmStarting;
this.s_step.blockSolve = this.m_blockSolve;
@ -831,6 +969,10 @@ export class World {
// Integrate velocities, solve velocity constraints, and integrate positions.
if (this.m_stepComplete && timeStep > 0.0) {
// LIQUID_FUN:
for (let p = this.m_particleSystemList; p; p = p.getNext()) {
p.solve(this.s_step); // Particle Simulation
}
this.m_solver.solveWorld(this.s_step);
// Synchronize fixtures, check for out of range bodies.
@ -881,6 +1023,38 @@ export class World {
}
}
// LIQUID_FUN:
static getSmallestRadius(world: World): number {
let smallestRadius = Infinity;
for (let system = world.getParticleSystemList();
system != null;
system = system.getNext())
{
smallestRadius = Math.min(smallestRadius, system.getRadius());
}
return smallestRadius;
}
/**
* LIQUID_FUN:
*
* Recommend a value to be used in `Step` for `particleIterations`.
* This calculation is necessarily a simplification and should only be
* used as a starting point. Please see "Particle Iterations" in the
* Programmer's Guide for details.
* @param timeStep is the value to be passed into `Step`.
*/
calculateReasonableParticleIterations(timeStep: number): number {
if (this.m_particleSystemList == null) {
return 1;
}
// Use the smallest radius, since that represents the worst-case.
return b2CalculateParticleIterations(this.m_gravity.length(),
World.getSmallestRadius(this),
timeStep);
}
/**
* @internal
* Call this method to find new contacts.
@ -1091,6 +1265,8 @@ export class World {
on(name: "remove-joint", listener: (joint: Joint) => void): World;
/** Listener is called whenever a fixture is removed implicitly or explicitly. */
on(name: "remove-fixture", listener: (fixture: Fixture) => void): World;
on(name: "remove-particle", listener: (system: b2ParticleSystem, index: number) => void): World;
on(name: "remove-particle-group", listener: (group: b2ParticleGroup) => void): World;
/**
* Register an event listener.
*/
@ -1116,6 +1292,8 @@ export class World {
off(name: "remove-body", listener: (body: Body) => void): World;
off(name: "remove-joint", listener: (joint: Joint) => void): World;
off(name: "remove-fixture", listener: (fixture: Fixture) => void): World;
off(name: "remove-particle", listener: (system: b2ParticleSystem, index: number) => void): World;
off(name: "remove-particle-group", listener: (group: b2ParticleGroup) => void): World;
/**
* Remove an event listener.
*/

418
src/particle/Particle.ts Normal file
View File

@ -0,0 +1,418 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { clamp } from "../common/Math"
import { Vec2 } from "../common/Vec2";
import { b2ParticleGroup } from "./ParticleGroup";
import { SettingsInternal as Settings } from "../Settings";
const {
b2_invalidParticleIndex,
} = Settings;
const B2PARTICLECOLOR_BITS_PER_COMPONENT = 8; // (sizeof(uint8) << 3);
// Maximum value of a b2ParticleColor component.
const B2PARTICLECOLOR_MAX_VALUE =
((1 << B2PARTICLECOLOR_BITS_PER_COMPONENT) - 1);
/**
* The particle type. Can be combined with the | operator.
*/
export const enum ParticleFlag {
/** Water particle. */
b2_waterParticle = 0,
/** Removed after next simulation step. */
b2_zombieParticle = 1 << 1,
/** Zero velocity. */
b2_wallParticle = 1 << 2,
/** With restitution from stretching. */
b2_springParticle = 1 << 3,
/** With restitution from deformation. */
b2_elasticParticle = 1 << 4,
/** With viscosity. */
b2_viscousParticle = 1 << 5,
/** Without isotropic pressure. */
b2_powderParticle = 1 << 6,
/** With surface tension. */
b2_tensileParticle = 1 << 7,
/** Mix color between contacting particles. */
b2_colorMixingParticle = 1 << 8,
/** Call b2DestructionListener on destruction. */
b2_destructionListenerParticle = 1 << 9,
/** Prevents other particles from leaking. */
b2_barrierParticle = 1 << 10,
/** Less compressibility. */
b2_staticPressureParticle = 1 << 11,
/** Makes pairs or triads with other particles. */
b2_reactiveParticle = 1 << 12,
/** With high repulsive force. */
b2_repulsiveParticle = 1 << 13,
/**
* Call b2ContactListener when this particle is about to interact with
* a rigid body or stops interacting with a rigid body.
* This results in an expensive operation compared to using
* b2_fixtureContactFilterParticle to detect collisions between
* particles.
*/
b2_fixtureContactListenerParticle = 1 << 14,
/**
* Call b2ContactListener when this particle is about to interact with
* another particle or stops interacting with another particle.
* This results in an expensive operation compared to using
* b2_particleContactFilterParticle to detect collisions between
* particles.
*/
b2_particleContactListenerParticle = 1 << 15,
/** Call b2ContactFilter when this particle interacts with rigid bodies. */
b2_fixtureContactFilterParticle = 1 << 16,
/**
* Call b2ContactFilter when this particle interacts with other
* particles.
*/
b2_particleContactFilterParticle = 1 << 17,
};
// TODO
/** Small color object for each particle */
export class b2ParticleColor {
public r: number;
public g: number;
public b: number;
public a: number;
/** Maximum value of a b2ParticleColor component. */
protected static k_maxValue = B2PARTICLECOLOR_MAX_VALUE;
/** 1.0 / k_maxValue. */
protected static k_inverseMaxValue = 1.0 / B2PARTICLECOLOR_MAX_VALUE;
/** Number of bits used to store each b2ParticleColor component. */
protected static k_bitsPerComponent = B2PARTICLECOLOR_BITS_PER_COMPONENT;
constructor();
/**
* Constructor with four elements: r (red), g (green), b (blue), and a
* (opacity).
* Each element can be specified 0 to 255.
*/
constructor(r: number, g: number, b: number, a: number); // TODO b2Inline?
// /**
// * Constructor that initializes the above four elements with the value of
// * the b2Color object.
// */
// constructor(const b2Color& color);
constructor(r = 0, g = 0, b = 0, a = 0) {
this.set(r, g, b, a);
}
/**
* True when all four color elements equal 0. When true, a particle color
* buffer isn't allocated by CreateParticle().
*/
isZero() {
return !this.r && !this.g && !this.b && !this.a;
}
/// Used internally to convert the value of b2Color.
///
// b2Color b2ParticleColor::getColor() const
// {
// return b2Color(k_inverseMaxValue * r,
// k_inverseMaxValue * g,
// k_inverseMaxValue * b);
// }
/**
* Sets color for current object using the four elements described above.
*/
set(r_: number, g_: number, b_: number, a_: number) {
this.r = r_;
this.g = g_;
this.b = b_;
this.a = a_;
}
/// Initializes the object with the value of the b2Color.
///
// void Set(const b2Color& color);
// void b2ParticleColor::Set(const b2Color& color)
// {
// Set((uint8)(k_maxValue * color.r),
// (uint8)(k_maxValue * color.g),
// (uint8)(k_maxValue * color.b),
// B2PARTICLECOLOR_MAX_VALUE);
// }
/// Assign a b2ParticleColor to this instance.
/* b2ParticleColor& operator = (const b2ParticleColor &color)
{
Set(color.r, color.g, color.b, color.a);
return *this;
}
/// Multiplies r, g, b, a members by s where s is a value between 0.0
/// and 1.0.
b2ParticleColor& operator *= (float32 s)
{
Set((uint8)(r * s), (uint8)(g * s), (uint8)(b * s), (uint8)(a * s));
return *this;
}
/// Scales r, g, b, a members by s where s is a value between 0 and 255.
b2ParticleColor& operator *= (uint8 s)
{
// 1..256 to maintain the complete dynamic range.
const int32 scale = (int32)s + 1;
Set((uint8)(((int32)r * scale) >> k_bitsPerComponent),
(uint8)(((int32)g * scale) >> k_bitsPerComponent),
(uint8)(((int32)b * scale) >> k_bitsPerComponent),
(uint8)(((int32)a * scale) >> k_bitsPerComponent));
return *this;
}
/// Scales r, g, b, a members by s returning the modified b2ParticleColor.
b2ParticleColor operator * (float32 s) const
{
return MultiplyByScalar(s);
}
/// Scales r, g, b, a members by s returning the modified b2ParticleColor.
b2ParticleColor operator * (uint8 s) const
{
return MultiplyByScalar(s);
}
/// Add two colors. This is a non-saturating addition so values
/// overflows will wrap.
b2Inline b2ParticleColor& operator += (const b2ParticleColor &color)
{
r += color.r;
g += color.g;
b += color.b;
a += color.a;
return *this;
}
/// Add two colors. This is a non-saturating addition so values
/// overflows will wrap.
b2ParticleColor operator + (const b2ParticleColor &color) const
{
b2ParticleColor newColor(*this);
newColor += color;
return newColor;
}
/// Subtract a color from this color. This is a subtraction without
/// saturation so underflows will wrap.
b2Inline b2ParticleColor& operator -= (const b2ParticleColor &color)
{
r -= color.r;
g -= color.g;
b -= color.b;
a -= color.a;
return *this;
}
/// Subtract a color from this color returning the result. This is a
/// subtraction without saturation so underflows will wrap.
b2ParticleColor operator - (const b2ParticleColor &color) const
{
b2ParticleColor newColor(*this);
newColor -= color;
return newColor;
}
/// Compare this color with the specified color.
bool operator == (const b2ParticleColor &color) const
{
return r == color.r && g == color.g && b == color.b && a == color.a;
}
*/
/**
* Mix mixColor with this color using strength to control how much of
* mixColor is mixed with this color and vice versa. The range of
* strength is 0..128 where 0 results in no color mixing and 128 results
* in an equal mix of both colors. strength 0..128 is analogous to an
* alpha channel value between 0.0f..0.5f.
*/
mix(mixColor: b2ParticleColor, strength: number) {
b2ParticleColor.mixColors(this, mixColor, strength);
}
/** Mix colorA with colorB using strength to control how much of
* colorA is mixed with colorB and vice versa. The range of
* strength is 0..128 where 0 results in no color mixing and 128 results
* in an equal mix of both colors. strength 0..128 is analogous to an
* alpha channel value between 0.0f..0.5f.
*/
static mixColors(colorA: b2ParticleColor, colorB: b2ParticleColor, strength: number) {
const dr = ((strength * (colorB.r - colorA.r)) >>
b2ParticleColor.k_bitsPerComponent) | 0;
const dg = ((strength * (colorB.g - colorA.g)) >>
b2ParticleColor.k_bitsPerComponent) | 0;
const db = ((strength * (colorB.b - colorA.b)) >>
b2ParticleColor.k_bitsPerComponent) | 0;
const da = ((strength * (colorB.a - colorA.a)) >>
b2ParticleColor.k_bitsPerComponent) | 0;
colorA.r += dr;
colorA.g += dg;
colorA.b += db;
colorA.a += da;
colorB.r -= dr;
colorB.g -= dg;
colorB.b -= db;
colorB.a -= da;
}
/*private:
/// Generalization of the multiply operator using a scalar in-place
/// multiplication.
template <typename T>
b2ParticleColor MultiplyByScalar(T s) const
{
b2ParticleColor color(*this);
color *= s;
return color;
}
*/
static zero(): b2ParticleColor {
const obj = Object.create(b2ParticleColor.prototype);
obj.r = 0;
obj.g = 0;
obj.b = 0;
obj.a = 0;
return obj;
}
}
/**
* A particle definition holds all the data needed to construct a particle.
* You can safely re-use these definitions.
*/
export interface ParticleDef {
// #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
// /** Set position with direct floats */
// setPosition(x: number, y: number) {
// this.position.set(x, y);
// }
// /** Set color with direct ints. */
// setColor(int32 r, int32 g, int32 b, int32 a) {
// this.color.Set((uint8)r, (uint8)g, (uint8)b, (uint8)a);
// }
// #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
/**
* Specifies the type of particle (see {@link ParticleFlag}).
*
* A particle may be more than one type.
* Multiple types are chained by logical sums, for example:
* ```
* pd.flags = b2_elasticParticle | b2_viscousParticle
* ```
*/
flags: number;
/**
* The world position of the particle.
*/
position: Vec2;
/**
* The linear velocity of the particle in world co-ordinates.
*/
velocity: Vec2;
/**
* The color of the particle.
*/
color: b2ParticleColor;
/**
* Lifetime of the particle in seconds. A value <= 0.0f indicates a
* particle with infinite lifetime.
*/
lifetime: number;
/**
* Use this to store application-specific body data.
*/
userData: any;
/**
* An existing particle group to which the particle will be added.
*/
group: b2ParticleGroup | null;
}
export const ParticleDefDefault: ParticleDef = {
flags: 0,
position: Vec2.zero(),
velocity: Vec2.zero(),
color: b2ParticleColor.zero(),
lifetime: 0.0,
userData: null,
group: null,
};
/**
* A helper function to calculate the optimal number of iterations.
*/
export function b2CalculateParticleIterations(
gravity: number, radius: number, timeStep: number) {
// In some situations you may want more particle iterations than this,
// but to avoid excessive cycle cost, don't recommend more than this.
const B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS = 8;
const B2_RADIUS_THRESHOLD = 0.01;
const iterations =
Math.ceil(Math.sqrt(gravity / (B2_RADIUS_THRESHOLD * radius)) * timeStep);
return clamp(iterations, 1, B2_MAX_RECOMMENDED_PARTICLE_ITERATIONS);
}
/**
* Handle to a particle. Particle indices are ephemeral: the same index might
* refer to a different particle, from frame-to-frame. If you need to keep a
* reference to a particular particle across frames, you should acquire a
* b2ParticleHandle. Use #b2ParticleSystem::GetParticleHandleFromIndex() to
* retrieve the b2ParticleHandle of a particle from the particle system.
*/
export class b2ParticleHandle { // extends b2TypedIntrusiveListNode<b2ParticleHandle> // TODO
// Allow b2ParticleSystem to use SetIndex() to associate particle handles
// with particle indices.
// friend class b2ParticleSystem;
/** Index of the particle within the particle system. */
private m_index: number;
/** Initialize the index associated with the handle to an invalid index. */
constructor() {
this.m_index = b2_invalidParticleIndex;
}
// /** Empty destructor. */
// ~b2ParticleHandle() { }
/** Get the index of the particle associated with this handle. */
getIndex() {
return this.m_index;
}
/** Set the index of the particle associated with this handle. */
setIndex(index: number) {
this.m_index = index;
}
};

View File

@ -0,0 +1,438 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { Vec2 } from "../common/Vec2";
import { Transform } from "../common/Transform";
import { Shape } from "../collision/Shape";
import { b2ParticleSystem } from "./ParticleSystem";
import { b2ParticleColor } from "./Particle";
const _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
/** The particle group type. Can be combined with the | operator. */
export const enum b2ParticleGroupFlag {
/** Prevents overlapping or leaking. */
b2_solidParticleGroup = 1 << 0,
/** Keeps its shape. */
b2_rigidParticleGroup = 1 << 1,
/** Won't be destroyed if it gets empty. */
b2_particleGroupCanBeEmpty = 1 << 2,
/** Will be destroyed on next simulation step. */
b2_particleGroupWillBeDestroyed = 1 << 3,
/** Updates depth data on next simulation step. */
b2_particleGroupNeedsUpdateDepth = 1 << 4,
b2_particleGroupInternalMask =
b2_particleGroupWillBeDestroyed |
b2_particleGroupNeedsUpdateDepth,
};
/**
* A particle group definition holds all the data needed to construct a
* particle group. You can safely re-use these definitions.
*/
export interface b2ParticleGroupDef {
// ~b2ParticleGroupDef()
// {
// #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
// FreeShapesMemory();
// #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
// }
/** The particle-behavior flags (See #b2ParticleFlag). */
flags: number;
/** The group-construction flags (See #b2ParticleGroupFlag). */
groupFlags: number;
/**
* The world position of the group.
* Moves the group's shape a distance equal to the value of position.
*/
position: Vec2;
/**
* The world angle of the group in radians.
* Rotates the shape by an angle equal to the value of angle.
*/
angle: number;
/** The linear velocity of the group's origin in world co-ordinates. */
linearVelocity: Vec2;
/** The angular velocity of the group. */
angularVelocity: number;
/** The color of all particles in the group. */
color: b2ParticleColor;
/**
* The strength of cohesion among the particles in a group with flag
* b2_elasticParticle or b2_springParticle.
*/
strength: number;
/** The shape where particles will be added. */
shape: Shape;
/** A array of shapes where particles will be added. */
// shapes: Shape[]; // LATER
/** The number of shapes. */
// shapeCount: number; // LATER
/**
* The interval of particles in the shape.
* If it is 0, b2_particleStride * particleDiameter is used instead.
*/
stride: number;
/** The number of particles in addition to ones added in the shape. */
particleCount: number;
/** The initial positions of the particleCount particles. */
positionData: Vec2[];
/**
* Lifetime of the particle group in seconds. A value <= 0.0f indicates a
* particle group with infinite lifetime.
*/
lifetime: number;
/** Use this to store application-specific group data. */
userData: any;
/** An existing particle group to which the particles will be added. */
group: b2ParticleGroup;
// #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
// /** Storage for constructed CircleShapes from an incoming vertex list */
// circleShapes: CircleShape[];
// /** True if we create the shapes array internally. */
// ownShapesArray: Boolean;
// /** Clean up all memory associated with SetCircleShapesFromVertexList */
// freeShapesMemory {
// if (this.circleShapes) {
// delete[] circleShapes;
// circleShapes = NULL;
// }
// if (ownShapesArray && shapes) {
// delete[] shapes;
// shapes = NULL;
// ownShapesArray = false;
// }
// }
// /**
// * From a vertex list created by an external language API, construct
// * a list of circle shapes that can be used to create a b2ParticleGroup
// * This eliminates cumbersome array-interfaces between languages.
// */
// void SetCircleShapesFromVertexList(void* inBuf,
// int numShapes,
// float radius) {
// float* points = (float*) inBuf;
// // Create circle shapes from vertex list and radius
// b2CircleShape* pCircleShapes = new b2CircleShape[numShapes];
// b2Shape** pShapes = new b2Shape*[numShapes];
// for (int i = 0; i < numShapes; ++i) {
// pCircleShapes[i].m_radius = radius;
// pCircleShapes[i].m_p = b2Vec2(points[i*2], points[i*2+1]);
// pShapes[i] = &pCircleShapes[i];
// }
// // Clean up existing buffers
// FreeShapesMemory();
// // Assign to newly created buffers
// ownShapesArray = true;
// circleShapes = pCircleShapes;
// shapes = pShapes;
// shapeCount = numShapes;
// }
// /** Set position with direct floats. */
// setPosition(x: number, y: number) {
// this.position.set(x, y);
// }
// /** Set color with direct ints. */
// setColor(r: number, g: number, b: number, a: number) {
// this.color.set((uint8)r, (uint8)g, (uint8)b, (uint8)a);
// }
// #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
}
export const ParticleGroupDefDefault: b2ParticleGroupDef = {
flags: 0,
groupFlags: 0,
position: Vec2.zero(),
angle: 0,
linearVelocity: Vec2.zero(),
angularVelocity: 0,
color: b2ParticleColor.zero(),
strength: 1,
shape: null,
// shapes: null, // LATER
// shapeCount: 0, // LATER
stride: 0,
particleCount: 0,
positionData: null,
lifetime: 0.0,
userData: null,
group: null,
// #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
// circleShapes = NULL;
// ownShapesArray = false;
// #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API
};
/** A group of particles. b2ParticleGroup::CreateParticleGroup creates these. */
export class b2ParticleGroup {
/** @internal */ m_system: b2ParticleSystem;
/** @internal */ m_firstIndex: number;
/** @internal */ m_lastIndex: number;
/** @internal */ m_groupFlags: number;
/** @internal */ m_strength: number;
/** @internal */ m_prev: b2ParticleGroup;
/** @internal */ m_next: b2ParticleGroup;
/** @internal */ m_timestamp: number;
/** @internal */ m_mass: number;
/** @internal */ m_inertia: number;
/** @internal */ m_center: Vec2;
/** @internal */ m_linearVelocity: Vec2;
/** @internal */ m_angularVelocity: number;
/** @internal */ m_transform: Transform;
/** @internal */ m_userData: any;
constructor() {
this.m_system = null;
this.m_firstIndex = 0;
this.m_lastIndex = 0;
this.m_groupFlags = 0;
this.m_strength = 1.0;
this.m_prev = null;
this.m_next = null;
this.m_timestamp = -1;
this.m_mass = 0;
this.m_inertia = 0;
this.m_center = Vec2.zero();
this.m_linearVelocity = Vec2.zero();
this.m_angularVelocity = 0;
this.m_transform = Transform.identity();
this.m_userData = null;
}
/** Get the next particle group from the list in b2_World. */
getNext() {
return this.m_next;
}
/** Get the particle system that holds this particle group. */
getParticleSystem() {
return this.m_system;
}
/** Get the number of particles. */
getParticleCount() {
return this.m_lastIndex - this.m_firstIndex;
}
/** Get the offset of this group in the global particle buffer */
getBufferIndex() {
return this.m_firstIndex;
}
/** Does this group contain the particle. */
containsParticle(index: number) {
return this.m_firstIndex <= index && index < this.m_lastIndex;
}
/** Get the logical sum of particle flags. */
getAllParticleFlags() {
let flags = 0;
for (let i = this.m_firstIndex; i < this.m_lastIndex; i++) {
flags |= this.m_system.m_flagsBuffer.data[i];
}
return flags;
}
/** Get the construction flags for the group. */
getGroupFlags() {
return this.m_groupFlags & ~b2ParticleGroupFlag.b2_particleGroupInternalMask;
}
/** Set the construction flags for the group. */
setGroupFlags(flags: number) {
console.assert((flags & b2ParticleGroupFlag.b2_particleGroupInternalMask) == 0);
flags |= this.m_groupFlags & b2ParticleGroupFlag.b2_particleGroupInternalMask;
this.m_system.setGroupFlags(this, flags);
}
/** Get the total mass of the group: the sum of all particles in it. */
getMass() {
this.updateStatistics();
return this.m_mass;
}
/** Get the moment of inertia for the group. */
getInertia() {
this.updateStatistics();
return this.m_inertia;
}
/** Get the center of gravity for the group. */
getCenter() {
this.updateStatistics();
return this.m_center;
}
/** Get the linear velocity of the group. */
getLinearVelocity() {
this.updateStatistics();
return this.m_linearVelocity;
}
/** Get the angular velocity of the group. */
getAngularVelocity() {
this.updateStatistics();
return this.m_angularVelocity;
}
/**
* Get the position of the group's origin and rotation.
* Used only with groups of rigid particles.
*/
getTransform() {
return this.m_transform;
}
/**
* Get position of the particle group as a whole.
* Used only with groups of rigid particles.
*/
getPosition() {
return this.m_transform.p;
}
/**
* Get the rotational angle of the particle group as a whole.
* Used only with groups of rigid particles.
*/
getAngle() {
return this.m_transform.q.getAngle();
}
/**
* Get the world linear velocity of a world point, from the average linear
* and angular velocities of the particle group.
* @param worldPoint a point in world coordinates.
* @return the world velocity of a point.
*/
getLinearVelocityFromWorldPoint(worldPoint: Vec2) {
this.updateStatistics();
return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, Vec2.sub(worldPoint, this.m_center)));
}
/** Get the user data pointer that was provided in the group definition. */
getUserData(): unknown {
return this.m_userData;
}
/** Set the user data. Use this to store your application specific data. */
setUserData(data: any) {
this.m_userData = data;
}
/** Call b2ParticleSystem::ApplyForce for every particle in the group. */
applyForce(force: Vec2) {
this.m_system.applyForce(this.m_firstIndex, this.m_lastIndex, force);
}
/**
* Call b2ParticleSystem::ApplyLinearImpulse for every particle in the
* group.
*/
applyLinearImpulse(impulse: Vec2) {
this.m_system.applyLinearImpulse(this.m_firstIndex, this.m_lastIndex, impulse);
}
/**
* Destroy all the particles in this group.
* This function is locked during callbacks.
* @param callDestructionListener Whether to call the world b2DestructionListener for each
* particle is destroyed.
* @warning This function is locked during callbacks.
*/
destroyParticles(callDestructionListener = false) {
_ASSERT && console.assert(this.m_system.m_world.isLocked() == false);
if (this.m_system.m_world.isLocked()) {
return;
}
for (let i = this.m_firstIndex; i < this.m_lastIndex; i++) {
this.m_system.destroyParticle(i, callDestructionListener);
}
}
// ~b2ParticleGroup();
updateStatistics() {
if (this.m_timestamp != this.m_system.m_timestamp) {
const m = this.m_system.getParticleMass();
this.m_mass = 0;
this.m_center.setZero();
this.m_linearVelocity.setZero();
for (let i = this.m_firstIndex; i < this.m_lastIndex; i++) {
this.m_mass += m;
this.m_center.addMul(m, this.m_system.m_positionBuffer.data[i]);
this.m_linearVelocity.addMul(m, this.m_system.m_velocityBuffer.data[i]);
}
if (this.m_mass > 0) {
this.m_center.mul(1 / this.m_mass);
this.m_linearVelocity.mul(1 / this.m_mass);
}
this.m_inertia = 0;
this.m_angularVelocity = 0;
for (let i = this.m_firstIndex; i < this.m_lastIndex; i++) {
const p = Vec2.sub(this.m_system.m_positionBuffer.data[i], this.m_center);
const v = Vec2.sub(this.m_system.m_velocityBuffer.data[i], this.m_linearVelocity);
this.m_inertia += m * Vec2.dot(p, p);
this.m_angularVelocity += m * Vec2.cross(p, v);
}
if (this.m_inertia > 0) {
this.m_angularVelocity *= 1 / this.m_inertia;
}
this.m_timestamp = this.m_system.m_timestamp;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
const _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
// TODO proper implementation
export class StackQueue<T> {
private queue = new Array<T>();
push(item: T) {
this.queue.push(item);
}
pop() {
_ASSERT && console.assert(this.queue.length > 0);
this.queue.shift();
}
empty() {
return this.queue.length === 0;
}
front(): T | undefined {
return this.queue[0];
}
}

View File

@ -0,0 +1,234 @@
/*
* Copyright (c) 2013 Google, Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
import { Vec2 } from "../common/Vec2";
import { StackQueue } from "./StackQueue";
const _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
interface Generator {
center: Vec2;
tag: number;
necessary: boolean;
}
class VoronoiDiagramTask {
m_x: number;
m_y: number;
m_i: number;
m_generator: Generator | null;
constructor();
constructor(x: number, y: number, i: number, g: Generator);
constructor(x = 0, y = 0, i = 0, g = null) {
this.m_x = x;
this.m_y = y;
this.m_i = i;
this.m_generator = g;
}
}
export class VoronoiDiagram {
private m_generatorBuffer: Generator[];
private m_generatorCapacity: number;
private m_generatorCount: number;
private m_countX: number;
private m_countY: number;
private m_diagram: Generator[] | null;
constructor(generatorCapacity: number) {
// TODO we don't have to allocate all generators
this.m_generatorBuffer = Array(generatorCapacity)
for(let i = 0; i < generatorCapacity; i++) {
this.m_generatorBuffer[i] = {
center: Vec2.zero(),
tag: 0,
necessary: false,
};
}
this.m_generatorCapacity = generatorCapacity;
this.m_generatorCount = 0;
this.m_countX = 0;
this.m_countY = 0;
this.m_diagram = null;
}
/**
* Add a generator.
* @param center the position of the generator.
* @param tag a tag used to identify the generator in callback functions.
* @param necessary whether to callback for nodes associated with the generator.
*/
addGenerator(center: Vec2, tag: number, necessary: boolean) {
_ASSERT && console.assert(this.m_generatorCount < this.m_generatorCapacity);
const g = this.m_generatorBuffer[this.m_generatorCount++];
g.center = center;
g.tag = tag;
g.necessary = necessary;
}
/**
* Generate the Voronoi diagram. It is rasterized with a given interval
* in the same range as the necessary generators exist.
* @param radius the interval of the diagram.
* @param margin margin for which the range of the diagram is extended.
*/
generate(radius: number, margin: number) {
_ASSERT && console.assert(this.m_diagram == null);
const inverseRadius = 1 / radius;
let lower = Vec2.neo(Infinity, Infinity);
let upper = Vec2.neo(-Infinity, -Infinity);
for (let k = 0; k < this.m_generatorCount; k++) {
const g = this.m_generatorBuffer[k];
if (g.necessary) {
lower = Vec2.lower(lower, g.center);
upper = Vec2.upper(upper, g.center);
}
}
lower.x -= margin;
lower.y -= margin;
upper.x += margin;
upper.y += margin;
this.m_countX = 1 + (inverseRadius * (upper.x - lower.x) | 0);
this.m_countY = 1 + (inverseRadius * (upper.y - lower.y) | 0);
this.m_diagram = new Array(this.m_countX * this.m_countY).fill(null);
for (let i = 0; i < this.m_countX * this.m_countY; i++) {
this.m_diagram[i] = null;
}
// (4 * m_countX * m_countY) is the queue capacity that is experimentally
// known to be necessary and sufficient for general particle distributions.
const queue = new StackQueue<VoronoiDiagramTask>();
for (let k = 0; k < this.m_generatorCount; k++) {
const g = this.m_generatorBuffer[k];
g.center.sub(lower).mul(inverseRadius);
const x = g.center.x | 0;
const y = g.center.y | 0;
if (x >= 0 && y >= 0 && x < this.m_countX && y < this.m_countY) {
queue.push(new VoronoiDiagramTask(x, y, x + y * this.m_countX, g));
}
}
// fill diagram using manhattan distance
while (!queue.empty()) {
const x = queue.front().m_x;
const y = queue.front().m_y;
const i = queue.front().m_i;
const g = queue.front().m_generator;
queue.pop();
if (!this.m_diagram[i]) {
this.m_diagram[i] = g;
if (x > 0) {
queue.push(new VoronoiDiagramTask(x - 1, y, i - 1, g));
}
if (y > 0) {
queue.push(new VoronoiDiagramTask(x, y - 1, i - this.m_countX, g));
}
if (x < this.m_countX - 1) {
queue.push(new VoronoiDiagramTask(x + 1, y, i + 1, g));
}
if (y < this.m_countY - 1) {
queue.push(new VoronoiDiagramTask(x, y + 1, i + this.m_countX, g));
}
}
}
// correct diagram to use euclidean metric
for (let y = 0; y < this.m_countY; y++) {
for (let x = 0; x < this.m_countX - 1; x++) {
const i = x + y * this.m_countX;
const a = this.m_diagram[i];
const b = this.m_diagram[i + 1];
if (a != b) {
queue.push(new VoronoiDiagramTask(x, y, i, b));
queue.push(new VoronoiDiagramTask(x + 1, y, i + 1, a));
}
}
}
for (let y = 0; y < this.m_countY - 1; y++) {
for (let x = 0; x < this.m_countX; x++) {
let i = x + y * this.m_countX;
const a = this.m_diagram[i];
const b = this.m_diagram[i + this.m_countX];
if (a != b) {
queue.push(new VoronoiDiagramTask(x, y, i, b));
queue.push(new VoronoiDiagramTask(x, y + 1, i + this.m_countX, a));
}
}
}
while (!queue.empty()) {
const task = queue.front();
const x = task.m_x;
const y = task.m_y;
const i = task.m_i;
const k = task.m_generator;
queue.pop();
const a = this.m_diagram[i];
const b = k;
if (a != b) {
const ax = a.center.x - x;
const ay = a.center.y - y;
const bx = b.center.x - x;
const by = b.center.y - y;
const a2 = ax * ax + ay * ay;
const b2 = bx * bx + by * by;
if (a2 > b2) {
this.m_diagram[i] = b;
if (x > 0) {
queue.push(new VoronoiDiagramTask(x - 1, y, i - 1, b));
}
if (y > 0) {
queue.push(new VoronoiDiagramTask(x, y - 1, i - this.m_countX, b));
}
if (x < this.m_countX - 1) {
queue.push(new VoronoiDiagramTask(x + 1, y, i + 1, b));
}
if (y < this.m_countY - 1) {
queue.push(new VoronoiDiagramTask(x, y + 1, i + this.m_countX, b));
}
}
}
}
}
/**
* Enumerate all nodes that contain at least one necessary generator.
* @param callback a callback function object called for each node.
*/
getNodes(callback: (a: number, b: number, c: number) => void) {
for (let y = 0; y < this.m_countY - 1; y++) {
for (let x = 0; x < this.m_countX - 1; x++) {
let i = x + y * this.m_countX;
const a = this.m_diagram[i];
const b = this.m_diagram[i + 1];
const c = this.m_diagram[i + this.m_countX];
const d = this.m_diagram[i + 1 + this.m_countX];
if (b != c) {
if (a != b && a != c &&
(a.necessary || b.necessary || c.necessary)) {
callback(a.tag, b.tag, c.tag);
}
if (d != b && d != c &&
(b.necessary || d.necessary || c.necessary)) {
callback(b.tag, d.tag, c.tag);
}
}
}
}
}
}

View File

@ -7,6 +7,7 @@ import type { Body } from "../src/dynamics/Body";
import type { AABBValue } from "../src/collision/AABB";
import { Testbed } from "../src/util/Testbed";
import { MouseJoint } from "../src/dynamics/joint/MouseJoint";
import { b2ParticleSystem } from "../src/particle/ParticleSystem";
import { WorldComponent, WorldDragEnd, WorldDragMove, WorldDragStart } from "./world-view";
const math_PI = Math.PI;

View File

@ -1,2 +1,2 @@
export * from "../src/index";
export * from "./StageTestbed";
export * from "./StageTestbed";

View File

@ -0,0 +1,37 @@
import * as Stage from "stage-js";
import type { b2ParticleSystem } from "../../src/particle/ParticleSystem";
const SIZE = 5; // TODO
export class ParticlesComponent extends Stage.Sprite {
constructor(particles: b2ParticleSystem) {
super();
const texture = Stage.canvas();
texture.setMemoizer(() => {
// always rerender
return Math.random();
});
texture.setDrawer(function () {
const ctx = this.getContext();
const ratio = this.getDevicePixelRatio();
this.setSize(SIZE * 2, SIZE * 2, ratio);
ctx.fillStyle = "#0077ff";
const positions = particles.getPositionBuffer()
for (let i = 0; i < particles.m_count; i++) {
const p = positions[i];
ctx.fillRect(p.x * ratio + SIZE * ratio, p.y * ratio + SIZE * ratio, 1, 1);
}
});
this.texture(texture);
this.tick(this.handleTick);
}
handleTick = () => {
this.offset(-SIZE, -SIZE);
};
}

View File

@ -18,6 +18,7 @@ import {
DistanceOutput,
Distance,
} from "../";
import type { b2ParticleSystem } from "../../src/particle/ParticleSystem";
import { ComputedJointStyle, ComputedShapeStyle } from "./ComputedStyle";
import { ChainShapeComponent } from "./ChainShapeComponent";
@ -27,6 +28,7 @@ import { PolygonShapeComponent } from "./PolygonShapeComponent";
import { JointComponent } from "./JointComponent";
import { PulleyJointComponent } from "./PulleyJointComponent";
import { BodyComponent } from "./BodyComponent";
import { ParticlesComponent } from "./ParticlesComponent";
import { WorldEventHandler } from "./WorldComponentTypes";
const math_abs = Math.abs;
@ -57,6 +59,7 @@ export class WorldComponent extends Stage.Node {
private bodies = new WeakMap<Body, Stage.Node>();
private shapes = new WeakMap<Fixture, Stage.Node>();
private particles = new WeakMap<b2ParticleSystem, Stage.Node>();
private joints = new WeakMap<Joint, Stage.Node>();
constructor(context: WorldComponentContext, emit?: WorldEventHandler) {
@ -134,6 +137,7 @@ export class WorldComponent extends Stage.Node {
this.empty();
this.bodies = new WeakMap();
this.shapes = new WeakMap();
this.particles = new WeakMap();
this.joints = new WeakMap();
this.renderWorld();
};
@ -148,6 +152,11 @@ export class WorldComponent extends Stage.Node {
this.bodies.delete(obj);
};
removeParticles = (obj: b2ParticleSystem) => {
this.particles.get(obj)?.remove();
this.particles.delete(obj);
};
removeJoint = (obj: Joint) => {
this.joints.get(obj)?.remove();
this.joints.delete(obj);
@ -162,6 +171,7 @@ export class WorldComponent extends Stage.Node {
this.empty();
this.shapes = new WeakMap();
this.bodies = new WeakMap();
this.particles = new WeakMap();
this.joints = new WeakMap();
}
@ -171,6 +181,9 @@ export class WorldComponent extends Stage.Node {
for (let b = world.getBodyList(); b; b = b.getNext()) {
this.renderBody(b);
}
for (let p = world.getParticleSystemList(); p; p = p.getNext()) {
this.renderParticles(p);
}
for (let j = world.getJointList(); j; j = j.getNext()) {
this.renderJoint(j);
}
@ -219,6 +232,18 @@ export class WorldComponent extends Stage.Node {
this.shapes.set(fixture, shapeComponent);
}
renderParticles(particleSystem: b2ParticleSystem) {
let component = this.particles.get(particleSystem);
if (component) {
return;
}
component = new ParticlesComponent(particleSystem);
component.appendTo(this);
this.particles.set(particleSystem, component);
}
renderJoint(joint: Joint) {
let component = this.joints.get(joint);