diff --git a/.gitignore b/.gitignore index aac1f4f..6e1d300 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ +.idea .packages .pub packages pubspec.lock +.dart_tool +build/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b4d3f2..28a9c43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +### 1.0.0 +* Make code more like the dart standard and less C++ + +### 0.4.6 +* Fix bug with torque not being modified from applyTorque + +### 0.4.5 +* Fixing warnings and formatting + +### 0.4.1 - 0.4.4 +* Updates related to Flame interop + bugfixes + ### 0.4.0 * Breaking: Made package strong-mode compliant diff --git a/README.md b/README.md index b62b447..a07adec 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,12 @@ -### A Dart 2D physics engine - -[![Build Status](https://travis-ci.org/google/box2d.dart.svg?branch=master)](https://travis-ci.org/google/box2d.dart) -[![Coverage Status](https://coveralls.io/repos/google/box2d.dart/badge.svg?branch=master)](https://coveralls.io/r/google/box2d.dart) - -*This is a Dart port of Java's Box2D libraries.* - -*The Java Box2D library was originally written by Daniel Murphy (status -February 2015).* - -``` -benchmark/bench2d.dart Benchmark used by Joel Webber -example/index.html Browser demos as written by Dominic Hamon -lib/ Port of Daniel Murphy's jbox2d -``` - -First Dart port of an earlier version of Box2D library was -done by Dominic Hamon. We are grateful for his work. - -__*Not an official Google project*__ +## Forge2D - A Dart port of the Box2D physics engine +This is a dart port of the famous Box2D physics engine. +You can use it indepentently in Dart or in your [flame](https://github.com/flame-engine/flame) project with the help of [flame_forge2d](https://github.com/flame-engine/flame_forge2d). +Some documentation of how to use it together with flame can be found [here](https://github.com/flame-engine/flame/blob/master/doc/box2d.md). + +### Timeline +Box2D was first written in C++ and released by [Erin Catto](https://github.com/erincatto) in 2007, but it is still maintained. +It was then ported to Java (jbox2d) by Daniel Murphy around 2015. +It was then ported from that Java port to Dart by [Dominic Hamon](https://github.com/dominichamon) and [Kevin Moore](https://github.com/kevmoo). +Then [Lukas Klingsbo](https://github.com/spydon) refactored the code to follow the dart standard more, since it still had a lot of reminiscence from C++. +After this refactor we renamed it to Forge2D since the upstream wasn't maintained to take in our PRs. +There has also been countless other contributors which we are very thankful to! \ No newline at end of file diff --git a/analysis_options.yaml b/analysis_options.yaml index 4135297..a61c88b 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -2,3 +2,6 @@ analyzer: strong-mode: implicit-casts: false implicit-dynamic: false +linter: + rules: + - slash_for_doc_comments \ No newline at end of file diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 0000000..dce5537 --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,15 @@ +### Benchmark for Dart Box2D + +Run: +```sh +pub global run webdev build --output=benchmark:build +``` + +Either from the command line or from your IDE. + +Then run: +```sh +pub global run webdev daemon example:53322 --launch-app=benchmark/index.html +``` + + diff --git a/benchmark/bench2d.dart b/benchmark/bench2d.dart index de66386..a29da22 100644 --- a/benchmark/bench2d.dart +++ b/benchmark/bench2d.dart @@ -1,31 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -import 'package:box2d/box2d.dart'; +import '../lib/box2d.dart'; void main() { - new Bench2d() + Bench2d() ..initialize() ..warmup() ..bench(); @@ -64,30 +40,33 @@ double percentile(List values, double pc) { class Bench2d { final World world; - Bench2d() : world = new World.withGravity(new Vector2(0.0, -10.0)); + Bench2d() : world = World(Vector2(0.0, -10.0)); void initialize() { - BodyDef bd = new BodyDef(); + BodyDef bd = BodyDef(); Body ground = world.createBody(bd); - EdgeShape groundShape = new EdgeShape() - ..set(new Vector2(-40.0, 0.0), new Vector2(40.0, 0.0)); + PolygonShape groundShape = PolygonShape() + ..setAsEdge(Vector2(-20.0, -30.0), Vector2(20.0, -30.0)); ground.createFixtureFromShape(groundShape, 0.0); + //EdgeShape groundShape = EdgeShape() + // ..set(Vector2(-40.0, -30.0), Vector2(40.0, -30.0)); + //ground.createFixtureFromShape(groundShape, 0.0); // add boxes const boxSize = .5; - PolygonShape shape = new PolygonShape()..setAsBoxXY(boxSize, boxSize); + PolygonShape shape = PolygonShape()..setAsBoxXY(boxSize, boxSize); - Vector2 x = new Vector2(-7.0, 0.75); - Vector2 y = new Vector2.zero(); - Vector2 deltaX = new Vector2(0.5625, 1.0); - Vector2 deltaY = new Vector2(1.125, 0.0); + Vector2 x = Vector2(-7.0, 0.75); + Vector2 y = Vector2.zero(); + Vector2 deltaX = Vector2(0.5625, 1.0); + Vector2 deltaY = Vector2(1.125, 0.0); for (int i = 0; i < PYRAMID_SIZE; ++i) { y.setFrom(x); for (int j = i; j < PYRAMID_SIZE; ++j) { - BodyDef bd = new BodyDef() + BodyDef bd = BodyDef() ..type = BodyType.DYNAMIC ..position.setFrom(y); world.createBody(bd)..createFixtureFromShape(shape, 5.0); @@ -96,11 +75,13 @@ class Bench2d { x.add(deltaX); } + // TODO: Why does some bodies sleep prematurely + world.setAllowSleep(false); } List bench() { - List times = new List(FRAMES); - Stopwatch stopwatch = new Stopwatch()..start(); + List times = List(FRAMES); + Stopwatch stopwatch = Stopwatch()..start(); for (int i = 0; i < FRAMES; ++i) { int begin = stopwatch.elapsedMilliseconds; step(); @@ -132,8 +113,8 @@ class Bench2d { } void checksum(World world) { - Vector2 positionSum = new Vector2.zero(); - Vector2 linearVelocitySum = new Vector2.zero(); + Vector2 positionSum = Vector2.zero(); + Vector2 linearVelocitySum = Vector2.zero(); double angularVelocitySum = 0.0; var checksum = (Body b) { positionSum = positionSum + b.position; diff --git a/benchmark/bench2d_web.dart b/benchmark/bench2d_web.dart index e840b62..33bffa2 100644 --- a/benchmark/bench2d_web.dart +++ b/benchmark/bench2d_web.dart @@ -1,36 +1,12 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - import 'dart:html'; -import 'package:box2d/box2d_browser.dart'; +import '../lib/box2d_browser.dart'; import 'bench2d.dart'; void main() { // Render version - new Bench2dWeb() + Bench2dWeb() ..initializeAnimation() ..runAnimation(); } @@ -45,13 +21,11 @@ class Bench2dWeb extends Bench2d { ViewportTransform viewport; DebugDraw debugDraw; - /** - * Creates the canvas and readies the demo for animation. Must be called - * before calling runAnimation. - */ + /// Creates the canvas and readies the demo for animation. Must be called + /// before calling runAnimation. void initializeAnimation() { // Setup the canvas. - canvas = new CanvasElement() + canvas = CanvasElement() ..width = CANVAS_WIDTH ..height = CANVAS_HEIGHT; @@ -59,12 +33,12 @@ class Bench2dWeb extends Bench2d { document.body.append(canvas); // Create the viewport transform with the center at extents. - final extents = new Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); - viewport = new CanvasViewportTransform(extents, extents) + final extents = Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); + viewport = CanvasViewportTransform(extents, extents) ..scale = _VIEWPORT_SCALE; // Create our canvas drawing tool to give to the world. - debugDraw = new CanvasDraw(viewport, ctx); + debugDraw = CanvasDraw(viewport, ctx); // Have the world draw itself for debugging purposes. world.debugDraw = debugDraw; diff --git a/benchmark/compile.sh b/benchmark/compile.sh new file mode 100755 index 0000000..0decc05 --- /dev/null +++ b/benchmark/compile.sh @@ -0,0 +1,9 @@ +#!/bin/bash -e + +shopt -s nullglob +for f in *.dart; do + if [ "$f" == "demo.dart" ] ; then + continue; + fi + dart2js -o $f.js $f +done diff --git a/benchmark/index.html b/benchmark/index.html index b1c67d1..204a8f3 100755 --- a/benchmark/index.html +++ b/benchmark/index.html @@ -14,7 +14,6 @@ console.log('Browser does not support Dart. Expect JS fallback.'); } - - + diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..8b613fb --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,3 @@ +*.js +*.js.deps +*.js.map diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..0e46b42 --- /dev/null +++ b/example/README.md @@ -0,0 +1,24 @@ +### Examples for Dart Box2D + +Run: +```sh +pub global run webdev build --output=example:build +``` + +Either from the command line or from your IDE. + +Then run: +```sh +pub global run webdev daemon example:53322 --launch-app=example/index.html +``` + +## Old way + +Run: +```sh +./compile.sh +``` + +and then open index.html in a browser. + + diff --git a/example/ball_cage.dart b/example/ball_cage.dart index e8107f2..375aa8a 100644 --- a/example/ball_cage.dart +++ b/example/ball_cage.dart @@ -1,50 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library BallCage; -import 'package:box2d/box2d.dart'; +import '../lib/box2d.dart'; import 'demo.dart'; class BallCage extends Demo { - /** Starting position of ball cage in the world. */ + /// Starting position of ball cage in the world. static const double START_X = -20.0; static const double START_Y = -20.0; - /** The radius of the balls forming the arena. */ + /// The radius of the balls forming the arena. static const double WALL_BALL_RADIUS = 2.0; - /** Radius of the active ball. */ + /// Radius of the active ball. static const double ACTIVE_BALL_RADIUS = 1.0; - /** Constructs a new BallCage. */ + /// Constructs a new BallCage. BallCage() : super("Ball cage"); - /** Entrypoint. */ + /// Entrypoint. static void main() { - final cage = new BallCage(); + final cage = BallCage(); cage.initialize(); cage.initializeAnimation(); cage.runAnimation(); @@ -52,17 +28,17 @@ class BallCage extends Demo { void initialize() { // Define the circle shape. - final circleShape = new CircleShape(); + final circleShape = CircleShape(); circleShape.radius = WALL_BALL_RADIUS; // Create fixture using the circle shape. - final circleFixtureDef = new FixtureDef(); + final circleFixtureDef = FixtureDef(); circleFixtureDef.shape = circleShape; circleFixtureDef.friction = .9; circleFixtureDef.restitution = 1.0; // Create a body def. - final circleBodyDef = new BodyDef(); + final circleBodyDef = BodyDef(); int maxShapeinRow = 10; final double borderLimitX = @@ -74,41 +50,41 @@ class BallCage extends Demo { final double shiftX = START_X + circleShape.radius * 2 * i; final double shiftY = START_Y + circleShape.radius * 2 * i; - circleBodyDef.position = new Vector2(shiftX, START_Y); + circleBodyDef.position = Vector2(shiftX, START_Y); Body circleBody = world.createBody(circleBodyDef); bodies.add(circleBody); circleBody.createFixtureFromFixtureDef(circleFixtureDef); - circleBodyDef.position = new Vector2(shiftX, borderLimitY); + circleBodyDef.position = Vector2(shiftX, borderLimitY); circleBody = world.createBody(circleBodyDef); bodies.add(circleBody); circleBody.createFixtureFromFixtureDef(circleFixtureDef); - circleBodyDef.position = new Vector2(START_X, shiftY); + circleBodyDef.position = Vector2(START_X, shiftY); circleBody = world.createBody(circleBodyDef); bodies.add(circleBody); circleBody.createFixtureFromFixtureDef(circleFixtureDef); - circleBodyDef.position = new Vector2(borderLimitX, shiftY); + circleBodyDef.position = Vector2(borderLimitX, shiftY); circleBody = world.createBody(circleBodyDef); bodies.add(circleBody); circleBody.createFixtureFromFixtureDef(circleFixtureDef); } // Create a bouncing ball. - final bouncingCircle = new CircleShape(); + final bouncingCircle = CircleShape(); bouncingCircle.radius = ACTIVE_BALL_RADIUS; // Create fixture for that ball shape. - final activeFixtureDef = new FixtureDef(); + final activeFixtureDef = FixtureDef(); activeFixtureDef.restitution = 1.0; activeFixtureDef.density = 0.05; activeFixtureDef.shape = bouncingCircle; // Create the active ball body. - final activeBodyDef = new BodyDef(); - activeBodyDef.linearVelocity = new Vector2(0.0, -20.0); - activeBodyDef.position = new Vector2(15.0, 15.0); + final activeBodyDef = BodyDef(); + activeBodyDef.linearVelocity = Vector2(0.0, -20.0); + activeBodyDef.position = Vector2(15.0, 15.0); activeBodyDef.type = BodyType.DYNAMIC; activeBodyDef.bullet = true; final activeBody = world.createBody(activeBodyDef); diff --git a/example/blob_test.dart b/example/blob_test.dart index 092c511..d230e07 100644 --- a/example/blob_test.dart +++ b/example/blob_test.dart @@ -1,41 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library BlobTest; import 'dart:math' as Math; -import 'package:box2d/box2d.dart'; -import 'package:box2d/src/math_utils.dart' as MathUtils; import 'demo.dart'; +import '../lib/box2d.dart'; +import '../lib/src/math_utils.dart'; class BlobTest extends Demo { - /** Constructs a new BlobTest. */ + /// Constructs a new BlobTest. BlobTest() : super("Blob test"); - /** Entrypoint. */ + /// Entrypoint. static void main() { - final blob = new BlobTest(); + final blob = BlobTest(); blob.initialize(); blob.initializeAnimation(); blob.runAnimation(); @@ -44,22 +20,22 @@ class BlobTest extends Demo { void initialize() { Body ground; { - PolygonShape sd = new PolygonShape(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(50.0, 0.4); - BodyDef bd = new BodyDef(); + BodyDef bd = BodyDef(); bd.position.setValues(0.0, 0.0); assert(world != null); ground = world.createBody(bd); ground.createFixtureFromShape(sd); - sd.setAsBox(0.4, 50.0, new Vector2(-10.0, 0.0), 0.0); + sd.setAsBox(0.4, 50.0, Vector2(-10.0, 0.0), 0.0); ground.createFixtureFromShape(sd); - sd.setAsBox(0.4, 50.0, new Vector2(10.0, 0.0), 0.0); + sd.setAsBox(0.4, 50.0, Vector2(10.0, 0.0), 0.0); ground.createFixtureFromShape(sd); } - ConstantVolumeJointDef cvjd = new ConstantVolumeJointDef(); + ConstantVolumeJointDef cvjd = ConstantVolumeJointDef(); double cx = 0.0; double cy = 10.0; @@ -68,19 +44,19 @@ class BlobTest extends Demo { double nBodies = 20.0; double bodyRadius = 0.5; for (int i = 0; i < nBodies; ++i) { - double angle = MathUtils.translateAndScale( - i.toDouble(), 0.0, nBodies, 0.0, Math.PI * 2); - BodyDef bd = new BodyDef(); + double angle = translateAndScale( + i.toDouble(), 0.0, nBodies, 0.0, Math.pi * 2); + BodyDef bd = BodyDef(); bd.fixedRotation = true; double x = cx + rx * Math.sin(angle); double y = cy + ry * Math.cos(angle); - bd.position.setFrom(new Vector2(x, y)); + bd.position.setFrom(Vector2(x, y)); bd.type = BodyType.DYNAMIC; Body body = world.createBody(bd); - FixtureDef fd = new FixtureDef(); - CircleShape cd = new CircleShape(); + FixtureDef fd = FixtureDef(); + CircleShape cd = CircleShape(); cd.radius = bodyRadius; fd.shape = cd; fd.density = 1.0; @@ -94,11 +70,11 @@ class BlobTest extends Demo { cvjd.collideConnected = false; world.createJoint(cvjd); - BodyDef bd2 = new BodyDef(); + BodyDef bd2 = BodyDef(); bd2.type = BodyType.DYNAMIC; - PolygonShape psd = new PolygonShape(); - psd.setAsBox(3.0, 1.5, new Vector2(cx, cy + 15.0), 0.0); - bd2.position = new Vector2(cx, cy + 15.0); + PolygonShape psd = PolygonShape(); + psd.setAsBox(3.0, 1.5, Vector2(cx, cy + 15.0), 0.0); + bd2.position = Vector2(cx, cy + 15.0); Body fallingBox = world.createBody(bd2); fallingBox.createFixtureFromShape(psd, 1.0); } diff --git a/example/box_test.dart b/example/box_test.dart index 08ef04b..352f3f7 100644 --- a/example/box_test.dart +++ b/example/box_test.dart @@ -1,40 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library BoxTest; import 'dart:math' as Math; -import 'package:box2d/box2d.dart'; import 'demo.dart'; +import '../lib/box2d.dart'; + class BoxTest extends Demo { - /** Constructs a new BoxTest. */ + /// Constructs a new BoxTest. BoxTest() : super("Box test"); - /** Entrypoint. */ + /// Entrypoint. static void main() { - final boxTest = new BoxTest(); + final boxTest = BoxTest(); boxTest.initialize(); boxTest.initializeAnimation(); boxTest.runAnimation(); @@ -48,10 +25,10 @@ class BoxTest extends Demo { void _createGround() { // Create shape - final PolygonShape shape = new PolygonShape(); + final PolygonShape shape = PolygonShape(); // Define body - final BodyDef bodyDef = new BodyDef(); + final BodyDef bodyDef = BodyDef(); bodyDef.position.setValues(0.0, 0.0); // Create body @@ -60,9 +37,9 @@ class BoxTest extends Demo { // Set shape 3 times and create fixture on the body for each shape.setAsBoxXY(50.0, 0.4); ground.createFixtureFromShape(shape); - shape.setAsBox(0.4, 50.0, new Vector2(-10.0, 0.0), 0.0); + shape.setAsBox(0.4, 50.0, Vector2(-10.0, 0.0), 0.0); ground.createFixtureFromShape(shape); - shape.setAsBox(0.4, 50.0, new Vector2(10.0, 0.0), 0.0); + shape.setAsBox(0.4, 50.0, Vector2(10.0, 0.0), 0.0); ground.createFixtureFromShape(shape); // Add composite body to list @@ -71,19 +48,19 @@ class BoxTest extends Demo { void _createBox() { // Create shape - final PolygonShape shape = new PolygonShape(); - shape.setAsBox(3.0, 1.5, new Vector2.zero(), Math.PI / 2); + final PolygonShape shape = PolygonShape(); + shape.setAsBox(3.0, 1.5, Vector2.zero(), Math.pi / 2); // Define fixture (links body and shape) - final FixtureDef activeFixtureDef = new FixtureDef(); + final FixtureDef activeFixtureDef = FixtureDef(); activeFixtureDef.restitution = 0.5; activeFixtureDef.density = 0.05; activeFixtureDef.shape = shape; // Define body - final BodyDef bodyDef = new BodyDef(); + final BodyDef bodyDef = BodyDef(); bodyDef.type = BodyType.DYNAMIC; - bodyDef.position = new Vector2(0.0, 30.0); + bodyDef.position = Vector2(0.0, 30.0); // Create body and fixture from definitions final Body fallingBox = world.createBody(bodyDef); diff --git a/example/circle_stress.dart b/example/circle_stress.dart index f75148b..bea77e2 100644 --- a/example/circle_stress.dart +++ b/example/circle_stress.dart @@ -1,104 +1,81 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library CircleStress; import 'dart:math' as Math; -import 'package:box2d/box2d.dart'; import 'demo.dart'; -/** Scale of the viewport for this Demo. */ +import '../lib/box2d.dart'; + +/// Scale of the viewport for this Demo. const double _MY_VIEWPORT_SCALE = 4.0; class CircleStress extends Demo { - /** The number of columns of balls in the pen. */ + /// The number of columns of balls in the pen. static const int COLUMNS = 8; - /** This number of balls will be created on each layer. */ + /// This number of balls will be created on each layer. static const int LOAD_SIZE = 20; - /** Construct a new Circle Stress Demo. */ + /// Construct a new Circle Stress Demo. CircleStress() : super("Circle stress"); - /** Creates all bodies. */ + /// Creates all bodies. void initialize() { { - final bd = new BodyDef(); + final bd = BodyDef(); final ground = world.createBody(bd); bodies.add(ground); - PolygonShape shape = new PolygonShape(); - shape.setAsEdge(new Vector2(-40.0, 0.0), new Vector2(40.0, 0.0)); + PolygonShape shape = PolygonShape(); + shape.setAsEdge(Vector2(-40.0, 0.0), Vector2(40.0, 0.0)); ground.createFixtureFromShape(shape); } { // Ground - final sd = new PolygonShape(); + final sd = PolygonShape(); sd.setAsBoxXY(50.0, 10.0); - final bd = new BodyDef(); + final bd = BodyDef(); bd.type = BodyType.STATIC; - bd.position = new Vector2(0.0, -10.0); + bd.position = Vector2(0.0, -10.0); final b = world.createBody(bd); bodies.add(b); - final fd = new FixtureDef(); + final fd = FixtureDef(); fd.shape = sd; fd.friction = 1.0; b.createFixtureFromFixtureDef(fd); // Walls sd.setAsBoxXY(3.0, 50.0); - final wallDef = new BodyDef(); - wallDef.position = new Vector2(45.0, 25.0); + final wallDef = BodyDef(); + wallDef.position = Vector2(45.0, 25.0); var rightWall = world.createBody(wallDef); bodies.add(rightWall); rightWall.createFixtureFromShape(sd); - wallDef.position = new Vector2(-45.0, 25.0); + wallDef.position = Vector2(-45.0, 25.0); var leftWall = world.createBody(wallDef); bodies.add(leftWall); leftWall.createFixtureFromShape(sd); // Corners - final cornerDef = new BodyDef(); + final cornerDef = BodyDef(); sd.setAsBoxXY(20.0, 3.0); - cornerDef.angle = (-Math.PI / 4.0); - cornerDef.position = new Vector2(-35.0, 8.0); + cornerDef.angle = (-Math.pi / 4.0); + cornerDef.position = Vector2(-35.0, 8.0); Body myBod = world.createBody(cornerDef); bodies.add(myBod); myBod.createFixtureFromShape(sd); - cornerDef.angle = (Math.PI / 4.0); - cornerDef.position = new Vector2(35.0, 8.0); + cornerDef.angle = (Math.pi / 4.0); + cornerDef.position = Vector2(35.0, 8.0); myBod = world.createBody(cornerDef); bodies.add(myBod); myBod.createFixtureFromShape(sd); // top sd.setAsBoxXY(50.0, 10.0); - var topDef = new BodyDef() + var topDef = BodyDef() ..type = BodyType.STATIC ..angle = 0.0 - ..position = new Vector2(0.0, 75.0); + ..position = Vector2(0.0, 75.0); final topBody = world.createBody(topDef); bodies.add(topBody); fd.shape = sd; @@ -107,9 +84,9 @@ class CircleStress extends Demo { } { - var bd = new BodyDef() + var bd = BodyDef() ..type = BodyType.DYNAMIC - ..position = new Vector2(0.0, 10.0); + ..position = Vector2(0.0, 10.0); int numPieces = 5; double radius = 6.0; var body = world.createBody(bd); @@ -117,15 +94,15 @@ class CircleStress extends Demo { for (int i = 0; i < numPieces; i++) { double xPos = - radius * Math.cos(2 * Math.PI * (i / numPieces.toDouble())); + radius * Math.cos(2 * Math.pi * (i / numPieces.toDouble())); double yPos = - radius * Math.sin(2 * Math.PI * (i / numPieces.toDouble())); + radius * Math.sin(2 * Math.pi * (i / numPieces.toDouble())); - var cd = new CircleShape() + var cd = CircleShape() ..radius = 1.2 - ..p.setValues(xPos, yPos); + ..position.setValues(xPos, yPos); - final fd = new FixtureDef() + final fd = FixtureDef() ..shape = cd ..density = 25.0 ..friction = .1 @@ -137,12 +114,12 @@ class CircleStress extends Demo { body.setBullet(false); // Create an empty ground body. - var bodyDef = new BodyDef(); + var bodyDef = BodyDef(); var groundBody = world.createBody(bodyDef); - RevoluteJointDef rjd = new RevoluteJointDef() + RevoluteJointDef rjd = RevoluteJointDef() ..initialize(body, groundBody, body.position) - ..motorSpeed = Math.PI + ..motorSpeed = Math.pi ..maxMotorTorque = 1000000.0 ..enableMotor = true; @@ -150,18 +127,18 @@ class CircleStress extends Demo { for (int j = 0; j < COLUMNS; j++) { for (int i = 0; i < LOAD_SIZE; i++) { - CircleShape circ = new CircleShape() + CircleShape circ = CircleShape() ..radius = 1.0 + (i % 2 == 0 ? 1.0 : -1.0) * .5 * .75; - var fd2 = new FixtureDef() + var fd2 = FixtureDef() ..shape = circ ..density = circ.radius * 1.5 ..friction = 0.5 ..restitution = 0.7; double xPos = -39.0 + 2 * i; double yPos = 50.0 + j; - var bod = new BodyDef() + var bod = BodyDef() ..type = BodyType.DYNAMIC - ..position = new Vector2(xPos, yPos); + ..position = Vector2(xPos, yPos); Body myBody = world.createBody(bod); bodies.add(myBody); myBody.createFixtureFromFixtureDef(fd2); @@ -172,7 +149,7 @@ class CircleStress extends Demo { } void main() { - new CircleStress() + CircleStress() ..initialize() ..initializeAnimation() ..viewport.scale = _MY_VIEWPORT_SCALE diff --git a/example/compile.sh b/example/compile.sh new file mode 100755 index 0000000..0decc05 --- /dev/null +++ b/example/compile.sh @@ -0,0 +1,9 @@ +#!/bin/bash -e + +shopt -s nullglob +for f in *.dart; do + if [ "$f" == "demo.dart" ] ; then + continue; + fi + dart2js -o $f.js $f +done diff --git a/example/demo.dart b/example/demo.dart index d49f155..00555f4 100644 --- a/example/demo.dart +++ b/example/demo.dart @@ -1,59 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library demo; import 'dart:async'; import 'dart:html' hide Body; -import 'package:box2d/box2d_browser.dart' hide Timer; +import '../lib/box2d_browser.dart' hide Timer; -/** - * An abstract class for any Demo of the Box2D library. - */ +/// An abstract class for any Demo of the Box2D library. abstract class Demo { static const int WORLD_POOL_SIZE = 100; static const int WORLD_POOL_CONTAINER_SIZE = 10; - /** All of the bodies in a simulation. */ - List bodies = new List(); + /// All of the bodies in a simulation. + List bodies = List(); - /** The default canvas width and height. */ + /// The default canvas width and height. static const int CANVAS_WIDTH = 900; static const int CANVAS_HEIGHT = 600; - /** Scale of the viewport. */ + /// Scale of the viewport. static const double _VIEWPORT_SCALE = 10.0; - /** The gravity vector's y value. */ + /// The gravity vector's y value. static const double GRAVITY = -10.0; - /** The timestep and iteration numbers. */ + /// The timestep and iteration numbers. static const double TIME_STEP = 1 / 60; static const int VELOCITY_ITERATIONS = 10; static const int POSITION_ITERATIONS = 10; - /** The physics world. */ + /// The physics world. final World world; // For timing the world.step call. It is kept running but reset and polled @@ -62,39 +36,37 @@ abstract class Demo { final double _viewportScale; - /** The drawing canvas. */ + /// The drawing canvas. CanvasElement canvas; - /** The canvas rendering context. */ + /// The canvas rendering context. CanvasRenderingContext2D ctx; - /** The transform abstraction layer between the world and drawing canvas. */ + /// The transform abstraction layer between the world and drawing canvas. ViewportTransform viewport; - /** The debug drawing tool. */ + /// The debug drawing tool. DebugDraw debugDraw; - /** Frame count for fps */ + /// Frame count for fps int frameCount; - /** HTML element used to display the FPS counter */ + /// HTML element used to display the FPS counter Element fpsCounter; - /** Microseconds for world step update */ + /// Microseconds for world step update int elapsedUs; - /** HTML element used to display the world step time */ + /// HTML element used to display the world step time Element worldStepTime; Demo(String name, [Vector2 gravity, this._viewportScale = _VIEWPORT_SCALE]) - : this.world = new World.withPool( - (gravity == null) ? new Vector2(0.0, GRAVITY) : gravity, - new DefaultWorldPool(WORLD_POOL_SIZE, WORLD_POOL_CONTAINER_SIZE)), - _stopwatch = new Stopwatch()..start() { + : this.world = World(gravity ?? Vector2(0.0, GRAVITY)), + _stopwatch = Stopwatch()..start() { querySelector("#title").innerHtml = name; } - /** Advances the world forward by timestep seconds. */ + /// Advances the world forward by timestep seconds. void step(num timestamp) { _stopwatch.reset(); world.stepDt(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS); @@ -108,25 +80,23 @@ abstract class Demo { window.requestAnimationFrame(step); } - /** - * Creates the canvas and readies the demo for animation. Must be called - * before calling runAnimation. - */ + /// Creates the canvas and readies the demo for animation. Must be called + /// before calling runAnimation. void initializeAnimation() { // Setup the canvas. - canvas = (new Element.tag('canvas') as CanvasElement) + canvas = (Element.tag('canvas') as CanvasElement) ..width = CANVAS_WIDTH ..height = CANVAS_HEIGHT; document.body.nodes.add(canvas); ctx = canvas.context2D; // Create the viewport transform with the center at extents. - var extents = new Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); - viewport = new CanvasViewportTransform(extents, extents) + var extents = Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); + viewport = CanvasViewportTransform(extents, extents) ..scale = _viewportScale; // Create our canvas drawing tool to give to the world. - debugDraw = new CanvasDraw(viewport, ctx); + debugDraw = CanvasDraw(viewport, ctx); // Have the world draw itself for debugging purposes. world.debugDraw = debugDraw; @@ -134,11 +104,11 @@ abstract class Demo { frameCount = 0; fpsCounter = querySelector("#fps-counter"); worldStepTime = querySelector("#world-step-time"); - new Timer.periodic(new Duration(seconds: 1), (Timer t) { + Timer.periodic(Duration(seconds: 1), (Timer t) { fpsCounter.innerHtml = frameCount.toString(); frameCount = 0; }); - new Timer.periodic(new Duration(milliseconds: 200), (Timer t) { + Timer.periodic(Duration(milliseconds: 200), (Timer t) { if (elapsedUs == null) return; worldStepTime.innerHtml = "${elapsedUs / 1000} ms"; }); @@ -146,9 +116,7 @@ abstract class Demo { void initialize(); - /** - * Starts running the demo as an animation using an animation scheduler. - */ + /// Starts running the demo as an animation using an animation scheduler. void runAnimation() { window.requestAnimationFrame(step); } diff --git a/example/domino_test.dart b/example/domino_test.dart index 051f9f3..48e46a1 100644 --- a/example/domino_test.dart +++ b/example/domino_test.dart @@ -1,47 +1,23 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library DominoTest; -import 'package:box2d/box2d.dart'; - import 'demo.dart'; -/** Demonstration of dominoes being knocked over. */ +import '../lib/box2d.dart'; + +/// Demonstration of dominoes being knocked over. class DominoTest extends Demo { DominoTest() : super("Domino test"); void initialize() { { // Floor - FixtureDef fd = new FixtureDef(); - PolygonShape sd = new PolygonShape(); + FixtureDef fd = FixtureDef(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(50.0, 10.0); fd.shape = sd; - BodyDef bd = new BodyDef(); - bd.position = new Vector2(0.0, -10.0); + BodyDef bd = BodyDef(); + bd.position = Vector2(0.0, -10.0); final body = world.createBody(bd); body.createFixtureFromFixtureDef(fd); bodies.add(body); @@ -50,13 +26,13 @@ class DominoTest extends Demo { { // Platforms for (int i = 0; i < 4; i++) { - FixtureDef fd = new FixtureDef(); - PolygonShape sd = new PolygonShape(); + FixtureDef fd = FixtureDef(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(15.0, 0.125); fd.shape = sd; - BodyDef bd = new BodyDef(); - bd.position = new Vector2(0.0, 5.0 + 5 * i); + BodyDef bd = BodyDef(); + bd.position = Vector2(0.0, 5.0 + 5 * i); final body = world.createBody(bd); body.createFixtureFromFixtureDef(fd); bodies.add(body); @@ -65,13 +41,13 @@ class DominoTest extends Demo { // Dominoes { - FixtureDef fd = new FixtureDef(); - PolygonShape sd = new PolygonShape(); + FixtureDef fd = FixtureDef(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(0.125, 2.0); fd.shape = sd; fd.density = 25.0; - BodyDef bd = new BodyDef(); + BodyDef bd = BodyDef(); bd.type = BodyType.DYNAMIC; double friction = .5; @@ -81,7 +57,7 @@ class DominoTest extends Demo { for (int j = 0; j < numPerRow; j++) { fd.friction = friction; bd.position = - new Vector2(-14.75 + j * (29.5 / (numPerRow - 1)), 7.3 + 5 * i); + Vector2(-14.75 + j * (29.5 / (numPerRow - 1)), 7.3 + 5 * i); if (i == 2 && j == 0) { bd.angle = -.1; bd.position.x += .1; @@ -101,7 +77,7 @@ class DominoTest extends Demo { } void main() { - final domino = new DominoTest(); + final domino = DominoTest(); domino.initialize(); domino.initializeAnimation(); domino.runAnimation(); diff --git a/example/domino_tower.dart b/example/domino_tower.dart index cd3bf47..5de732d 100644 --- a/example/domino_tower.dart +++ b/example/domino_tower.dart @@ -1,33 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library DominoTower; import 'dart:math' as Math; -import 'package:box2d/box2d.dart'; import 'demo.dart'; +import '../lib/box2d.dart'; class DominoTower extends Demo { static const double DOMINO_WIDTH = .2; @@ -35,51 +11,47 @@ class DominoTower extends Demo { static const double DOMINO_HEIGHT = 1.0; static const int BASE_COUNT = 25; - /** - * The density of the dominos under construction. Varies for different parts - * of the tower. - */ + /// The density of the dominos under construction. Varies for different parts + /// of the tower. double dominoDensity; - /** Construct a new DominoTower. */ + /// Construct a DominoTower. DominoTower() : super("Domino tower"); - /** Entrypoint. */ + /// Entrypoint. static void main() { - final tower = new DominoTower(); + final tower = DominoTower(); tower.initialize(); tower.initializeAnimation(); tower.runAnimation(); } void makeDomino(double x, double y, bool horizontal) { - PolygonShape sd = new PolygonShape(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(.5 * DOMINO_WIDTH, .5 * DOMINO_HEIGHT); - FixtureDef fd = new FixtureDef(); + FixtureDef fd = FixtureDef(); fd.shape = sd; fd.density = dominoDensity; - BodyDef bd = new BodyDef(); + BodyDef bd = BodyDef(); bd.type = BodyType.DYNAMIC; fd.friction = DOMINO_FRICTION; fd.restitution = 0.65; - bd.position = new Vector2(x, y); - bd.angle = horizontal ? (Math.PI / 2.0) : 0.0; + bd.position = Vector2(x, y); + bd.angle = horizontal ? (Math.pi / 2.0) : 0.0; Body myBody = world.createBody(bd); myBody.createFixtureFromFixtureDef(fd); bodies.add(myBody); } - /** - * Sets up the dominoes. - */ + /// Sets up the dominoes. void initialize() { // Create the floor. { - PolygonShape sd = new PolygonShape(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(50.0, 10.0); - BodyDef bd = new BodyDef(); - bd.position = new Vector2(0.0, -10.0); + BodyDef bd = BodyDef(); + bd.position = Vector2(0.0, -10.0); final body = world.createBody(bd); body.createFixtureFromShape(sd); bodies.add(body); @@ -88,29 +60,29 @@ class DominoTower extends Demo { { dominoDensity = 10.0; // Make bullet - PolygonShape sd = new PolygonShape(); + PolygonShape sd = PolygonShape(); sd.setAsBoxXY(.7, .7); - FixtureDef fd = new FixtureDef(); + FixtureDef fd = FixtureDef(); fd.density = 35.0; - BodyDef bd = new BodyDef(); + BodyDef bd = BodyDef(); bd.type = BodyType.DYNAMIC; fd.shape = sd; fd.friction = 0.0; fd.restitution = 0.85; bd.bullet = true; - bd.position = new Vector2(30.0, 5.00); + bd.position = Vector2(30.0, 5.00); Body b = world.createBody(bd); bodies.add(b); b.createFixtureFromFixtureDef(fd); - b.linearVelocity = new Vector2(-25.0, -25.0); + b.linearVelocity = Vector2(-25.0, -25.0); b.angularVelocity = 6.7; fd.density = 25.0; - bd.position = new Vector2(-30.0, 25.0); + bd.position = Vector2(-30.0, 25.0); b = world.createBody(bd); bodies.add(b); b.createFixtureFromFixtureDef(fd); - b.linearVelocity = new Vector2(35.0, -10.0); + b.linearVelocity = Vector2(35.0, -10.0); b.angularVelocity = -8.3; } diff --git a/example/friction_joint_test.dart b/example/friction_joint_test.dart index 71669bb..dcd76db 100644 --- a/example/friction_joint_test.dart +++ b/example/friction_joint_test.dart @@ -1,40 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library FrictionJointTest; import 'dart:math' as Math; -import 'package:box2d/box2d.dart'; import 'demo.dart'; +import '../lib/box2d.dart'; class FrictionJointTest extends Demo { FrictionJointTest() : super("FrictionJoint test"); - /** Entrypoint. */ + /// Entrypoint. static void main() { - final test = new FrictionJointTest(); + final test = FrictionJointTest(); test.initialize(); test.initializeAnimation(); test.debugDraw.appendFlags(DebugDraw.JOINT_BIT); @@ -52,10 +28,10 @@ class FrictionJointTest extends Demo { void _createGround() { // Create shape - final PolygonShape shape = new PolygonShape(); + final PolygonShape shape = PolygonShape(); // Define body - final BodyDef bodyDef = new BodyDef(); + final BodyDef bodyDef = BodyDef(); bodyDef.position.setValues(0.0, 0.0); // Create body @@ -64,9 +40,9 @@ class FrictionJointTest extends Demo { // Set shape 3 times and create fixture on the body for each shape.setAsBoxXY(50.0, 0.4); _ground.createFixtureFromShape(shape); - shape.setAsBox(0.4, 50.0, new Vector2(-20.0, 0.0), 0.0); + shape.setAsBox(0.4, 50.0, Vector2(-20.0, 0.0), 0.0); _ground.createFixtureFromShape(shape); - shape.setAsBox(0.4, 50.0, new Vector2(20.0, 0.0), 0.0); + shape.setAsBox(0.4, 50.0, Vector2(20.0, 0.0), 0.0); _ground.createFixtureFromShape(shape); // Add composite body to list @@ -74,11 +50,11 @@ class FrictionJointTest extends Demo { } void _createBoxShapeAndFixture() { - final PolygonShape boxShape = new PolygonShape(); - boxShape.setAsBox(3.0, 1.5, new Vector2.zero(), Math.PI / 2); + final PolygonShape boxShape = PolygonShape(); + boxShape.setAsBox(3.0, 1.5, Vector2.zero(), Math.pi / 2); // Define fixture (links body and shape) - _boxFixture = new FixtureDef(); + _boxFixture = FixtureDef(); _boxFixture.restitution = 0.5; _boxFixture.density = 0.10; _boxFixture.shape = boxShape; @@ -86,9 +62,9 @@ class FrictionJointTest extends Demo { void _createBox() { // Define body - final BodyDef bodyDef = new BodyDef(); + final BodyDef bodyDef = BodyDef(); bodyDef.type = BodyType.DYNAMIC; - bodyDef.position = new Vector2(-10.0, 30.0); + bodyDef.position = Vector2(-10.0, 30.0); // Create body and fixture from definitions final Body fallingBox = world.createBody(bodyDef); @@ -100,15 +76,15 @@ class FrictionJointTest extends Demo { void _createFrictionBox() { // Define body - final BodyDef bodyDef = new BodyDef(); + final BodyDef bodyDef = BodyDef(); bodyDef.type = BodyType.DYNAMIC; - bodyDef.position = new Vector2(10.0, 30.0); + bodyDef.position = Vector2(10.0, 30.0); // Create body and fixture from definitions final Body fallingBox = world.createBody(bodyDef); fallingBox.createFixtureFromFixtureDef(_boxFixture); - final FrictionJointDef frictionJointDef = new FrictionJointDef(); + final FrictionJointDef frictionJointDef = FrictionJointDef(); frictionJointDef.bodyA = fallingBox; frictionJointDef.bodyB = _ground; frictionJointDef.maxForce = 3.0; diff --git a/example/index.html b/example/index.html index d44bc04..1599990 100644 --- a/example/index.html +++ b/example/index.html @@ -67,8 +67,8 @@

document.getElementById('fps').style.display = 'block'; document.getElementById('world-step').style.display = 'block'; var script = document.createElement('script'); - script.setAttribute('type', 'application/dart'); - script.setAttribute('src', demo + '.dart'); + script.setAttribute('defer', ''); + script.setAttribute('src', demo + '.dart.js'); document.body.appendChild(script); } else { console.log('Creating menu'); @@ -87,7 +87,6 @@

document.body.appendChild(menu); } - diff --git a/example/racer.dart b/example/racer.dart index fe0c0c3..8ccb13d 100644 --- a/example/racer.dart +++ b/example/racer.dart @@ -1,35 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library racer; import 'dart:html' hide Body; import 'dart:math'; -import 'package:box2d/box2d.dart'; -import 'package:box2d/src/math_utils.dart' as MathUtils; import 'demo.dart'; +import '../lib/box2d.dart'; +import '../lib/src/math_utils.dart' as MathUtils; part 'racer/car.dart'; part 'racer/control_state.dart'; @@ -38,21 +14,21 @@ part 'racer/tire.dart'; class Racer extends Demo implements ContactListener { static void main() { - final racer = new Racer(); + final racer = Racer(); racer.initialize(); racer.initializeAnimation(); document.body.nodes - .add(new Element.html("

Use the arrow keys to drive the car.

")); + .add(Element.html("

Use the arrow keys to drive the car.

")); racer.runAnimation(); } - Racer() : super("Racer", new Vector2.zero(), 2.5); + Racer() : super("Racer", Vector2.zero(), 2.5); void initialize() { _createGround(); _createBoundary(); - _car = new Car(world); + _car = Car(world); _controlState = 0; // Bind to keyboard events. @@ -81,56 +57,56 @@ class Racer extends Demo implements ContactListener { void preSolve(Contact contact, Manifold oldManifold) {} void postSolve(Contact contact, ContactImpulse impulse) {} - double radians(double deg) => deg * (PI / 180.0); + double radians(double deg) => deg * (pi / 180.0); void _createGround() { - BodyDef def = new BodyDef(); + BodyDef def = BodyDef(); _groundBody = world.createBody(def); _groundBody.userData = "Ground"; - PolygonShape shape = new PolygonShape(); + PolygonShape shape = PolygonShape(); - FixtureDef fixtureDef = new FixtureDef(); + FixtureDef fixtureDef = FixtureDef(); fixtureDef.shape = shape; fixtureDef.isSensor = true; - fixtureDef.userData = new GroundArea(0.001, false); - shape.setAsBox(27.0, 21.0, new Vector2(-30.0, 30.0), radians(20.0)); + fixtureDef.userData = GroundArea(0.001, false); + shape.setAsBox(27.0, 21.0, Vector2(-30.0, 30.0), radians(20.0)); _groundBody.createFixtureFromFixtureDef(fixtureDef); - fixtureDef.userData = new GroundArea(0.2, false); - shape.setAsBox(27.0, 15.0, new Vector2(20.0, 40.0), radians(-40.0)); + fixtureDef.userData = GroundArea(0.2, false); + shape.setAsBox(27.0, 15.0, Vector2(20.0, 40.0), radians(-40.0)); _groundBody.createFixtureFromFixtureDef(fixtureDef); } void _createBoundary() { - BodyDef def = new BodyDef(); + BodyDef def = BodyDef(); Body boundaryBody = world.createBody(def); boundaryBody.userData = "Boundary"; - PolygonShape shape = new PolygonShape(); + PolygonShape shape = PolygonShape(); - FixtureDef fixtureDef = new FixtureDef(); + FixtureDef fixtureDef = FixtureDef(); fixtureDef.shape = shape; final double boundaryX = 150.0; final double boundaryY = 100.0; - shape.setAsEdge(new Vector2(-boundaryX, -boundaryY), - new Vector2(boundaryX, -boundaryY)); + shape.setAsEdge( + Vector2(-boundaryX, -boundaryY), Vector2(boundaryX, -boundaryY)); boundaryBody.createFixtureFromFixtureDef(fixtureDef); shape.setAsEdge( - new Vector2(boundaryX, -boundaryY), new Vector2(boundaryX, boundaryY)); + Vector2(boundaryX, -boundaryY), Vector2(boundaryX, boundaryY)); boundaryBody.createFixtureFromFixtureDef(fixtureDef); shape.setAsEdge( - new Vector2(boundaryX, boundaryY), new Vector2(-boundaryX, boundaryY)); + Vector2(boundaryX, boundaryY), Vector2(-boundaryX, boundaryY)); boundaryBody.createFixtureFromFixtureDef(fixtureDef); - shape.setAsEdge(new Vector2(-boundaryX, boundaryY), - new Vector2(-boundaryX, -boundaryY)); + shape.setAsEdge( + Vector2(-boundaryX, boundaryY), Vector2(-boundaryX, -boundaryY)); boundaryBody.createFixtureFromFixtureDef(fixtureDef); } diff --git a/example/racer/car.dart b/example/racer/car.dart index 19e0f9d..c8f5731 100644 --- a/example/racer/car.dart +++ b/example/racer/car.dart @@ -16,53 +16,53 @@ part of racer; class Car { Car(World world) { - final BodyDef def = new BodyDef(); + final BodyDef def = BodyDef(); def.type = BodyType.DYNAMIC; _body = world.createBody(def); _body.userData = "Car"; _body.angularDamping = 3.0; - final List vertices = new List(8); - vertices[0] = new Vector2(1.5, 0.0); - vertices[1] = new Vector2(3.0, 2.5); - vertices[2] = new Vector2(2.8, 5.5); - vertices[3] = new Vector2(1.0, 10.0); - vertices[4] = new Vector2(-1.0, 10.0); - vertices[5] = new Vector2(-2.8, 5.5); - vertices[6] = new Vector2(-3.0, 2.5); - vertices[7] = new Vector2(-1.5, 0.0); - - final PolygonShape shape = new PolygonShape(); + final List vertices = List(8); + vertices[0] = Vector2(1.5, 0.0); + vertices[1] = Vector2(3.0, 2.5); + vertices[2] = Vector2(2.8, 5.5); + vertices[3] = Vector2(1.0, 10.0); + vertices[4] = Vector2(-1.0, 10.0); + vertices[5] = Vector2(-2.8, 5.5); + vertices[6] = Vector2(-3.0, 2.5); + vertices[7] = Vector2(-1.5, 0.0); + + final PolygonShape shape = PolygonShape(); shape.set(vertices, vertices.length); _body.createFixtureFromShape(shape, 0.1); - final RevoluteJointDef jointDef = new RevoluteJointDef(); + final RevoluteJointDef jointDef = RevoluteJointDef(); jointDef.bodyA = _body; jointDef.enableLimit = true; jointDef.lowerAngle = 0.0; jointDef.upperAngle = 0.0; jointDef.localAnchorB.setZero(); - _blTire = new Tire(world, _maxForwardSpeed, _maxBackwardSpeed, + _blTire = Tire(world, _maxForwardSpeed, _maxBackwardSpeed, _backTireMaxDriveForce, _backTireMaxLateralImpulse); jointDef.bodyB = _blTire._body; jointDef.localAnchorA.setValues(-3.0, 0.75); world.createJoint(jointDef); - _brTire = new Tire(world, _maxForwardSpeed, _maxBackwardSpeed, + _brTire = Tire(world, _maxForwardSpeed, _maxBackwardSpeed, _backTireMaxDriveForce, _backTireMaxLateralImpulse); jointDef.bodyB = _brTire._body; jointDef.localAnchorA.setValues(3.0, 0.75); world.createJoint(jointDef); - _flTire = new Tire(world, _maxForwardSpeed, _maxBackwardSpeed, + _flTire = Tire(world, _maxForwardSpeed, _maxBackwardSpeed, _frontTireMaxDriveForce, _frontTireMaxLateralImpulse); jointDef.bodyB = _flTire._body; jointDef.localAnchorA.setValues(-3.0, 8.5); _flJoint = world.createJoint(jointDef) as RevoluteJoint; - _frTire = new Tire(world, _maxForwardSpeed, _maxBackwardSpeed, + _frTire = Tire(world, _maxForwardSpeed, _maxBackwardSpeed, _frontTireMaxDriveForce, _frontTireMaxLateralImpulse); jointDef.bodyB = _frTire._body; jointDef.localAnchorA.setValues(3.0, 8.5); @@ -114,8 +114,8 @@ class Car { final double _backTireMaxLateralImpulse = 8.5; final double _frontTireMaxLateralImpulse = 7.5; - final double _lockAngle = (PI / 180) * 35; - final double _turnSpeedPerSec = (PI / 180) * 160; + final double _lockAngle = (pi / 180) * 35; + final double _turnSpeedPerSec = (pi / 180) * 160; Body _body; Tire _blTire, _brTire, _flTire, _frTire; diff --git a/example/racer/control_state.dart b/example/racer/control_state.dart index 7121fb2..08c5cc8 100644 --- a/example/racer/control_state.dart +++ b/example/racer/control_state.dart @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/** Used to track keyboard state. Entries are masked bitwise. */ +/// Used to track keyboard state. Entries are masked bitwise. part of racer; diff --git a/example/racer/tire.dart b/example/racer/tire.dart index a2cd537..b2f2d88 100644 --- a/example/racer/tire.dart +++ b/example/racer/tire.dart @@ -17,12 +17,12 @@ part of racer; class Tire { Tire(World world, this._maxForwardSpeed, this._maxBackwardSpeed, this._maxDriveForce, this._maxLateralImpulse) { - BodyDef def = new BodyDef(); + BodyDef def = BodyDef(); def.type = BodyType.DYNAMIC; _body = world.createBody(def); _body.userData = "Tire"; - PolygonShape polygonShape = new PolygonShape(); + PolygonShape polygonShape = PolygonShape(); polygonShape.setAsBoxXY(0.5, 1.25); Fixture fixture = _body.createFixtureFromShape(polygonShape, 1.0); fixture.userData = this; @@ -75,7 +75,7 @@ class Tire { return; } - Vector2 currentForwardNormal = _body.getWorldVector(new Vector2(0.0, 1.0)); + Vector2 currentForwardNormal = _body.getWorldVector(Vector2(0.0, 1.0)); final double currentSpeed = _forwardVelocity.dot(currentForwardNormal); double force = 0.0; if (desiredSpeed < currentSpeed) { @@ -132,9 +132,9 @@ class Tire { final double _maxDriveForce; final double _maxLateralImpulse; double _currentTraction; - final Set _groundAreas = new Set(); + final Set _groundAreas = Set(); // Cached Vectors to reduce unnecessary object creation. - final Vector2 _worldLeft = new Vector2(1.0, 0.0); - final Vector2 _worldUp = new Vector2(0.0, 1.0); + final Vector2 _worldLeft = Vector2(1.0, 0.0); + final Vector2 _worldUp = Vector2(0.0, 1.0); } diff --git a/lib/box2d.dart b/lib/box2d.dart index b826ece..3a3e868 100644 --- a/lib/box2d.dart +++ b/lib/box2d.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d; import 'dart:collection'; @@ -151,21 +127,4 @@ part 'src/particle/particle_group_def.dart'; part 'src/particle/particle_group_type.dart'; part 'src/particle/particle_system.dart'; part 'src/particle/particle_type.dart'; -part 'src/particle/stack_queue.dart'; part 'src/particle/voronoi_diagram.dart'; - -part 'src/pooling/idynamic_stack.dart'; -part 'src/pooling/iordered_stack.dart'; -part 'src/pooling/iworld_pool.dart'; - -part 'src/pooling/arrays/float_array.dart'; -part 'src/pooling/arrays/generator_array.dart'; -part 'src/pooling/arrays/int_array.dart'; -part 'src/pooling/arrays/vec2_array.dart'; - -part 'src/pooling/normal/circle_stack.dart'; -part 'src/pooling/normal/default_world_pool.dart'; -part 'src/pooling/normal/mutable_stack.dart'; -part 'src/pooling/normal/ordered_stack.dart'; - -part 'src/pooling/stacks/dynamic_int_stack.dart'; diff --git a/lib/box2d_browser.dart b/lib/box2d_browser.dart index 608e217..6bcbcde 100644 --- a/lib/box2d_browser.dart +++ b/lib/box2d_browser.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d_browser; export 'box2d.dart'; diff --git a/lib/src/buffer_utils.dart b/lib/src/buffer_utils.dart index 6784a1b..3f6f419 100644 --- a/lib/src/buffer_utils.dart +++ b/lib/src/buffer_utils.dart @@ -1,38 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d.buffer_utils; import 'dart:typed_data'; -/** Reallocate a buffer. */ +/// Reallocate a buffer. List reallocateBufferWithAlloc( List oldBuffer, int oldCapacity, int newCapacity, T alloc()) { assert(newCapacity > oldCapacity); - List newBuffer = new List(newCapacity); + List newBuffer = List(newCapacity); if (oldBuffer != null) { - arraycopy(oldBuffer, 0, newBuffer, 0, oldCapacity); + arrayCopy(oldBuffer, 0, newBuffer, 0, oldCapacity); } for (int i = oldCapacity; i < newCapacity; i++) { try { @@ -44,13 +20,13 @@ List reallocateBufferWithAlloc( return newBuffer; } -/** Reallocate a buffer. */ +/// Reallocate a buffer. List reallocateBufferInt( List oldBuffer, int oldCapacity, int newCapacity) { assert(newCapacity > oldCapacity); - List newBuffer = new List(newCapacity); + List newBuffer = List(newCapacity); if (oldBuffer != null) { - arraycopy(oldBuffer, 0, newBuffer, 0, oldCapacity); + arrayCopy(oldBuffer, 0, newBuffer, 0, oldCapacity); } for (int i = oldCapacity; i < newCapacity; i++) { newBuffer[i] = 0; @@ -58,21 +34,19 @@ List reallocateBufferInt( return newBuffer; } -/** Reallocate a buffer. */ +/// Reallocate a buffer. Float64List reallocateBuffer( Float64List oldBuffer, int oldCapacity, int newCapacity) { assert(newCapacity > oldCapacity); - Float64List newBuffer = new Float64List(newCapacity); + Float64List newBuffer = Float64List(newCapacity); if (oldBuffer != null) { - arraycopy(oldBuffer, 0, newBuffer, 0, oldCapacity); + arrayCopy(oldBuffer, 0, newBuffer, 0, oldCapacity); } return newBuffer; } -/** - * Reallocate a buffer. A 'deferred' buffer is reallocated only if it is not NULL. If - * 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. - */ +/// Reallocate a buffer. A 'deferred' buffer is reallocated only if it is not NULL. +/// If 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. List reallocateBufferWithAllocDeferred( List buffer, int userSuppliedCapacity, @@ -88,10 +62,8 @@ List reallocateBufferWithAllocDeferred( return buffer; } -/** - * Reallocate an int buffer. A 'deferred' buffer is reallocated only if it is not NULL. If - * 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. - */ +/// Reallocate an int buffer. A 'deferred' buffer is reallocated only if it is not NULL. +/// If 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. List reallocateBufferIntDeferred(List buffer, int userSuppliedCapacity, int oldCapacity, int newCapacity, bool deferred) { assert(newCapacity > oldCapacity); @@ -102,10 +74,8 @@ List reallocateBufferIntDeferred(List buffer, return buffer; } -/** - * Reallocate a float buffer. A 'deferred' buffer is reallocated only if it is not NULL. If - * 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. - */ +/// Reallocate a float buffer. A 'deferred' buffer is reallocated only if it is not NULL. +/// If 'userSuppliedCapacity' is not zero, buffer is user supplied and must be kept. Float64List reallocateBufferFloat64Deferred(Float64List buffer, int userSuppliedCapacity, int oldCapacity, int newCapacity, bool deferred) { assert(newCapacity > oldCapacity); @@ -116,9 +86,9 @@ Float64List reallocateBufferFloat64Deferred(Float64List buffer, return buffer; } -/** Rotate an array, see std::rotate */ -void rotate(List ray, int first, int new_first, int last) { - int next = new_first; +/// Rotate an array, see std::rotate +void rotate(List ray, int first, int newFirst, int last) { + int next = newFirst; while (next != first) { var temp = ray[first]; ray[first] = ray[next]; @@ -126,27 +96,25 @@ void rotate(List ray, int first, int new_first, int last) { first++; next++; if (next == last) { - next = new_first; - } else if (first == new_first) { - new_first = next; + next = newFirst; + } else if (first == newFirst) { + newFirst = next; } } } -/** Helper function to allocate a list of integers and set all elements to 0. */ -List allocClearIntList(int size) => new List.filled(size, 0); +/// Helper function to allocate a list of integers and set all elements to 0. +List intList(int size) => List.filled(size, 0); -/** - * Helper function for ease of porting Java to Dart. - */ -void arraycopy(List src, int srcPos, List dest, int destPos, int length) { +/// Helper function for ease of porting Java to Dart. +void arrayCopy(List src, int srcPos, List dest, int destPos, int length) { dest.setRange(destPos, length + destPos, src, srcPos); } // Replace Java's Arrays::sort. // TODO(srdjan): Make a version that does not require copying. -void sort(List list, int fromPos, int toPos) { - List temp = new List.from(list.getRange(fromPos, toPos)); +void sort(List list, int fromPos, int toPos) { + List temp = List.from(list.getRange(fromPos, toPos)); temp.sort(); list.setRange(fromPos, toPos, temp); } diff --git a/lib/src/callbacks/canvas_draw.dart b/lib/src/callbacks/canvas_draw.dart index 43e7399..4f3030f 100644 --- a/lib/src/callbacks/canvas_draw.dart +++ b/lib/src/callbacks/canvas_draw.dart @@ -1,55 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d.callbacks.canvas_draw; import 'dart:html'; -import 'package:box2d/box2d.dart'; -import 'package:box2d/src/math_utils.dart' as MathUtils; +import '../../box2d.dart'; +import '../math_utils.dart' as MathUtils; class CanvasDraw extends DebugDraw { - /** The canvas rendering context with which to draw. */ + /// The canvas rendering context with which to draw. final CanvasRenderingContext2D ctx; CanvasDraw(ViewportTransform viewport, this.ctx) : super(viewport) { assert(null != viewport && null != ctx); } - /** - * Draw a closed polygon provided in CCW order. WARNING: This mutates - * [vertices]. - */ + /// Draw a closed polygon provided in CCW order. WARNING: This mutates + /// [vertices]. void drawPolygon(List vertices, int vertexCount, Color3i color) { _pathPolygon(vertices, vertexCount, color); ctx.stroke(); } - /** - * Draw a solid closed polygon provided in CCW order. WARNING: This mutates - * [vertices]. - */ + /// Draw a solid closed polygon provided in CCW order. WARNING: This mutates + /// [vertices]. void drawSolidPolygon( List vertices, int vertexCount, Color3i color) { _pathPolygon(vertices, vertexCount, color); @@ -62,7 +34,7 @@ class CanvasDraw extends DebugDraw { // TODO(gregbglw): Do a single ctx transform rather than convert all of // these vectors. for (int i = 0; i < vertexCount; ++i) { - getWorldToScreenToOut(vertices[i], vertices[i]); + vertices[i] = getWorldToScreen(vertices[i]); } ctx.beginPath(); @@ -80,11 +52,11 @@ class CanvasDraw extends DebugDraw { ctx.closePath(); } - /** Draw a line segment. WARNING: This mutates [p1] and [p2]. */ + /// Draw a line segment. WARNING: This mutates [p1] and [p2]. void drawSegment(Vector2 p1, Vector2 p2, Color3i color) { _setColor(color); - getWorldToScreenToOut(p1, p1); - getWorldToScreenToOut(p2, p2); + p1 = getWorldToScreen(p1); + p2 = getWorldToScreen(p2); ctx.beginPath(); ctx.moveTo(p1.x, p1.y); @@ -93,24 +65,22 @@ class CanvasDraw extends DebugDraw { ctx.stroke(); } - /** Draw a circle. WARNING: This mutates [center]. */ + /// Draw a circle. WARNING: This mutates [center]. void drawCircle(Vector2 center, num radius, Color3i color, [Vector2 axis]) { radius *= viewportTransform.scale; _pathCircle(center, radius, color); ctx.stroke(); } - /** Draw a solid circle. WARNING: This mutates [center]. */ + /// Draw a solid circle. WARNING: This mutates [center]. void drawSolidCircle( Vector2 center, num radius, Vector2 axis, Color3i color) { radius *= viewportTransform.scale; drawPoint(center, radius, color); } - /** - * Draws the given point with the given *unscaled* radius, in the given [color]. - * WARNING: This mutates [point]. - */ + /// Draws the given point with the given *unscaled* radius, in the given [color]. + /// WARNING: This mutates [point]. void drawPoint(Vector2 point, num radiusOnScreen, Color3i color) { _pathCircle(point, radiusOnScreen, color); ctx.fill(); @@ -118,29 +88,27 @@ class CanvasDraw extends DebugDraw { void _pathCircle(Vector2 center, num radius, Color3i color) { _setColor(color); - getWorldToScreenToOut(center, center); + center = getWorldToScreen(center); ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, MathUtils.TWOPI, true); ctx.closePath(); } - /** - * Draw a transform. Choose your own length scale. WARNING: This mutates - * [xf.position]. - */ + /// Draw a transform. Choose your own length scale. WARNING: This mutates + /// [xf.position]. void drawTransform(Transform xf, Color3i color) { drawCircle(xf.p, 0.1, color); // TODO(rupertk): Draw rotation representation (drawCircle axis parameter?) } - /** Draw a string. */ + /// Draw a string. void drawStringXY(num x, num y, String s, Color3i color) { _setColor(color); ctx.strokeText(s, x, y); } - /** Sets the rendering context stroke and fill color to [color]. */ + /// Sets the rendering context stroke and fill color to [color]. void _setColor(Color3i color) { ctx.setStrokeColorRgb(color.x, color.y, color.z, 0.9); ctx.setFillColorRgb(color.x, color.y, color.z, 0.8); diff --git a/lib/src/callbacks/contact_filter.dart b/lib/src/callbacks/contact_filter.dart index 68a4d0f..3550fe3 100644 --- a/lib/src/callbacks/contact_filter.dart +++ b/lib/src/callbacks/contact_filter.dart @@ -1,41 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Implement this class to provide collision filtering. In other words, you can implement - * this class if you want finer control over contact creation. - */ +/// Implement this class to provide collision filtering. In other words, you can implement +/// this class if you want finer control over contact creation. class ContactFilter { - /** - * Return true if contact calculations should be performed between these two shapes. - * @warning for performance reasons this is only called when the AABBs begin to overlap. - * @param fixtureA - * @param fixtureB - * @return - */ + /// Return true if contact calculations should be performed between these two shapes. + /// @warning for performance reasons this is only called when the AABBs begin to overlap. bool shouldCollide(Fixture fixtureA, Fixture fixtureB) { Filter filterA = fixtureA.getFilterData(); Filter filterB = fixtureB.getFilterData(); diff --git a/lib/src/callbacks/contact_impulse.dart b/lib/src/callbacks/contact_impulse.dart index 53b34ef..0572915 100644 --- a/lib/src/callbacks/contact_impulse.dart +++ b/lib/src/callbacks/contact_impulse.dart @@ -1,36 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may - * approach infinity for rigid body collisions. These match up one-to-one with the contact points in - * b2Manifold. - */ +/// Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may +/// approach infinity for rigid body collisions. These match up one-to-one with the contact points in +/// b2Manifold. class ContactImpulse { - Float64List normalImpulses = new Float64List(Settings.maxManifoldPoints); - Float64List tangentImpulses = new Float64List(Settings.maxManifoldPoints); + Float64List normalImpulses = Float64List(Settings.maxManifoldPoints); + Float64List tangentImpulses = Float64List(Settings.maxManifoldPoints); int count = 0; } diff --git a/lib/src/callbacks/contact_listener.dart b/lib/src/callbacks/contact_listener.dart index e016c76..fe0c731 100644 --- a/lib/src/callbacks/contact_listener.dart +++ b/lib/src/callbacks/contact_listener.dart @@ -1,82 +1,42 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Implement this class to get contact information. You can use these results for - * things like sounds and game logic. You can also get contact results by - * traversing the contact lists after the time step. However, you might miss - * some contacts because continuous physics leads to sub-stepping. - * Additionally you may receive multiple callbacks for the same contact in a - * single time step. - * You should strive to make your callbacks efficient because there may be - * many callbacks per time step. - * @warning You cannot create/destroy Box2D entities inside these callbacks. - * - */ +/// Implement this class to get contact information. You can use these results for +/// things like sounds and game logic. You can also get contact results by +/// traversing the contact lists after the time step. However, you might miss +/// some contacts because continuous physics leads to sub-stepping. +/// Additionally you may receive multiple callbacks for the same contact in a +/// single time step. +/// You should strive to make your callbacks efficient because there may be +/// many callbacks per time step. +/// @warning You cannot create/destroy Box2D entities inside these callbacks. abstract class ContactListener { - /** - * Called when two fixtures begin to touch. - * @param contact - */ + /// Called when two fixtures begin to touch. void beginContact(Contact contact); - /** - * Called when two fixtures cease to touch. - * @param contact - */ + /// Called when two fixtures cease to touch. void endContact(Contact contact); - /** - * This is called after a contact is updated. This allows you to inspect a - * contact before it goes to the solver. If you are careful, you can modify the - * contact manifold (e.g. disable contact). - * A copy of the old manifold is provided so that you can detect changes. - * Note: this is called only for awake bodies. - * Note: this is called even when the number of contact points is zero. - * Note: this is not called for sensors. - * Note: if you set the number of contact points to zero, you will not - * get an EndContact callback. However, you may get a BeginContact callback - * the next step. - * Note: the oldManifold parameter is pooled, so it will be the same object for every callback - * for each thread. - * @param contact - * @param oldManifold - */ + /// This is called after a contact is updated. This allows you to inspect a + /// contact before it goes to the solver. If you are careful, you can modify the + /// contact manifold (e.g. disable contact). + /// A copy of the old manifold is provided so that you can detect changes. + /// Note: this is called only for awake bodies. + /// Note: this is called even when the number of contact points is zero. + /// Note: this is not called for sensors. + /// Note: if you set the number of contact points to zero, you will not + /// get an EndContact callback. However, you may get a BeginContact callback + /// the next step. + /// Note: the oldManifold parameter is pooled, so it will be the same object for every callback + /// for each thread. void preSolve(Contact contact, Manifold oldManifold); - /** - * This lets you inspect a contact after the solver is finished. This is useful - * for inspecting impulses. - * Note: the contact manifold does not include time of impact impulses, which can be - * arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - * in a separate data structure. - * Note: this is only called for contacts that are touching, solid, and awake. - * @param contact - * @param impulse this is usually a pooled variable, so it will be modified after - * this call - */ + /// This lets you inspect a contact after the solver is finished. This is useful + /// for inspecting impulses. + /// Note: the contact manifold does not include time of impact impulses, which can be + /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly + /// in a separate data structure. + /// Note: this is only called for contacts that are touching, solid, and awake. + /// @param contact + /// @param impulse this is usually a pooled variable, so it will be modified after this call void postSolve(Contact contact, ContactImpulse impulse); } diff --git a/lib/src/callbacks/debug_draw.dart b/lib/src/callbacks/debug_draw.dart index 80915a1..e3284e9 100644 --- a/lib/src/callbacks/debug_draw.dart +++ b/lib/src/callbacks/debug_draw.dart @@ -1,49 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Implement this abstract class to allow DBox2d to automatically draw your physics for debugging - * purposes. Not intended to replace your own custom rendering routines! - * - * @author Daniel Murphy - */ +/// Implement this abstract class to allow DBox2d to automatically draw your physics for debugging +/// purposes. Not intended to replace your own custom rendering routines! abstract class DebugDraw { - /** Draw shapes */ + /// Draw shapes static const int SHAPE_BIT = 1 << 1; - /** Draw joint connections */ + + /// Draw joint connections static const int JOINT_BIT = 1 << 2; - /** Draw axis aligned bounding boxes */ + + /// Draw axis aligned bounding boxes static const int AABB_BIT = 1 << 3; - /** Draw pairs of connected objects */ + + /// Draw pairs of connected objects static const int PAIR_BIT = 1 << 4; - /** Draw center of mass frame */ + + /// Draw center of mass frame static const int CENTER_OF_MASS_BIT = 1 << 5; - /** Draw dynamic tree */ + + /// Draw dynamic tree static const int DYNAMIC_TREE_BIT = 1 << 6; - /** Draw only the wireframe for drawing performance */ + + /// Draw only the wireframe for drawing performance static const int WIREFRAME_DRAWING_BIT = 1 << 7; int drawFlags = SHAPE_BIT; @@ -64,14 +42,8 @@ abstract class DebugDraw { drawFlags &= ~flags; } - /** - * Draw a closed polygon provided in CCW order. This implementation uses - * {@link #drawSegment(Vec2, Vec2, Color3f)} to draw each side of the polygon. - * - * @param vertices - * @param vertexCount - * @param color - */ + /// Draw a closed polygon provided in CCW order. This implementation uses + /// {@link #drawSegment(Vec2, Vec2, Color3f)} to draw each side of the polygon. void drawPolygon(List vertices, int vertexCount, Color3i color) { if (vertexCount == 1) { drawSegment(vertices[0], vertices[0], color); @@ -89,84 +61,42 @@ abstract class DebugDraw { void drawPoint(Vector2 argPoint, double argRadiusOnScreen, Color3i argColor); - /** - * Draw a solid closed polygon provided in CCW order. - * - * @param vertices - * @param vertexCount - * @param color - */ + /// Draw a solid closed polygon provided in CCW order. void drawSolidPolygon(List vertices, int vertexCount, Color3i color); - /** - * Draw a circle. - * - * @param center - * @param radius - * @param color - */ + /// Draw a circle. void drawCircle(Vector2 center, double radius, Color3i color); - /** Draws a circle with an axis */ + /// Draws a circle with an axis void drawCircleAxis( Vector2 center, double radius, Vector2 axis, Color3i color) { drawCircle(center, radius, color); } - /** - * Draw a solid circle. - * - * @param center - * @param radius - * @param axis - * @param color - */ + /// Draw a solid circle. void drawSolidCircle( Vector2 center, double radius, Vector2 axis, Color3i color); - /** - * Draw a line segment. - * - * @param p1 - * @param p2 - * @param color - */ + /// Draw a line segment. void drawSegment(Vector2 p1, Vector2 p2, Color3i color); - /** - * Draw a transform. Choose your own length scale - * - * @param xf - */ + /// Draw a transform. Choose your own length scale void drawTransform(Transform xf, Color3i color); - /** - * Draw a string. - * - * @param x - * @param y - * @param s - * @param color - */ + /// Draw a string. void drawStringXY(double x, double y, String s, Color3i color); - /** - * Draw a particle array - * - * @param colors can be null - */ + /// Draw a particle array + /// @param colors can be null void drawParticles(List centers, double radius, List colors, int count); - /** - * Draw a particle array - * - * @param colors can be null - */ + /// Draw a particle array + /// @param colors can be null void drawParticlesWireframe(List centers, double radius, List colors, int count); - /** Called at the end of drawing a world */ + /// Called at the end of drawing a world void flush() {} void drawString(Vector2 pos, String s, Color3i color) { @@ -177,101 +107,20 @@ abstract class DebugDraw { return viewportTransform; } - /** - * @param x - * @param y - * @param scale - * @deprecated use the viewport transform in {@link #getViewportTranform()} - */ + /// @deprecated use the viewport transform in {@link #getViewportTranform()} void setCamera(double x, double y, double scale) { viewportTransform.setCamera(x, y, scale); } - /** - * @param argScreen - * @param argWorld - */ - void getScreenToWorldToOut(Vector2 argScreen, Vector2 argWorld) { - viewportTransform.getScreenToWorld(argScreen, argWorld); - } - - /** - * @param argWorld - * @param argScreen - */ - void getWorldToScreenToOut(Vector2 argWorld, Vector2 argScreen) { - viewportTransform.getWorldToScreen(argWorld, argScreen); - } - - /** - * Takes the world coordinates and puts the corresponding screen coordinates in argScreen. - * - * @param worldX - * @param worldY - * @param argScreen - */ - void getWorldToScreenToOutXY( - double worldX, double worldY, Vector2 argScreen) { - argScreen.setValues(worldX, worldY); - viewportTransform.getWorldToScreen(argScreen, argScreen); - } - - /** - * takes the world coordinate (argWorld) and returns the screen coordinates. - * - * @param argWorld - */ - Vector2 getWorldToScreen(Vector2 argWorld) { - Vector2 screen = new Vector2.zero(); - viewportTransform.getWorldToScreen(argWorld, screen); - return screen; - } - - /** - * Takes the world coordinates and returns the screen coordinates. - * - * @param worldX - * @param worldY - */ - Vector2 getWorldToScreenXY(double worldX, double worldY) { - Vector2 argScreen = new Vector2(worldX, worldY); - viewportTransform.getWorldToScreen(argScreen, argScreen); - return argScreen; - } + /// Takes the world coordinate and returns the screen coordinates. + Vector2 getWorldToScreen(Vector2 argWorld) => + viewportTransform.getWorldToScreen(argWorld); - /** - * takes the screen coordinates and puts the corresponding world coordinates in argWorld. - * - * @param screenX - * @param screenY - * @param argWorld - */ - void getScreenToWorldToOutXY( - double screenX, double screenY, Vector2 argWorld) { - argWorld.setValues(screenX, screenY); - viewportTransform.getScreenToWorld(argWorld, argWorld); - } + /// Takes the world coordinates and returns the screen coordinates + Vector2 getWorldToScreenXY(double worldX, double worldY) => + viewportTransform.getWorldToScreen(Vector2(worldX, worldY)); - /** - * takes the screen coordinates (argScreen) and returns the world coordinates - * - * @param argScreen - */ - Vector2 getScreenToWorld(Vector2 argScreen) { - Vector2 world = new Vector2.zero(); - viewportTransform.getScreenToWorld(argScreen, world); - return world; - } - - /** - * takes the screen coordinates and returns the world coordinates. - * - * @param screenX - * @param screenY - */ - Vector2 getScreenToWorldXY(double screenX, double screenY) { - Vector2 screen = new Vector2(screenX, screenY); - viewportTransform.getScreenToWorld(screen, screen); - return screen; - } + /// Takes the screen coordinates (argScreen) and returns the world coordinates + Vector2 getScreenToWorld(Vector2 argScreen) => + viewportTransform.getScreenToWorld(argScreen); } diff --git a/lib/src/callbacks/destruction_listener.dart b/lib/src/callbacks/destruction_listener.dart index abca62b..47ca41b 100644 --- a/lib/src/callbacks/destruction_listener.dart +++ b/lib/src/callbacks/destruction_listener.dart @@ -1,46 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Joints and fixtures are destroyed when their associated - * body is destroyed. Implement this listener so that you - * may nullify references to these joints and shapes. - */ +/// Joints and fixtures are destroyed when their associated +/// body is destroyed. Implement this listener so that you +/// may nullify references to these joints and shapes. abstract class DestructionListener { - /** - * Called when any joint is about to be destroyed due - * to the destruction of one of its attached bodies. - * @param joint - */ + /// Called when any joint is about to be destroyed due + /// to the destruction of one of its attached bodies. + /// @param joint void sayGoodbyeJoint(Joint joint); - /** - * Called when any fixture is about to be destroyed due - * to the destruction of its parent body. - * @param fixture - */ + /// Called when any fixture is about to be destroyed due + /// to the destruction of its parent body. + /// @param fixture void sayGoodbyeFixture(Fixture fixture); } diff --git a/lib/src/callbacks/pair_callback.dart b/lib/src/callbacks/pair_callback.dart index cc68542..16a6097 100644 --- a/lib/src/callbacks/pair_callback.dart +++ b/lib/src/callbacks/pair_callback.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class PairCallback { diff --git a/lib/src/callbacks/particle_destruction_listener.dart b/lib/src/callbacks/particle_destruction_listener.dart index a221d47..924e430 100644 --- a/lib/src/callbacks/particle_destruction_listener.dart +++ b/lib/src/callbacks/particle_destruction_listener.dart @@ -1,40 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class ParticleDestructionListener { - /** - * Called when any particle group is about to be destroyed. - */ + /// Called when any particle group is about to be destroyed. void sayGoodbyeParticleGroup(ParticleGroup group); - /** - * Called when a particle is about to be destroyed. The index can be used in conjunction with - * {@link World#getParticleUserDataBuffer} to determine which particle has been destroyed. - * - * @param index - */ + /// Called when a particle is about to be destroyed. The index can be used in conjunction with + /// {@link World#getParticleUserDataBuffer} to determine which particle has been destroyed. void sayGoodbyeIndex(int index); } diff --git a/lib/src/callbacks/particle_query_callback.dart b/lib/src/callbacks/particle_query_callback.dart index 2d4466a..7deec77 100644 --- a/lib/src/callbacks/particle_query_callback.dart +++ b/lib/src/callbacks/particle_query_callback.dart @@ -1,38 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Callback class for AABB queries. See - * {@link World#queryAABB(QueryCallback, org.jbox2d.collision.AABB)}. - */ +/// Callback class for AABB queries. See +/// {@link World#queryAABB(QueryCallback, org.jbox2d.collision.AABB)}. abstract class ParticleQueryCallback { - /** - * Called for each particle found in the query AABB. - * - * @return false to terminate the query. - */ + /// Called for each particle found in the query AABB. + /// + /// @return false to terminate the query. bool reportParticle(int index); } diff --git a/lib/src/callbacks/particle_raycast_callback.dart b/lib/src/callbacks/particle_raycast_callback.dart index 44b841c..92dfacb 100644 --- a/lib/src/callbacks/particle_raycast_callback.dart +++ b/lib/src/callbacks/particle_raycast_callback.dart @@ -1,41 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class ParticleRaycastCallback { - /** - * Called for each particle found in the query. See - * {@link RayCastCallback#reportFixture(org.jbox2d.dynamics.Fixture, Vec2, Vec2, float)} for - * argument info. - * - * @param index - * @param point - * @param normal - * @param fraction - * @return - */ + /// Called for each particle found in the query. See + /// {@link RayCastCallback#reportFixture(org.jbox2d.dynamics.Fixture, Vec2, Vec2, float)} for argument info. double reportParticle( int index, Vector2 point, Vector2 normal, double fraction); } diff --git a/lib/src/callbacks/query_callback.dart b/lib/src/callbacks/query_callback.dart index d67f116..9c2a619 100644 --- a/lib/src/callbacks/query_callback.dart +++ b/lib/src/callbacks/query_callback.dart @@ -1,38 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Callback class for AABB queries. - * See {@link World#queryAABB(QueryCallback, org.jbox2d.collision.AABB)}. - */ +/// Callback class for AABB queries. +/// See {@link World#queryAABB(QueryCallback, org.jbox2d.collision.AABB)}. abstract class QueryCallback { - /** - * Called for each fixture found in the query AABB. - * @param fixture - * @return false to terminate the query. - */ + /// Called for each fixture found in the query AABB. + /// @param fixture + /// @return false to terminate the query. bool reportFixture(Fixture fixture); } diff --git a/lib/src/callbacks/raycast_callback.dart b/lib/src/callbacks/raycast_callback.dart index adb4713..35c2ca3 100644 --- a/lib/src/callbacks/raycast_callback.dart +++ b/lib/src/callbacks/raycast_callback.dart @@ -1,48 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Callback class for ray casts. - * See {@link World#raycast(RayCastCallback, Vec2, Vec2)} - */ +/// Callback class for ray casts. +/// See {@link World#raycast(RayCastCallback, Vec2, Vec2)} abstract class RayCastCallback { - /** - * Called for each fixture found in the query. You control how the ray cast - * proceeds by returning a float: - * return -1: ignore this fixture and continue - * return 0: terminate the ray cast - * return fraction: clip the ray to this point - * return 1: don't clip the ray and continue - * @param fixture the fixture hit by the ray - * @param point the point of initial intersection - * @param normal the normal vector at the point of intersection - * @return -1 to filter, 0 to terminate, fraction to clip the ray for - * closest hit, 1 to continue - * @param fraction - */ + /// Called for each fixture found in the query. You control how the ray cast + /// proceeds by returning a float: + /// return -1: ignore this fixture and continue + /// return 0: terminate the ray cast + /// return fraction: clip the ray to this point + /// return 1: don't clip the ray and continue + /// @param fixture the fixture hit by the ray + /// @param point the point of initial intersection + /// @param normal the normal vector at the point of intersection + /// @param fraction + /// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue double reportFixture( Fixture fixture, Vector2 point, Vector2 normal, double fraction); } diff --git a/lib/src/callbacks/tree_callback.dart b/lib/src/callbacks/tree_callback.dart index d87abc0..a9206ea 100644 --- a/lib/src/callbacks/tree_callback.dart +++ b/lib/src/callbacks/tree_callback.dart @@ -1,38 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * callback for {@link DynamicTree} - * - */ +/// Callback for {@link DynamicTree} abstract class TreeCallback { - /** - * Callback from a query request. - * @param proxyId the id of the proxy - * @return if the query should be continued - */ + /// Callback from a query request. + /// @param proxyId the id of the proxy + /// @return if the query should be continued bool treeCallback(int proxyId); } diff --git a/lib/src/callbacks/tree_raycast_callback.dart b/lib/src/callbacks/tree_raycast_callback.dart index f25859e..5b9d333 100644 --- a/lib/src/callbacks/tree_raycast_callback.dart +++ b/lib/src/callbacks/tree_raycast_callback.dart @@ -1,40 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * callback for {@link DynamicTree} - * @author Daniel Murphy - * - */ +/// Callback for {@link DynamicTree} abstract class TreeRayCastCallback { - /** - * - * @param input - * @param nodeId - * @return the fraction to the node - */ + /// retruns the fraction to the node double raycastCallback(RayCastInput input, int nodeId); } diff --git a/lib/src/collision/aabb.dart b/lib/src/collision/aabb.dart index 079d114..13aabbb 100644 --- a/lib/src/collision/aabb.dart +++ b/lib/src/collision/aabb.dart @@ -1,67 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** An axis-aligned bounding box. */ +/// An axis-aligned bounding box. class AABB { - /** Bottom left vertex of bounding box. */ + /// Bottom left vertex of bounding box. final Vector2 lowerBound; - /** Top right vertex of bounding box. */ + + /// Top right vertex of bounding box. final Vector2 upperBound; - /** - * Creates the default object, with vertices at 0,0 and 0,0. - */ + /// Creates the default object, with vertices at 0,0 and 0,0. AABB() - : lowerBound = new Vector2.zero(), - upperBound = new Vector2.zero(); - - /** - * Copies from the given object - * - * @param copy the object to copy from - */ + : lowerBound = Vector2.zero(), + upperBound = Vector2.zero(); + + /// Copies from the given object + /// @param copy the object to copy from AABB.copy(final AABB copy) - : lowerBound = new Vector2.copy(copy.lowerBound), - upperBound = new Vector2.copy(copy.upperBound); - - /** - * Creates an AABB object using the given bounding vertices. - * - * @param lowerVertex the bottom left vertex of the bounding box - * @param maxVertex the top right vertex of the bounding box - */ + : lowerBound = Vector2.copy(copy.lowerBound), + upperBound = Vector2.copy(copy.upperBound); + + /// Creates an AABB object using the given bounding vertices. + /// @param lowerVertex the bottom left vertex of the bounding box + /// @param maxVertex the top right vertex of the bounding box AABB.withVec2(final Vector2 lowerVertex, final Vector2 upperVertex) - : lowerBound = new Vector2.copy(lowerVertex), - upperBound = new Vector2.copy(upperVertex); - - /** - * Sets this object from the given object - * - * @param aabb the object to copy from - */ + : lowerBound = Vector2.copy(lowerVertex), + upperBound = Vector2.copy(upperVertex); + + /// Sets this object from the given object + /// @param aabb the object to copy from void set(final AABB aabb) { Vector2 v = aabb.lowerBound; lowerBound.x = v.x; @@ -71,7 +37,7 @@ class AABB { upperBound.y = v1.y; } - /** Verify that the bounds are sorted */ + /// Verify that the bounds are sorted bool isValid() { final double dx = upperBound.x - lowerBound.x; if (dx < 0.0) { @@ -85,30 +51,12 @@ class AABB { MathUtils.vector2IsValid(upperBound); } - /** - * Get the center of the AABB - * - * @return - */ - Vector2 getCenter() { - final Vector2 center = new Vector2.copy(lowerBound); - center.add(upperBound); - center.scale(.5); - return center; - } - - void getCenterToOut(final Vector2 out) { - out.x = (lowerBound.x + upperBound.x) * .5; - out.y = (lowerBound.y + upperBound.y) * .5; - } + /// Get the center of the AABB + Vector2 getCenter() => (lowerBound + upperBound)..scale(0.5); - /** - * Get the extents of the AABB (half-widths). - * - * @return - */ + /// Get the extents of the AABB (half-widths). Vector2 getExtents() { - final Vector2 center = new Vector2.copy(upperBound); + final Vector2 center = Vector2.copy(upperBound); center.sub(lowerBound); center.scale(.5); return center; @@ -128,12 +76,7 @@ class AABB { argRay[3].x -= upperBound.x - lowerBound.x; } - /** - * Combine two AABBs into this one. - * - * @param aabb1 - * @param aab - */ + /// Combine two AABBs into this one. void combine2(final AABB aabb1, final AABB aab) { lowerBound.x = aabb1.lowerBound.x < aab.lowerBound.x ? aabb1.lowerBound.x @@ -149,20 +92,12 @@ class AABB { : aab.upperBound.y; } - /** - * Gets the perimeter length - * - * @return - */ + /// Gets the perimeter length double getPerimeter() { return 2.0 * (upperBound.x - lowerBound.x + upperBound.y - lowerBound.y); } - /** - * Combines another aabb with this one - * - * @param aabb - */ + /// Combines another aabb with this one void combine(final AABB aabb) { lowerBound.x = lowerBound.x < aabb.lowerBound.x ? lowerBound.x : aabb.lowerBound.x; @@ -174,17 +109,8 @@ class AABB { upperBound.y > aabb.upperBound.y ? upperBound.y : aabb.upperBound.y; } - /** - * Does this aabb contain the provided AABB. - * - * @return - */ + /// Does this aabb contain the provided AABB. bool contains(final AABB aabb) { - /* - * boolean result = true; result = result && lowerBound.x <= aabb.lowerBound.x; result = result - * && lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= upperBound.x; - * result = result && aabb.upperBound.y <= upperBound.y; return result; - */ // djm: faster putting all of them together, as if one is false we leave the logic // early return lowerBound.x <= aabb.lowerBound.x && @@ -193,32 +119,23 @@ class AABB { aabb.upperBound.y <= upperBound.y; } - /** - * @deprecated please use {@link #raycast(RayCastOutput, RayCastInput, IWorldPool)} for better - * performance - * @param output - * @param input - * @return - */ - bool raycast(final RayCastOutput output, final RayCastInput input) { - return raycastWithPool(output, input, new DefaultWorldPool(4, 4)); - } + /// @deprecated please use {@link #raycast(RayCastOutput, RayCastInput, IWorldPool)} for better performance + //bool raycast(final RayCastOutput output, final RayCastInput input) { + // return raycastWithPool(output, input, DefaultWorldPool(4, 4)); + //} + + /// From Real-time Collision Detection, p179. + bool raycastWithPool( + final RayCastOutput output, + final RayCastInput input, + ) { + double tmin = -double.maxFinite; + double tmax = double.maxFinite; - /** - * From Real-time Collision Detection, p179. - * - * @param output - * @param input - */ - bool raycastWithPool(final RayCastOutput output, final RayCastInput input, - IWorldPool argPool) { - double tmin = -double.MAX_FINITE; - double tmax = double.MAX_FINITE; - - final Vector2 p = argPool.popVec2(); - final Vector2 d = argPool.popVec2(); - final Vector2 absD = argPool.popVec2(); - final Vector2 normal = argPool.popVec2(); + final Vector2 p = Vector2.zero(); + final Vector2 d = Vector2.zero(); + final Vector2 absD = Vector2.zero(); + final Vector2 normal = Vector2.zero(); p.setFrom(input.p1); d @@ -232,7 +149,6 @@ class AABB { if (absD.x < Settings.EPSILON) { // Parallel. if (p.x < lowerBound.x || upperBound.x < p.x) { - argPool.pushVec2(4); return false; } } else { @@ -261,7 +177,6 @@ class AABB { tmax = Math.min(tmax, t2); if (tmin > tmax) { - argPool.pushVec2(4); return false; } } @@ -269,7 +184,6 @@ class AABB { if (absD.y < Settings.EPSILON) { // Parallel. if (p.y < lowerBound.y || upperBound.y < p.y) { - argPool.pushVec2(4); return false; } } else { @@ -298,7 +212,6 @@ class AABB { tmax = Math.min(tmax, t2); if (tmin > tmax) { - argPool.pushVec2(4); return false; } } @@ -306,7 +219,6 @@ class AABB { // Does the ray start inside the box? // Does the ray intersect beyond the max fraction? if (tmin < 0.0 || input.maxFraction < tmin) { - argPool.pushVec2(4); return false; } @@ -314,7 +226,6 @@ class AABB { output.fraction = tmin; output.normal.x = normal.x; output.normal.y = normal.y; - argPool.pushVec2(4); return true; } diff --git a/lib/src/collision/broadphase/broadphase.dart b/lib/src/collision/broadphase/broadphase.dart index 0bd0fbf..aa30bc5 100644 --- a/lib/src/collision/broadphase/broadphase.dart +++ b/lib/src/collision/broadphase/broadphase.dart @@ -1,52 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class BroadPhase { static const int NULL_PROXY = -1; - /** - * Create a proxy with an initial AABB. Pairs are not reported until updatePairs is called. - * - * @param aabb - * @param userData - * @return - */ + /// Create a proxy with an initial AABB. Pairs are not reported until updatePairs is called. int createProxy(AABB aabb, Object userData); - /** - * Destroy a proxy. It is up to the client to remove any pairs. - * - * @param proxyId - */ + /// Destroy a proxy. It is up to the client to remove any pairs. void destroyProxy(int proxyId); - /** - * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized - * the proxy pairs (for your time step). - */ + /// Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized + /// the proxy pairs (for your time step). void moveProxy(int proxyId, AABB aabb, Vector2 displacement); void touchProxy(int proxyId); @@ -57,47 +21,28 @@ abstract class BroadPhase { bool testOverlap(int proxyIdA, int proxyIdB); - /** - * Get the number of proxies. - * - * @return - */ + /// Get the number of proxies. int getProxyCount(); void drawTree(DebugDraw argDraw); - /** - * Update the pairs. This results in pair callbacks. This can only add pairs. - * - * @param callback - */ + /// Update the pairs. This results in pair callbacks. This can only add pairs. void updatePairs(PairCallback callback); - /** - * Query an AABB for overlapping proxies. The callback class is called for each proxy that - * overlaps the supplied AABB. - * - * @param callback - * @param aabb - */ + /// Query an AABB for overlapping proxies. The callback class is called for each proxy that + /// overlaps the supplied AABB. void query(TreeCallback callback, AABB aabb); - /** - * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact - * ray-cast in the case were the proxy contains a shape. The callback also performs the any - * collision filtering. This has performance roughly equal to k * log(n), where k is the number of - * collisions and n is the number of proxies in the tree. - * - * @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - * @param callback a callback class that is called for each proxy that is hit by the ray. - */ + /// Ray-cast against the proxies in the tree. This relies on the callback to perform a exact + /// ray-cast in the case were the proxy contains a shape. The callback also performs the any + /// collision filtering. This has performance roughly equal to k * log(n), where k is the number of + /// collisions and n is the number of proxies in the tree. + /// + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. void raycast(TreeRayCastCallback callback, RayCastInput input); - /** - * Get the height of the embedded tree. - * - * @return - */ + /// Get the height of the embedded tree. int getTreeHeight(); int getTreeBalance(); diff --git a/lib/src/collision/broadphase/broadphase_strategy.dart b/lib/src/collision/broadphase/broadphase_strategy.dart index 1b079b1..7919e86 100644 --- a/lib/src/collision/broadphase/broadphase_strategy.dart +++ b/lib/src/collision/broadphase/broadphase_strategy.dart @@ -1,103 +1,50 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class BroadPhaseStrategy { - /** - * Create a proxy. Provide a tight fitting AABB and a userData pointer. - * - * @param aabb - * @param userData - * @return - */ + /// Create a proxy. Provide a tight fitting AABB and a userData pointer. int createProxy(AABB aabb, Object userData); - /** - * Destroy a proxy - * - * @param proxyId - */ + /// Destroy a proxy void destroyProxy(int proxyId); - /** - * Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, then the - * proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. - * - * @return true if the proxy was re-inserted. - */ + /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, then the + /// proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. + /// @return true if the proxy was re-inserted. bool moveProxy(int proxyId, AABB aabb, Vector2 displacement); Object getUserData(int proxyId); AABB getFatAABB(int proxyId); - /** - * Query an AABB for overlapping proxies. The callback class is called for each proxy that - * overlaps the supplied AABB. - * - * @param callback - * @param araabbgAABB - */ + /// Query an AABB for overlapping proxies. The callback class is called for each proxy that + /// overlaps the supplied AABB. + /// + /// @param callback + /// @param araabbgAABB void query(TreeCallback callback, AABB aabb); - /** - * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact - * ray-cast in the case were the proxy contains a shape. The callback also performs the any - * collision filtering. This has performance roughly equal to k * log(n), where k is the number of - * collisions and n is the number of proxies in the tree. - * - * @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - * @param callback a callback class that is called for each proxy that is hit by the ray. - */ + /// Ray-cast against the proxies in the tree. This relies on the callback to perform a exact + /// ray-cast in the case were the proxy contains a shape. The callback also performs the any + /// collision filtering. This has performance roughly equal to k * log(n), where k is the number of + /// collisions and n is the number of proxies in the tree. + /// + /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). + /// @param callback a callback class that is called for each proxy that is hit by the ray. void raycast(TreeRayCastCallback callback, RayCastInput input); - /** - * Compute the height of the tree. - */ + /// Compute the height of the tree. int computeHeight(); - /** - * Compute the height of the binary tree in O(N) time. Should not be called often. - * - * @return - */ + /// Compute the height of the binary tree in O(N) time. Should not be called often. + /// + /// @return int getHeight(); - /** - * Get the maximum balance of an node in the tree. The balance is the difference in height of the - * two children of a node. - * - * @return - */ + /// Get the maximum balance of an node in the tree. The balance is the difference in height of the + /// two children of a node. int getMaxBalance(); - /** - * Get the ratio of the sum of the node areas to the root area. - * - * @return - */ + /// Get the ratio of the sum of the node areas to the root area. double getAreaRatio(); void drawTree(DebugDraw draw); diff --git a/lib/src/collision/broadphase/default_broadphase_buffer.dart b/lib/src/collision/broadphase/default_broadphase_buffer.dart index ec3744f..957289c 100644 --- a/lib/src/collision/broadphase/default_broadphase_buffer.dart +++ b/lib/src/collision/broadphase/default_broadphase_buffer.dart @@ -1,38 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * The broad-phase is used for computing pairs and performing volume queries and ray casts. This - * broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the - * client to consume the new pairs and to track subsequent overlap. - * - * @author Daniel Murphy - */ +/// The broad-phase is used for computing pairs and performing volume queries and ray casts. This +/// broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the +/// client to consume the new pairs and to track subsequent overlap. class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { final BroadPhaseStrategy _tree; + final int _mask32Bits = 4294967295; // 2^32-1 int _proxyCount = 0; @@ -40,18 +13,18 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { int _moveCapacity = 16; int _moveCount = 0; - List _pairBuffer; + List _pairBuffer; int _pairCapacity = 16; int _pairCount = 0; int _queryProxyId = BroadPhase.NULL_PROXY; DefaultBroadPhaseBuffer(BroadPhaseStrategy strategy) : _tree = strategy { - _pairBuffer = new List(_pairCapacity); + _pairBuffer = List(_pairCapacity); for (int i = 0; i < _pairCapacity; i++) { - _pairBuffer[i] = new Pair(); + _pairBuffer[i] = 0; } - _moveBuffer = BufferUtils.allocClearIntList(_moveCapacity); + _moveBuffer = BufferUtils.intList(_moveCapacity); } int createProxy(final AABB aabb, Object userData) { @@ -87,8 +60,6 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { } bool testOverlap(int proxyIdA, int proxyIdB) { - // return AABB.testOverlap(proxyA.aabb, proxyB.aabb); - // return _tree.overlap(proxyIdA, proxyIdB); final AABB a = _tree.getFatAABB(proxyIdA); final AABB b = _tree.getFatAABB(proxyIdB); if (b.lowerBound.x - a.upperBound.x > 0.0 || @@ -128,10 +99,8 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { final AABB fatAABB = _tree.getFatAABB(_queryProxyId); // Query tree, create pairs and add them pair buffer. - // log.debug("quering aabb: "+_queryProxy.aabb); _tree.query(this, fatAABB); } - // log.debug("Number of pairs found: "+_pairCount); // Reset move buffer _moveCount = 0; @@ -142,19 +111,17 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { // Send the pairs back to the client. int i = 0; while (i < _pairCount) { - Pair primaryPair = _pairBuffer[i]; - Object userDataA = _tree.getUserData(primaryPair.proxyIdA); - Object userDataB = _tree.getUserData(primaryPair.proxyIdB); + int primaryPair = _pairBuffer[i]; + Object userDataA = _tree.getUserData(primaryPair >> 32); + Object userDataB = _tree.getUserData(primaryPair & _mask32Bits); - // log.debug("returning pair: "+userDataA+", "+userDataB); callback.addPair(userDataA, userDataB); ++i; // Skip any duplicate pairs. while (i < _pairCount) { - Pair pair = _pairBuffer[i]; - if (pair.proxyIdA != primaryPair.proxyIdA || - pair.proxyIdB != primaryPair.proxyIdB) { + int pair = _pairBuffer[i]; + if (pair != primaryPair) { break; } ++i; @@ -186,8 +153,8 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { if (_moveCount == _moveCapacity) { List old = _moveBuffer; _moveCapacity *= 2; - _moveBuffer = new List(_moveCapacity); - BufferUtils.arraycopy(old, 0, _moveBuffer, 0, old.length); + _moveBuffer = List(_moveCapacity); + BufferUtils.arrayCopy(old, 0, _moveBuffer, 0, old.length); } _moveBuffer[_moveCount] = proxyId; @@ -202,9 +169,7 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { } } - /** - * This is called from DynamicTree::query when we are gathering pairs. - */ + /// This is called from DynamicTree::query when we are gathering pairs. bool treeCallback(int proxyId) { // A proxy cannot form a pair with itself. if (proxyId == _queryProxyId) { @@ -213,21 +178,19 @@ class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { // Grow the pair buffer as needed. if (_pairCount == _pairCapacity) { - List oldBuffer = _pairBuffer; + List oldBuffer = _pairBuffer; _pairCapacity *= 2; - _pairBuffer = new List(_pairCapacity); - BufferUtils.arraycopy(oldBuffer, 0, _pairBuffer, 0, oldBuffer.length); + _pairBuffer = List(_pairCapacity); + BufferUtils.arrayCopy(oldBuffer, 0, _pairBuffer, 0, oldBuffer.length); for (int i = oldBuffer.length; i < _pairCapacity; i++) { - _pairBuffer[i] = new Pair(); + _pairBuffer[i] = 0; } } if (proxyId < _queryProxyId) { - _pairBuffer[_pairCount].proxyIdA = proxyId; - _pairBuffer[_pairCount].proxyIdB = _queryProxyId; + _pairBuffer[_pairCount] = (proxyId << 32) | _queryProxyId; } else { - _pairBuffer[_pairCount].proxyIdA = _queryProxyId; - _pairBuffer[_pairCount].proxyIdB = proxyId; + _pairBuffer[_pairCount] = (_queryProxyId << 32) | proxyId; } ++_pairCount; diff --git a/lib/src/collision/broadphase/dynamic_tree.dart b/lib/src/collision/broadphase/dynamic_tree.dart index 086d7fe..801f8f5 100644 --- a/lib/src/collision/broadphase/dynamic_tree.dart +++ b/lib/src/collision/broadphase/dynamic_tree.dart @@ -1,62 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and - * ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by _fatAABBFactor - * so that the proxy AABB is bigger than the client object. This allows the client object to move by - * small amounts without triggering a tree update. - * - * @author daniel - */ +/// A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and +/// ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by _fatAABBFactor +/// so that the proxy AABB is bigger than the client object. This allows the client object to move by +/// small amounts without triggering a tree update. class DynamicTree implements BroadPhaseStrategy { static const int MAX_STACK_SIZE = 64; static const int NULL_NODE = -1; DynamicTreeNode _root; - List _nodes = new List(16); + List _nodes = List(16); int _nodeCount = 0; int _nodeCapacity = 16; int _freeList = 0; - final List drawVecs = new List(4); - List nodeStack = new List(20); + final List drawVecs = List(4); + List nodeStack = List(20); int nodeStackIndex = 0; DynamicTree() { // Build a linked list for the free list. for (int i = _nodeCapacity - 1; i >= 0; i--) { - _nodes[i] = new DynamicTreeNode(i); + _nodes[i] = DynamicTreeNode(i); _nodes[i].parent = (i == _nodeCapacity - 1) ? null : _nodes[i + 1]; _nodes[i].height = -1; } for (int i = 0; i < drawVecs.length; i++) { - drawVecs[i] = new Vector2.zero(); + drawVecs[i] = Vector2.zero(); } } @@ -160,8 +132,8 @@ class DynamicTree implements BroadPhaseStrategy { } else { if (nodeStack.length - nodeStackIndex - 2 <= 0) { List newBuffer = - new List(nodeStack.length * 2); - BufferUtils.arraycopy(nodeStack, 0, newBuffer, 0, nodeStack.length); + List(nodeStack.length * 2); + BufferUtils.arrayCopy(nodeStack, 0, newBuffer, 0, nodeStack.length); nodeStack = newBuffer; } nodeStack[nodeStackIndex++] = node.child1; @@ -171,9 +143,9 @@ class DynamicTree implements BroadPhaseStrategy { } } - final Vector2 _r = new Vector2.zero(); - final AABB _aabb = new AABB(); - final RayCastInput _subInput = new RayCastInput(); + final Vector2 _r = Vector2.zero(); + final AABB _aabb = AABB(); + final RayCastInput _subInput = RayCastInput(); void raycast(TreeRayCastCallback callback, RayCastInput input) { final Vector2 p1 = input.p1; @@ -205,18 +177,12 @@ class DynamicTree implements BroadPhaseStrategy { // Build a bounding box for the segment. final AABB segAABB = _aabb; - // Vec2 t = p1 + maxFraction * (p2 - p1); - // before inline - // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); - // Vec2.minToOut(p1, temp, segAABB.lowerBound); - // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; - segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; - segAABB.lowerBound.y = p1y < tempy ? p1y : tempy; - segAABB.upperBound.x = p1x > tempx ? p1x : tempx; - segAABB.upperBound.y = p1y > tempy ? p1y : tempy; - // end inline + segAABB.lowerBound.x = Math.min(p1x, tempx); + segAABB.lowerBound.y = Math.min(p1y, tempy); + segAABB.upperBound.x = Math.max(p1x, tempx); + segAABB.upperBound.y = Math.max(p1y, tempy); nodeStackIndex = 0; nodeStack[nodeStackIndex++] = _root; @@ -233,8 +199,6 @@ class DynamicTree implements BroadPhaseStrategy { // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) - // node.aabb.getCenterToOut(c); - // node.aabb.getExtentsToOut(h); cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x) * .5; cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y) * .5; hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x) * .5; @@ -264,21 +228,18 @@ class DynamicTree implements BroadPhaseStrategy { if (value > 0.0) { // Update segment bounding box. maxFraction = value; - // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); - // Vec2.minToOut(p1, temp, segAABB.lowerBound); - // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; - segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; - segAABB.lowerBound.y = p1y < tempy ? p1y : tempy; - segAABB.upperBound.x = p1x > tempx ? p1x : tempx; - segAABB.upperBound.y = p1y > tempy ? p1y : tempy; + segAABB.lowerBound.x = Math.min(p1x, tempx); + segAABB.lowerBound.y = Math.min(p1y, tempy); + segAABB.upperBound.x = Math.max(p1x, tempx); + segAABB.upperBound.y = Math.max(p1y, tempy); } } else { if (nodeStack.length - nodeStackIndex - 2 <= 0) { List newBuffer = - new List(nodeStack.length * 2); - BufferUtils.arraycopy(nodeStack, 0, newBuffer, 0, nodeStack.length); + List(nodeStack.length * 2); + BufferUtils.arrayCopy(nodeStack, 0, newBuffer, 0, nodeStack.length); nodeStack = newBuffer; } nodeStack[nodeStackIndex++] = node.child1; @@ -299,12 +260,10 @@ class DynamicTree implements BroadPhaseStrategy { } int height1 = _computeHeight(node.child1); int height2 = _computeHeight(node.child2); - return 1 + Math.max(height1, height2); + return 1 + Math.max(height1, height2); } - /** - * Validate this tree. For testing. - */ + /// Validate this tree. For testing. void validate() { _validateStructure(_root); _validateMetrics(_root); @@ -339,7 +298,7 @@ class DynamicTree implements BroadPhaseStrategy { continue; } - assert((node.child1 == null) == false); + assert(node.child1 != null); DynamicTreeNode child1 = node.child1; DynamicTreeNode child2 = node.child2; @@ -372,11 +331,9 @@ class DynamicTree implements BroadPhaseStrategy { return totalArea / rootArea; } - /** - * Build an optimal tree. Very expensive. For testing. - */ + /// Build an optimal tree. Very expensive. For testing. void rebuildBottomUp() { - List nodes = BufferUtils.allocClearIntList(_nodeCount); + List nodes = BufferUtils.intList(_nodeCount); int count = 0; // Build array of leaves. Free the rest. @@ -396,9 +353,9 @@ class DynamicTree implements BroadPhaseStrategy { } } - AABB b = new AABB(); + AABB b = AABB(); while (count > 1) { - double minCost = double.MAX_FINITE; + double minCost = double.maxFinite; int iMin = -1, jMin = -1; for (int i = 0; i < count; ++i) { AABB aabbi = _nodes[nodes[i]].aabb; @@ -423,7 +380,7 @@ class DynamicTree implements BroadPhaseStrategy { DynamicTreeNode parent = _allocateNode(); parent.child1 = child1; parent.child2 = child2; - parent.height = 1 + Math.max(child1.height, child2.height); + parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine2(child1.aabb, child2.aabb); parent.parent = null; @@ -446,12 +403,12 @@ class DynamicTree implements BroadPhaseStrategy { List old = _nodes; _nodeCapacity *= 2; - _nodes = new List(_nodeCapacity); - BufferUtils.arraycopy(old, 0, _nodes, 0, old.length); + _nodes = List(_nodeCapacity); + BufferUtils.arrayCopy(old, 0, _nodes, 0, old.length); // Build a linked list for the free list. for (int i = _nodeCapacity - 1; i >= _nodeCount; i--) { - _nodes[i] = new DynamicTreeNode(i); + _nodes[i] = DynamicTreeNode(i); _nodes[i].parent = (i == _nodeCapacity - 1) ? null : _nodes[i + 1]; _nodes[i].height = -1; } @@ -470,9 +427,7 @@ class DynamicTree implements BroadPhaseStrategy { return treeNode; } - /** - * returns a node to the pool - */ + /// returns a node to the pool void _freeNode(DynamicTreeNode node) { assert(node != null); assert(0 < _nodeCount); @@ -482,7 +437,7 @@ class DynamicTree implements BroadPhaseStrategy { _nodeCount--; } - final AABB _combinedAABB = new AABB(); + final AABB _combinedAABB = AABB(); void _insertLeaf(int leaf_index) { DynamicTreeNode leaf = _nodes[leaf_index]; @@ -588,7 +543,7 @@ class DynamicTree implements BroadPhaseStrategy { assert(child1 != null); assert(child2 != null); - index.height = 1 + Math.max(child1.height, child2.height); + index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine2(child1.aabb, child2.aabb); index = index.parent; @@ -630,7 +585,7 @@ class DynamicTree implements BroadPhaseStrategy { DynamicTreeNode child2 = index.child2; index.aabb.combine2(child1.aabb, child2.aabb); - index.height = 1 + Math.max(child1.height, child2.height); + index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } @@ -699,8 +654,8 @@ class DynamicTree implements BroadPhaseStrategy { A.aabb.combine2(B.aabb, G.aabb); C.aabb.combine2(A.aabb, F.aabb); - A.height = 1 + Math.max(B.height, G.height); - C.height = 1 + Math.max(A.height, F.height); + A.height = 1 + Math.max(B.height, G.height); + C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = iG; A.child2 = iF; @@ -708,8 +663,8 @@ class DynamicTree implements BroadPhaseStrategy { A.aabb.combine2(B.aabb, F.aabb); C.aabb.combine2(A.aabb, G.aabb); - A.height = 1 + Math.max(B.height, F.height); - C.height = 1 + Math.max(A.height, G.height); + A.height = 1 + Math.max(B.height, F.height); + C.height = 1 + Math.max(A.height, G.height); } return iC; @@ -749,8 +704,8 @@ class DynamicTree implements BroadPhaseStrategy { A.aabb.combine2(C.aabb, E.aabb); B.aabb.combine2(A.aabb, D.aabb); - A.height = 1 + Math.max(C.height, E.height); - B.height = 1 + Math.max(A.height, D.height); + A.height = 1 + Math.max(C.height, E.height); + B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = iE; A.child1 = iD; @@ -758,8 +713,8 @@ class DynamicTree implements BroadPhaseStrategy { A.aabb.combine2(C.aabb, D.aabb); B.aabb.combine2(A.aabb, E.aabb); - A.height = 1 + Math.max(C.height, D.height); - B.height = 1 + Math.max(A.height, E.height); + A.height = 1 + Math.max(C.height, D.height); + B.height = 1 + Math.max(A.height, E.height); } return iB; @@ -819,10 +774,10 @@ class DynamicTree implements BroadPhaseStrategy { int height1 = child1.height; int height2 = child2.height; int height; - height = 1 + Math.max(height1, height2); + height = 1 + Math.max(height1, height2); assert(node.height == height); - AABB aabb = new AABB(); + AABB aabb = AABB(); aabb.combine2(child1.aabb, child2.aabb); assert(MathUtils.vector2Equals(aabb.lowerBound, node.aabb.lowerBound)); @@ -840,8 +795,7 @@ class DynamicTree implements BroadPhaseStrategy { drawTreeX(argDraw, _root, 0, height); } - final Color3i _color = new Color3i.zero(); - final Vector2 _textVec = new Vector2.zero(); + final Color3i _color = Color3i.zero(); void drawTreeX( DebugDraw argDraw, DynamicTreeNode node, int spot, int height) { @@ -851,11 +805,10 @@ class DynamicTree implements BroadPhaseStrategy { 1.0, (height - spot) * 1.0 / height, (height - spot) * 1.0 / height); argDraw.drawPolygon(drawVecs, 4, _color); - argDraw - .getViewportTranform() - .getWorldToScreen(node.aabb.upperBound, _textVec); + Vector2 textVec = + argDraw.getViewportTranform().getWorldToScreen(node.aabb.upperBound); argDraw.drawStringXY( - _textVec.x, _textVec.y, "$node.id-${(spot + 1)}/$height", _color); + textVec.x, textVec.y, "$node.id-${(spot + 1)}/$height", _color); if (node.child1 != null) { drawTreeX(argDraw, node.child1, spot + 1, height); diff --git a/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart b/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart index bfd7507..3bdffad 100644 --- a/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart +++ b/lib/src/collision/broadphase/dynamic_tree_flatnodes.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class DynamicTreeFlatNodes implements BroadPhaseStrategy { @@ -42,18 +18,18 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { int _freeList; - final List drawVecs = new List(4); + final List drawVecs = List(4); DynamicTreeFlatNodes() { _expandBuffers(0, _nodeCapacity); for (int i = 0; i < drawVecs.length; i++) { - drawVecs[i] = new Vector2.zero(); + drawVecs[i] = Vector2.zero(); } } - static AABB allocAABB() => new AABB(); - static Object allocObject() => new Object(); + static AABB allocAABB() => AABB(); + static Object allocObject() => Object(); void _expandBuffers(int oldSize, int newSize) { _aabb = BufferUtils.reallocateBufferWithAlloc( @@ -67,7 +43,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { // Build a linked list for the free list. for (int i = oldSize; i < newSize; i++) { - _aabb[i] = new AABB(); + _aabb[i] = AABB(); _parent[i] = (i == newSize - 1) ? NULL_NODE : i + 1; _height[i] = -1; _child1[i] = -1; @@ -152,7 +128,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { return _aabb[proxyId]; } - List _nodeStack = BufferUtils.allocClearIntList(20); + List _nodeStack = BufferUtils.intList(20); int _nodeStackIndex = 0; void query(TreeCallback callback, AABB aabb) { @@ -184,9 +160,9 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { } } - final Vector2 _r = new Vector2.zero(); - final AABB _aabbTemp = new AABB(); - final RayCastInput _subInput = new RayCastInput(); + final Vector2 _r = Vector2.zero(); + final AABB _aabbTemp = AABB(); + final RayCastInput _subInput = RayCastInput(); void raycast(TreeRayCastCallback callback, RayCastInput input) { final Vector2 p1 = input.p1; @@ -218,18 +194,12 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { // Build a bounding box for the segment. final AABB segAABB = _aabbTemp; - // Vec2 t = p1 + maxFraction * (p2 - p1); - // before inline - // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); - // Vec2.minToOut(p1, temp, segAABB.lowerBound); - // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; segAABB.lowerBound.y = p1y < tempy ? p1y : tempy; segAABB.upperBound.x = p1x > tempx ? p1x : tempx; segAABB.upperBound.y = p1y > tempy ? p1y : tempy; - // end inline _nodeStackIndex = 0; _nodeStack[_nodeStackIndex++] = _root; @@ -246,8 +216,6 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) - // node.aabb.getCenterToOut(c); - // node.aabb.getExtentsToOut(h); cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x) * .5; cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y) * .5; hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x) * .5; @@ -278,9 +246,6 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { if (value > 0.0) { // Update segment bounding box. maxFraction = value; - // temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1); - // Vec2.minToOut(p1, temp, segAABB.lowerBound); - // Vec2.maxToOut(p1, temp, segAABB.upperBound); tempx = (p2x - p1x) * maxFraction + p1x; tempy = (p2y - p1y) * maxFraction + p1y; segAABB.lowerBound.x = p1x < tempx ? p1x : tempx; @@ -307,12 +272,10 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { } int height1 = _computeHeight(_child1[node]); int height2 = _computeHeight(_child2[node]); - return 1 + Math.max(height1, height2); + return 1 + Math.max(height1, height2); } - /** - * Validate this tree. For testing. - */ + /// Validate this tree. For testing. void validate() { _validateStructure(_root); _validateMetrics(_root); @@ -391,9 +354,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { return node; } - /** - * returns a node to the pool - */ + /// returns a node to the pool void _freeNode(int node) { assert(node != NULL_NODE); assert(0 < _nodeCount); @@ -403,7 +364,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { _nodeCount--; } - final AABB _combinedAABB = new AABB(); + final AABB _combinedAABB = AABB(); void _insertLeaf(int leaf) { if (_root == NULL_NODE) { @@ -510,7 +471,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { assert(child1 != NULL_NODE); assert(child2 != NULL_NODE); - _height[index] = 1 + Math.max(_height[child1], _height[child2]); + _height[index] = 1 + Math.max(_height[child1], _height[child2]); _aabb[index].combine2(_aabb[child1], _aabb[child2]); index = _parent[index]; @@ -554,7 +515,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { int child2 = _child2[index]; _aabb[index].combine2(_aabb[child1], _aabb[child2]); - _height[index] = 1 + Math.max(_height[child1], _height[child2]); + _height[index] = 1 + Math.max(_height[child1], _height[child2]); index = _parent[index]; } @@ -593,8 +554,6 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { int iG = _child2[C]; int F = iF; int G = iG; - // assert (F != null); - // assert (G != null); assert(0 <= iF && iF < _nodeCapacity); assert(0 <= iG && iG < _nodeCapacity); @@ -623,8 +582,8 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { _aabb[A].combine2(_aabb[B], _aabb[G]); _aabb[C].combine2(_aabb[A], _aabb[F]); - _height[A] = 1 + Math.max(_height[B], _height[G]); - _height[C] = 1 + Math.max(_height[A], _height[F]); + _height[A] = 1 + Math.max(_height[B], _height[G]); + _height[C] = 1 + Math.max(_height[A], _height[F]); } else { _child2[C] = iG; _child2[A] = iF; @@ -632,8 +591,8 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { _aabb[A].combine2(_aabb[B], _aabb[F]); _aabb[C].combine2(_aabb[A], _aabb[G]); - _height[A] = 1 + Math.max(_height[B], _height[F]); - _height[C] = 1 + Math.max(_height[A], _height[G]); + _height[A] = 1 + Math.max(_height[B], _height[F]); + _height[C] = 1 + Math.max(_height[A], _height[G]); } return iC; @@ -673,8 +632,8 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { _aabb[A].combine2(_aabb[C], _aabb[E]); _aabb[B].combine2(_aabb[A], _aabb[D]); - _height[A] = 1 + Math.max(_height[C], _height[E]); - _height[B] = 1 + Math.max(_height[A], _height[D]); + _height[A] = 1 + Math.max(_height[C], _height[E]); + _height[B] = 1 + Math.max(_height[A], _height[D]); } else { _child2[B] = iE; _child1[A] = iD; @@ -682,8 +641,8 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { _aabb[A].combine2(_aabb[C], _aabb[D]); _aabb[B].combine2(_aabb[A], _aabb[E]); - _height[A] = 1 + Math.max(_height[C], _height[D]); - _height[B] = 1 + Math.max(_height[A], _height[E]); + _height[A] = 1 + Math.max(_height[C], _height[D]); + _height[B] = 1 + Math.max(_height[A], _height[E]); } return iB; @@ -742,10 +701,10 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { int height1 = _height[child1]; int height2 = _height[child2]; int height; - height = 1 + Math.max(height1, height2); + height = 1 + Math.max(height1, height2); assert(_height[node] == height); - AABB aabb = new AABB(); + AABB aabb = AABB(); aabb.combine2(_aabb[child1], _aabb[child2]); assert(MathUtils.vector2Equals(aabb.lowerBound, _aabb[node].lowerBound)); @@ -763,8 +722,7 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { drawTreeX(argDraw, _root, 0, height); } - final Color3i _color = new Color3i.zero(); - final Vector2 _textVec = new Vector2.zero(); + final Color3i _color = Color3i.zero(); void drawTreeX(DebugDraw argDraw, int node, int spot, int height) { AABB a = _aabb[node]; @@ -774,9 +732,10 @@ class DynamicTreeFlatNodes implements BroadPhaseStrategy { 1.0, (height - spot) * 1.0 / height, (height - spot) * 1.0 / height); argDraw.drawPolygon(drawVecs, 4, _color); - argDraw.getViewportTranform().getWorldToScreen(a.upperBound, _textVec); + Vector2 textVec = + argDraw.getViewportTranform().getWorldToScreen(a.upperBound); argDraw.drawStringXY( - _textVec.x, _textVec.y, "$node-${(spot + 1)}/$height", _color); + textVec.x, textVec.y, "$node-${(spot + 1)}/$height", _color); int c1 = _child1[node]; int c2 = _child2[node]; diff --git a/lib/src/collision/broadphase/dynamic_tree_node.dart b/lib/src/collision/broadphase/dynamic_tree_node.dart index 8f1aff4..f889b56 100644 --- a/lib/src/collision/broadphase/dynamic_tree_node.dart +++ b/lib/src/collision/broadphase/dynamic_tree_node.dart @@ -1,34 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class DynamicTreeNode { - /** - * Enlarged AABB - */ - final AABB aabb = new AABB(); + /// Enlarged AABB + final AABB aabb = AABB(); Object userData; diff --git a/lib/src/collision/broadphase/pair.dart b/lib/src/collision/broadphase/pair.dart index 90a5906..fb4b20a 100644 --- a/lib/src/collision/broadphase/pair.dart +++ b/lib/src/collision/broadphase/pair.dart @@ -1,33 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Java note: at the "creation" of each node, a random key is given to that node, and that's what we - * sort from. - */ +/// Java note: at the "creation" of each node, a random key is given to that node, and that's what we +/// sort from. class Pair implements Comparable { int proxyIdA = 0; int proxyIdB = 0; diff --git a/lib/src/collision/collision.dart b/lib/src/collision/collision.dart index d7bddf7..a35bfae 100644 --- a/lib/src/collision/collision.dart +++ b/lib/src/collision/collision.dart @@ -1,43 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Java-specific class for returning edge results - */ +/// Java-specific class for returning edge results class _EdgeResults { double separation = 0.0; int edgeIndex = 0; } -/** - * Used for computing contact manifolds. - */ +/// Used for computing contact manifolds. class ClipVertex { - final Vector2 v = new Vector2.zero(); - final ContactID id = new ContactID(); + final Vector2 v = Vector2.zero(); + final ContactID id = ContactID(); void set(final ClipVertex cv) { Vector2 v1 = cv.v; @@ -51,33 +23,22 @@ class ClipVertex { } } -/** - * This is used for determining the state of contact points. - * - * @author Daniel Murphy - */ +/// This is used for determining the state of contact points. enum PointState { - /** - * point does not exist - */ + /// point does not exist NULL_STATE, - /** - * point was added in the update - */ + + /// point was added in the update ADD_STATE, - /** - * point persisted across the update - */ + + /// point persisted across the update PERSIST_STATE, - /** - * point was removed in the update - */ + + /// point was removed in the update REMOVE_STATE } -/** - * This structure is used to keep track of the best separating axis. - */ +/// This structure is used to keep track of the best separating axis. enum EPAxisType { UNKNOWN, EDGE_A, EDGE_B } @@ -87,70 +48,54 @@ class EPAxis { double separation = 0.0; } -/** - * This holds polygon B expressed in frame A. - */ +/// This holds polygon B expressed in frame A. class TempPolygon { - final List vertices = new List(Settings.maxPolygonVertices); - final List normals = new List(Settings.maxPolygonVertices); + final List vertices = List(Settings.maxPolygonVertices); + final List normals = List(Settings.maxPolygonVertices); int count = 0; TempPolygon() { for (int i = 0; i < vertices.length; i++) { - vertices[i] = new Vector2.zero(); - normals[i] = new Vector2.zero(); + vertices[i] = Vector2.zero(); + normals[i] = Vector2.zero(); } } } -/** - * Reference face used for clipping - */ +/// Reference face used for clipping class _ReferenceFace { int i1 = 0, i2 = 0; - final Vector2 v1 = new Vector2.zero(); - final Vector2 v2 = new Vector2.zero(); - final Vector2 normal = new Vector2.zero(); + final Vector2 v1 = Vector2.zero(); + final Vector2 v2 = Vector2.zero(); + final Vector2 normal = Vector2.zero(); - final Vector2 sideNormal1 = new Vector2.zero(); + final Vector2 sideNormal1 = Vector2.zero(); double sideOffset1 = 0.0; - final Vector2 sideNormal2 = new Vector2.zero(); + final Vector2 sideNormal2 = Vector2.zero(); double sideOffset2 = 0.0; } -/** - * Functions used for computing contact points, distance queries, and TOI queries. Collision methods - * are non-static for pooling speed, retrieve a collision object from the {@link SingletonPool}. - * Should not be finalructed. - */ +/// Functions used for computing contact points, distance queries, and TOI queries. Collision methods +/// are non-static for pooling speed, retrieve a collision object from the {@link SingletonPool}. +/// Should not be finalructed. class Collision { static const int NULL_FEATURE = 0x3FFFFFFF; // Integer.MAX_VALUE; - final IWorldPool _pool; - - Collision(this._pool) { - _incidentEdge[0] = new ClipVertex(); - _incidentEdge[1] = new ClipVertex(); - _clipPoints1[0] = new ClipVertex(); - _clipPoints1[1] = new ClipVertex(); - _clipPoints2[0] = new ClipVertex(); - _clipPoints2[1] = new ClipVertex(); + Collision() { + _incidentEdge[0] = ClipVertex(); + _incidentEdge[1] = ClipVertex(); + _clipPoints1[0] = ClipVertex(); + _clipPoints1[1] = ClipVertex(); + _clipPoints2[0] = ClipVertex(); + _clipPoints2[1] = ClipVertex(); } - final DistanceInput _input = new DistanceInput(); - final SimplexCache _cache = new SimplexCache(); - final DistanceOutput _output = new DistanceOutput(); - - /** - * Determine if two generic shapes overlap. - * - * @param shapeA - * @param shapeB - * @param xfA - * @param xfB - * @return - */ + final DistanceInput _input = DistanceInput(); + final SimplexCache _cache = SimplexCache(); + final DistanceOutput _output = DistanceOutput(); + + /// Determine if two generic shapes overlap. bool testOverlap(Shape shapeA, int indexA, Shape shapeB, int indexB, Transform xfA, Transform xfB) { _input.proxyA.set(shapeA, indexA); @@ -161,21 +106,14 @@ class Collision { _cache.count = 0; - _pool.getDistance().distance(_output, _cache, _input); + World.distance.compute(_output, _cache, _input); // djm note: anything significant about 10.0f? return _output.distance < 10.0 * Settings.EPSILON; } - /** - * Compute the point states given two manifolds. The states pertain to the transition from - * manifold1 to manifold2. So state1 is either persist or remove while state2 is either add or - * persist. - * - * @param state1 - * @param state2 - * @param manifold1 - * @param manifold2 - */ + /// Compute the point states given two manifolds. The states pertain to the transition from + /// manifold1 to manifold2. So state1 is either persist or remove while state2 is either add or + /// persist. static void getPointStates( final List state1, final List state2, @@ -215,15 +153,7 @@ class Collision { } } - /** - * Clipping for contact manifolds. Sutherland-Hodgman clipping. - * - * @param vOut - * @param vIn - * @param normal - * @param offset - * @return - */ + /// Clipping for contact manifolds. Sutherland-Hodgman clipping. static int clipSegmentToLine( final List vOut, final List vIn, @@ -273,29 +203,16 @@ class Collision { // #### COLLISION STUFF (not from collision.h or collision.cpp) #### // djm pooling - static Vector2 _d = new Vector2.zero(); - - /** - * Compute the collision manifold between two circles. - * - * @param manifold - * @param circle1 - * @param xfA - * @param circle2 - * @param xfB - */ + static Vector2 _d = Vector2.zero(); + + /// Compute the collision manifold between two circles. void collideCircles(Manifold manifold, final CircleShape circle1, final Transform xfA, final CircleShape circle2, final Transform xfB) { manifold.pointCount = 0; - // before inline: - // Transform.mulToOut(xfA, circle1.p, pA); - // Transform.mulToOut(xfB, circle2.p, pB); - // d.set(pB).subLocal(pA); - // double distSqr = d.x * d.x + d.y * d.y; // after inline: - Vector2 circle1p = circle1.p; - Vector2 circle2p = circle2.p; + Vector2 circle1p = circle1.position; + Vector2 circle2p = circle2.position; double pAx = (xfA.q.c * circle1p.x - xfA.q.s * circle1p.y) + xfA.p.x; double pAy = (xfA.q.s * circle1p.x + xfA.q.c * circle1p.y) + xfA.p.y; double pBx = (xfB.q.c * circle2p.x - xfB.q.s * circle2p.y) + xfB.p.x; @@ -321,15 +238,7 @@ class Collision { // djm pooling, and from above - /** - * Compute the collision manifold between a polygon and a circle. - * - * @param manifold - * @param polygon - * @param xfA - * @param circle - * @param xfB - */ + /// Compute the collision manifold between a polygon and a circle. void collidePolygonAndCircle(Manifold manifold, final PolygonShape polygon, final Transform xfA, final CircleShape circle, final Transform xfB) { manifold.pointCount = 0; @@ -341,8 +250,9 @@ class Collision { // Transform.mulTransToOut(xfA, c, cLocal); // final double cLocalx = cLocal.x; // final double cLocaly = cLocal.y; + // after inline: - final Vector2 circlep = circle.p; + final Vector2 circlep = circle.position; final Rot xfBq = xfB.q; final Rot xfAq = xfA.q; final double cx = (xfBq.c * circlep.x - xfBq.s * circlep.y) + xfB.p.x; @@ -355,7 +265,7 @@ class Collision { // Find the min separating edge. int normalIndex = 0; - double separation = -double.MAX_FINITE; + double separation = -double.maxFinite; final double radius = polygon.radius + circle.radius; final int vertexCount = polygon.count; double s; @@ -394,11 +304,6 @@ class Collision { manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; - // before inline: - // manifold._localNormal.set(normals[normalIndex]); - // manifold.localPoint.set(v1).addLocal(v2).mulLocal(.5f); - // manifold.points[0].localPoint.set(circle.p); - // after inline: final Vector2 normal = normals[normalIndex]; manifold.localNormal.x = normal.x; manifold.localNormal.y = normal.y; @@ -414,14 +319,6 @@ class Collision { } // Compute barycentric coordinates - // before inline: - // temp.set(cLocal).subLocal(v1); - // temp2.set(v2).subLocal(v1); - // double u1 = Vec2.dot(temp, temp2); - // temp.set(cLocal).subLocal(v2); - // temp2.set(v1).subLocal(v2); - // double u2 = Vec2.dot(temp, temp2); - // after inline: final double tempX = cLocalx - v1.x; final double tempY = cLocaly - v1.y; final double temp2X = v2.x - v1.x; @@ -433,10 +330,8 @@ class Collision { final double temp4X = v1.x - v2.x; final double temp4Y = v1.y - v2.y; final double u2 = temp3X * temp4X + temp3Y * temp4Y; - // end inline if (u1 <= 0.0) { - // inlined final double dx = cLocalx - v1.x; final double dy = cLocaly - v1.y; if (dx * dx + dy * dy > radius * radius) { @@ -445,18 +340,13 @@ class Collision { manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; - // before inline: - // manifold._localNormal.set(cLocal).subLocal(v1); - // after inline: manifold.localNormal.x = cLocalx - v1.x; manifold.localNormal.y = cLocaly - v1.y; - // end inline manifold.localNormal.normalize(); manifold.localPoint.setFrom(v1); manifold.points[0].localPoint.setFrom(circlep); manifold.points[0].id.zero(); } else if (u2 <= 0.0) { - // inlined final double dx = cLocalx - v2.x; final double dy = cLocaly - v2.y; if (dx * dx + dy * dy > radius * radius) { @@ -465,28 +355,13 @@ class Collision { manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; - // before inline: - // manifold._localNormal.set(cLocal).subLocal(v2); - // after inline: manifold.localNormal.x = cLocalx - v2.x; manifold.localNormal.y = cLocaly - v2.y; - // end inline manifold.localNormal.normalize(); manifold.localPoint.setFrom(v2); manifold.points[0].localPoint.setFrom(circlep); manifold.points[0].id.zero(); } else { - // Vec2 faceCenter = 0.5f * (v1 + v2); - // (temp is faceCenter) - // before inline: - // temp.set(v1).addLocal(v2).mulLocal(.5f); - // - // temp2.set(cLocal).subLocal(temp); - // separation = Vec2.dot(temp2, normals[vertIndex1]); - // if (separation > radius) { - // return; - // } - // after inline: final double fcx = (v1.x + v2.x) * .5; final double fcy = (v1.y + v2.y) * .5; @@ -497,7 +372,6 @@ class Collision { if (separation > radius) { return; } - // end inline manifold.pointCount = 1; manifold.type = ManifoldType.FACE_A; @@ -510,21 +384,12 @@ class Collision { } // djm pooling, and from above - final Vector2 _temp = new Vector2.zero(); - final Transform _xf = new Transform.zero(); - final Vector2 _n = new Vector2.zero(); - final Vector2 _v1 = new Vector2.zero(); - - /** - * Find the max separation between poly1 and poly2 using edge normals from poly1. - * - * @param edgeIndex - * @param poly1 - * @param xf1 - * @param poly2 - * @param xf2 - * @return - */ + final Vector2 _temp = Vector2.zero(); + final Transform _xf = Transform.zero(); + final Vector2 _n = Vector2.zero(); + final Vector2 _v1 = Vector2.zero(); + + /// Find the max separation between poly1 and poly2 using edge normals from poly1. void findMaxSeparation(_EdgeResults results, final PolygonShape poly1, final Transform xf1, final PolygonShape poly2, final Transform xf2) { int count1 = poly1.count; @@ -533,18 +398,18 @@ class Collision { List v1s = poly1.vertices; List v2s = poly2.vertices; - Transform.mulTransToOutUnsafe(xf2, xf1, _xf); + _xf.set(Transform.mulTrans(xf2, xf1)); final Rot xfq = _xf.q; int bestIndex = 0; - double maxSeparation = -double.MAX_FINITE; + double maxSeparation = -double.maxFinite; for (int i = 0; i < count1; i++) { // Get poly1 normal in frame2. - Rot.mulToOutUnsafe(xfq, n1s[i], _n); - Transform.mulToOutUnsafeVec2(_xf, v1s[i], _v1); + _n.setFrom(Rot.mulVec2(xfq, n1s[i])); + _v1.setFrom(Transform.mulVec2(_xf, v1s[i])); // Find deepest point for normal i. - double si = double.MAX_FINITE; + double si = double.maxFinite; for (int j = 0; j < count2; ++j) { Vector2 v2sj = v2s[j]; double sij = _n.x * (v2sj.x - _v1.x) + _n.y * (v2sj.y - _v1.y); @@ -585,22 +450,15 @@ class Collision { final Rot xf2q = xf2.q; // Get the normal of the reference edge in poly2's frame. - // Vec2 normal1 = MulT(xf2.R, Mul(xf1.R, normals1[edge1])); - // before inline: - // Rot.mulToOutUnsafe(xf1.q, normals1[edge1], normal1); // temporary - // Rot.mulTrans(xf2.q, normal1, normal1); - // after inline: final Vector2 v = normals1[edge1]; final double tempx = xf1q.c * v.x - xf1q.s * v.y; final double tempy = xf1q.s * v.x + xf1q.c * v.y; final double normal1x = xf2q.c * tempx + xf2q.s * tempy; final double normal1y = -xf2q.s * tempx + xf2q.c * tempy; - // end inline - // Find the incident edge on poly2. int index = 0; - double minDot = double.MAX_FINITE; + double minDot = double.maxFinite; for (int i = 0; i < count2; ++i) { Vector2 b = normals2[i]; double dot = normal1x * b.x + normal1y * b.y; @@ -614,7 +472,6 @@ class Collision { int i1 = index; int i2 = i1 + 1 < count2 ? i1 + 1 : 0; - // c0.v = Mul(xf2, vertices2[i1]); Vector2 v1 = vertices2[i1]; Vector2 out = c0.v; out.x = (xf2q.c * v1.x - xf2q.s * v1.y) + xf2.p.x; @@ -624,7 +481,6 @@ class Collision { c0.id.typeA = ContactIDType.FACE.index & 0xFF; c0.id.typeB = ContactIDType.VERTEX.index & 0xFF; - // c1.v = Mul(xf2, vertices2[i2]); Vector2 v2 = vertices2[i2]; Vector2 out1 = c1.v; out1.x = (xf2q.c * v2.x - xf2q.s * v2.y) + xf2.p.x; @@ -635,27 +491,19 @@ class Collision { c1.id.typeB = ContactIDType.VERTEX.index & 0xFF; } - final _EdgeResults _results1 = new _EdgeResults(); - final _EdgeResults results2 = new _EdgeResults(); - final List _incidentEdge = new List(2); - final Vector2 _localTangent = new Vector2.zero(); - final Vector2 _localNormal = new Vector2.zero(); - final Vector2 _planePoint = new Vector2.zero(); - final Vector2 _tangent = new Vector2.zero(); - final Vector2 _v11 = new Vector2.zero(); - final Vector2 _v12 = new Vector2.zero(); - final List _clipPoints1 = new List(2); - final List _clipPoints2 = new List(2); - - /** - * Compute the collision manifold between two polygons. - * - * @param manifold - * @param polygon1 - * @param xf1 - * @param polygon2 - * @param xf2 - */ + final _EdgeResults _results1 = _EdgeResults(); + final _EdgeResults results2 = _EdgeResults(); + final List _incidentEdge = List(2); + final Vector2 _localTangent = Vector2.zero(); + final Vector2 _localNormal = Vector2.zero(); + final Vector2 _planePoint = Vector2.zero(); + final Vector2 _tangent = Vector2.zero(); + final Vector2 _v11 = Vector2.zero(); + final Vector2 _v12 = Vector2.zero(); + final List _clipPoints1 = List(2); + final List _clipPoints2 = List(2); + + /// Compute the collision manifold between two polygons. void collidePolygons(Manifold manifold, final PolygonShape polyA, final Transform xfA, final PolygonShape polyB, final Transform xfB) { // Find edge normal of max separation on A - return if separating axis is found @@ -718,46 +566,34 @@ class Collision { _localTangent.y = _v12.y - _v11.y; _localTangent.normalize(); - // Vec2 _localNormal = Vec2.cross(dv, 1.0f); _localNormal.x = 1.0 * _localTangent.y; _localNormal.y = -1.0 * _localTangent.x; - // Vec2 _planePoint = 0.5f * (_v11+ _v12); _planePoint.x = (_v11.x + _v12.x) * .5; _planePoint.y = (_v11.y + _v12.y) * .5; - // Rot.mulToOutUnsafe(xf1.q, _localTangent, _tangent); _tangent.x = xf1q.c * _localTangent.x - xf1q.s * _localTangent.y; _tangent.y = xf1q.s * _localTangent.x + xf1q.c * _localTangent.y; - // Vec2.crossToOutUnsafe(_tangent, 1f, normal); final double normalx = 1.0 * _tangent.y; final double normaly = -1.0 * _tangent.x; - Transform.mulToOutVec2(xf1, _v11, _v11); - Transform.mulToOutVec2(xf1, _v12, _v12); - // _v11 = Mul(xf1, _v11); - // _v12 = Mul(xf1, _v12); + _v11.setFrom(Transform.mulVec2(xf1, _v11)); + _v12.setFrom(Transform.mulVec2(xf1, _v12)); // Face offset - // double frontOffset = Vec2.dot(normal, _v11); double frontOffset = normalx * _v11.x + normaly * _v11.y; // Side offsets, extended by polytope skin thickness. - // double sideOffset1 = -Vec2.dot(_tangent, _v11) + totalRadius; - // double sideOffset2 = Vec2.dot(_tangent, _v12) + totalRadius; double sideOffset1 = -(_tangent.x * _v11.x + _tangent.y * _v11.y) + totalRadius; double sideOffset2 = _tangent.x * _v12.x + _tangent.y * _v12.y + totalRadius; // Clip incident edge against extruded edge1 side edges. - // ClipVertex _clipPoints1[2]; - // ClipVertex _clipPoints2[2]; int np; // Clip to box side 1 - // np = ClipSegmentToLine(_clipPoints1, _incidentEdge, -sideNormal, sideOffset1); _tangent.negate(); np = clipSegmentToLine( _clipPoints1, _incidentEdge, _tangent, sideOffset1, iv1); @@ -781,14 +617,12 @@ class Collision { int pointCount = 0; for (int i = 0; i < Settings.maxManifoldPoints; ++i) { - // double separation = Vec2.dot(normal, _clipPoints2[i].v) - frontOffset; double separation = normalx * _clipPoints2[i].v.x + normaly * _clipPoints2[i].v.y - frontOffset; if (separation <= totalRadius) { ManifoldPoint cp = manifold.points[pointCount]; - // cp.localPoint = MulT(xf2, _clipPoints2[i].v); Vector2 out = cp.localPoint; final double px = _clipPoints2[i].v.x - xf2.p.x; final double py = _clipPoints2[i].v.y - xf2.p.y; @@ -806,11 +640,11 @@ class Collision { manifold.pointCount = pointCount; } - final Vector2 _Q = new Vector2.zero(); - final Vector2 _e = new Vector2.zero(); - final ContactID _cf = new ContactID(); - final Vector2 _e1 = new Vector2.zero(); - final Vector2 _P = new Vector2.zero(); + final Vector2 _q = Vector2.zero(); + final Vector2 _e = Vector2.zero(); + final ContactID _cf = ContactID(); + final Vector2 _e1 = Vector2.zero(); + final Vector2 _p = Vector2.zero(); // Compute contact points for edge versus circle. // This accounts for edge connectivity. @@ -820,8 +654,8 @@ class Collision { // Compute circle in frame of edge // Vec2 Q = MulT(xfA, Mul(xfB, circleB.p)); - Transform.mulToOutUnsafeVec2(xfB, circleB.p, _temp); - Transform.mulTransToOutUnsafeVec2(xfA, _temp, _Q); + _temp.setFrom(Transform.mulVec2(xfB, circleB.position)); + _q.setFrom(Transform.mulTransVec2(xfA, _temp)); final Vector2 A = edgeA.vertex1; final Vector2 B = edgeA.vertex2; @@ -832,14 +666,13 @@ class Collision { // Barycentric coordinates double u = _e.dot(_temp ..setFrom(B) - ..sub(_Q)); + ..sub(_q)); double v = _e.dot(_temp - ..setFrom(_Q) + ..setFrom(_q) ..sub(A)); double radius = edgeA.radius + circleB.radius; - // ContactFeature cf; _cf.indexB = 0; _cf.typeB = ContactIDType.VERTEX.index & 0xFF; @@ -847,7 +680,7 @@ class Collision { if (v <= 0.0) { final Vector2 P = A; _d - ..setFrom(_Q) + ..setFrom(_q) ..sub(P); double dd = _d.dot(_d); if (dd > radius * radius) { @@ -863,7 +696,7 @@ class Collision { ..sub(A1); double u1 = _e1.dot(_temp ..setFrom(B1) - ..sub(_Q)); + ..sub(_q)); // Is the circle in Region AB of the previous edge? if (u1 > 0.0) { @@ -879,7 +712,7 @@ class Collision { manifold.localPoint.setFrom(P); // manifold.points[0].id.key = 0; manifold.points[0].id.set(_cf); - manifold.points[0].localPoint.setFrom(circleB.p); + manifold.points[0].localPoint.setFrom(circleB.position); return; } @@ -887,7 +720,7 @@ class Collision { if (u <= 0.0) { Vector2 P = B; _d - ..setFrom(_Q) + ..setFrom(_q) ..sub(P); double dd = _d.dot(_d); if (dd > radius * radius) { @@ -903,7 +736,7 @@ class Collision { ..setFrom(B2) ..sub(A2); double v2 = e2.dot(_temp - ..setFrom(_Q) + ..setFrom(_q) ..sub(A2)); // Is the circle in Region AB of the next edge? @@ -918,9 +751,8 @@ class Collision { manifold.type = ManifoldType.CIRCLES; manifold.localNormal.setZero(); manifold.localPoint.setFrom(P); - // manifold.points[0].id.key = 0; manifold.points[0].id.set(_cf); - manifold.points[0].localPoint.setFrom(circleB.p); + manifold.points[0].localPoint.setFrom(circleB.position); return; } @@ -929,16 +761,16 @@ class Collision { assert(den > 0.0); // Vec2 P = (1.0f / den) * (u * A + v * B); - _P + _p ..setFrom(A) ..scale(u) ..add(_temp ..setFrom(B) ..scale(v)); - _P.scale(1.0 / den); + _p.scale(1.0 / den); _d - ..setFrom(_Q) - ..sub(_P); + ..setFrom(_q) + ..sub(_p); double dd = _d.dot(_d); if (dd > radius * radius) { return; @@ -947,7 +779,7 @@ class Collision { _n.x = -_e.y; _n.y = _e.x; if (_n.dot(_temp - ..setFrom(_Q) + ..setFrom(_q) ..sub(A)) < 0.0) { _n.setValues(-_n.x, -_n.y); @@ -962,67 +794,65 @@ class Collision { manifold.localPoint.setFrom(A); // manifold.points[0].id.key = 0; manifold.points[0].id.set(_cf); - manifold.points[0].localPoint.setFrom(circleB.p); + manifold.points[0].localPoint.setFrom(circleB.position); } - final EPCollider _collider = new EPCollider(); + final EPCollider _collider = EPCollider(); void collideEdgeAndPolygon(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB, final Transform xfB) { _collider.collide(manifold, edgeA, xfA, polygonB, xfB); } - /** - * This class collides and edge and a polygon, taking into account edge adjacency. - */ + /// This class collides and edge and a polygon, taking into account edge adjacency. } enum VertexType { ISOLATED, CONCAVE, CONVEX } class EPCollider { - final TempPolygon polygonB = new TempPolygon(); - - final Transform xf = new Transform.zero(); - final Vector2 centroidB = new Vector2.zero(); - Vector2 v0 = new Vector2.zero(); - Vector2 v1 = new Vector2.zero(); - Vector2 v2 = new Vector2.zero(); - Vector2 v3 = new Vector2.zero(); - final Vector2 normal0 = new Vector2.zero(); - final Vector2 normal1 = new Vector2.zero(); - final Vector2 normal2 = new Vector2.zero(); - final Vector2 normal = new Vector2.zero(); + final TempPolygon polygonB = TempPolygon(); + + final Transform xf = Transform.zero(); + final Vector2 centroidB = Vector2.zero(); + Vector2 v0 = Vector2.zero(); + Vector2 v1 = Vector2.zero(); + Vector2 v2 = Vector2.zero(); + Vector2 v3 = Vector2.zero(); + final Vector2 normal0 = Vector2.zero(); + final Vector2 normal1 = Vector2.zero(); + final Vector2 normal2 = Vector2.zero(); + final Vector2 normal = Vector2.zero(); VertexType type1 = VertexType.ISOLATED, type2 = VertexType.ISOLATED; - final Vector2 lowerLimit = new Vector2.zero(); - final Vector2 upperLimit = new Vector2.zero(); + final Vector2 lowerLimit = Vector2.zero(); + final Vector2 upperLimit = Vector2.zero(); double radius = 0.0; bool front = false; EPCollider() { for (int i = 0; i < 2; i++) { - _ie[i] = new ClipVertex(); - _clipPoints1[i] = new ClipVertex(); - _clipPoints2[i] = new ClipVertex(); + _ie[i] = ClipVertex(); + _clipPoints1[i] = ClipVertex(); + _clipPoints2[i] = ClipVertex(); } } - final Vector2 _edge1 = new Vector2.zero(); - final Vector2 _temp = new Vector2.zero(); - final Vector2 _edge0 = new Vector2.zero(); - final Vector2 _edge2 = new Vector2.zero(); - final List _ie = new List(2); - final List _clipPoints1 = new List(2); - final List _clipPoints2 = new List(2); - final _ReferenceFace _rf = new _ReferenceFace(); - final EPAxis _edgeAxis = new EPAxis(); - final EPAxis _polygonAxis = new EPAxis(); + final Vector2 _edge1 = Vector2.zero(); + final Vector2 _temp = Vector2.zero(); + final Vector2 _edge0 = Vector2.zero(); + final Vector2 _edge2 = Vector2.zero(); + final List _ie = List(2); + final List _clipPoints1 = List(2); + final List _clipPoints2 = List(2); + final _ReferenceFace _rf = _ReferenceFace(); + final EPAxis _edgeAxis = EPAxis(); + final EPAxis _polygonAxis = EPAxis(); void collide(Manifold manifold, final EdgeShape edgeA, final Transform xfA, final PolygonShape polygonB_, final Transform xfB) { - Transform.mulTransToOutUnsafe(xfA, xfB, xf); - Transform.mulToOutUnsafeVec2(xf, polygonB_.centroid, centroidB); + xf.set(Transform.mulTrans(xfA, xfB)); + centroidB.setFrom(Transform.mulVec2(xf, polygonB_.centroid)); v0 = edgeA.vertex0; v1 = edgeA.vertex1; @@ -1234,9 +1064,9 @@ class EPCollider { // Get polygonB in frameA polygonB.count = polygonB_.count; for (int i = 0; i < polygonB_.count; ++i) { - Transform.mulToOutUnsafeVec2( - xf, polygonB_.vertices[i], polygonB.vertices[i]); - Rot.mulToOutUnsafe(xf.q, polygonB_.normals[i], polygonB.normals[i]); + polygonB.vertices[i] + .setFrom(Transform.mulVec2(xf, polygonB_.vertices[i])); + polygonB.normals[i].setFrom(Rot.mulVec2(xf.q, polygonB_.normals[i])); } radius = 2.0 * Settings.polygonRadius; @@ -1390,9 +1220,7 @@ class EPCollider { ManifoldPoint cp = manifold.points[pointCount]; if (primaryAxis.type == EPAxisType.EDGE_A) { - // cp.localPoint = MulT(xf, _clipPoints2[i].v); - Transform.mulTransToOutUnsafeVec2( - xf, _clipPoints2[i].v, cp.localPoint); + cp.localPoint.setFrom(Transform.mulTransVec2(xf, _clipPoints2[i].v)); cp.id.set(_clipPoints2[i].id); } else { cp.localPoint.setFrom(_clipPoints2[i].v); @@ -1412,7 +1240,7 @@ class EPCollider { void computeEdgeSeparation(EPAxis axis) { axis.type = EPAxisType.EDGE_A; axis.index = front ? 0 : 1; - axis.separation = double.MAX_FINITE; + axis.separation = double.maxFinite; double nx = normal.x; double ny = normal.y; @@ -1427,13 +1255,13 @@ class EPCollider { } } - final Vector2 _perp = new Vector2.zero(); - final Vector2 _n = new Vector2.zero(); + final Vector2 _perp = Vector2.zero(); + final Vector2 _n = Vector2.zero(); void computePolygonSeparation(EPAxis axis) { axis.type = EPAxisType.UNKNOWN; axis.index = -1; - axis.separation = -double.MAX_FINITE; + axis.separation = -double.maxFinite; _perp.x = -normal.y; _perp.y = normal.x; diff --git a/lib/src/collision/contactid.dart b/lib/src/collision/contactid.dart index 4b3d5eb..e48f72e 100644 --- a/lib/src/collision/contactid.dart +++ b/lib/src/collision/contactid.dart @@ -1,33 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; enum ContactIDType { VERTEX, FACE } class ContactID implements Comparable { - Int8List _data = new Int8List(4); + Int8List _data = Int8List(4); void set indexA(int v) { _data[0] = v; @@ -81,9 +57,7 @@ class ContactID implements Comparable { typeB = tempA; } - /** - * zeros out the data - */ + /// zeros out the data void zero() { indexA = 0; indexB = 0; diff --git a/lib/src/collision/distance.dart b/lib/src/collision/distance.dart index 5a6d3d1..7c7da90 100644 --- a/lib/src/collision/distance.dart +++ b/lib/src/collision/distance.dart @@ -1,36 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. - */ +/// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. class _SimplexVertex { - final Vector2 wA = new Vector2.zero(); // support point in shapeA - final Vector2 wB = new Vector2.zero(); // support point in shapeB - final Vector2 w = new Vector2.zero(); // wB - wA + final Vector2 wA = Vector2.zero(); // support point in shapeA + final Vector2 wB = Vector2.zero(); // support point in shapeB + final Vector2 w = Vector2.zero(); // wB - wA double a = 0.0; // barycentric coordinate for closest point int indexA = 0; // wA index int indexB = 0; // wB index @@ -46,13 +20,15 @@ class _SimplexVertex { } class SimplexCache { - /** length or area */ + /// length or area double metric = 0.0; int count = 0; - /** vertices on shape A */ - final List indexA = BufferUtils.allocClearIntList(3); - /** vertices on shape B */ - final List indexB = BufferUtils.allocClearIntList(3); + + /// vertices on shape A + final List indexA = BufferUtils.intList(3); + + /// vertices on shape B + final List indexB = BufferUtils.intList(3); SimplexCache() { indexA[0] = Settings.INTEGER_MAX_VALUE; @@ -64,18 +40,18 @@ class SimplexCache { } void set(SimplexCache sc) { - BufferUtils.arraycopy(sc.indexA, 0, indexA, 0, indexA.length); - BufferUtils.arraycopy(sc.indexB, 0, indexB, 0, indexB.length); + BufferUtils.arrayCopy(sc.indexA, 0, indexA, 0, indexA.length); + BufferUtils.arrayCopy(sc.indexB, 0, indexB, 0, indexB.length); metric = sc.metric; count = sc.count; } } class _Simplex { - final _SimplexVertex v1 = new _SimplexVertex(); - final _SimplexVertex v2 = new _SimplexVertex(); - final _SimplexVertex v3 = new _SimplexVertex(); - final List<_SimplexVertex> vertices = new List<_SimplexVertex>(3); + final _SimplexVertex v1 = _SimplexVertex(); + final _SimplexVertex v2 = _SimplexVertex(); + final _SimplexVertex v3 = _SimplexVertex(); + final List<_SimplexVertex> vertices = List<_SimplexVertex>(3); int count = 0; _Simplex() { @@ -97,8 +73,8 @@ class _Simplex { v.indexB = cache.indexB[i]; Vector2 wALocal = proxyA.getVertex(v.indexA); Vector2 wBLocal = proxyB.getVertex(v.indexB); - Transform.mulToOutUnsafeVec2(transformA, wALocal, v.wA); - Transform.mulToOutUnsafeVec2(transformB, wBLocal, v.wB); + v.wA.setFrom(Transform.mulVec2(transformA, wALocal)); + v.wB.setFrom(Transform.mulVec2(transformB, wBLocal)); v.w ..setFrom(v.wB) ..sub(v.wA); @@ -125,8 +101,8 @@ class _Simplex { v.indexB = 0; Vector2 wALocal = proxyA.getVertex(0); Vector2 wBLocal = proxyB.getVertex(0); - Transform.mulToOutUnsafeVec2(transformA, wALocal, v.wA); - Transform.mulToOutUnsafeVec2(transformB, wBLocal, v.wB); + v.wA.setFrom(Transform.mulVec2(transformA, wALocal)); + v.wB.setFrom(Transform.mulVec2(transformB, wBLocal)); v.w ..setFrom(v.wB) ..sub(v.wA); @@ -144,7 +120,7 @@ class _Simplex { } } - final Vector2 _e12 = new Vector2.zero(); + final Vector2 _e12 = Vector2.zero(); void getSearchDirection(final Vector2 out) { switch (count) { @@ -179,14 +155,10 @@ class _Simplex { } // djm pooled - final Vector2 _case2 = new Vector2.zero(); - final Vector2 _case22 = new Vector2.zero(); - - /** - * this returns pooled objects. don't keep or modify them - * - * @return - */ + final Vector2 _case2 = Vector2.zero(); + final Vector2 _case22 = Vector2.zero(); + + /// This returns pooled objects. don't keep or modify them void getClosestPoint(final Vector2 out) { switch (count) { case 0: @@ -217,8 +189,8 @@ class _Simplex { } // djm pooled, and from above - final Vector2 _case3 = new Vector2.zero(); - final Vector2 _case33 = new Vector2.zero(); + final Vector2 _case3 = Vector2.zero(); + final Vector2 _case33 = Vector2.zero(); void getWitnessPoints(Vector2 pA, Vector2 pB) { switch (count) { @@ -303,9 +275,7 @@ class _Simplex { } // djm pooled from above - /** - * Solve a line segment using barycentric coordinates. - */ + /// Solve a line segment using barycentric coordinates. void solve2() { // Solve a line segment using barycentric coordinates. // @@ -363,20 +333,18 @@ class _Simplex { } // djm pooled, and from above - final Vector2 _e13 = new Vector2.zero(); - final Vector2 _e23 = new Vector2.zero(); - final Vector2 _w1 = new Vector2.zero(); - final Vector2 _w2 = new Vector2.zero(); - final Vector2 _w3 = new Vector2.zero(); - - /** - * Solve a line segment using barycentric coordinates.
- * Possible regions:
- * - points[2]
- * - edge points[0]-points[2]
- * - edge points[1]-points[2]
- * - inside the triangle - */ + final Vector2 _e13 = Vector2.zero(); + final Vector2 _e23 = Vector2.zero(); + final Vector2 _w1 = Vector2.zero(); + final Vector2 _w2 = Vector2.zero(); + final Vector2 _w3 = Vector2.zero(); + + /// Solve a line segment using barycentric coordinates.
+ /// Possible regions:
+ /// - points[2]
+ /// - edge points[0]-points[2]
+ /// - edge points[1]-points[2]
+ /// - inside the triangle void solve3() { _w1.setFrom(v1.w); _w2.setFrom(v2.w); @@ -493,24 +461,22 @@ class DistanceProxy { final List buffer; DistanceProxy() - : vertices = new List(Settings.maxPolygonVertices), - buffer = new List(2) { + : vertices = List(Settings.maxPolygonVertices), + buffer = List(2) { for (int i = 0; i < vertices.length; i++) { - vertices[i] = new Vector2.zero(); + vertices[i] = Vector2.zero(); } _count = 0; radius = 0.0; } - /** - * Initialize the proxy using the given shape. The shape must remain in scope while the proxy is - * in use. - */ + /// Initialize the proxy using the given shape. The shape must remain in scope while the proxy is + /// in use. void set(final Shape shape, int index) { switch (shape.shapeType) { case ShapeType.CIRCLE: final circle = shape as CircleShape; - vertices[0].setFrom(circle.p); + vertices[0].setFrom(circle.position); _count = 1; radius = circle.radius; @@ -551,12 +517,7 @@ class DistanceProxy { } } - /** - * Get the supporting vertex index in the given direction. - * - * @param d - * @return - */ + /// Get the supporting vertex index in the given direction. int getSupport(final Vector2 d) { int bestIndex = 0; double bestValue = vertices[0].dot(d); @@ -571,12 +532,7 @@ class DistanceProxy { return bestIndex; } - /** - * Get the supporting vertex in the given direction. - * - * @param d - * @return - */ + /// Get the supporting vertex in the given direction. Vector2 getSupportVertex(final Vector2 d) { int bestIndex = 0; double bestValue = vertices[0].dot(d); @@ -591,21 +547,12 @@ class DistanceProxy { return vertices[bestIndex]; } - /** - * Get the vertex count. - * - * @return - */ + /// Get the vertex count. int getVertexCount() { return _count; } - /** - * Get a vertex by index. Used by Distance. - * - * @param index - * @return - */ + /// Get a vertex by index. Used by Distance. Vector2 getVertex(int index) { assert(0 <= index && index < _count); return vertices[index]; @@ -619,24 +566,18 @@ class Distance { static int GJK_ITERS = 0; static int GJK_MAX_ITERS = 20; - final _Simplex _simplex = new _Simplex(); - final List _saveA = BufferUtils.allocClearIntList(3); - final List _saveB = BufferUtils.allocClearIntList(3); - final Vector2 _closestPoint = new Vector2.zero(); - final Vector2 _d = new Vector2.zero(); - final Vector2 _temp = new Vector2.zero(); - final Vector2 _normal = new Vector2.zero(); - - /** - * Compute the closest points between two shapes. Supports any combination of: CircleShape and - * PolygonShape. The simplex cache is input/output. On the first call set SimplexCache.count to - * zero. - * - * @param output - * @param cache - * @param input - */ - void distance(final DistanceOutput output, final SimplexCache cache, + final _Simplex _simplex = _Simplex(); + final List _saveA = BufferUtils.intList(3); + final List _saveB = BufferUtils.intList(3); + final Vector2 _closestPoint = Vector2.zero(); + final Vector2 _d = Vector2.zero(); + final Vector2 _temp = Vector2.zero(); + final Vector2 _normal = Vector2.zero(); + + /// Compute the closest points between two shapes. Supports any combination of: CircleShape and + /// PolygonShape. The simplex cache is input/output. On the first call set SimplexCache.count to + /// zero. + void compute(final DistanceOutput output, final SimplexCache cache, final DistanceInput input) { GJK_CALLS++; @@ -723,15 +664,15 @@ class Distance { // Compute a tentative new simplex vertex using support points. _SimplexVertex vertex = vertices[_simplex.count]; - Rot.mulTransUnsafeVec2(transformA.q, _d..negate(), _temp); + _temp.setFrom(Rot.mulTransVec2(transformA.q, _d..negate())); vertex.indexA = proxyA.getSupport(_temp); - Transform.mulToOutUnsafeVec2( - transformA, proxyA.getVertex(vertex.indexA), vertex.wA); + vertex.wA.setFrom( + Transform.mulVec2(transformA, proxyA.getVertex(vertex.indexA))); // Vec2 wBLocal; - Rot.mulTransUnsafeVec2(transformB.q, _d..negate(), _temp); + _temp.setFrom(Rot.mulTransVec2(transformB.q, _d..negate())); vertex.indexB = proxyB.getSupport(_temp); - Transform.mulToOutUnsafeVec2( - transformB, proxyB.getVertex(vertex.indexB), vertex.wB); + vertex.wB.setFrom( + Transform.mulVec2(transformB, proxyB.getVertex(vertex.indexB))); (vertex.w..setFrom(vertex.wB)).sub(vertex.wA); // Iteration count is equated to the number of support point calls. diff --git a/lib/src/collision/distance_input.dart b/lib/src/collision/distance_input.dart index 2c4e6cf..f39c649 100644 --- a/lib/src/collision/distance_input.dart +++ b/lib/src/collision/distance_input.dart @@ -1,39 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Input for Distance. - * You have to option to use the shape radii - * in the computation. - * - */ +/// Input for Distance. +/// You have to option to use the shape radii in the computation. class DistanceInput { - DistanceProxy proxyA = new DistanceProxy(); - DistanceProxy proxyB = new DistanceProxy(); - Transform transformA = new Transform.zero(); - Transform transformB = new Transform.zero(); + DistanceProxy proxyA = DistanceProxy(); + DistanceProxy proxyB = DistanceProxy(); + Transform transformA = Transform.zero(); + Transform transformB = Transform.zero(); bool useRadii = false; } diff --git a/lib/src/collision/distance_output.dart b/lib/src/collision/distance_output.dart index 989ebbd..d40b49d 100644 --- a/lib/src/collision/distance_output.dart +++ b/lib/src/collision/distance_output.dart @@ -1,41 +1,15 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Output for Distance. - */ +/// Output for Distance. class DistanceOutput { - /** Closest point on shapeA */ - final Vector2 pointA = new Vector2.zero(); + /// Closest point on shapeA + final Vector2 pointA = Vector2.zero(); - /** Closest point on shapeB */ - final Vector2 pointB = new Vector2.zero(); + /// Closest point on shapeB + final Vector2 pointB = Vector2.zero(); double distance = 0.0; - /** number of gjk iterations used */ + /// number of gjk iterations used int iterations = 0; } diff --git a/lib/src/collision/manifold.dart b/lib/src/collision/manifold.dart index 12816e1..346a1b7 100644 --- a/lib/src/collision/manifold.dart +++ b/lib/src/collision/manifold.dart @@ -1,103 +1,69 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A manifold for two touching convex shapes. Box2D supports multiple types of contact: - *
    - *
  • clip point versus plane with radius
  • - *
  • point versus point with radius (circles)
  • - *
- * The local point usage depends on the manifold type: - *
    - *
  • e_circles: the local center of circleA
  • - *
  • e_faceA: the center of faceA
  • - *
  • e_faceB: the center of faceB
  • - *
- * Similarly the local normal usage: - *
    - *
  • e_circles: not used
  • - *
  • e_faceA: the normal on polygonA
  • - *
  • e_faceB: the normal on polygonB
  • - *
- * We store contacts in this way so that position correction can account for movement, which is - * critical for continuous physics. All contact scenarios must be expressed in one of these types. - * This structure is stored across time steps, so we keep it small. - */ +/// A manifold for two touching convex shapes. Box2D supports multiple types of contact: +///
    +///
  • clip point versus plane with radius
  • +///
  • point versus point with radius (circles)
  • +///
+/// The local point usage depends on the manifold type: +///
    +///
  • e_circles: the local center of circleA
  • +///
  • e_faceA: the center of faceA
  • +///
  • e_faceB: the center of faceB
  • +///
+/// Similarly the local normal usage: +///
    +///
  • e_circles: not used
  • +///
  • e_faceA: the normal on polygonA
  • +///
  • e_faceB: the normal on polygonB
  • +///
+/// We store contacts in this way so that position correction can account for movement, which is +/// critical for continuous physics. All contact scenarios must be expressed in one of these types. +/// This structure is stored across time steps, so we keep it small. enum ManifoldType { CIRCLES, FACE_A, FACE_B } class Manifold { - /** The points of contact. */ + /// The points of contact. final List points; - /** not use for Type::e_points */ + /// not use for Type::e_points final Vector2 localNormal; - /** usage depends on manifold type */ + /// usage depends on manifold type final Vector2 localPoint; ManifoldType type = ManifoldType.CIRCLES; - /** The number of manifold points. */ + /// The number of manifold points. int pointCount = 0; - /** - * creates a manifold with 0 points, with it's points array full of instantiated ManifoldPoints. - */ + /// creates a manifold with 0 points, with it's points array full of instantiated ManifoldPoints. Manifold() - : points = new List(Settings.maxManifoldPoints), - localNormal = new Vector2.zero(), - localPoint = new Vector2.zero() { + : points = List(Settings.maxManifoldPoints), + localNormal = Vector2.zero(), + localPoint = Vector2.zero() { for (int i = 0; i < Settings.maxManifoldPoints; i++) { - points[i] = new ManifoldPoint(); + points[i] = ManifoldPoint(); } } - /** - * Creates this manifold as a copy of the other - * - * @param other - */ + /// Creates this manifold as a copy of the other Manifold.copy(Manifold other) - : points = new List(Settings.maxManifoldPoints), + : points = List(Settings.maxManifoldPoints), localNormal = other.localNormal.clone(), localPoint = other.localPoint.clone(), pointCount = other.pointCount { type = other.type; // djm: this is correct now for (int i = 0; i < Settings.maxManifoldPoints; i++) { - points[i] = new ManifoldPoint.copy(other.points[i]); + points[i] = ManifoldPoint.copy(other.points[i]); } } - /** - * copies this manifold from the given one - * - * @param cp manifold to copy from - */ + /// copies this manifold from the given one + /// + /// @param cp manifold to copy from void set(Manifold cp) { for (int i = 0; i < cp.pointCount; i++) { points[i].set(cp.points[i]); diff --git a/lib/src/collision/manifold_point.dart b/lib/src/collision/manifold_point.dart index 23963c7..63ca6bd 100644 --- a/lib/src/collision/manifold_point.dart +++ b/lib/src/collision/manifold_point.dart @@ -1,72 +1,43 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A manifold point is a contact point belonging to a contact - * manifold. It holds details related to the geometry and dynamics - * of the contact points. - * The local point usage depends on the manifold type: - *
  • e_circles: the local center of circleB
  • - *
  • e_faceA: the local center of cirlceB or the clip point of polygonB
  • - *
  • e_faceB: the clip point of polygonA
- * This structure is stored across time steps, so we keep it small.
- * Note: the impulses are used for internal caching and may not - * provide reliable contact forces, especially for high speed collisions. - */ +/// A manifold point is a contact point belonging to a contact +/// manifold. It holds details related to the geometry and dynamics +/// of the contact points. +/// The local point usage depends on the manifold type: +///
  • e_circles: the local center of circleB
  • +///
  • e_faceA: the local center of cirlceB or the clip point of polygonB
  • +///
  • e_faceB: the clip point of polygonA
+/// This structure is stored across time steps, so we keep it small.
+/// Note: the impulses are used for internal caching and may not +/// provide reliable contact forces, especially for high speed collisions. class ManifoldPoint { - /** usage depends on manifold type */ + /// usage depends on manifold type final Vector2 localPoint; - /** the non-penetration impulse */ + + /// the non-penetration impulse double normalImpulse = 0.0; - /** the friction impulse */ + + /// the friction impulse double tangentImpulse = 0.0; - /** uniquely identifies a contact point between two shapes */ + + /// uniquely identifies a contact point between two shapes final ContactID id; - /** - * Blank manifold point with everything zeroed out. - */ + /// Blank manifold point with everything zeroed out. ManifoldPoint() - : localPoint = new Vector2.zero(), - id = new ContactID(); + : localPoint = Vector2.zero(), + id = ContactID(); - /** - * Creates a manifold point as a copy of the given point - * @param cp point to copy from - */ + /// Creates a manifold point as a copy of the given point + /// @param cp point to copy from ManifoldPoint.copy(final ManifoldPoint cp) : localPoint = cp.localPoint.clone(), normalImpulse = cp.normalImpulse, tangentImpulse = cp.tangentImpulse, - id = new ContactID.copy(cp.id); + id = ContactID.copy(cp.id); - /** - * Sets this manifold point form the given one - * @param cp the point to copy from - */ + /// Sets this manifold point form the given one + /// @param cp the point to copy from void set(final ManifoldPoint cp) { localPoint.setFrom(cp.localPoint); normalImpulse = cp.normalImpulse; diff --git a/lib/src/collision/raycast_input.dart b/lib/src/collision/raycast_input.dart index b636bda..4cd8660 100644 --- a/lib/src/collision/raycast_input.dart +++ b/lib/src/collision/raycast_input.dart @@ -1,34 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - */ +/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). class RayCastInput { - final Vector2 p1 = new Vector2.zero(), p2 = new Vector2.zero(); + final Vector2 p1 = Vector2.zero(), p2 = Vector2.zero(); double maxFraction = 0.0; void set(final RayCastInput rci) { diff --git a/lib/src/collision/raycast_output.dart b/lib/src/collision/raycast_output.dart index 1e1bec6..162bffc 100644 --- a/lib/src/collision/raycast_output.dart +++ b/lib/src/collision/raycast_output.dart @@ -1,35 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 - * come from b2RayCastInput. - */ +/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 +/// come from b2RayCastInput. class RayCastOutput { - final Vector2 normal = new Vector2.zero(); + final Vector2 normal = Vector2.zero(); double fraction = 0.0; void set(final RayCastOutput rco) { diff --git a/lib/src/collision/shapes/chain_shape.dart b/lib/src/collision/shapes/chain_shape.dart index adecaa5..3cd7719 100644 --- a/lib/src/collision/shapes/chain_shape.dart +++ b/lib/src/collision/shapes/chain_shape.dart @@ -1,44 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/*** - * A chain shape is a free form sequence of line segments. The chain has two-sided collision, so you - * can use inside and outside collision. Therefore, you may use any winding order. Connectivity - * information is used to create smooth collisions. WARNING: The chain will not collide properly if - * there are self-intersections. - */ - +/// A chain shape is a free form sequence of line segments. The chain has two-sided collision, so you +/// can use inside and outside collision. Therefore, you may use any winding order. Connectivity +/// information is used to create smooth collisions. WARNING: The chain will not collide properly if +/// there are self-intersections. class ChainShape extends Shape { List _vertices; int _count = 0; - final Vector2 _prevVertex = new Vector2.zero(), - _nextVertex = new Vector2.zero(); - bool _hasPrevVertex = false, _hasNextVertex = false; + final Vector2 _prevVertex = Vector2.zero(); + final Vector2 _nextVertex = Vector2.zero(); + bool _hasPrevVertex = false; + bool _hasNextVertex = false; - final EdgeShape _pool0 = new EdgeShape(); + final EdgeShape _pool0 = EdgeShape(); ChainShape() : super(ShapeType.CHAIN) { radius = Settings.polygonRadius; @@ -53,9 +27,7 @@ class ChainShape extends Shape { return _count - 1; } - /** - * Get a child edge. - */ + /// Get a child edge. void getChildEdge(EdgeShape edge, int index) { assert(0 <= index && index < _count - 1); edge.radius = radius; @@ -155,7 +127,7 @@ class ChainShape extends Shape { } Shape clone() { - ChainShape clone = new ChainShape(); + ChainShape clone = ChainShape(); clone.createChain(_vertices, _count); clone._prevVertex.setFrom(_prevVertex); clone._nextVertex.setFrom(_nextVertex); @@ -164,17 +136,28 @@ class ChainShape extends Shape { return clone; } - /** - * Create a loop. This automatically adjusts connectivity. - * - * @param vertices an array of vertices, these are copied - * @param count the vertex count - */ + /// Returns the vertex at the given position (index). + /// + /// @param index the index of the vertex 0 <= index < getVertexCount( ) + /// @param vertex output vertex object, must be initialized + Vector2 getVertex(int index) { + assert(index >= 0 && index < _vertices.length); + return _vertices[index].clone(); + } + + int getVertexCount() { + return _vertices.length; + } + + /// Create a loop. This automatically adjusts connectivity. + /// + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count void createLoop(final List vertices, int count) { assert(_vertices == null && _count == 0); assert(count >= 3); _count = count + 1; - _vertices = new List(_count); + _vertices = List(_count); for (int i = 1; i < count; i++) { Vector2 v1 = vertices[i - 1]; Vector2 v2 = vertices[i]; @@ -185,26 +168,24 @@ class ChainShape extends Shape { } } for (int i = 0; i < count; i++) { - _vertices[i] = new Vector2.copy(vertices[i]); + _vertices[i] = Vector2.copy(vertices[i]); } - _vertices[count] = new Vector2.copy(_vertices[0]); + _vertices[count] = Vector2.copy(_vertices[0]); _prevVertex.setFrom(_vertices[_count - 2]); _nextVertex.setFrom(_vertices[1]); _hasPrevVertex = true; _hasNextVertex = true; } - /** - * Create a chain with isolated end vertices. - * - * @param vertices an array of vertices, these are copied - * @param count the vertex count - */ + /// Create a chain with isolated end vertices. + /// + /// @param vertices an array of vertices, these are copied + /// @param count the vertex count void createChain(final List vertices, int count) { assert(_vertices == null && _count == 0); assert(count >= 2); _count = count; - _vertices = new List(_count); + _vertices = List(_count); for (int i = 1; i < _count; i++) { Vector2 v1 = vertices[i - 1]; Vector2 v2 = vertices[i]; @@ -215,7 +196,7 @@ class ChainShape extends Shape { } } for (int i = 0; i < _count; i++) { - _vertices[i] = new Vector2.copy(vertices[i]); + _vertices[i] = Vector2.copy(vertices[i]); } _hasPrevVertex = false; _hasNextVertex = false; @@ -224,21 +205,13 @@ class ChainShape extends Shape { _nextVertex.setZero(); } - /** - * Establish connectivity to a vertex that precedes the first vertex. Don't call this for loops. - * - * @param prevVertex - */ + /// Establish connectivity to a vertex that precedes the first vertex. Don't call this for loops. void setPrevVertex(final Vector2 prevVertex) { _prevVertex.setFrom(prevVertex); _hasPrevVertex = true; } - /** - * Establish connectivity to a vertex that follows the last vertex. Don't call this for loops. - * - * @param nextVertex - */ + /// Establish connectivity to a vertex that follows the last vertex. Don't call this for loops. void setNextVertex(final Vector2 nextVertex) { _nextVertex.setFrom(nextVertex); _hasNextVertex = true; diff --git a/lib/src/collision/shapes/circle_shape.dart b/lib/src/collision/shapes/circle_shape.dart index c26b8b6..73522d3 100644 --- a/lib/src/collision/shapes/circle_shape.dart +++ b/lib/src/collision/shapes/circle_shape.dart @@ -1,104 +1,54 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A circle shape. - */ +/// A circle shape. class CircleShape extends Shape { - final Vector2 p = new Vector2.zero(); + final Vector2 position = Vector2.zero(); CircleShape() : super(ShapeType.CIRCLE) { radius = 0.0; } Shape clone() { - CircleShape shape = new CircleShape(); - shape.p.x = p.x; - shape.p.y = p.y; + CircleShape shape = CircleShape(); + shape.position.x = position.x; + shape.position.y = position.y; shape.radius = radius; return shape; } int getChildCount() => 1; - /** - * Get the supporting vertex index in the given direction. - * - * @param d - * @return - */ + /// Get the supporting vertex index in the given direction. int getSupport(final Vector2 d) => 0; - /** - * Get the supporting vertex in the given direction. - * - * @param d - * @return - */ - Vector2 getSupportVertex(final Vector2 d) => p; - - /** - * Get the vertex count. - * - * @return - */ + /// Get the supporting vertex in the given direction. + Vector2 getSupportVertex(final Vector2 d) => position; + + /// Get the vertex count. int getVertexCount() => 1; - /** - * Get a vertex by index. - * - * @param index - * @return - */ + /// Get a vertex by index. Vector2 getVertex(final int index) { assert(index == 0); - return p; + return position; } - bool testPoint(final Transform transform, final Vector2 p) { - // Rot.mulToOutUnsafe(transform.q, _p, center); - // center.addLocal(transform.p); - // - // final Vec2 d = center.subLocal(p).negateLocal(); - // return Vec2.dot(d, d) <= _radius * _radius; + bool testPoint(final Transform transform, final Vector2 point) { final Rot q = transform.q; final Vector2 tp = transform.p; - double centerx = -(q.c * p.x - q.s * p.y + tp.x - p.x); - double centery = -(q.s * p.x + q.c * p.y + tp.y - p.y); + double centerX = -(q.c * position.x - q.s * position.y + tp.x - point.x); + double centerY = -(q.s * position.x + q.c * position.y + tp.y - point.y); - return centerx * centerx + centery * centery <= radius * radius; + return centerX * centerX + centerY * centerY <= radius * radius; } double computeDistanceToOut( Transform xf, Vector2 p, int childIndex, Vector2 normalOut) { final Rot xfq = xf.q; - double centerx = xfq.c * p.x - xfq.s * p.y + xf.p.x; - double centery = xfq.s * p.x + xfq.c * p.y + xf.p.y; - double dx = p.x - centerx; - double dy = p.y - centery; + double centerX = xfq.c * p.x - xfq.s * p.y + xf.p.x; + double centerY = xfq.s * p.x + xfq.c * p.y + xf.p.y; + double dx = p.x - centerX; + double dy = p.y - centerY; double d1 = Math.sqrt(dx * dx + dy * dy); normalOut.x = dx * 1 / d1; normalOut.y = dy * 1 / d1; @@ -118,8 +68,8 @@ class CircleShape extends Shape { // Rot.mulToOutUnsafe(transform.q, _p, position); // position.addLocal(transform.p); - final double positionx = tq.c * p.x - tq.s * p.y + tp.x; - final double positiony = tq.s * p.x + tq.c * p.y + tp.y; + final double positionx = tq.c * position.x - tq.s * position.y + tp.x; + final double positiony = tq.s * position.x + tq.c * position.y + tp.y; final double sx = inputp1.x - positionx; final double sy = inputp1.y - positiony; @@ -159,8 +109,8 @@ class CircleShape extends Shape { void computeAABB(final AABB aabb, final Transform transform, int childIndex) { final Rot tq = transform.q; final Vector2 tp = transform.p; - final double px = tq.c * p.x - tq.s * p.y + tp.x; - final double py = tq.s * p.x + tq.c * p.y + tp.y; + final double px = tq.c * position.x - tq.s * position.y + tp.x; + final double py = tq.s * position.x + tq.c * position.y + tp.y; aabb.lowerBound.x = px - radius; aabb.lowerBound.y = py - radius; @@ -169,13 +119,13 @@ class CircleShape extends Shape { } void computeMass(final MassData massData, final double density) { - massData.mass = density * Math.PI * radius * radius; - massData.center.x = p.x; - massData.center.y = p.y; + massData.mass = density * Math.pi * radius * radius; + massData.center.x = position.x; + massData.center.y = position.y; // inertia about the local origin - // massData.I = massData.mass * (0.5f * _radius * _radius + Vec2.dot(_p, _p)); - massData.I = - massData.mass * (0.5 * radius * radius + (p.x * p.x + p.y * p.y)); + massData.I = massData.mass * + (0.5 * radius * radius + + (position.x * position.x + position.y * position.y)); } } diff --git a/lib/src/collision/shapes/edge_shape.dart b/lib/src/collision/shapes/edge_shape.dart index a7ae16a..35b1700 100644 --- a/lib/src/collision/shapes/edge_shape.dart +++ b/lib/src/collision/shapes/edge_shape.dart @@ -1,54 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A line segment (edge) shape. These can be connected in chains or loops to other edge shapes. The - * connectivity information is used to ensure correct contact normals. - * - * @author Daniel - */ +/// A line segment (edge) shape. These can be connected in chains or loops to other edge shapes. The +/// connectivity information is used to ensure correct contact normals. class EdgeShape extends Shape { - /** - * edge vertex 1 - */ - final Vector2 vertex1 = new Vector2.zero(); - /** - * edge vertex 2 - */ - final Vector2 vertex2 = new Vector2.zero(); - - /** - * optional adjacent vertex 1. Used for smooth collision - */ - final Vector2 vertex0 = new Vector2.zero(); - /** - * optional adjacent vertex 2. Used for smooth collision - */ - final Vector2 vertex3 = new Vector2.zero(); - bool hasVertex0 = false, hasVertex3 = false; + /// edge vertex 1 + final Vector2 vertex1 = Vector2.zero(); + + /// edge vertex 2 + final Vector2 vertex2 = Vector2.zero(); + + /// optional adjacent vertex 1. Used for smooth collision + final Vector2 vertex0 = Vector2.zero(); + + /// optional adjacent vertex 2. Used for smooth collision + final Vector2 vertex3 = Vector2.zero(); + bool hasVertex0 = false; + bool hasVertex3 = false; EdgeShape() : super(ShapeType.EDGE) { radius = Settings.polygonRadius; @@ -69,7 +36,7 @@ class EdgeShape extends Shape { } // for pooling - final Vector2 normal = new Vector2.zero(); + final Vector2 normal = Vector2.zero(); double computeDistanceToOut( Transform xf, Vector2 p, int childIndex, Vector2 normalOut) { @@ -109,48 +76,36 @@ class EdgeShape extends Shape { return d1; } - // p = p1 + t * d - // v = v1 + s * e - // p1 + t * d = v1 + s * e - // s * e - t * d = p1 - v1 bool raycast( RayCastOutput output, RayCastInput input, Transform xf, int childIndex) { - double tempx, tempy; final Vector2 v1 = vertex1; final Vector2 v2 = vertex2; final Rot xfq = xf.q; final Vector2 xfp = xf.p; // Put the ray into the edge's frame of reference. - // b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - // b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - tempx = input.p1.x - xfp.x; - tempy = input.p1.y - xfp.y; - final double p1x = xfq.c * tempx + xfq.s * tempy; - final double p1y = -xfq.s * tempx + xfq.c * tempy; - - tempx = input.p2.x - xfp.x; - tempy = input.p2.y - xfp.y; - final double p2x = xfq.c * tempx + xfq.s * tempy; - final double p2y = -xfq.s * tempx + xfq.c * tempy; + double tempX = input.p1.x - xfp.x; + double tempY = input.p1.y - xfp.y; + final double p1x = xfq.c * tempX + xfq.s * tempY; + final double p1y = -xfq.s * tempX + xfq.c * tempY; + + tempX = input.p2.x - xfp.x; + tempY = input.p2.y - xfp.y; + final double p2x = xfq.c * tempX + xfq.s * tempY; + final double p2y = -xfq.s * tempX + xfq.c * tempY; final double dx = p2x - p1x; final double dy = p2y - p1y; - // final Vec2 normal = pool2.set(v2).subLocal(v1); - // normal.set(normal.y, -normal.x); normal.x = v2.y - v1.y; normal.y = v1.x - v2.x; normal.normalize(); final double normalx = normal.x; final double normaly = normal.y; - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - tempx = v1.x - p1x; - tempy = v1.y - p1y; - double numerator = normalx * tempx + normaly * tempy; + tempX = v1.x - p1x; + tempY = v1.y - p1y; + double numerator = normalx * tempX + normaly * tempY; double denominator = normalx * dx + normaly * dy; if (denominator == 0.0) { @@ -162,34 +117,27 @@ class EdgeShape extends Shape { return false; } - // Vec2 q = p1 + t * d; final double qx = p1x + t * dx; final double qy = p1y + t * dy; - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - // Vec2 r = v2 - v1; final double rx = v2.x - v1.x; final double ry = v2.y - v1.y; final double rr = rx * rx + ry * ry; if (rr == 0.0) { return false; } - tempx = qx - v1.x; - tempy = qy - v1.y; - // double s = Vec2.dot(pool5, r) / rr; - double s = (tempx * rx + tempy * ry) / rr; + tempX = qx - v1.x; + tempY = qy - v1.y; + double s = (tempX * rx + tempY * ry) / rr; if (s < 0.0 || 1.0 < s) { return false; } output.fraction = t; if (numerator > 0.0) { - // output.normal = -b2Mul(xf.q, normal); output.normal.x = -xfq.c * normal.x + xfq.s * normal.y; output.normal.y = -xfq.s * normal.x - xfq.c * normal.y; } else { - // output->normal = b2Mul(xf.q, normal); output.normal.x = xfq.c * normal.x - xfq.s * normal.y; output.normal.y = xfq.s * normal.x + xfq.c * normal.y; } @@ -227,7 +175,7 @@ class EdgeShape extends Shape { } Shape clone() { - EdgeShape edge = new EdgeShape(); + EdgeShape edge = EdgeShape(); edge.radius = this.radius; edge.hasVertex0 = this.hasVertex0; edge.hasVertex3 = this.hasVertex3; diff --git a/lib/src/collision/shapes/mass_data.dart b/lib/src/collision/shapes/mass_data.dart index 0da3975..74eea49 100644 --- a/lib/src/collision/shapes/mass_data.dart +++ b/lib/src/collision/shapes/mass_data.dart @@ -1,49 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** This holds the mass data computed for a shape. */ +/// This holds the mass data computed for a shape. class MassData { - /** The mass of the shape, usually in kilograms. */ + /// The mass of the shape, usually in kilograms. double mass = 0.0; - /** The position of the shape's centroid relative to the shape's origin. */ + + /// The position of the shape's centroid relative to the shape's origin. final Vector2 center; - /** The rotational inertia of the shape about the local origin. */ + + /// The rotational inertia of the shape about the local origin. double I = 0.0; - /** - * Blank mass data - */ - MassData() : this.center = new Vector2.zero(); + /// Blank mass data + MassData() : this.center = Vector2.zero(); - /** - * Copies from the given mass data - * - * @param md - * mass data to copy from - */ + /// Copies from the given mass data + /// + /// @param md mass data to copy from MassData.copy(MassData md) : mass = md.mass, center = md.center.clone(), @@ -55,8 +28,8 @@ class MassData { center.setFrom(md.center); } - /** Return a copy of this object. */ + /// Return a copy of this object. MassData clone() { - return new MassData.copy(this); + return MassData.copy(this); } } diff --git a/lib/src/collision/shapes/polygon_shape.dart b/lib/src/collision/shapes/polygon_shape.dart index 32057fe..f11f139 100644 --- a/lib/src/collision/shapes/polygon_shape.dart +++ b/lib/src/collision/shapes/polygon_shape.dart @@ -1,124 +1,61 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A convex polygon shape. Polygons have a maximum number of vertices equal to _maxPolygonVertices. - * In most cases you should not need many vertices for a convex polygon. - */ +/// A convex polygon shape. Polygons have a maximum number of vertices equal to _maxPolygonVertices. +/// In most cases you should not need many vertices for a convex polygon. class PolygonShape extends Shape { - /** Dump lots of debug information. */ + /// Dump lots of debug information. static const bool _debug = false; - /** - * Local position of the shape centroid in parent body frame. - */ - final Vector2 centroid = new Vector2.zero(); - - /** - * The vertices of the shape. Note: use getVertexCount(), not _vertices.length, to get number of - * active vertices. - */ - final List vertices = new List(Settings.maxPolygonVertices); - - /** - * The normals of the shape. Note: use getVertexCount(), not _normals.length, to get number of - * active normals. - */ - final List normals = new List(Settings.maxPolygonVertices); - - /** - * Number of active vertices in the shape. - */ - int count = 0; + /// Local position of the shape centroid in parent body frame. + final Vector2 centroid = Vector2.zero(); - // pooling - final Vector2 _pool1 = new Vector2.zero(); - final Vector2 _pool2 = new Vector2.zero(); - final Vector2 _pool3 = new Vector2.zero(); - final Vector2 _pool4 = new Vector2.zero(); - Transform _poolt1 = new Transform.zero(); + /// The vertices of the shape. Note: use getVertexCount(), not _vertices.length, to get number of + /// active vertices. + final List vertices = List.generate( + Settings.maxPolygonVertices, (i) => Vector2.zero()); - PolygonShape() : super(ShapeType.POLYGON) { - for (int i = 0; i < vertices.length; i++) { - vertices[i] = new Vector2.zero(); - } + /// The normals of the shape. Note: use getVertexCount(), not _normals.length, to get number of + /// active normals. + final List normals = List.generate( + Settings.maxPolygonVertices, (i) => Vector2.zero()); - for (int i = 0; i < normals.length; i++) { - normals[i] = new Vector2.zero(); - } + /// Number of active vertices in the shape. + int count = 0; + + PolygonShape() : super(ShapeType.POLYGON) { radius = Settings.polygonRadius; } Shape clone() { - PolygonShape shape = new PolygonShape(); - shape.centroid.setFrom(this.centroid); + PolygonShape shape = PolygonShape(); + shape.centroid.setFrom(centroid); for (int i = 0; i < shape.normals.length; i++) { shape.normals[i].setFrom(normals[i]); shape.vertices[i].setFrom(vertices[i]); } - shape.radius = this.radius; - shape.count = this.count; + shape.radius = radius; + shape.count = count; return shape; } - /** - * Create a convex hull from the given array of points. The count must be in the range [3, - * Settings.maxPolygonVertices]. - * - * @warning the points may be re-ordered, even if they form a convex polygon. - * @warning collinear points are removed. - */ - void set(final List vertices, final int count) { - setWithPools(vertices, count, null, null); - } - - /** - * Create a convex hull from the given array of points. The count must be in the range [3, - * Settings.maxPolygonVertices]. This method takes an arraypool for pooling. - * - * @warning the points may be re-ordered, even if they form a convex polygon. - * @warning collinear points are removed. - */ - void setWithPools(final List verts, final int num, - final Vec2Array vecPool, final IntArray intPool) { - assert(3 <= num && num <= Settings.maxPolygonVertices); - if (num < 3) { + /// Create a convex hull from the given array of points. The count must be in the range [3, + /// Settings.maxPolygonVertices]. + /// @warning the points may be re-ordered, even if they form a convex polygon. + /// @warning collinear points are removed. + void set(final List updatedVertices, final int updatedCount) { + assert(3 <= updatedCount && updatedCount <= Settings.maxPolygonVertices); + if (updatedCount < 3) { setAsBoxXY(1.0, 1.0); return; } - int n = Math.min(num, Settings.maxPolygonVertices); + int n = Math.min(updatedCount, Settings.maxPolygonVertices); // Perform welding and copy vertices into local buffer. - List ps = (vecPool != null) - ? vecPool.get(Settings.maxPolygonVertices) - : new List(Settings.maxPolygonVertices); + List ps = List(Settings.maxPolygonVertices); int tempCount = 0; for (int i = 0; i < n; ++i) { - Vector2 v = verts[i]; + Vector2 v = updatedVertices[i]; bool unique = true; for (int j = 0; j < tempCount; ++j) { if (MathUtils.distanceSquared(v, ps[j]) < 0.5 * Settings.linearSlop) { @@ -154,9 +91,7 @@ class PolygonShape extends Shape { } } - List hull = (intPool != null) - ? intPool.get(Settings.maxPolygonVertices) - : BufferUtils.allocClearIntList(Settings.maxPolygonVertices); + List hull = List(Settings.maxPolygonVertices); int m = 0; int ih = i0; @@ -170,12 +105,8 @@ class PolygonShape extends Shape { continue; } - Vector2 r = _pool1 - ..setFrom(ps[ie]) - ..sub(ps[hull[m]]); - Vector2 v = _pool2 - ..setFrom(ps[j]) - ..sub(ps[hull[m]]); + Vector2 r = Vector2.copy(ps[ie])..sub(ps[hull[m]]); + Vector2 v = Vector2.copy(ps[j])..sub(ps[hull[m]]); double c = r.cross(v); if (c < 0.0) { ie = j; @@ -200,12 +131,12 @@ class PolygonShape extends Shape { // Copy vertices. for (int i = 0; i < count; ++i) { if (vertices[i] == null) { - vertices[i] = new Vector2.zero(); + vertices[i] = Vector2.zero(); } vertices[i].setFrom(ps[hull[i]]); } - final Vector2 edge = _pool1; + final Vector2 edge = Vector2.zero(); // Compute normals. Ensure the edges have non-zero length. for (int i = 0; i < count; ++i) { @@ -221,15 +152,13 @@ class PolygonShape extends Shape { } // Compute the polygon centroid. - computeCentroidToOut(vertices, count, centroid); + computeCentroid(vertices, count); } - /** - * Build vertices to represent an axis-aligned box. - * - * @param hx the half-width. - * @param hy the half-height. - */ + /// Build vertices to represent an axis-aligned box. + /// + /// @param hx the half-width. + /// @param hy the half-height. void setAsBoxXY(final double hx, final double hy) { count = 4; vertices[0].setValues(-hx, -hy); @@ -243,41 +172,29 @@ class PolygonShape extends Shape { centroid.setZero(); } - /** - * Build vertices to represent an oriented box. - * - * @param hx the half-width. - * @param hy the half-height. - * @param center the center of the box in local coordinates. - * @param angle the rotation of the box in local coordinates. - */ + /// Build vertices to represent an oriented box. + /// + /// @param hx the half-width. + /// @param hy the half-height. + /// @param center the center of the box in local coordinates. + /// @param angle the rotation of the box in local coordinates. void setAsBox(final double hx, final double hy, final Vector2 center, final double angle) { - count = 4; - vertices[0].setValues(-hx, -hy); - vertices[1].setValues(hx, -hy); - vertices[2].setValues(hx, hy); - vertices[3].setValues(-hx, hy); - normals[0].setValues(0.0, -1.0); - normals[1].setValues(1.0, 0.0); - normals[2].setValues(0.0, 1.0); - normals[3].setValues(-1.0, 0.0); + setAsBoxXY(hx, hy); centroid.setFrom(center); - final Transform xf = _poolt1; + final Transform xf = Transform.zero(); xf.p.setFrom(center); xf.q.setAngle(angle); // Transform vertices and normals. for (int i = 0; i < count; ++i) { - Transform.mulToOutVec2(xf, vertices[i], vertices[i]); - Rot.mulToOut(xf.q, normals[i], normals[i]); + vertices[i].setFrom(Transform.mulVec2(xf, vertices[i])); + normals[i].setFrom(Rot.mulVec2(xf.q, normals[i])); } } - /** - * Set this as a single edge. - */ + /// Set this as a single edge. void setAsEdge(Vector2 v1, Vector2 v2) { count = 2; vertices[0].setFrom(v1); @@ -301,13 +218,12 @@ class PolygonShape extends Shape { } bool testPoint(final Transform xf, final Vector2 p) { - double tempx, tempy; final Rot xfq = xf.q; - tempx = p.x - xf.p.x; - tempy = p.y - xf.p.y; - final double pLocalx = xfq.c * tempx + xfq.s * tempy; - final double pLocaly = -xfq.s * tempx + xfq.c * tempy; + double tempX = p.x - xf.p.x; + double tempY = p.y - xf.p.y; + final double pLocalx = xfq.c * tempX + xfq.s * tempY; + final double pLocaly = -xfq.s * tempX + xfq.c * tempY; if (_debug) { print("--testPoint debug--"); @@ -321,9 +237,9 @@ class PolygonShape extends Shape { for (int i = 0; i < count; ++i) { Vector2 vertex = vertices[i]; Vector2 normal = normals[i]; - tempx = pLocalx - vertex.x; - tempy = pLocaly - vertex.y; - final double dot = normal.x * tempx + normal.y * tempy; + tempX = pLocalx - vertex.x; + tempY = pLocaly - vertex.y; + final double dot = normal.x * tempX + normal.y * tempY; if (dot > 0.0) { return false; } @@ -362,21 +278,12 @@ class PolygonShape extends Shape { upper.y += radius; } - /** - * Get the vertex count. - * - * @return - */ + /// Get the vertex count. int getVertexCount() { return count; } - /** - * Get a vertex by index. - * - * @param index - * @return - */ + /// Get a vertex by index. Vector2 getVertex(final int index) { assert(0 <= index && index < count); return vertices[index]; @@ -391,7 +298,7 @@ class PolygonShape extends Shape { double pLocalx = xfqc * tx + xfqs * ty; double pLocaly = -xfqs * tx + xfqc * ty; - double maxDistance = -double.MAX_FINITE; + double maxDistance = -double.maxFinite; double normalForMaxDistanceX = pLocalx; double normalForMaxDistanceY = pLocaly; @@ -443,18 +350,15 @@ class PolygonShape extends Shape { final double xfqc = xf.q.c; final double xfqs = xf.q.s; final Vector2 xfp = xf.p; - double tempx, tempy; - // b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - // b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - tempx = input.p1.x - xfp.x; - tempy = input.p1.y - xfp.y; - final double p1x = xfqc * tempx + xfqs * tempy; - final double p1y = -xfqs * tempx + xfqc * tempy; - - tempx = input.p2.x - xfp.x; - tempy = input.p2.y - xfp.y; - final double p2x = xfqc * tempx + xfqs * tempy; - final double p2y = -xfqs * tempx + xfqc * tempy; + double tempX = input.p1.x - xfp.x; + double tempY = input.p1.y - xfp.y; + final double p1x = xfqc * tempX + xfqs * tempY; + final double p1y = -xfqs * tempX + xfqc * tempY; + + tempX = input.p2.x - xfp.x; + tempY = input.p2.y - xfp.y; + final double p2x = xfqc * tempX + xfqs * tempY; + final double p2y = -xfqs * tempX + xfqc * tempY; final double dx = p2x - p1x; final double dy = p2y - p1y; @@ -466,9 +370,6 @@ class PolygonShape extends Shape { for (int i = 0; i < count; ++i) { Vector2 normal = normals[i]; Vector2 vertex = vertices[i]; - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 double tempxn = vertex.x - p1x; double tempyn = vertex.y - p1y; final double numerator = normal.x * tempxn + normal.y * tempyn; @@ -505,7 +406,6 @@ class PolygonShape extends Shape { if (index >= 0) { output.fraction = lower; - // normal = Mul(xf.R, _normals[index]); Vector2 normal = normals[index]; Vector2 out = output.normal; out.x = xfqc * normal.x - xfqs * normal.y; @@ -515,20 +415,18 @@ class PolygonShape extends Shape { return false; } - void computeCentroidToOut( - final List vs, final int count, final Vector2 out) { + void computeCentroid(final List vs, final int count) { assert(count >= 3); - out.setValues(0.0, 0.0); + centroid.setZero(); double area = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). - final Vector2 pRef = _pool1; - pRef.setZero(); + final Vector2 pRef = Vector2.zero(); - final Vector2 e1 = _pool2; - final Vector2 e2 = _pool3; + final Vector2 e1 = Vector2.zero(); + final Vector2 e2 = Vector2.zero(); final double inv3 = 1.0 / 3.0; @@ -556,12 +454,12 @@ class PolygonShape extends Shape { ..add(p2) ..add(p3) ..scale(triangleArea * inv3); - out.add(e1); + centroid.add(e1); } // Centroid assert(area > Settings.EPSILON); - out.scale(1.0 / area); + centroid.scale(1.0 / area); } void computeMass(final MassData massData, double density) { @@ -591,15 +489,13 @@ class PolygonShape extends Shape { assert(count >= 3); - final Vector2 center = _pool1; - center.setZero(); + final Vector2 center = Vector2.zero(); double area = 0.0; double I = 0.0; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). - final Vector2 s = _pool2; - s.setZero(); + final Vector2 s = Vector2.zero(); // This code would put the reference point inside the polygon. for (int i = 0; i < count; ++i) { s.add(vertices[i]); @@ -608,8 +504,8 @@ class PolygonShape extends Shape { final double k_inv3 = 1.0 / 3.0; - final Vector2 e1 = _pool3; - final Vector2 e2 = _pool4; + final Vector2 e1 = Vector2.zero(); + final Vector2 e2 = Vector2.zero(); for (int i = 0; i < count; ++i) { // Triangle vertices. @@ -656,28 +552,20 @@ class PolygonShape extends Shape { massData.I += massData.mass * (massData.center.dot(massData.center)); } - /** - * Validate convexity. This is a very time consuming operation. - * - * @return - */ + /// Validate convexity. This is a very time consuming operation. bool validate() { for (int i = 0; i < count; ++i) { int i1 = i; int i2 = i < count - 1 ? i1 + 1 : 0; Vector2 p = vertices[i1]; - Vector2 e = _pool1 - ..setFrom(vertices[i2]) - ..sub(p); + Vector2 e = Vector2.copy(vertices[i2])..sub(p); for (int j = 0; j < count; ++j) { if (j == i1 || j == i2) { continue; } - Vector2 v = _pool2 - ..setFrom(vertices[j]) - ..sub(p); + Vector2 v = Vector2.copy(vertices[j])..sub(p); double c = e.cross(v); if (c < 0.0) { return false; @@ -688,14 +576,8 @@ class PolygonShape extends Shape { return true; } - /** Get the centroid and apply the supplied transform. */ + /// Get the centroid and apply the supplied transform. Vector2 applyToCentroid(final Transform xf) { return Transform.mulVec2(xf, centroid); } - - /** Get the centroid and apply the supplied transform. */ - Vector2 centroidToOut(final Transform xf, final Vector2 out) { - Transform.mulToOutUnsafeVec2(xf, centroid, out); - return out; - } } diff --git a/lib/src/collision/shapes/shape.dart b/lib/src/collision/shapes/shape.dart index 002b0c5..d3babd9 100644 --- a/lib/src/collision/shapes/shape.dart +++ b/lib/src/collision/shapes/shape.dart @@ -1,93 +1,53 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A shape is used for collision detection. You can create a shape however you like. Shapes used for - * simulation in World are created automatically when a Fixture is created. Shapes may encapsulate a - * one or more child shapes. - */ +/// A shape is used for collision detection. You can create a shape however you like. Shapes used for +/// simulation in World are created automatically when a Fixture is created. Shapes may encapsulate a +/// one or more child shapes. abstract class Shape { final ShapeType shapeType; double radius = 0.0; Shape(this.shapeType); - /** - * Get the number of child primitives - * - * @return - */ + /// Get the number of child primitives int getChildCount(); - /** - * Test a point for containment in this shape. This only works for convex shapes. - * - * @param xf the shape world transform. - * @param p a point in world coordinates. - */ + /// Test a point for containment in this shape. This only works for convex shapes. + /// + /// @param xf the shape world transform. + /// @param p a point in world coordinates. bool testPoint(final Transform xf, final Vector2 p); - /** - * Cast a ray against a child shape. - * - * @param argOutput the ray-cast results. - * @param argInput the ray-cast input parameters. - * @param argTransform the transform to be applied to the shape. - * @param argChildIndex the child shape index - * @return if hit - */ + /// Cast a ray against a child shape. + /// + /// @param argOutput the ray-cast results. + /// @param argInput the ray-cast input parameters. + /// @param argTransform the transform to be applied to the shape. + /// @param argChildIndex the child shape index + /// @return if hit bool raycast(RayCastOutput output, RayCastInput input, Transform transform, int childIndex); - /** - * Given a transform, compute the associated axis aligned bounding box for a child shape. - * - * @param argAabb returns the axis aligned box. - * @param argXf the world transform of the shape. - */ + /// Given a transform, compute the associated axis aligned bounding box for a child shape. + /// + /// @param argAabb returns the axis aligned box. + /// @param argXf the world transform of the shape. void computeAABB(final AABB aabb, final Transform xf, int childIndex); - /** - * Compute the mass properties of this shape using its dimensions and density. The inertia tensor - * is computed about the local origin. - * - * @param massData returns the mass data for this shape. - * @param density the density in kilograms per meter squared. - */ + /// Compute the mass properties of this shape using its dimensions and density. The inertia tensor + /// is computed about the local origin. + /// + /// @param massData returns the mass data for this shape. + /// @param density the density in kilograms per meter squared. void computeMass(final MassData massData, final double density); - /** - * 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 normalOut returns the direction in which the distance increases. - * @return distance returns the distance from the current shape. - */ + /// 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 normalOut returns the direction in which the distance increases. + /// @return distance returns the distance from the current shape. double computeDistanceToOut( Transform xf, Vector2 p, int childIndex, Vector2 normalOut); diff --git a/lib/src/collision/shapes/shape_type.dart b/lib/src/collision/shapes/shape_type.dart index ff73a5f..33d7102 100644 --- a/lib/src/collision/shapes/shape_type.dart +++ b/lib/src/collision/shapes/shape_type.dart @@ -1,7 +1,4 @@ part of box2d; -/** - * Types of shapes - * @author Daniel - */ +/// Types of shapes enum ShapeType { CIRCLE, EDGE, POLYGON, CHAIN } diff --git a/lib/src/collision/time_of_impact.dart b/lib/src/collision/time_of_impact.dart index 8e6d466..57f36fb 100644 --- a/lib/src/collision/time_of_impact.dart +++ b/lib/src/collision/time_of_impact.dart @@ -1,63 +1,26 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Input parameters for TOI - * - * @author Daniel Murphy - */ +/// Input parameters for TOI class TOIInput { - final DistanceProxy proxyA = new DistanceProxy(); - final DistanceProxy proxyB = new DistanceProxy(); - final Sweep sweepA = new Sweep(); - final Sweep sweepB = new Sweep(); - /** - * defines sweep interval [0, tMax] - */ + final DistanceProxy proxyA = DistanceProxy(); + final DistanceProxy proxyB = DistanceProxy(); + final Sweep sweepA = Sweep(); + final Sweep sweepB = Sweep(); + + /// defines sweep interval [0, tMax] double tMax = 0.0; } enum TOIOutputState { UNKNOWN, FAILED, OVERLAPPED, TOUCHING, SEPARATED } -/** - * Output parameters for TimeOfImpact - * - * @author daniel - */ +/// Output parameters for TimeOfImpact class TOIOutput { TOIOutputState state = TOIOutputState.UNKNOWN; double t = 0.0; } -/** - * Class used for computing the time of impact. This class should not be constructed usually, just - * retrieve from the {@link SingletonPool#getTOI()}. - * - * @author daniel - */ +/// Class used for computing the time of impact. This class should not be constructed usually, just +/// retrieve from the {@link SingletonPool#getTOI()}. class TimeOfImpact { static const int MAX_ITERATIONS = 20; static const int MAX_ROOT_ITERATIONS = 50; @@ -69,29 +32,22 @@ class TimeOfImpact { static int toiMaxRootIters = 0; // djm pooling - final SimplexCache _cache = new SimplexCache(); - final DistanceInput _distanceInput = new DistanceInput(); - final Transform _xfA = new Transform.zero(); - final Transform _xfB = new Transform.zero(); - final DistanceOutput _distanceOutput = new DistanceOutput(); - final SeparationFunction _fcn = new SeparationFunction(); - final List _indexes = BufferUtils.allocClearIntList(2); - final Sweep _sweepA = new Sweep(); - final Sweep _sweepB = new Sweep(); - - final IWorldPool _pool; - - TimeOfImpact(this._pool); - - /** - * Compute the upper bound on time before two shapes penetrate. Time is represented as a fraction - * between [0,tMax]. This uses a swept separating axis and may miss some intermediate, - * non-tunneling collision. If you change the time interval, you should call this function again. - * Note: use Distance to compute the contact point and normal at the time of impact. - * - * @param output - * @param input - */ + final SimplexCache _cache = SimplexCache(); + final DistanceInput _distanceInput = DistanceInput(); + final Transform _xfA = Transform.zero(); + final Transform _xfB = Transform.zero(); + final DistanceOutput _distanceOutput = DistanceOutput(); + final SeparationFunction _fcn = SeparationFunction(); + final List _indexes = BufferUtils.intList(2); + final Sweep _sweepA = Sweep(); + final Sweep _sweepB = Sweep(); + + TimeOfImpact(); + + /// Compute the upper bound on time before two shapes penetrate. Time is represented as a fraction + /// between [0,tMax]. This uses a swept separating axis and may miss some intermediate, + /// non-tunneling collision. If you change the time interval, you should call this function again. + /// Note: use Distance to compute the contact point and normal at the time of impact. void timeOfImpact(TOIOutput output, TOIInput input) { // CCD via the local separating axis method. This seeks progression // by computing the largest time at which separation is maintained. @@ -135,18 +91,11 @@ class TimeOfImpact { for (;;) { _sweepA.getTransform(_xfA, t1); _sweepB.getTransform(_xfB, t1); - // System.out.printf("sweepA: %f, %f, sweepB: %f, %f\n", - // sweepA.c.x, sweepA.c.y, sweepB.c.x, sweepB.c.y); // Get the distance between shapes. We can also use the results // to get a separating axis _distanceInput.transformA = _xfA; _distanceInput.transformB = _xfB; - _pool.getDistance().distance(_distanceOutput, _cache, _distanceInput); - - // System.out.printf("Dist: %f at points %f, %f and %f, %f. %d iterations\n", - // distanceOutput.distance, distanceOutput.pointA.x, distanceOutput.pointA.y, - // distanceOutput.pointB.x, distanceOutput.pointB.y, - // distanceOutput.iterations); + World.distance.compute(_distanceOutput, _cache, _distanceInput); // If the shapes are overlapped, we give up on continuous collision. if (_distanceOutput.distance <= 0.0) { @@ -175,7 +124,6 @@ class TimeOfImpact { for (;;) { // Find the deepest point at t2. Store the witness point indices. double s2 = _fcn.findMinSeparation(_indexes, t2); - // System.out.printf("s2: %f\n", s2); // Is the final configuration separated? if (s2 > target + tolerance) { // Victory! @@ -196,8 +144,6 @@ class TimeOfImpact { double s1 = _fcn.evaluate(_indexes[0], _indexes[1], t1); // Check for initial overlap. This might happen if the root finder // runs out of iterations. - // System.out.printf("s1: %f, target: %f, tolerance: %f\n", s1, target, - // tolerance); if (s1 < target - tolerance) { output.state = TOIOutputState.FAILED; output.t = t1; @@ -267,12 +213,10 @@ class TimeOfImpact { ++toiIters; if (done) { - // System.out.println("done"); break; } if (iter == MAX_ITERATIONS) { - // System.out.println("failed, root finder stuck"); // Root finder got stuck. Semi-victory. output.state = TOIOutputState.FAILED; output.t = t1; @@ -280,7 +224,6 @@ class TimeOfImpact { } } - // System.out.printf("final sweeps: %f, %f, %f; %f, %f, %f", input.s) toiMaxIters = Math.max(toiMaxIters, iter); } } // Class TimeOfImpact. @@ -291,24 +234,24 @@ class SeparationFunction { DistanceProxy proxyA; DistanceProxy proxyB; SeparationFunctionType type; - final Vector2 localPoint = new Vector2.zero(); - final Vector2 axis = new Vector2.zero(); + final Vector2 localPoint = Vector2.zero(); + final Vector2 axis = Vector2.zero(); Sweep sweepA; Sweep sweepB; // djm pooling - final Vector2 _localPointA = new Vector2.zero(); - final Vector2 _localPointB = new Vector2.zero(); - final Vector2 _pointA = new Vector2.zero(); - final Vector2 _pointB = new Vector2.zero(); - final Vector2 _localPointA1 = new Vector2.zero(); - final Vector2 _localPointA2 = new Vector2.zero(); - final Vector2 _normal = new Vector2.zero(); - final Vector2 _localPointB1 = new Vector2.zero(); - final Vector2 _localPointB2 = new Vector2.zero(); - final Vector2 _temp = new Vector2.zero(); - final Transform _xfa = new Transform.zero(); - final Transform _xfb = new Transform.zero(); + final Vector2 _localPointA = Vector2.zero(); + final Vector2 _localPointB = Vector2.zero(); + final Vector2 _pointA = Vector2.zero(); + final Vector2 _pointB = Vector2.zero(); + final Vector2 _localPointA1 = Vector2.zero(); + final Vector2 _localPointA2 = Vector2.zero(); + final Vector2 _normal = Vector2.zero(); + final Vector2 _localPointB1 = Vector2.zero(); + final Vector2 _localPointB2 = Vector2.zero(); + final Vector2 _temp = Vector2.zero(); + final Transform _xfa = Transform.zero(); + final Transform _xfb = Transform.zero(); // TODO_ERIN might not need to return the separation @@ -330,21 +273,12 @@ class SeparationFunction { sweepA.getTransform(_xfa, t1); sweepB.getTransform(_xfb, t1); - // log.debug("initializing separation.\n" + - // "cache: "+cache.count+"-"+cache.metric+"-"+cache.indexA+"-"+cache.indexB+"\n" - // "distance: "+proxyA. - if (count == 1) { type = SeparationFunctionType.POINTS; - /* - * Vec2 localPointA = proxyA.GetVertex(cache.indexA[0]); Vec2 localPointB = - * proxyB.GetVertex(cache.indexB[0]); Vec2 pointA = Mul(transformA, localPointA); Vec2 - * pointB = Mul(transformB, localPointB); axis = pointB - pointA; axis.Normalize(); - */ _localPointA.setFrom(proxyA.getVertex(cache.indexA[0])); _localPointB.setFrom(proxyB.getVertex(cache.indexB[0])); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); axis ..setFrom(_pointB) ..sub(_pointA); @@ -363,16 +297,16 @@ class SeparationFunction { _temp.scaleOrthogonalInto(-1.0, axis); axis.normalize(); - Rot.mulToOutUnsafe(_xfb.q, axis, _normal); + _normal.setFrom(Rot.mulVec2(_xfb.q, axis)); localPoint ..setFrom(_localPointB1) ..add(_localPointB2) ..scale(.5); - Transform.mulToOutUnsafeVec2(_xfb, localPoint, _pointB); + _pointB.setFrom(Transform.mulVec2(_xfb, localPoint)); _localPointA.setFrom(proxyA.getVertex(cache.indexA[0])); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); _temp ..setFrom(_pointA) @@ -396,16 +330,16 @@ class SeparationFunction { _temp.scaleOrthogonalInto(-1.0, axis); axis.normalize(); - Rot.mulToOutUnsafe(_xfa.q, axis, _normal); + _normal.setFrom(Rot.mulVec2(_xfa.q, axis)); localPoint ..setFrom(_localPointA1) ..add(_localPointA2) ..scale(.5); - Transform.mulToOutUnsafeVec2(_xfa, localPoint, _pointA); + _pointA.setFrom(Transform.mulVec2(_xfa, localPoint)); _localPointB.setFrom(proxyB.getVertex(cache.indexB[0])); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); _temp ..setFrom(_pointB) @@ -419,8 +353,8 @@ class SeparationFunction { } } - final Vector2 _axisA = new Vector2.zero(); - final Vector2 _axisB = new Vector2.zero(); + final Vector2 _axisA = Vector2.zero(); + final Vector2 _axisB = Vector2.zero(); // double FindMinSeparation(int* indexA, int* indexB, double t) const double findMinSeparation(List indexes, double t) { @@ -429,8 +363,8 @@ class SeparationFunction { switch (type) { case SeparationFunctionType.POINTS: - Rot.mulTransUnsafeVec2(_xfa.q, axis, _axisA); - Rot.mulTransUnsafeVec2(_xfb.q, axis..negate(), _axisB); + _axisA.setFrom(Rot.mulTransVec2(_xfa.q, axis)); + _axisB.setFrom(Rot.mulTransVec2(_xfb.q, axis..negate())); axis.negate(); indexes[0] = proxyA.getSupport(_axisA); @@ -439,40 +373,40 @@ class SeparationFunction { _localPointA.setFrom(proxyA.getVertex(indexes[0])); _localPointB.setFrom(proxyB.getVertex(indexes[1])); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); double separation = (_pointB..sub(_pointA)).dot(axis); return separation; case SeparationFunctionType.FACE_A: - Rot.mulToOutUnsafe(_xfa.q, axis, _normal); - Transform.mulToOutUnsafeVec2(_xfa, localPoint, _pointA); + _normal.setFrom(Rot.mulVec2(_xfa.q, axis)); + _pointA.setFrom(Transform.mulVec2(_xfa, localPoint)); - Rot.mulTransUnsafeVec2(_xfb.q, _normal..negate(), _axisB); + _axisB.setFrom(Rot.mulTransVec2(_xfb.q, _normal..negate())); _normal.negate(); indexes[0] = -1; indexes[1] = proxyB.getSupport(_axisB); _localPointB.setFrom(proxyB.getVertex(indexes[1])); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); double separation = (_pointB..sub(_pointA)).dot(_normal); return separation; case SeparationFunctionType.FACE_B: - Rot.mulToOutUnsafe(_xfb.q, axis, _normal); - Transform.mulToOutUnsafeVec2(_xfb, localPoint, _pointB); + _normal.setFrom(Rot.mulVec2(_xfb.q, axis)); + _pointB.setFrom(Transform.mulVec2(_xfb, localPoint)); - Rot.mulTransUnsafeVec2(_xfa.q, _normal..negate(), _axisA); + _axisA.setFrom(Rot.mulTransVec2(_xfa.q, _normal..negate())); _normal.negate(); indexes[1] = -1; indexes[0] = proxyA.getSupport(_axisA); _localPointA.setFrom(proxyA.getVertex(indexes[0])); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); double separation = (_pointA..sub(_pointB)).dot(_normal); return separation; @@ -494,27 +428,27 @@ class SeparationFunction { _localPointA.setFrom(proxyA.getVertex(indexA)); _localPointB.setFrom(proxyB.getVertex(indexB)); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); double separation = (_pointB..sub(_pointA)).dot(axis); return separation; case SeparationFunctionType.FACE_A: - Rot.mulToOutUnsafe(_xfa.q, axis, _normal); - Transform.mulToOutUnsafeVec2(_xfa, localPoint, _pointA); + _normal.setFrom(Rot.mulVec2(_xfa.q, axis)); + _pointA.setFrom(Transform.mulVec2(_xfa, localPoint)); _localPointB.setFrom(proxyB.getVertex(indexB)); - Transform.mulToOutUnsafeVec2(_xfb, _localPointB, _pointB); + _pointB.setFrom(Transform.mulVec2(_xfb, _localPointB)); double separation = (_pointB..sub(_pointA)).dot(_normal); return separation; case SeparationFunctionType.FACE_B: - Rot.mulToOutUnsafe(_xfb.q, axis, _normal); - Transform.mulToOutUnsafeVec2(_xfb, localPoint, _pointB); + _normal.setFrom(Rot.mulVec2(_xfb.q, axis)); + _pointB.setFrom(Transform.mulVec2(_xfb, localPoint)); _localPointA.setFrom(proxyA.getVertex(indexA)); - Transform.mulToOutUnsafeVec2(_xfa, _localPointA, _pointA); + _pointA.setFrom(Transform.mulVec2(_xfa, _localPointA)); double separation = (_pointA..sub(_pointB)).dot(_normal); return separation; diff --git a/lib/src/collision/world_manifold.dart b/lib/src/collision/world_manifold.dart index 3e73bfc..32bf00e 100644 --- a/lib/src/collision/world_manifold.dart +++ b/lib/src/collision/world_manifold.dart @@ -1,58 +1,24 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * This is used to compute the current state of a contact manifold. - * - * @author daniel - */ +/// This is used to compute the current state of a contact manifold. class WorldManifold { - /** - * World vector pointing from A to B - */ - final Vector2 normal = new Vector2.zero(); + /// World vector pointing from A to B + final Vector2 normal = Vector2.zero(); - /** - * World contact point (point of intersection) - */ - final List points = new List(Settings.maxManifoldPoints); + /// World contact point (point of intersection) + final List points = List(Settings.maxManifoldPoints); - /** - * A negative value indicates overlap, in meters. - */ - final Float64List separations = new Float64List(Settings.maxManifoldPoints); + /// A negative value indicates overlap, in meters. + final Float64List separations = Float64List(Settings.maxManifoldPoints); WorldManifold() { for (int i = 0; i < Settings.maxManifoldPoints; i++) { - points[i] = new Vector2.zero(); + points[i] = Vector2.zero(); } } - final Vector2 _pool3 = new Vector2.zero(); - final Vector2 _pool4 = new Vector2.zero(); + final Vector2 _pool3 = Vector2.zero(); + final Vector2 _pool4 = Vector2.zero(); void initialize(final Manifold manifold, final Transform xfA, double radiusA, final Transform xfB, double radiusB) { @@ -69,8 +35,6 @@ class WorldManifold { normal.x = 1.0; normal.y = 0.0; Vector2 v = manifold.localPoint; - // Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA); - // Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB); pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x; pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y; Vector2 mp0p = manifold.points[0].localPoint; @@ -99,25 +63,14 @@ class WorldManifold { { final Vector2 planePoint = _pool3; - Rot.mulToOutUnsafe(xfA.q, manifold.localNormal, normal); - Transform.mulToOutVec2(xfA, manifold.localPoint, planePoint); + normal.setFrom(Rot.mulVec2(xfA.q, manifold.localNormal)); + planePoint.setFrom(Transform.mulVec2(xfA, manifold.localPoint)); final Vector2 clipPoint = _pool4; for (int i = 0; i < manifold.pointCount; i++) { - // b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); - // b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, - // normal)) * normal; - // b2Vec2 cB = clipPoint - radiusB * normal; - // points[i] = 0.5f * (cA + cB); - Transform.mulToOutVec2( - xfB, manifold.points[i].localPoint, clipPoint); - // use cA as temporary for now - // cA.set(clipPoint).subLocal(planePoint); - // double scalar = radiusA - Vec2.dot(cA, normal); - // cA.set(normal).mulLocal(scalar).addLocal(clipPoint); - // cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal(); - // points[i].set(cA).addLocal(cB).mulLocal(0.5f); + clipPoint + .setFrom(Transform.mulVec2(xfB, manifold.points[i].localPoint)); final double scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + @@ -137,39 +90,14 @@ class WorldManifold { break; case ManifoldType.FACE_B: final Vector2 planePoint = _pool3; - Rot.mulToOutUnsafe(xfB.q, manifold.localNormal, normal); - Transform.mulToOutVec2(xfB, manifold.localPoint, planePoint); - - // final Mat22 R = xfB.q; - // normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y; - // normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y; - // final Vec2 v = manifold.localPoint; - // planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y; - // planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y; + normal.setFrom(Rot.mulVec2(xfB.q, manifold.localNormal)); + planePoint.setFrom(Transform.mulVec2(xfB, manifold.localPoint)); final Vector2 clipPoint = _pool4; for (int i = 0; i < manifold.pointCount; i++) { - // b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); - // b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, - // normal)) * normal; - // b2Vec2 cA = clipPoint - radiusA * normal; - // points[i] = 0.5f * (cA + cB); - - Transform.mulToOutVec2(xfA, manifold.points[i].localPoint, clipPoint); - // cB.set(clipPoint).subLocal(planePoint); - // double scalar = radiusB - Vec2.dot(cB, normal); - // cB.set(normal).mulLocal(scalar).addLocal(clipPoint); - // cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal(); - // points[i].set(cA).addLocal(cB).mulLocal(0.5f); - - // points[i] = 0.5f * (cA + cB); - - // - // clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x * - // manifold.points[i].localPoint.y; - // clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y * - // manifold.points[i].localPoint.y; + clipPoint + .setFrom(Transform.mulVec2(xfA, manifold.points[i].localPoint)); final double scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + diff --git a/lib/src/common/canvas_viewport_transform.dart b/lib/src/common/canvas_viewport_transform.dart index f187bcf..a42dee5 100644 --- a/lib/src/common/canvas_viewport_transform.dart +++ b/lib/src/common/canvas_viewport_transform.dart @@ -1,52 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2015, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d.common.canvas_viewport_transform; import 'dart:html'; -import 'package:box2d/box2d.dart'; +import '../../box2d.dart'; -/** - * Transform for drawing using a canvas context. Y-flip is permenantly set - * to true. - */ +/// Transform for drawing using a canvas context. Y-flip is permanently set +/// to true. class CanvasViewportTransform extends ViewportTransform { static const double DEFAULT_DRAWING_SCALE = 20.0; - /** - * Constructs a new viewport transform with the default scale. - */ + /// Constructs a new viewport transform with the default scale. CanvasViewportTransform(Vector2 _extents, Vector2 _center) : super(_extents, _center, DEFAULT_DRAWING_SCALE) { yFlip = true; } - /** - * Sets the rendering context such that all drawing commands given in terms - * of the world coordinate system will display correctly on the canvas screen. - */ + /// Sets the rendering context such that all drawing commands given in terms + /// of the world coordinate system will display correctly on the canvas screen. void updateTransformation(CanvasRenderingContext2D ctx) { // Clear all previous transformation. ctx.setTransform(1, 0, 0, 1, 0, 0); diff --git a/lib/src/common/color3i.dart b/lib/src/common/color3i.dart index c00bf3b..df8a13b 100644 --- a/lib/src/common/color3i.dart +++ b/lib/src/common/color3i.dart @@ -1,35 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; class Color3i { - static final Color3i WHITE = new Color3i(255, 255, 255); - static final Color3i BLACK = new Color3i(0, 0, 0); - static final Color3i BLUE = new Color3i(0, 0, 255); - static final Color3i GREEN = new Color3i(0, 255, 0); - static final Color3i RED = new Color3i(255, 0, 0); + static final Color3i WHITE = Color3i(255, 255, 255); + static final Color3i BLACK = Color3i(0, 0, 0); + static final Color3i BLUE = Color3i(0, 0, 255); + static final Color3i GREEN = Color3i(0, 255, 0); + static final Color3i RED = Color3i(255, 0, 0); int x = 0; int y = 0; diff --git a/lib/src/common/raycast_result.dart b/lib/src/common/raycast_result.dart index d1052ef..e052bd9 100644 --- a/lib/src/common/raycast_result.dart +++ b/lib/src/common/raycast_result.dart @@ -1,32 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; class RaycastResult { double lambda = 0.0; - final Vector2 normal = new Vector2.zero(); + final Vector2 normal = Vector2.zero(); RaycastResult set(RaycastResult argOther) { lambda = argOther.lambda; diff --git a/lib/src/common/rot.dart b/lib/src/common/rot.dart index 13b2f15..fd11955 100644 --- a/lib/src/common/rot.dart +++ b/lib/src/common/rot.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; class Rot { @@ -33,100 +9,56 @@ class Rot { : s = Math.sin(angle), c = Math.cos(angle); - Rot setAngle(double angle) { + void setAngle(double angle) { s = Math.sin(angle); c = Math.cos(angle); - return this; } - Rot set(Rot other) { + void setFrom(Rot other) { s = other.s; c = other.c; - return this; } - Rot setIdentity() { + void setIdentity() { s = 0.0; c = 1.0; - return this; } double getSin() => s; - String toString() { - return "Rot(s:$s, c:$c)"; - } + String toString() => "Rot(s:$s, c:$c)"; double getCos() => c; double getAngle() => Math.atan2(s, c); - void getXAxis(Vector2 xAxis) { - xAxis.setValues(c, s); - } + Vector2 getXAxis(Vector2 xAxis) => Vector2(c, s); - void getYAxis(Vector2 yAxis) { - yAxis.setValues(-s, c); - } + Vector2 getYAxis(Vector2 yAxis) => Vector2(-s, c); Rot clone() { - Rot copy = new Rot(); - copy.s = s; - copy.c = c; - return copy; - } - - static void mul(Rot q, Rot r, Rot out) { - double tempc = q.c * r.c - q.s * r.s; - out.s = q.s * r.c + q.c * r.s; - out.c = tempc; - } - - static void mulUnsafe(Rot q, Rot r, Rot out) { - assert(r != out); - assert(q != out); - // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] - // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] - // s = qs * rc + qc * rs - // c = qc * rc - qs * rs - out.s = q.s * r.c + q.c * r.s; - out.c = q.c * r.c - q.s * r.s; - } - - static void mulTrans(Rot q, Rot r, Rot out) { - final double tempc = q.c * r.c + q.s * r.s; - out.s = q.c * r.s - q.s * r.c; - out.c = tempc; - } - - static void mulTransUnsafe(Rot q, Rot r, Rot out) { - // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] - // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] - // s = qc * rs - qs * rc - // c = qc * rc + qs * rs - out.s = q.c * r.s - q.s * r.c; - out.c = q.c * r.c + q.s * r.s; + return Rot() + ..s = s + ..c = c; } - static void mulToOut(Rot q, Vector2 v, Vector2 out) { - double tempy = q.s * v.x + q.c * v.y; - out.x = q.c * v.x - q.s * v.y; - out.y = tempy; + static Rot mul(Rot q, Rot r) { + return Rot() + ..s = q.s * r.c + q.c * r.s + ..c = q.c * r.c - q.s * r.s; } - static void mulToOutUnsafe(Rot q, Vector2 v, Vector2 out) { - out.x = q.c * v.x - q.s * v.y; - out.y = q.s * v.x + q.c * v.y; + static Rot mulTrans(Rot q, Rot r) { + return Rot() + ..s = q.c * r.s - q.s * r.c + ..c = q.c * r.c + q.s * r.s; } - static void mulTransVec2(Rot q, Vector2 v, Vector2 out) { - final double tempy = -q.s * v.x + q.c * v.y; - out.x = q.c * v.x + q.s * v.y; - out.y = tempy; + static Vector2 mulVec2(Rot q, Vector2 v) { + return Vector2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); } - static void mulTransUnsafeVec2(Rot q, Vector2 v, Vector2 out) { - out.x = q.c * v.x + q.s * v.y; - out.y = -q.s * v.x + q.c * v.y; + static Vector2 mulTransVec2(Rot q, Vector2 v) { + return Vector2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); } } diff --git a/lib/src/common/sweep.dart b/lib/src/common/sweep.dart index c1e649d..137030f 100644 --- a/lib/src/common/sweep.dart +++ b/lib/src/common/sweep.dart @@ -1,43 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; -/** - * This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to - * the body origin, which may not coincide with the center of mass. However, to support dynamics we - * must interpolate the center of mass position. - */ +/// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to +/// the body origin, which may not coincide with the center of mass. However, to support dynamics we +/// must interpolate the center of mass position. class Sweep { - /** Local center of mass position */ - final Vector2 localCenter = new Vector2.zero(); - /** Center world positions */ - final Vector2 c0 = new Vector2.zero(), c = new Vector2.zero(); - /** World angles */ + /// Local center of mass position + final Vector2 localCenter = Vector2.zero(); + + /// Center world positions + final Vector2 c0 = Vector2.zero(), c = Vector2.zero(); + + /// World angles double a0 = 0.0, a = 0.0; - /** Fraction of the current time step in the range [0,1] c0 and a0 are the positions at alpha0. */ + /// Fraction of the current time step in the range [0,1] c0 and a0 are the positions at alpha0. double alpha0 = 0.0; String toString() { @@ -64,12 +40,10 @@ class Sweep { return this; } - /** - * Get the interpolated transform at a specific time. - * - * @param xf the result is placed here - must not be null - * @param t the normalized time in [0,1]. - */ + /// Get the interpolated transform at a specific time. + /// + /// @param xf the result is placed here - must not be null + /// @param t the normalized time in [0,1]. void getTransform(final Transform xf, final double beta) { assert(xf != null); // xf->p = (1.0f - beta) * c0 + beta * c; @@ -87,11 +61,9 @@ class Sweep { xf.p.y -= q.s * localCenter.x + q.c * localCenter.y; } - /** - * Advance the sweep forward, yielding a new initial state. - * - * @param alpha the new initial time. - */ + /// Advance the sweep forward, yielding a new initial state. + /// + /// @param alpha the new initial time. void advance(double alpha) { assert(alpha0 < 1.0); // float32 beta = (alpha - alpha0) / (1.0f - alpha0); diff --git a/lib/src/common/timer.dart b/lib/src/common/timer.dart index 3c121e4..8ead2d9 100644 --- a/lib/src/common/timer.dart +++ b/lib/src/common/timer.dart @@ -1,31 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; class Timer { - final _stopWatch = new Stopwatch(); + final _stopWatch = Stopwatch(); Timer() { _stopWatch.start(); diff --git a/lib/src/common/transform.dart b/lib/src/common/transform.dart index bfdf232..1208dda 100644 --- a/lib/src/common/transform.dart +++ b/lib/src/common/transform.dart @@ -1,171 +1,75 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; -/** - * A transform contains translation and rotation. It is used to represent the position and - * orientation of rigid frames. - */ +/// A transform contains translation and rotation. It is used to represent the position and +/// orientation of rigid frames. class Transform { - /** The translation caused by the transform */ + /// The translation caused by the transform final Vector2 p; - /** A matrix representing a rotation */ + /// A matrix representing a rotation final Rot q; - /** The default constructor. */ + /// The default constructor. Transform.zero() - : p = new Vector2.zero(), - q = new Rot(); + : p = Vector2.zero(), + q = Rot(); - /** Initialize as a copy of another transform. */ + /// Initialize as a copy of another transform. Transform.clone(final Transform xf) : p = xf.p.clone(), q = xf.q.clone(); - /** Initialize using a position vector and a rotation matrix. */ + /// Initialize using a position vector and a rotation matrix. Transform.from(final Vector2 _position, final Rot _R) : p = _position.clone(), q = _R.clone(); - /** Set this to equal another transform. */ + /// Set this to equal another transform. Transform set(final Transform xf) { p.setFrom(xf.p); - q.set(xf.q); + q.setFrom(xf.q); return this; } - /** - * Set this based on the position and angle. - * - * @param p - * @param angle - */ + /// Set this based on the position and angle. void setVec2Angle(Vector2 p, double angle) { p.setFrom(p); q.setAngle(angle); } - /** Set this to the identity transform. */ + /// Set this to the identity transform. void setIdentity() { p.setZero(); q.setIdentity(); } static Vector2 mulVec2(final Transform T, final Vector2 v) { - return new Vector2((T.q.c * v.x - T.q.s * v.y) + T.p.x, + return Vector2((T.q.c * v.x - T.q.s * v.y) + T.p.x, (T.q.s * v.x + T.q.c * v.y) + T.p.y); } - static void mulToOutVec2( - final Transform T, final Vector2 v, final Vector2 out) { - final double tempy = (T.q.s * v.x + T.q.c * v.y) + T.p.y; - out.x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; - out.y = tempy; - } - - static void mulToOutUnsafeVec2( - final Transform transform, final Vector2 v, final Vector2 out) { - out.x = (transform.q.c * v.x - transform.q.s * v.y) + transform.p.x; - out.y = (transform.q.s * v.x + transform.q.c * v.y) + transform.p.y; - } - static Vector2 mulTransVec2(final Transform T, final Vector2 v) { final double px = v.x - T.p.x; final double py = v.y - T.p.y; - return new Vector2((T.q.c * px + T.q.s * py), (-T.q.s * px + T.q.c * py)); - } - - static void mulTransToOutVec2( - final Transform T, final Vector2 v, final Vector2 out) { - final double px = v.x - T.p.x; - final double py = v.y - T.p.y; - final double tempy = (-T.q.s * px + T.q.c * py); - out.x = (T.q.c * px + T.q.s * py); - out.y = tempy; - } - - static void mulTransToOutUnsafeVec2( - final Transform T, final Vector2 v, final Vector2 out) { - assert(v != out); - final double px = v.x - T.p.x; - final double py = v.y - T.p.y; - out.x = (T.q.c * px + T.q.s * py); - out.y = (-T.q.s * px + T.q.c * py); + return Vector2((T.q.c * px + T.q.s * py), (-T.q.s * px + T.q.c * py)); } static Transform mul(final Transform A, final Transform B) { - Transform C = new Transform.zero(); - Rot.mulUnsafe(A.q, B.q, C.q); - Rot.mulToOutUnsafe(A.q, B.p, C.p); - C.p.add(A.p); - return C; - } - - static void mulToOut( - final Transform A, final Transform B, final Transform out) { - assert(out != A); - Rot.mul(A.q, B.q, out.q); - Rot.mulToOut(A.q, B.p, out.p); - out.p.add(A.p); + Transform c = Transform.zero(); + c.q.setFrom(Rot.mul(A.q, B.q)); + c.p.setFrom(Rot.mulVec2(A.q, B.p)); + c.p.add(A.p); + return c; } - static void mulToOutUnsafe( - final Transform A, final Transform B, final Transform out) { - assert(out != B); - assert(out != A); - Rot.mulUnsafe(A.q, B.q, out.q); - Rot.mulToOutUnsafe(A.q, B.p, out.p); - out.p.add(A.p); - } - - static Vector2 _pool = new Vector2.zero(); + static Vector2 _pool = Vector2.zero(); static Transform mulTrans(final Transform A, final Transform B) { - Transform C = new Transform.zero(); - Rot.mulTransUnsafe(A.q, B.q, C.q); - (_pool..setFrom(B.p)).sub(A.p); - Rot.mulTransUnsafeVec2(A.q, _pool, C.p); - return C; - } - - void mulTransToOut( - final Transform A, final Transform B, final Transform out) { - assert(out != A); - Rot.mulTrans(A.q, B.q, out.q); - (_pool..setFrom(B.p)).sub(A.p); - Rot.mulTransVec2(A.q, _pool, out.p); - } - - static void mulTransToOutUnsafe( - final Transform A, final Transform B, final Transform out) { - assert(out != A); - assert(out != B); - Rot.mulTransUnsafe(A.q, B.q, out.q); + Transform c = Transform.zero(); + c.q.setFrom(Rot.mulTrans(A.q, B.q)); (_pool..setFrom(B.p)).sub(A.p); - Rot.mulTransUnsafeVec2(A.q, _pool, out.p); + c.p.setFrom(Rot.mulTransVec2(A.q, _pool)); + return c; } String toString() { diff --git a/lib/src/common/viewport_transform.dart b/lib/src/common/viewport_transform.dart index 80b369e..b308326 100644 --- a/lib/src/common/viewport_transform.dart +++ b/lib/src/common/viewport_transform.dart @@ -1,74 +1,38 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d.common; class ViewportTransform { ViewportTransform(Vector2 e, Vector2 c, this.scale) - : extents = new Vector2.copy(e), - center = new Vector2.copy(c); + : extents = Vector2.copy(e), + center = Vector2.copy(c); - /** - * if we flip the y axis when transforming. - */ + /// if we flip the y axis when transforming. bool yFlip; - /** - * This is the half-width and half-height. - * This should be the actual half-width and - * half-height, not anything transformed or scaled. - */ + /// This is the half-width and half-height. + /// This should be the actual half-width and + /// half-height, not anything transformed or scaled. Vector2 extents; - /** - * Returns the scaling factor used in converting from world sizes to rendering - * sizes. - */ + /// Returns the scaling factor used in converting from world sizes to rendering + /// sizes. double scale; - /** - * center of the viewport. - */ + /// center of the viewport. Vector2 center; - /** - * Sets the transform's center to the given x and y coordinates, - * and using the given scale. - */ + /// Sets the transform's center to the given x and y coordinates, + /// and using the given scale. void setCamera(double x, double y, double s) { center.setValues(x, y); scale = s; } - /** - * The current translation is the difference in canvas units between the - * actual center of the canvas and the currently specified center. For - * example, if the actual canvas center is (5, 5) but the current center is - * (6, 6), the translation is (1, 1). - */ + /// The current translation is the difference in canvas units between the + /// actual center of the canvas and the currently specified center. For + /// example, if the actual canvas center is (5, 5) but the current center is + /// (6, 6), the translation is (1, 1). Vector2 get translation { - Vector2 result = new Vector2.copy(extents); + Vector2 result = Vector2.copy(extents); return result..sub(center); } @@ -77,33 +41,24 @@ class ViewportTransform { center.sub(translation); } - /** - * Takes the world coordinate (argWorld) puts the corresponding - * screen coordinate in argScreen. It should be safe to give the - * same object as both parameters. - */ - void getWorldToScreen(Vector2 argWorld, Vector2 argScreen) { + /// Takes the world coordinates and return the corresponding screen coordinates + Vector2 getWorldToScreen(Vector2 argWorld) { // Correct for canvas considering the upper-left corner, rather than the // center, to be the origin. double gridCorrectedX = (argWorld.x * scale) + extents.x; double gridCorrectedY = extents.y - (argWorld.y * scale); - Vector2 translationTemp = translation; - argScreen.setValues(gridCorrectedX + translationTemp.x, - gridCorrectedY + -translationTemp.y); + return Vector2( + gridCorrectedX + translation.x, gridCorrectedY + -translation.y); } - /** - * Takes the screen coordinates (argScreen) and puts the - * corresponding world coordinates in argWorld. It should be safe - * to give the same object as both parameters. - */ - void getScreenToWorld(Vector2 argScreen, Vector2 argWorld) { + /// Takes the screen coordinates and return the corresponding world coordinates + Vector2 getScreenToWorld(Vector2 argScreen) { double translationCorrectedX = argScreen.x - translation.x; double translationCorrectedY = argScreen.y + translation.y; double gridCorrectedX = (translationCorrectedX - extents.x) / scale; double gridCorrectedY = ((translationCorrectedY - extents.y) * -1) / scale; - argWorld.setValues(gridCorrectedX, gridCorrectedY); + return Vector2(gridCorrectedX, gridCorrectedY); } } diff --git a/lib/src/dynamics/body.dart b/lib/src/dynamics/body.dart index b2bf4ab..411cff3 100644 --- a/lib/src/dynamics/body.dart +++ b/lib/src/dynamics/body.dart @@ -1,34 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A rigid body. These are created via World.createBody. - * - * @author Daniel Murphy - */ +/// A rigid body. These are created via World.createBody. class Body { static const int ISLAND_FLAG = 0x0001; static const int AWAKE_FLAG = 0x0002; @@ -44,25 +16,20 @@ class Body { int _islandIndex = 0; - /** - * The body origin transform. - */ - final Transform _transform = new Transform.zero(); - /** - * The previous transform for particle simulation - */ - final Transform _xf0 = new Transform.zero(); + /// The body origin transform. + final Transform _transform = Transform.zero(); + + /// The previous transform for particle simulation + final Transform _xf0 = Transform.zero(); - /** - * The swept motion for CCD - */ - final Sweep _sweep = new Sweep(); + /// The swept motion for CCD + final Sweep _sweep = Sweep(); /// the linear velocity of the center of mass - final Vector2 _linearVelocity = new Vector2.zero(); + final Vector2 _linearVelocity = Vector2.zero(); double _angularVelocity = 0.0; - final Vector2 _force = new Vector2.zero(); + final Vector2 _force = Vector2.zero(); double _torque = 0.0; final World world; @@ -159,15 +126,13 @@ class Body { _fixtureCount = 0; } - /** - * Creates a fixture and attach it to this body. Use this function if you need to set some fixture - * parameters, like friction. Otherwise you can create the fixture directly from a shape. If the - * density is non-zero, this function automatically updates the mass of the body. Contacts are not - * created until the next time step. - * - * @param def the fixture definition. - * @warning This function is locked during callbacks. - */ + /// Creates a fixture and attach it to this body. Use this function if you need to set some fixture + /// parameters, like friction. Otherwise you can create the fixture directly from a shape. If the + /// density is non-zero, this function automatically updates the mass of the body. Contacts are not + /// created until the next time step. + /// + /// @param def the fixture definition. + /// @warning This function is locked during callbacks. Fixture createFixtureFromFixtureDef(FixtureDef def) { assert(world.isLocked() == false); @@ -175,7 +140,7 @@ class Body { return null; } - Fixture fixture = new Fixture(); + Fixture fixture = Fixture(); fixture.create(this, def); if ((_flags & ACTIVE_FLAG) == ACTIVE_FLAG) { @@ -201,17 +166,15 @@ class Body { return fixture; } - final FixtureDef _fixDef = new FixtureDef(); - - /** - * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use - * FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. - * If the density is non-zero, this function automatically updates the mass of the body. - * - * @param shape the shape to be cloned. - * @param density the shape density (set to zero for static bodies). - * @warning This function is locked during callbacks. - */ + final FixtureDef _fixDef = FixtureDef(); + + /// Creates a fixture from a shape and attach it to this body. This is a convenience function. Use + /// FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. + /// If the density is non-zero, this function automatically updates the mass of the body. + /// + /// @param shape the shape to be cloned. + /// @param density the shape density (set to zero for static bodies). + /// @warning This function is locked during callbacks. Fixture createFixtureFromShape(Shape shape, [double density = 0.0]) { _fixDef.shape = shape; _fixDef.density = density; @@ -219,15 +182,13 @@ class Body { return createFixtureFromFixtureDef(_fixDef); } - /** - * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts - * associated with this fixture. This will automatically adjust the mass of the body if the body - * is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly - * destroyed when the body is destroyed. - * - * @param fixture the fixture to be removed. - * @warning This function is locked during callbacks. - */ + /// Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts + /// associated with this fixture. This will automatically adjust the mass of the body if the body + /// is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly + /// destroyed when the body is destroyed. + /// + /// @param fixture the fixture to be removed. + /// @warning This function is locked during callbacks. void destroyFixture(Fixture fixture) { assert(world.isLocked() == false); if (world.isLocked() == true) { @@ -293,14 +254,12 @@ class Body { resetMassData(); } - /** - * Set the position of the body's origin and rotation. This breaks any contacts and wakes the - * other bodies. Manipulating a body's transform may cause non-physical behavior. Note: contacts - * are updated on the next call to World.step(). - * - * @param position the world position of the body's local origin. - * @param angle the world rotation in radians. - */ + /// Set the position of the body's origin and rotation. This breaks any contacts and wakes the + /// other bodies. Manipulating a body's transform may cause non-physical behavior. Note: contacts + /// are updated on the next call to World.step(). + /// + /// @param position the world position of the body's local origin. + /// @param angle the world rotation in radians. void setTransform(Vector2 position, double angle) { assert(world.isLocked() == false); if (world.isLocked() == true) { @@ -310,8 +269,7 @@ class Body { _transform.q.setAngle(angle); _transform.p.setFrom(position); - // _sweep.c0 = _sweep.c = Mul(_xf, _sweep.localCenter); - Transform.mulToOutUnsafeVec2(_transform, _sweep.localCenter, _sweep.c); + _sweep.c.setFrom(Transform.mulVec2(_transform, _sweep.localCenter)); _sweep.a = angle; _sweep.c0.setFrom(_sweep.c); @@ -323,39 +281,25 @@ class Body { } } - /** - * Get the world body origin position. Do not modify. - * - * @return the world position of the body's origin. - */ + /// Get the world body origin position. Do not modify. + /// + /// @return the world position of the body's origin. Vector2 get position => _transform.p; - /** - * Get the angle in radians. - * - * @return the current world rotation angle in radians. - */ - double getAngle() { - return _sweep.a; - } + /// Get the angle in radians. + /// + /// @return the current world rotation angle in radians. + double getAngle() => _sweep.a; - /** - * Get the world position of the center of mass. Do not modify. - */ + /// Get the world position of the center of mass. Do not modify. Vector2 get worldCenter => _sweep.c; - /** - * Get the local position of the center of mass. Do not modify. - */ - Vector2 getLocalCenter() { - return _sweep.localCenter; - } + /// Get the local position of the center of mass. Do not modify. + Vector2 getLocalCenter() => _sweep.localCenter; - /** - * Set the linear velocity of the center of mass. - * - * @param v the new linear velocity of the center of mass. - */ + /// Set the linear velocity of the center of mass. + /// + /// @param v the new linear velocity of the center of mass. void set linearVelocity(Vector2 v) { if (_bodyType == BodyType.STATIC) { return; @@ -368,19 +312,15 @@ class Body { _linearVelocity.setFrom(v); } - /** - * Get the linear velocity of the center of mass. Do not modify, instead use - * {@link #setLinearVelocity(Vec2)}. - * - * @return the linear velocity of the center of mass. - */ + /// Get the linear velocity of the center of mass. Do not modify, instead use + /// {@link #setLinearVelocity(Vec2)}. + /// + /// @return the linear velocity of the center of mass. Vector2 get linearVelocity => _linearVelocity; - /** - * Set the angular velocity. - * - * @param omega the new angular velocity in radians/second. - */ + /// Set the angular velocity. + /// + /// @param omega the new angular velocity in radians/second. void set angularVelocity(double w) { if (_bodyType == BodyType.STATIC) { return; @@ -393,48 +333,25 @@ class Body { _angularVelocity = w; } - /** - * Get the angular velocity. - * - * @return the angular velocity in radians/second. - */ - double get angularVelocity { - return _angularVelocity; - } + /// Get the angular velocity. + /// + /// @return the angular velocity in radians/second. + double get angularVelocity => _angularVelocity; - /** - * Apply a force at a world point. If the force is not applied at the center of mass, it will - * generate a torque and affect the angular velocity. This wakes up the body. - * - * @param force the world force vector, usually in Newtons (N). - * @param point the world position of the point of application. - */ + /// Apply a force at a world point. If the force is not applied at the center of mass, it will + /// generate a torque and affect the angular velocity. This wakes up the body. + /// + /// @param force the world force vector, usually in Newtons (N). + /// @param point the world position of the point of application. void applyForce(Vector2 force, Vector2 point) { - if (_bodyType != BodyType.DYNAMIC) { - return; - } - - if (isAwake() == false) { - setAwake(true); - } - - // _force.addLocal(force); - // Vec2 temp = tltemp.get(); - // temp.set(point).subLocal(_sweep.c); - // _torque += Vec2.cross(temp, force); - - _force.x += force.x; - _force.y += force.y; - + applyForceToCenter(force); _torque += (point.x - _sweep.c.x) * force.y - (point.y - _sweep.c.y) * force.x; } - /** - * Apply a force to the center of mass. This wakes up the body. - * - * @param force the world force vector, usually in Newtons (N). - */ + /// Apply a force to the center of mass. This wakes up the body. + /// + /// @param force the world force vector, usually in Newtons (N). void applyForceToCenter(Vector2 force) { if (_bodyType != BodyType.DYNAMIC) { return; @@ -448,12 +365,10 @@ class Body { _force.y += force.y; } - /** - * Apply a torque. This affects the angular velocity without affecting the linear velocity of the - * center of mass. This wakes up the body. - * - * @param torque about the z-axis (out of the screen), usually in N-m. - */ + /// Apply a torque. This affects the angular velocity without affecting the linear velocity of the + /// center of mass. This wakes up the body. + /// + /// @param torque about the z-axis (out of the screen), usually in N-m. void applyTorque(double torque) { if (_bodyType != BodyType.DYNAMIC) { return; @@ -463,19 +378,17 @@ class Body { setAwake(true); } - torque += torque; + _torque += torque; } - /** - * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the - * angular velocity if the point of application is not at the center of mass. This wakes up the - * body if 'wake' is set to true. If the body is sleeping and 'wake' is false, then there is no - * effect. - * - * @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - * @param point the world position of the point of application. - * @param wake also wake up the body - */ + /// Apply an impulse at a point. This immediately modifies the velocity. It also modifies the + /// angular velocity if the point of application is not at the center of mass. This wakes up the + /// body if 'wake' is set to true. If the body is sleeping and 'wake' is false, then there is no + /// effect. + /// + /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. + /// @param point the world position of the point of application. + /// @param wake also wake up the body void applyLinearImpulse(Vector2 impulse, Vector2 point, bool wake) { if (_bodyType != BodyType.DYNAMIC) { return; @@ -497,11 +410,9 @@ class Body { (point.y - _sweep.c.y) * impulse.x); } - /** - * Apply an angular impulse. - * - * @param impulse the angular impulse in units of kg*m*m/s - */ + /// Apply an angular impulse. + /// + /// @param impulse the angular impulse in units of kg*m*m/s void applyAngularImpulse(double impulse) { if (_bodyType != BodyType.DYNAMIC) { return; @@ -513,18 +424,14 @@ class Body { _angularVelocity += _invI * impulse; } - /** - * Get the total mass of the body. - * - * @return the mass, usually in kilograms (kg). - */ + /// Get the total mass of the body. + /// + /// @return the mass, usually in kilograms (kg). double get mass => _mass; - /** - * Get the central rotational inertia of the body. - * - * @return the rotational inertia, usually in kg-m^2. - */ + /// Get the central rotational inertia of the body. + /// + /// @return the rotational inertia, usually in kg-m^2. double getInertia() { return _I + _mass * @@ -532,32 +439,22 @@ class Body { _sweep.localCenter.y * _sweep.localCenter.y); } - /** - * Get the mass data of the body. The rotational inertia is relative to the center of mass. - * - * @return a struct containing the mass, inertia and center of the body. - */ - void getMassData(MassData data) { - // data.mass = _mass; - // data.I = _I + _mass * Vec2.dot(_sweep.localCenter, _sweep.localCenter); - // data.center.set(_sweep.localCenter); - - data.mass = _mass; - data.I = _I + - _mass * - (_sweep.localCenter.x * _sweep.localCenter.x + - _sweep.localCenter.y * _sweep.localCenter.y); - data.center.x = _sweep.localCenter.x; - data.center.y = _sweep.localCenter.y; + /// Get the mass data of the body. The rotational inertia is relative to the center of mass. + /// + /// @return a struct containing the mass, inertia and center of the body. + MassData getMassData() { + return MassData() + ..mass = _mass + ..I = _I + getInertia() + ..center.x = _sweep.localCenter.x + ..center.y = _sweep.localCenter.y; } - /** - * Set the mass properties to override the mass properties of the fixtures. Note that this changes - * the center of mass position. Note that creating or destroying fixtures can also alter the mass. - * This function has no effect if the body isn't dynamic. - * - * @param massData the mass properties. - */ + /// Set the mass properties to override the mass properties of the fixtures. Note that this changes + /// the center of mass position. Note that creating or destroying fixtures can also alter the mass. + /// This function has no effect if the body isn't dynamic. + /// + /// @param massData the mass properties. void setMassData(MassData massData) { // TODO_ERIN adjust linear velocity and torque to account for movement of center. assert(world.isLocked() == false); @@ -586,31 +483,23 @@ class Body { _invI = 1.0 / _I; } - final Vector2 oldCenter = world.getPool().popVec2(); // Move center of mass. - oldCenter.setFrom(_sweep.c); + final Vector2 oldCenter = Vector2.copy(_sweep.c); _sweep.localCenter.setFrom(massData.center); - // _sweep.c0 = _sweep.c = Mul(_xf, _sweep.localCenter); - Transform.mulToOutUnsafeVec2(_transform, _sweep.localCenter, _sweep.c0); + _sweep.c0.setFrom(Transform.mulVec2(_transform, _sweep.localCenter)); _sweep.c.setFrom(_sweep.c0); // Update center of mass velocity. - // _linearVelocity += Cross(_angularVelocity, _sweep.c - oldCenter); - final Vector2 temp = world.getPool().popVec2(); - (temp..setFrom(_sweep.c)).sub(oldCenter); + final Vector2 temp = Vector2.copy(_sweep.c)..sub(oldCenter); temp.scaleOrthogonalInto(_angularVelocity, temp); _linearVelocity.add(temp); - - world.getPool().pushVec2(2); } - final MassData _pmd = new MassData(); + final MassData _pmd = MassData(); - /** - * This resets the mass properties to the sum of the mass properties of the fixtures. This - * normally does not need to be called unless you called setMassData to override the mass and you - * later want to reset the mass. - */ + /// This resets the mass properties to the sum of the mass properties of the fixtures. This + /// normally does not need to be called unless you called setMassData to override the mass and you + /// later want to reset the mass. void resetMassData() { // Compute mass data from shapes. Each shape has its own density. _mass = 0.0; @@ -621,7 +510,6 @@ class Body { // Static and kinematic bodies have zero mass. if (_bodyType == BodyType.STATIC || _bodyType == BodyType.KINEMATIC) { - // _sweep.c0 = _sweep.c = _xf.position; _sweep.c0.setFrom(_transform.p); _sweep.c.setFrom(_transform.p); _sweep.a0 = _sweep.a; @@ -631,9 +519,8 @@ class Body { assert(_bodyType == BodyType.DYNAMIC); // Accumulate mass over all fixtures. - final Vector2 localCenter = world.getPool().popVec2(); - localCenter.setZero(); - final Vector2 temp = world.getPool().popVec2(); + final Vector2 localCenter = Vector2.zero(); + final Vector2 temp = Vector2.zero(); final MassData massData = _pmd; for (Fixture f = _fixtureList; f != null; f = f._next) { if (f._density == 0.0) { @@ -641,7 +528,6 @@ class Body { } f.getMassData(massData); _mass += massData.mass; - // center += massData.mass * massData.center; (temp..setFrom(massData.center)).scale(massData.mass); localCenter.add(temp); _I += massData.I; @@ -667,142 +553,78 @@ class Body { _invI = 0.0; } - Vector2 oldCenter = world.getPool().popVec2(); // Move center of mass. - oldCenter.setFrom(_sweep.c); + Vector2 oldCenter = Vector2.copy(_sweep.c); _sweep.localCenter.setFrom(localCenter); - // _sweep.c0 = _sweep.c = Mul(_xf, _sweep.localCenter); - Transform.mulToOutUnsafeVec2(_transform, _sweep.localCenter, _sweep.c0); + _sweep.c0.setFrom(Transform.mulVec2(_transform, _sweep.localCenter)); _sweep.c.setFrom(_sweep.c0); // Update center of mass velocity. - // _linearVelocity += Cross(_angularVelocity, _sweep.c - oldCenter); (temp..setFrom(_sweep.c)).sub(oldCenter); final Vector2 temp2 = oldCenter; temp.scaleOrthogonalInto(_angularVelocity, temp2); _linearVelocity.add(temp2); - - world.getPool().pushVec2(3); } - /** - * Get the world coordinates of a point given the local coordinates. - * - * @param localPoint a point on the body measured relative the the body's origin. - * @return the same point expressed in world coordinates. - */ + /// Get the world coordinates of a point given the local coordinates. + /// + /// @param localPoint a point on the body measured relative the the body's origin. + /// @return the same point expressed in world coordinates. Vector2 getWorldPoint(Vector2 localPoint) { - Vector2 v = new Vector2.zero(); - getWorldPointToOut(localPoint, v); - return v; - } - - void getWorldPointToOut(Vector2 localPoint, Vector2 out) { - Transform.mulToOutVec2(_transform, localPoint, out); + return Transform.mulVec2(_transform, localPoint); } - /** - * Get the world coordinates of a vector given the local coordinates. - * - * @param localVector a vector fixed in the body. - * @return the same vector expressed in world coordinates. - */ + /// Get the world coordinates of a vector given the local coordinates. + /// + /// @param localVector a vector fixed in the body. + /// @return the same vector expressed in world coordinates. Vector2 getWorldVector(Vector2 localVector) { - Vector2 out = new Vector2.zero(); - getWorldVectorToOut(localVector, out); - return out; + return Rot.mulVec2(_transform.q, localVector); } - void getWorldVectorToOut(Vector2 localVector, Vector2 out) { - Rot.mulToOut(_transform.q, localVector, out); - } - - void getWorldVectorToOutUnsafe(Vector2 localVector, Vector2 out) { - Rot.mulToOutUnsafe(_transform.q, localVector, out); - } - - /** - * Gets a local point relative to the body's origin given a world point. - * - * @param a point in world coordinates. - * @return the corresponding local point relative to the body's origin. - */ + /// Gets a local point relative to the body's origin given a world point. + /// + /// @param a point in world coordinates. + /// @return the corresponding local point relative to the body's origin. Vector2 getLocalPoint(Vector2 worldPoint) { - Vector2 out = new Vector2.zero(); - getLocalPointToOut(worldPoint, out); - return out; - } - - void getLocalPointToOut(Vector2 worldPoint, Vector2 out) { - Transform.mulTransToOutVec2(_transform, worldPoint, out); + return Transform.mulTransVec2(_transform, worldPoint); } - /** - * Gets a local vector given a world vector. - * - * @param a vector in world coordinates. - * @return the corresponding local vector. - */ + /// Gets a local vector given a world vector. + /// + /// @param a vector in world coordinates. + /// @return the corresponding local vector. Vector2 getLocalVector(Vector2 worldVector) { - Vector2 out = new Vector2.zero(); - getLocalVectorToOut(worldVector, out); - return out; - } - - void getLocalVectorToOut(Vector2 worldVector, Vector2 out) { - Rot.mulTransVec2(_transform.q, worldVector, out); - } - - void getLocalVectorToOutUnsafe(Vector2 worldVector, Vector2 out) { - Rot.mulTransUnsafeVec2(_transform.q, worldVector, out); + return Rot.mulTransVec2(_transform.q, worldVector); } - /** - * Get the world linear velocity of a world point attached to this body. - * - * @param a point in world coordinates. - * @return the world velocity of a point. - */ + /// Get the world linear velocity of a world point attached to this body. + /// + /// @param a point in world coordinates. + /// @return the world velocity of a point. Vector2 getLinearVelocityFromWorldPoint(Vector2 worldPoint) { - Vector2 out = new Vector2.zero(); - getLinearVelocityFromWorldPointToOut(worldPoint, out); - return out; + return Vector2( + -_angularVelocity * (worldPoint.y - _sweep.c.y) + _linearVelocity.x, + _angularVelocity * (worldPoint.x - _sweep.c.x) + _linearVelocity.y, + ); } - void getLinearVelocityFromWorldPointToOut(Vector2 worldPoint, Vector2 out) { - final double tempX = worldPoint.x - _sweep.c.x; - final double tempY = worldPoint.y - _sweep.c.y; - out.x = -_angularVelocity * tempY + _linearVelocity.x; - out.y = _angularVelocity * tempX + _linearVelocity.y; - } - - /** - * Get the world velocity of a local point. - * - * @param a point in local coordinates. - * @return the world velocity of a point. - */ + /// Get the world velocity of a local point. + /// + /// @param a point in local coordinates. + /// @return the world velocity of a point. Vector2 getLinearVelocityFromLocalPoint(Vector2 localPoint) { - Vector2 out = new Vector2.zero(); - getLinearVelocityFromLocalPointToOut(localPoint, out); - return out; - } - - void getLinearVelocityFromLocalPointToOut(Vector2 localPoint, Vector2 out) { - getWorldPointToOut(localPoint, out); - getLinearVelocityFromWorldPointToOut(out, out); + return getLinearVelocityFromWorldPoint(getWorldPoint(localPoint)); } BodyType getType() { return _bodyType; } - /** - * Set the type of this body. This may alter the mass and velocity. - * - * @param type - */ + /// Set the type of this body. This may alter the mass and velocity. + /// + /// @param type void setType(BodyType type) { assert(world.isLocked() == false); if (world.isLocked() == true) { @@ -849,12 +671,12 @@ class Body { } } - /** Is this body treated like a bullet for continuous collision detection? */ + /// Is this body treated like a bullet for continuous collision detection? bool isBullet() { return (_flags & BULLET_FLAG) == BULLET_FLAG; } - /** Should this body be treated like a bullet for continuous collision detection? */ + /// Should this body be treated like a bullet for continuous collision detection? void setBullet(bool flag) { if (flag) { _flags |= BULLET_FLAG; @@ -863,11 +685,9 @@ class Body { } } - /** - * You can disable sleeping on this body. If you disable sleeping, the body will be woken. - * - * @param flag - */ + /// You can disable sleeping on this body. If you disable sleeping, the body will be woken. + /// + /// @param flag void setSleepingAllowed(bool flag) { if (flag) { _flags |= AUTO_SLEEP_FLAG; @@ -877,21 +697,17 @@ class Body { } } - /** - * Is this body allowed to sleep - * - * @return - */ + /// Is this body allowed to sleep + /// + /// @return bool isSleepingAllowed() { return (_flags & AUTO_SLEEP_FLAG) == AUTO_SLEEP_FLAG; } - /** - * Set the sleep state of the body. A sleeping body has very low CPU cost. - * - * @param flag set to true to put body to sleep, false to wake it. - * @param flag - */ + /// Set the sleep state of the body. A sleeping body has very low CPU cost. + /// + /// @param flag set to true to put body to sleep, false to wake it. + /// @param flag void setAwake(bool flag) { if (flag) { if ((_flags & AWAKE_FLAG) == 0) { @@ -908,27 +724,21 @@ class Body { } } - /** - * Get the sleeping state of this body. - * - * @return true if the body is awake. - */ + /// Get the sleeping state of this body. + /// + /// @return true if the body is awake. bool isAwake() { return (_flags & AWAKE_FLAG) == AWAKE_FLAG; } - /** - * Set the active state of the body. An inactive body is not simulated and cannot be collided with - * or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you - * pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will - * be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy - * fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive - * and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive - * body are implicitly inactive. An inactive body is still owned by a World object and remains in - * the body list. - * - * @param flag - */ + /// Set the active state of the body. An inactive body is not simulated and cannot be collided with + /// or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you + /// pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will + /// be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy + /// fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive + /// and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive + /// body are implicitly inactive. An inactive body is still owned by a World object and remains in + /// the body list. void setActive(bool flag) { assert(world.isLocked() == false); @@ -966,20 +776,16 @@ class Body { } } - /** - * Get the active state of the body. - * - * @return - */ + /// Get the active state of the body. + /// + /// @return bool isActive() { return (_flags & ACTIVE_FLAG) == ACTIVE_FLAG; } - /** - * Set this body to have fixed rotation. This causes the mass to be reset. - * - * @param flag - */ + /// Set this body to have fixed rotation. This causes the mass to be reset. + /// + /// @param flag void setFixedRotation(bool flag) { if (flag) { _flags |= FIXED_ROTATION_FLAG; @@ -990,51 +796,41 @@ class Body { resetMassData(); } - /** - * Does this body have fixed rotation? - * - * @return - */ + /// Does this body have fixed rotation? + /// + /// @return bool isFixedRotation() { return (_flags & FIXED_ROTATION_FLAG) == FIXED_ROTATION_FLAG; } - /** Get the list of all fixtures attached to this body. */ + /// Get the list of all fixtures attached to this body. Fixture getFixtureList() { return _fixtureList; } - /** Get the list of all joints attached to this body. */ + /// Get the list of all joints attached to this body. JointEdge getJointList() { return _jointList; } - /** - * Get the list of all contacts attached to this body. - * - * @warning this list changes during the time step and you may miss some collisions if you don't - * use ContactListener. - */ + /// Get the list of all contacts attached to this body. + /// + /// @warning this list changes during the time step and you may miss some collisions if you don't + /// use ContactListener. ContactEdge getContactList() { return _contactList; } - /** Get the next body in the world's body list. */ + /// Get the next body in the world's body list. Body getNext() { return _next; } // djm pooling - final Transform _pxf = new Transform.zero(); + final Transform _pxf = Transform.zero(); void synchronizeFixtures() { final Transform xf1 = _pxf; - // xf1.position = _sweep.c0 - Mul(xf1.R, _sweep.localCenter); - - // xf1.q.set(_sweep.a0); - // Rot.mulToOutUnsafe(xf1.q, _sweep.localCenter, xf1.p); - // xf1.p.mulLocal(-1).addLocal(_sweep.c0); - // inlined: xf1.q.s = Math.sin(_sweep.a0); xf1.q.c = Math.cos(_sweep.a0); xf1.p.x = _sweep.c0.x - @@ -1043,7 +839,6 @@ class Body { xf1.p.y = _sweep.c0.y - xf1.q.s * _sweep.localCenter.x - xf1.q.c * _sweep.localCenter.y; - // end inline for (Fixture f = _fixtureList; f != null; f = f._next) { f.synchronize(world._contactManager.broadPhase, xf1, _transform); @@ -1051,12 +846,6 @@ class Body { } void synchronizeTransform() { - // _xf.q.set(_sweep.a); - // - // // _xf.position = _sweep.c - Mul(_xf.R, _sweep.localCenter); - // Rot.mulToOutUnsafe(_xf.q, _sweep.localCenter, _xf.p); - // _xf.p.mulLocal(-1).addLocal(_sweep.c); - // _transform.q.s = Math.sin(_sweep.a); _transform.q.c = Math.cos(_sweep.a); Rot q = _transform.q; @@ -1065,13 +854,11 @@ class Body { _transform.p.y = _sweep.c.y - q.s * v.x - q.c * v.y; } - /** - * This is used to prevent connected bodies from colliding. It may lie, depending on the - * collideConnected flag. - * - * @param other - * @return - */ + /// This is used to prevent connected bodies from colliding. It may lie, depending on the + /// collideConnected flag. + /// + /// @param other + /// @return bool shouldCollide(Body other) { // At least one body should be dynamic. if (_bodyType != BodyType.DYNAMIC && other._bodyType != BodyType.DYNAMIC) { @@ -1096,8 +883,7 @@ class Body { _sweep.c.setFrom(_sweep.c0); _sweep.a = _sweep.a0; _transform.q.setAngle(_sweep.a); - // _xf.position = _sweep.c - Mul(_xf.R, _sweep.localCenter); - Rot.mulToOutUnsafe(_transform.q, _sweep.localCenter, _transform.p); + _transform.p.setFrom(Rot.mulVec2(_transform.q, _sweep.localCenter)); (_transform.p..scale(-1.0)).add(_sweep.c); } diff --git a/lib/src/dynamics/body_def.dart b/lib/src/dynamics/body_def.dart index 3412ccb..ef3ad88 100644 --- a/lib/src/dynamics/body_def.dart +++ b/lib/src/dynamics/body_def.dart @@ -1,330 +1,219 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A body definition holds all the data needed to construct a rigid body. You can safely re-use body - * definitions. Shapes are added to a body after construction. - - */ +/// A body definition holds all the data needed to construct a rigid body. You can safely re-use body +/// definitions. Shapes are added to a body after construction. class BodyDef { - /** - * The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the - * mass is set to one. - */ + /// The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the + /// mass is set to one. BodyType type = BodyType.STATIC; - /** - * Use this to store application specific body data. - */ + /// Use this to store application specific body data. Object userData; - /** - * The world position of the body. Avoid creating bodies at the origin since this can lead to many - * overlapping shapes. - */ - Vector2 position = new Vector2.zero(); + /// The world position of the body. Avoid creating bodies at the origin since this can lead to many + /// overlapping shapes. + Vector2 position = Vector2.zero(); - /** - * The world angle of the body in radians. - */ + /// The world angle of the body in radians. double angle = 0.0; - /** - * The linear velocity of the body in world co-ordinates. - */ - Vector2 linearVelocity = new Vector2.zero(); + /// The linear velocity of the body in world co-ordinates. + Vector2 linearVelocity = Vector2.zero(); - /** - * The angular velocity of the body. - */ + /// The angular velocity of the body. double angularVelocity = 0.0; - /** - * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Linear damping is use to reduce the linear velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. double linearDamping = 0.0; - /** - * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Angular damping is use to reduce the angular velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. double angularDamping = 0.0; - /** - * Set this flag to false if this body should never fall asleep. Note that this increases CPU - * usage. - */ + /// Set this flag to false if this body should never fall asleep. Note that this increases CPU + /// usage. bool allowSleep = true; - /** - * Is this body initially sleeping? - */ + /// Is this body initially sleeping? bool awake = true; - /** - * Should this body be prevented from rotating? Useful for characters. - */ + /// Should this body be prevented from rotating? Useful for characters. bool fixedRotation = false; - /** - * Is this a fast moving body that should be prevented from tunneling through other moving bodies? - * Note that all bodies are prevented from tunneling through kinematic and static bodies. This - * setting is only considered on dynamic bodies. - * - * @warning You should use this flag sparingly since it increases processing time. - */ + /// Is this a fast moving body that should be prevented from tunneling through other moving bodies? + /// Note that all bodies are prevented from tunneling through kinematic and static bodies. This + /// setting is only considered on dynamic bodies. + /// + /// @warning You should use this flag sparingly since it increases processing time. bool bullet = false; - /** - * Does this body start out active? - */ + /// Does this body start out active? bool active = true; - /** - * Experimental: scales the inertia tensor. - */ + /// Experimental: scales the inertia tensor. double gravityScale = 1.0; - /** - * The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the - * mass is set to one. - */ + /// The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the + /// mass is set to one. BodyType getType() { return type; } - /** - * The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the - * mass is set to one. - */ + /// The body type: static, kinematic, or dynamic. Note: if a dynamic body would have zero mass, the + /// mass is set to one. void setType(BodyType type) { this.type = type; } - /** - * Use this to store application specific body data. - */ + /// Use this to store application specific body data. Object getUserData() { return userData; } - /** - * Use this to store application specific body data. - */ + /// Use this to store application specific body data. void setUserData(Object userData) { this.userData = userData; } - /** - * The world position of the body. Avoid creating bodies at the origin since this can lead to many - * overlapping shapes. - */ + /// The world position of the body. Avoid creating bodies at the origin since this can lead to many + /// overlapping shapes. Vector2 getPosition() { return position; } - /** - * The world position of the body. Avoid creating bodies at the origin since this can lead to many - * overlapping shapes. - */ + /// The world position of the body. Avoid creating bodies at the origin since this can lead to many + /// overlapping shapes. void setPosition(Vector2 position) { this.position = position; } - /** - * The world angle of the body in radians. - */ + /// The world angle of the body in radians. double getAngle() { return angle; } - /** - * The world angle of the body in radians. - */ + /// The world angle of the body in radians. void setAngle(double angle) { this.angle = angle; } - /** - * The linear velocity of the body in world co-ordinates. - */ + /// The linear velocity of the body in world co-ordinates. Vector2 getLinearVelocity() { return linearVelocity; } - /** - * The linear velocity of the body in world co-ordinates. - */ + /// The linear velocity of the body in world co-ordinates. void setLinearVelocity(Vector2 linearVelocity) { this.linearVelocity = linearVelocity; } - /** - * The angular velocity of the body. - */ + /// The angular velocity of the body. double getAngularVelocity() { return angularVelocity; } - /** - * The angular velocity of the body. - */ + /// The angular velocity of the body. void setAngularVelocity(double angularVelocity) { this.angularVelocity = angularVelocity; } - /** - * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Linear damping is use to reduce the linear velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. double getLinearDamping() { return linearDamping; } - /** - * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Linear damping is use to reduce the linear velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. void setLinearDamping(double linearDamping) { this.linearDamping = linearDamping; } - /** - * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Angular damping is use to reduce the angular velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. double getAngularDamping() { return angularDamping; } - /** - * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than - * 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - */ + /// Angular damping is use to reduce the angular velocity. The damping parameter can be larger than + /// 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. void setAngularDamping(double angularDamping) { this.angularDamping = angularDamping; } - /** - * Set this flag to false if this body should never fall asleep. Note that this increases CPU - * usage. - */ + /// Set this flag to false if this body should never fall asleep. Note that this increases CPU + /// usage. bool isAllowSleep() { return allowSleep; } - /** - * Set this flag to false if this body should never fall asleep. Note that this increases CPU - * usage. - */ + /// Set this flag to false if this body should never fall asleep. Note that this increases CPU + /// usage. void setAllowSleep(bool allowSleep) { this.allowSleep = allowSleep; } - /** - * Is this body initially sleeping? - */ + /// Is this body initially sleeping? bool isAwake() { return awake; } - /** - * Is this body initially sleeping? - */ + /// Is this body initially sleeping? void setAwake(bool awake) { this.awake = awake; } - /** - * Should this body be prevented from rotating? Useful for characters. - */ + /// Should this body be prevented from rotating? Useful for characters. bool isFixedRotation() { return fixedRotation; } - /** - * Should this body be prevented from rotating? Useful for characters. - */ + /// Should this body be prevented from rotating? Useful for characters. void setFixedRotation(bool fixedRotation) { this.fixedRotation = fixedRotation; } - /** - * Is this a fast moving body that should be prevented from tunneling through other moving bodies? - * Note that all bodies are prevented from tunneling through kinematic and static bodies. This - * setting is only considered on dynamic bodies. - * - * @warning You should use this flag sparingly since it increases processing time. - */ + /// Is this a fast moving body that should be prevented from tunneling through other moving bodies? + /// Note that all bodies are prevented from tunneling through kinematic and static bodies. This + /// setting is only considered on dynamic bodies. + /// + /// @warning You should use this flag sparingly since it increases processing time. bool isBullet() { return bullet; } - /** - * Is this a fast moving body that should be prevented from tunneling through other moving bodies? - * Note that all bodies are prevented from tunneling through kinematic and static bodies. This - * setting is only considered on dynamic bodies. - * - * @warning You should use this flag sparingly since it increases processing time. - */ + /// Is this a fast moving body that should be prevented from tunneling through other moving bodies? + /// Note that all bodies are prevented from tunneling through kinematic and static bodies. This + /// setting is only considered on dynamic bodies. + /// + /// @warning You should use this flag sparingly since it increases processing time. void setBullet(bool bullet) { this.bullet = bullet; } - /** - * Does this body start out active? - */ + /// Does this body start out active? bool isActive() { return active; } - /** - * Does this body start out active? - */ + /// Does this body start out active? void setActive(bool active) { this.active = active; } - /** - * Experimental: scales the inertia tensor. - */ + /// Experimental: scales the inertia tensor. double getGravityScale() { return gravityScale; } - /** - * Experimental: scales the inertia tensor. - */ + /// Experimental: scales the inertia tensor. void setGravityScale(double gravityScale) { this.gravityScale = gravityScale; } diff --git a/lib/src/dynamics/body_type.dart b/lib/src/dynamics/body_type.dart index 95e1e55..52b9b61 100644 --- a/lib/src/dynamics/body_type.dart +++ b/lib/src/dynamics/body_type.dart @@ -1,10 +1,7 @@ part of box2d; -/** - * The body type. - * static: zero mass, zero velocity, may be manually moved - * kinematic: zero mass, non-zero velocity set by user, moved by solver - * dynamic: positive mass, non-zero velocity determined by forces, moved by solver - * - */ +/// The body type. +/// static: zero mass, zero velocity, may be manually moved +/// kinematic: zero mass, non-zero velocity set by user, moved by solver +/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver enum BodyType { STATIC, KINEMATIC, DYNAMIC } diff --git a/lib/src/dynamics/contact_manager.dart b/lib/src/dynamics/contact_manager.dart index db82737..a62cb19 100644 --- a/lib/src/dynamics/contact_manager.dart +++ b/lib/src/dynamics/contact_manager.dart @@ -1,35 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Delegate of World. - * - * @author Daniel Murphy - */ - +/// Delegate of World. class ContactManager implements PairCallback { BroadPhase broadPhase; Contact contactList; @@ -37,21 +8,16 @@ class ContactManager implements PairCallback { ContactFilter contactFilter; ContactListener contactListener; - final World _pool; + final World _world; - ContactManager(this._pool, BroadPhase broadPhase_) { + ContactManager(this._world, BroadPhase broadPhase_) { contactList = null; - contactFilter = new ContactFilter(); + contactFilter = ContactFilter(); contactListener = null; broadPhase = broadPhase_; } - /** - * Broad-phase callback. - * - * @param proxyUserDataA - * @param proxyUserDataB - */ + /// Broad-phase callback. void addPair(FixtureProxy proxyUserDataA, FixtureProxy proxyUserDataB) { FixtureProxy proxyA = proxyUserDataA; FixtureProxy proxyB = proxyUserDataB; @@ -106,8 +72,7 @@ class ContactManager implements PairCallback { return; } - // Call the factory. - Contact c = _pool.popContact(fixtureA, indexA, fixtureB, indexB); + Contact c = Contact.init(fixtureA, indexA, fixtureB, indexB); if (c == null) { return; } @@ -214,15 +179,17 @@ class ContactManager implements PairCallback { bodyB._contactList = c._nodeB.next; } - // Call the factory. - _pool.pushContact(c); + if (c._manifold.pointCount > 0 && + !fixtureA.isSensor() && + !fixtureB.isSensor()) { + fixtureA.getBody().setAwake(true); + fixtureB.getBody().setAwake(true); + } --contactCount; } - /** - * This is the top level collision call for the time step. Here all the narrow phase collision is - * processed for the world contact list. - */ + /// This is the top level collision call for the time step. Here all the narrow phase collision is + /// processed for the world contact list. void collide() { // Update awake contacts. Contact c = contactList; diff --git a/lib/src/dynamics/contacts/chain_and_circle_contact.dart b/lib/src/dynamics/contacts/chain_and_circle_contact.dart index c7056e4..35feab0 100644 --- a/lib/src/dynamics/contacts/chain_and_circle_contact.dart +++ b/lib/src/dynamics/contacts/chain_and_circle_contact.dart @@ -1,44 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ChainAndCircleContact extends Contact { - ChainAndCircleContact(IWorldPool argPool) : super(argPool); - - void init(Fixture fA, int indexA, Fixture fB, int indexB) { - super.init(fA, indexA, fB, indexB); + ChainAndCircleContact(Fixture fA, int indexA, Fixture fB, int indexB) + : super(fA, indexA, fB, indexB) { assert(_fixtureA.getType() == ShapeType.CHAIN); assert(_fixtureB.getType() == ShapeType.CIRCLE); } - final EdgeShape _edge = new EdgeShape(); + final EdgeShape _edge = EdgeShape(); void evaluate(Manifold manifold, Transform xfA, Transform xfB) { final chain = _fixtureA.getShape() as ChainShape; chain.getChildEdge(_edge, _indexA); - _pool.getCollision().collideEdgeAndCircle( + World.collision.collideEdgeAndCircle( manifold, _edge, xfA, _fixtureB.getShape() as CircleShape, xfB); } } diff --git a/lib/src/dynamics/contacts/chain_and_polygon_contact.dart b/lib/src/dynamics/contacts/chain_and_polygon_contact.dart index 481752d..921dc59 100644 --- a/lib/src/dynamics/contacts/chain_and_polygon_contact.dart +++ b/lib/src/dynamics/contacts/chain_and_polygon_contact.dart @@ -1,44 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ChainAndPolygonContact extends Contact { - ChainAndPolygonContact(IWorldPool argPool) : super(argPool); - - void init(Fixture fA, int indexA, Fixture fB, int indexB) { - super.init(fA, indexA, fB, indexB); + ChainAndPolygonContact(Fixture fA, int indexA, Fixture fB, int indexB) + : super(fA, indexA, fB, indexB) { assert(_fixtureA.getType() == ShapeType.CHAIN); assert(_fixtureB.getType() == ShapeType.POLYGON); } - final EdgeShape _edge = new EdgeShape(); + final EdgeShape _edge = EdgeShape(); void evaluate(Manifold manifold, Transform xfA, Transform xfB) { final chain = _fixtureA.getShape() as ChainShape; chain.getChildEdge(_edge, _indexA); - _pool.getCollision().collideEdgeAndPolygon( + World.collision.collideEdgeAndPolygon( manifold, _edge, xfA, _fixtureB.getShape() as PolygonShape, xfB); } } diff --git a/lib/src/dynamics/contacts/circle_contact.dart b/lib/src/dynamics/contacts/circle_contact.dart index 07ed274..067d05c 100644 --- a/lib/src/dynamics/contacts/circle_contact.dart +++ b/lib/src/dynamics/contacts/circle_contact.dart @@ -1,40 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class CircleContact extends Contact { - CircleContact(IWorldPool argPool) : super(argPool); - - void init0(Fixture fixtureA, Fixture fixtureB) { - init(fixtureA, 0, fixtureB, 0); + CircleContact(Fixture fixtureA, Fixture fixtureB) + : super(fixtureA, 0, fixtureB, 0) { assert(_fixtureA.getType() == ShapeType.CIRCLE); assert(_fixtureB.getType() == ShapeType.CIRCLE); } void evaluate(Manifold manifold, Transform xfA, Transform xfB) { - _pool.getCollision().collideCircles( + World.collision.collideCircles( manifold, _fixtureA.getShape() as CircleShape, xfA, diff --git a/lib/src/dynamics/contacts/contact.dart b/lib/src/dynamics/contacts/contact.dart index 3314fb2..af0a732 100644 --- a/lib/src/dynamics/contacts/contact.dart +++ b/lib/src/dynamics/contacts/contact.dart @@ -1,34 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ part of box2d; -/** - * The class manages contact between two shapes. A contact exists for each overlapping AABB in the - * broad-phase (except if filtered). Therefore a contact object may exist that has no contact - * points. - * - */ +/// The class manages contact between two shapes. A contact exists for each overlapping AABB in the +/// broad-phase (except if filtered). Therefore a contact object may exist that has no contact +/// points. abstract class Contact { // Flags stored in _flags // Used when crawling contact graph when forming islands. @@ -51,8 +25,8 @@ abstract class Contact { Contact _next; // Nodes for connecting bodies. - ContactEdge _nodeA = new ContactEdge(); - ContactEdge _nodeB = new ContactEdge(); + ContactEdge _nodeA = ContactEdge(); + ContactEdge _nodeB = ContactEdge(); Fixture _fixtureA; Fixture _fixtureB; @@ -60,7 +34,7 @@ abstract class Contact { int _indexA = 0; int _indexB = 0; - final Manifold _manifold = new Manifold(); + final Manifold _manifold = Manifold(); int _toiCount = 0; double _toi = 0.0; @@ -70,12 +44,7 @@ abstract class Contact { double _tangentSpeed = 0.0; - final IWorldPool _pool; - - Contact(this._pool); - - /** initialization for pooling */ - void init(Fixture fA, int indexA, Fixture fB, int indexB) { + Contact(Fixture fA, int indexA, Fixture fB, int indexB) { _flags = ENABLED_FLAG; _fixtureA = fA; @@ -106,9 +75,38 @@ abstract class Contact { _tangentSpeed = 0.0; } - /** - * Get the world manifold. - */ + static Contact init(Fixture fA, int indexA, Fixture fB, int indexB) { + // Remember that we use the order in the enum here to determine in which + // order the arguments should come in the different contact classes. + // { CIRCLE, EDGE, POLYGON, CHAIN } + ShapeType typeA = + fA.getType().index < fB.getType().index ? fA.getType() : fB.getType(); + ShapeType typeB = fA.getType() == typeA ? fB.getType() : fA.getType(); + Fixture temp = fA; + fA = fA.getType() == typeA ? fA : fB; + fB = fB.getType() == typeB ? fB : temp; + + if (typeA == ShapeType.CIRCLE && typeB == ShapeType.CIRCLE) { + return CircleContact(fA, fB); + } else if (typeA == ShapeType.POLYGON && typeB == ShapeType.POLYGON) { + return PolygonContact(fA, fB); + } else if (typeA == ShapeType.CIRCLE && typeB == ShapeType.POLYGON) { + return PolygonAndCircleContact(fB, fA); + } else if (typeA == ShapeType.CIRCLE && typeB == ShapeType.EDGE) { + return EdgeAndCircleContact(fB, indexB, fA, indexA); + } else if (typeA == ShapeType.CIRCLE && typeB == ShapeType.POLYGON) { + return EdgeAndPolygonContact(fA, indexA, fB, indexB); + } else if (typeA == ShapeType.CIRCLE && typeB == ShapeType.CHAIN) { + return ChainAndCircleContact(fB, indexB, fA, indexA); + } else if (typeA == ShapeType.POLYGON && typeB == ShapeType.CHAIN) { + return ChainAndPolygonContact(fB, indexB, fA, indexA); + } else { + assert(false, "Not compatible contact type"); + return CircleContact(fA, fB); + } + } + + /// Get the world manifold. void getWorldManifold(WorldManifold worldManifold) { final Body bodyA = _fixtureA.getBody(); final Body bodyB = _fixtureB.getBody(); @@ -119,21 +117,13 @@ abstract class Contact { bodyB._transform, shapeB.radius); } - /** - * Is this contact touching - * - * @return - */ + /// Is this contact touching bool isTouching() { return (_flags & TOUCHING_FLAG) == TOUCHING_FLAG; } - /** - * Enable/disable this contact. This can be used inside the pre-solve contact listener. The - * contact is only disabled for the current time step (or sub-step in continuous collisions). - * - * @param flag - */ + /// Enable/disable this contact. This can be used inside the pre-solve contact listener. The + /// contact is only disabled for the current time step (or sub-step in continuous collisions). void setEnabled(bool flag) { if (flag) { _flags |= ENABLED_FLAG; @@ -142,40 +132,24 @@ abstract class Contact { } } - /** - * Has this contact been disabled? - * - * @return - */ + /// Has this contact been disabled? bool isEnabled() { return (_flags & ENABLED_FLAG) == ENABLED_FLAG; } - /** - * Get the next contact in the world's contact list. - * - * @return - */ + /// Get the next contact in the world's contact list. Contact getNext() { return _next; } - /** - * Get the first fixture in this contact. - * - * @return - */ + /// Get the first fixture in this contact. Fixture get fixtureA => _fixtureA; int getChildIndexA() { return _indexA; } - /** - * Get the second fixture in this contact. - * - * @return - */ + /// Get the second fixture in this contact. Fixture get fixtureB => _fixtureB; int getChildIndexB() { @@ -193,15 +167,13 @@ abstract class Contact { void evaluate(Manifold manifold, Transform xfA, Transform xfB); - /** - * Flag this contact for filtering. Filtering will occur the next time step. - */ + /// Flag this contact for filtering. Filtering will occur the next time step. void flagForFiltering() { _flags |= FILTER_FLAG; } // djm pooling - final Manifold _oldManifold = new Manifold(); + final Manifold _oldManifold = Manifold(); void update(ContactListener listener) { _oldManifold.set(_manifold); @@ -220,14 +192,11 @@ abstract class Contact { Body bodyB = _fixtureB.getBody(); Transform xfA = bodyA._transform; Transform xfB = bodyB._transform; - // log.debug("TransformA: "+xfA); - // log.debug("TransformB: "+xfB); if (sensor) { Shape shapeA = _fixtureA.getShape(); Shape shapeB = _fixtureB.getShape(); - touching = _pool - .getCollision() + touching = World.collision .testOverlap(shapeA, _indexA, shapeB, _indexB, xfA, xfB); // Sensors don't generate manifolds. @@ -284,26 +253,14 @@ abstract class Contact { } } - /** - * Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. For - * example, anything slides on ice. - * - * @param friction1 - * @param friction2 - * @return - */ + /// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. For + /// example, anything slides on ice. static double mixFriction(double friction1, double friction2) { return Math.sqrt(friction1 * friction2); } - /** - * Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. For - * example, a superball bounces on anything. - * - * @param restitution1 - * @param restitution2 - * @return - */ + /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. For + /// example, a superball bounces on anything. static double mixRestitution(double restitution1, double restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } diff --git a/lib/src/dynamics/contacts/contact_creator.dart b/lib/src/dynamics/contacts/contact_creator.dart index 57b7428..6eef34e 100644 --- a/lib/src/dynamics/contacts/contact_creator.dart +++ b/lib/src/dynamics/contacts/contact_creator.dart @@ -1,32 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class ContactCreator { - Contact contactCreateFcn( - IWorldPool argPool, Fixture fixtureA, Fixture fixtureB); + Contact contactCreateFcn(Fixture fixtureA, Fixture fixtureB); - void contactDestroyFcn(IWorldPool argPool, Contact contact); + void contactDestroyFcn(Contact contact); } diff --git a/lib/src/dynamics/contacts/contact_edge.dart b/lib/src/dynamics/contacts/contact_edge.dart index 04ec0bb..f3de0b5 100644 --- a/lib/src/dynamics/contacts/contact_edge.dart +++ b/lib/src/dynamics/contacts/contact_edge.dart @@ -1,53 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A contact edge is used to connect bodies and contacts together in a contact graph where each body - * is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained - * in each attached body. Each contact has two contact nodes, one for each attached body. - * - */ +/// A contact edge is used to connect bodies and contacts together in a contact graph where each body +/// is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained +/// in each attached body. Each contact has two contact nodes, one for each attached body. +/// class ContactEdge { - /** - * provides quick access to the other body attached. - */ + /// provides quick access to the other body attached. Body other; - /** - * the contact - */ + /// the contact Contact contact; - /** - * the previous contact edge in the body's contact list - */ + /// the previous contact edge in the body's contact list ContactEdge prev; - /** - * the next contact edge in the body's contact list - */ + /// the next contact edge in the body's contact list ContactEdge next; } diff --git a/lib/src/dynamics/contacts/contact_position_and_constraint.dart b/lib/src/dynamics/contacts/contact_position_and_constraint.dart index 06c3daf..923b7f9 100644 --- a/lib/src/dynamics/contacts/contact_position_and_constraint.dart +++ b/lib/src/dynamics/contacts/contact_position_and_constraint.dart @@ -1,38 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ContactPositionConstraint { - List localPoints = new List(Settings.maxManifoldPoints); - final Vector2 localNormal = new Vector2.zero(); - final Vector2 localPoint = new Vector2.zero(); + List localPoints = List(Settings.maxManifoldPoints); + final Vector2 localNormal = Vector2.zero(); + final Vector2 localPoint = Vector2.zero(); int indexA = 0; int indexB = 0; double invMassA = 0.0, invMassB = 0.0; - final Vector2 localCenterA = new Vector2.zero(); - final Vector2 localCenterB = new Vector2.zero(); + final Vector2 localCenterA = Vector2.zero(); + final Vector2 localCenterB = Vector2.zero(); double invIA = 0.0, invIB = 0.0; ManifoldType type; double radiusA = 0.0, radiusB = 0.0; @@ -40,7 +16,7 @@ class ContactPositionConstraint { ContactPositionConstraint() { for (int i = 0; i < localPoints.length; i++) { - localPoints[i] = new Vector2.zero(); + localPoints[i] = Vector2.zero(); } } } diff --git a/lib/src/dynamics/contacts/contact_register.dart b/lib/src/dynamics/contacts/contact_register.dart index 5b090bc..41a87a5 100644 --- a/lib/src/dynamics/contacts/contact_register.dart +++ b/lib/src/dynamics/contacts/contact_register.dart @@ -1,30 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ContactRegister { - IDynamicStack creator; + ListQueue creator; bool primary = false; } diff --git a/lib/src/dynamics/contacts/contact_solver.dart b/lib/src/dynamics/contacts/contact_solver.dart index fc72f28..3fd0597 100644 --- a/lib/src/dynamics/contacts/contact_solver.dart +++ b/lib/src/dynamics/contacts/contact_solver.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ContactSolverDef { @@ -35,15 +11,12 @@ class ContactSolverDef { class ContactSolver { static const bool DEBUG_SOLVER = false; static const double k_errorTol = 1e-3; - /** - * For each solver, this is the initial number of constraints in the array, which expands as - * needed. - */ + + /// For each solver, this is the initial number of constraints in the array, which expands as + /// needed. static const int INITIAL_NUM_CONSTRAINTS = 256; - /** - * Ensure a reasonable condition number. for the block solver - */ + /// Ensure a reasonable condition number. for the block solver static final double k_maxConditionNumber = 100.0; TimeStep _step; @@ -56,37 +29,36 @@ class ContactSolver { ContactSolver() { _positionConstraints = - new List(INITIAL_NUM_CONSTRAINTS); + List(INITIAL_NUM_CONSTRAINTS); _velocityConstraints = - new List(INITIAL_NUM_CONSTRAINTS); + List(INITIAL_NUM_CONSTRAINTS); for (int i = 0; i < INITIAL_NUM_CONSTRAINTS; i++) { - _positionConstraints[i] = new ContactPositionConstraint(); - _velocityConstraints[i] = new ContactVelocityConstraint(); + _positionConstraints[i] = ContactPositionConstraint(); + _velocityConstraints[i] = ContactVelocityConstraint(); } } void init(ContactSolverDef def) { - // System.out.println("Initializing contact solver"); _step = def.step; _count = def.count; if (_positionConstraints.length < _count) { List old = _positionConstraints; _positionConstraints = - new List(Math.max(old.length * 2, _count)); - BufferUtils.arraycopy(old, 0, _positionConstraints, 0, old.length); + List(Math.max(old.length * 2, _count)); + BufferUtils.arrayCopy(old, 0, _positionConstraints, 0, old.length); for (int i = old.length; i < _positionConstraints.length; i++) { - _positionConstraints[i] = new ContactPositionConstraint(); + _positionConstraints[i] = ContactPositionConstraint(); } } if (_velocityConstraints.length < _count) { List old = _velocityConstraints; _velocityConstraints = - new List(Math.max(old.length * 2, _count)); - BufferUtils.arraycopy(old, 0, _velocityConstraints, 0, old.length); + List(Math.max(old.length * 2, _count)); + BufferUtils.arrayCopy(old, 0, _velocityConstraints, 0, old.length); for (int i = old.length; i < _velocityConstraints.length; i++) { - _velocityConstraints[i] = new ContactVelocityConstraint(); + _velocityConstraints[i] = ContactVelocityConstraint(); } } @@ -95,7 +67,6 @@ class ContactSolver { _contacts = def.contacts; for (int i = 0; i < _count; ++i) { - // System.out.println("contacts: " + _count); final Contact contact = _contacts[i]; final Fixture fixtureA = contact._fixtureA; @@ -142,14 +113,11 @@ class ContactSolver { pc.radiusB = radiusB; pc.type = manifold.type; - // System.out.println("contact point count: " + pointCount); for (int j = 0; j < pointCount; j++) { ManifoldPoint cp = manifold.points[j]; VelocityConstraintPoint vcp = vc.points[j]; if (_step.warmStarting) { - // assert(cp.normalImpulse == 0); - // System.out.println("contact normal impulse: " + cp.normalImpulse); vcp.normalImpulse = _step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = _step.dtRatio * cp.tangentImpulse; } else { @@ -187,15 +155,15 @@ class ContactSolver { double wB = _velocities[indexB].w; Vector2 normal = vc.normal; - double tangentx = 1.0 * normal.y; - double tangenty = -1.0 * normal.x; + double tangentX = 1.0 * normal.y; + double tangentY = -1.0 * normal.x; for (int j = 0; j < pointCount; ++j) { VelocityConstraintPoint vcp = vc.points[j]; double Px = - tangentx * vcp.tangentImpulse + normal.x * vcp.normalImpulse; + tangentX * vcp.tangentImpulse + normal.x * vcp.normalImpulse; double Py = - tangenty * vcp.tangentImpulse + normal.y * vcp.normalImpulse; + tangentY * vcp.tangentImpulse + normal.y * vcp.normalImpulse; wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px); vA.x -= Px * mA; @@ -211,9 +179,9 @@ class ContactSolver { // djm pooling, and from above // TODO(srdjan): make them private. - final Transform xfA = new Transform.zero(); - final Transform xfB = new Transform.zero(); - final WorldManifold worldManifold = new WorldManifold(); + final Transform xfA = Transform.zero(); + final Transform xfB = Transform.zero(); + final WorldManifold worldManifold = WorldManifold(); void initializeVelocityConstraints() { // Warm start. @@ -258,9 +226,9 @@ class ContactSolver { worldManifold.initialize(manifold, xfA, radiusA, xfB, radiusB); - final Vector2 vcnormal = vc.normal; - vcnormal.x = worldManifold.normal.x; - vcnormal.y = worldManifold.normal.y; + final Vector2 vcNormal = vc.normal; + vcNormal.x = worldManifold.normal.x; + vcNormal.y = worldManifold.normal.y; int pointCount = vc.pointCount; for (int j = 0; j < pointCount; ++j) { @@ -273,18 +241,18 @@ class ContactSolver { vcprB.x = wmPj.x - cB.x; vcprB.y = wmPj.y - cB.y; - double rnA = vcprA.x * vcnormal.y - vcprA.y * vcnormal.x; - double rnB = vcprB.x * vcnormal.y - vcprB.y * vcnormal.x; + double rnA = vcprA.x * vcNormal.y - vcprA.y * vcNormal.x; + double rnB = vcprB.x * vcNormal.y - vcprB.y * vcNormal.x; double kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0.0 ? 1.0 / kNormal : 0.0; - double tangentx = 1.0 * vcnormal.y; - double tangenty = -1.0 * vcnormal.x; + double tangentX = 1.0 * vcNormal.y; + double tangentY = -1.0 * vcNormal.x; - double rtA = vcprA.x * tangenty - vcprA.y * tangentx; - double rtB = vcprB.x * tangenty - vcprB.y * tangentx; + double rtA = vcprA.x * tangentY - vcprA.y * tangentX; + double rtB = vcprB.x * tangentY - vcprB.y * tangentX; double kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; @@ -294,7 +262,7 @@ class ContactSolver { vcp.velocityBias = 0.0; double tempx = vB.x + -wB * vcprB.y - vA.x - (-wA * vcprA.y); double tempy = vB.y + wB * vcprB.x - vA.y - (wA * vcprA.x); - double vRel = vcnormal.x * tempx + vcnormal.y * tempy; + double vRel = vcNormal.x * tempx + vcNormal.y * tempy; if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -vc.restitution * vRel; } @@ -304,10 +272,10 @@ class ContactSolver { if (vc.pointCount == 2) { VelocityConstraintPoint vcp1 = vc.points[0]; VelocityConstraintPoint vcp2 = vc.points[1]; - double rn1A = vcp1.rA.x * vcnormal.y - vcp1.rA.y * vcnormal.x; - double rn1B = vcp1.rB.x * vcnormal.y - vcp1.rB.y * vcnormal.x; - double rn2A = vcp2.rA.x * vcnormal.y - vcp2.rA.y * vcnormal.x; - double rn2B = vcp2.rB.x * vcnormal.y - vcp2.rB.y * vcnormal.x; + double rn1A = vcp1.rA.x * vcNormal.y - vcp1.rA.y * vcNormal.x; + double rn1B = vcp1.rB.x * vcNormal.y - vcp1.rB.y * vcNormal.x; + double rn2A = vcp2.rA.x * vcNormal.y - vcp2.rA.y * vcNormal.x; + double rn2B = vcp2.rB.x * vcNormal.y - vcp2.rB.y * vcNormal.x; double k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; double k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; @@ -345,10 +313,10 @@ class ContactSolver { double wB = _velocities[indexB].w; Vector2 normal = vc.normal; - final double normalx = normal.x; - final double normaly = normal.y; - double tangentx = 1.0 * vc.normal.y; - double tangenty = -1.0 * vc.normal.x; + final double normalX = normal.x; + final double normalY = normal.y; + double tangentX = 1.0 * vc.normal.y; + double tangentY = -1.0 * vc.normal.x; final double friction = vc.friction; assert(pointCount == 1 || pointCount == 2); @@ -361,7 +329,7 @@ class ContactSolver { double dvy = wB * vcp.rB.x + vB.y - vA.y - wA * a.x; // Compute tangent force - final double vt = dvx * tangentx + dvy * tangenty - vc.tangentSpeed; + final double vt = dvx * tangentX + dvy * tangentY - vc.tangentSpeed; double lambda = vcp.tangentMass * (-vt); // Clamp the accumulated force @@ -374,8 +342,8 @@ class ContactSolver { // Apply contact impulse // Vec2 P = lambda * tangent; - final double Px = tangentx * lambda; - final double Py = tangenty * lambda; + final double Px = tangentX * lambda; + final double Py = tangentY * lambda; // vA -= invMassA * P; vA.x -= Px * mA; @@ -399,7 +367,7 @@ class ContactSolver { double dvy = wB * vcp.rB.x + vB.y - vA.y - wA * vcp.rA.x; // Compute normal impulse - final double vn = dvx * normalx + dvy * normaly; + final double vn = dvx * normalX + dvy * normalY; double lambda = -vcp.normalMass * (vn - vcp.velocityBias); // Clamp the accumulated impulse @@ -409,10 +377,9 @@ class ContactSolver { vcp.normalImpulse = newImpulse; // Apply contact impulse - double Px = normalx * lambda; - double Py = normaly * lambda; + double Px = normalX * lambda; + double Py = normalY * lambda; - // vA -= invMassA * P; vA.x -= Px * mA; vA.y -= Py * mA; wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px); @@ -481,8 +448,8 @@ class ContactSolver { double dv2y = wB * cp2rB.x + vB.y - vA.y - wA * cp2rA.x; // Compute normal velocity - double vn1 = dv1x * normalx + dv1y * normaly; - double vn2 = dv2x * normalx + dv2y * normaly; + double vn1 = dv1x * normalX + dv1y * normalY; + double vn2 = dv2x * normalX + dv2y * normalY; double bx = vn1 - cp1.velocityBias; double by = vn2 - cp2.velocityBias; @@ -513,17 +480,14 @@ class ContactSolver { if (xx >= 0.0 && xy >= 0.0) { // Get the incremental impulse - // Vec2 d = x - a; double dx = xx - ax; double dy = xy - ay; // Apply incremental impulse - // Vec2 P1 = d.x * normal; - // Vec2 P2 = d.y * normal; - double P1x = dx * normalx; - double P1y = dx * normaly; - double P2x = dy * normalx; - double P2y = dy * normaly; + double P1x = dx * normalX; + double P1y = dx * normalY; + double P2x = dy * normalX; + double P2y = dy * normalY; /* * vA -= invMassA * (P1 + P2); wA -= invIA * (Cross(cp1.rA, P1) + Cross(cp2.rA, P2)); @@ -593,12 +557,10 @@ class ContactSolver { double dy = xy - ay; // Apply incremental impulse - // Vec2 P1 = d.x * normal; - // Vec2 P2 = d.y * normal; - double P1x = normalx * dx; - double P1y = normaly * dx; - double P2x = normalx * dy; - double P2y = normaly * dy; + double P1x = normalX * dx; + double P1y = normalY * dx; + double P2x = normalX * dy; + double P2y = normalY * dy; /* * Vec2 P1 = d.x * normal; Vec2 P2 = d.y * normal; vA -= invMassA * (P1 + P2); wA -= @@ -670,10 +632,10 @@ class ContactSolver { * vB += invMassB * (P1 + P2); wB += invIB * (Cross(cp1.rB, P1) + Cross(cp2.rB, P2)); */ - double P1x = normalx * dx; - double P1y = normaly * dx; - double P2x = normalx * dy; - double P2y = normaly * dy; + double P1x = normalX * dx; + double P1y = normalY * dx; + double P2x = normalX * dy; + double P2y = normalY * dy; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); @@ -737,10 +699,10 @@ class ContactSolver { * vB += invMassB * (P1 + P2); wB += invIB * (Cross(cp1.rB, P1) + Cross(cp2.rB, P2)); */ - double P1x = normalx * dx; - double P1y = normaly * dx; - double P2x = normalx * dy; - double P2y = normaly * dy; + double P1x = normalX * dx; + double P1y = normalY * dx; + double P2x = normalX * dy; + double P2y = normalY * dy; vA.x -= mA * (P1x + P2x); vA.y -= mA * (P1y + P2y); @@ -768,9 +730,7 @@ class ContactSolver { } } - // _velocities[indexA].v.set(vA); _velocities[indexA].w = wA; - // _velocities[indexB].v.set(vB); _velocities[indexB].w = wB; } } @@ -787,51 +747,9 @@ class ContactSolver { } } - /* - * #if 0 // Sequential solver. bool ContactSolver::SolvePositionConstraints(double baumgarte) { - * double minSeparation = 0.0; - * - * for (int i = 0; i < _constraintCount; ++i) { ContactConstraint* c = _constraints + i; Body* - * bodyA = c.bodyA; Body* bodyB = c.bodyB; double invMassA = bodyA._mass * bodyA._invMass; double - * invIA = bodyA._mass * bodyA._invI; double invMassB = bodyB._mass * bodyB._invMass; double - * invIB = bodyB._mass * bodyB._invI; - * - * Vec2 normal = c.normal; - * - * // Solve normal constraints for (int j = 0; j < c.pointCount; ++j) { ContactConstraintPoint* - * ccp = c.points + j; - * - * Vec2 r1 = Mul(bodyA.GetXForm().R, ccp.localAnchorA - bodyA.GetLocalCenter()); Vec2 r2 = - * Mul(bodyB.GetXForm().R, ccp.localAnchorB - bodyB.GetLocalCenter()); - * - * Vec2 p1 = bodyA._sweep.c + r1; Vec2 p2 = bodyB._sweep.c + r2; Vec2 dp = p2 - p1; - * - * // Approximate the current separation. double separation = Dot(dp, normal) + ccp.separation; - * - * // Track max constraint error. minSeparation = Min(minSeparation, separation); - * - * // Prevent large corrections and allow slop. double C = Clamp(baumgarte * (separation + - * _linearSlop), -_maxLinearCorrection, 0.0); - * - * // Compute normal impulse double impulse = -ccp.equalizedMass * C; - * - * Vec2 P = impulse * normal; - * - * bodyA._sweep.c -= invMassA * P; bodyA._sweep.a -= invIA * Cross(r1, P); - * bodyA.SynchronizeTransform(); - * - * bodyB._sweep.c += invMassB * P; bodyB._sweep.a += invIB * Cross(r2, P); - * bodyB.SynchronizeTransform(); } } - * - * // We can't expect minSpeparation >= -_linearSlop because we don't // push the separation above - * -_linearSlop. return minSeparation >= -1.5f * _linearSlop; } - */ - - final PositionSolverManifold _psolver = new PositionSolverManifold(); - - /** - * Sequential solver. - */ + final PositionSolverManifold _pSolver = PositionSolverManifold(); + + /// Sequential solver. bool solvePositionConstraints() { double minSeparation = 0.0; @@ -869,7 +787,7 @@ class ContactSolver { xfB.p.x = cB.x - xfBq.c * localCenterBx + xfBq.s * localCenterBy; xfB.p.y = cB.y - xfBq.s * localCenterBx - xfBq.c * localCenterBy; - final PositionSolverManifold psm = _psolver; + final PositionSolverManifold psm = _pSolver; psm.initialize(pc, xfA, xfB, j); final Vector2 normal = psm.normal; final Vector2 point = psm.point; @@ -909,14 +827,11 @@ class ContactSolver { aB += iB * (rBx * Py - rBy * Px); } - // _positions[indexA].c.set(cA); _positions[indexA].a = aA; - - // _positions[indexB].c.set(cB); _positions[indexB].a = aB; } - // We can't expect minSpeparation >= -linearSlop because we don't + // We can't expect minSeparation >= -linearSlop because we don't // push the separation above -linearSlop. return minSeparation >= -3.0 * Settings.linearSlop; } @@ -969,7 +884,7 @@ class ContactSolver { xfB.p.x = cB.x - xfBq.c * localCenterBx + xfBq.s * localCenterBy; xfB.p.y = cB.y - xfBq.s * localCenterBx - xfBq.c * localCenterBy; - final PositionSolverManifold psm = _psolver; + final PositionSolverManifold psm = _pSolver; psm.initialize(pc, xfA, xfB, j); Vector2 normal = psm.normal; @@ -1010,22 +925,19 @@ class ContactSolver { aB += iB * (rBx * Py - rBy * Px); } - // _positions[indexA].c.set(cA); _positions[indexA].a = aA; - - // _positions[indexB].c.set(cB); _positions[indexB].a = aB; } - // We can't expect minSpeparation >= -_linearSlop because we don't + // We can't expect minSeparation >= -_linearSlop because we don't // push the separation above -_linearSlop. return minSeparation >= -1.5 * Settings.linearSlop; } } class PositionSolverManifold { - final Vector2 normal = new Vector2.zero(); - final Vector2 point = new Vector2.zero(); + final Vector2 normal = Vector2.zero(); + final Vector2 point = Vector2.zero(); double separation = 0.0; void initialize( @@ -1037,14 +949,6 @@ class PositionSolverManifold { final Vector2 pcLocalPointsI = pc.localPoints[index]; switch (pc.type) { case ManifoldType.CIRCLES: - // Transform.mulToOutUnsafe(xfA, pc.localPoint, pointA); - // Transform.mulToOutUnsafe(xfB, pc.localPoints[0], pointB); - // normal.set(pointB).subLocal(pointA); - // normal.normalize(); - // - // point.set(pointA).addLocal(pointB).mulLocal(.5f); - // temp.set(pointB).subLocal(pointA); - // separation = Vec2.dot(temp, normal) - pc.radiusA - pc.radiusB; final Vector2 plocalPoint = pc.localPoint; final Vector2 pLocalPoints0 = pc.localPoints[0]; final double pointAx = @@ -1068,13 +972,6 @@ class PositionSolverManifold { break; case ManifoldType.FACE_A: - // Rot.mulToOutUnsafe(xfAq, pc.localNormal, normal); - // Transform.mulToOutUnsafe(xfA, pc.localPoint, planePoint); - // - // Transform.mulToOutUnsafe(xfB, pc.localPoints[index], clipPoint); - // temp.set(clipPoint).subLocal(planePoint); - // separation = Vec2.dot(temp, normal) - pc.radiusA - pc.radiusB; - // point.set(clipPoint); final Vector2 pcLocalNormal = pc.localNormal; final Vector2 pcLocalPoint = pc.localPoint; normal.x = xfAq.c * pcLocalNormal.x - xfAq.s * pcLocalNormal.y; @@ -1097,16 +994,6 @@ class PositionSolverManifold { break; case ManifoldType.FACE_B: - // Rot.mulToOutUnsafe(xfBq, pc.localNormal, normal); - // Transform.mulToOutUnsafe(xfB, pc.localPoint, planePoint); - // - // Transform.mulToOutUnsafe(xfA, pcLocalPointsI, clipPoint); - // temp.set(clipPoint).subLocal(planePoint); - // separation = Vec2.dot(temp, normal) - pc.radiusA - pc.radiusB; - // point.set(clipPoint); - // - // // Ensure normal points from A to B - // normal.negateLocal(); final Vector2 pcLocalNormal = pc.localNormal; final Vector2 pcLocalPoint = pc.localPoint; normal.x = xfBq.c * pcLocalNormal.x - xfBq.s * pcLocalNormal.y; diff --git a/lib/src/dynamics/contacts/contact_velocity_constraint.dart b/lib/src/dynamics/contacts/contact_velocity_constraint.dart index b7b4d9b..ca3eee3 100644 --- a/lib/src/dynamics/contacts/contact_velocity_constraint.dart +++ b/lib/src/dynamics/contacts/contact_velocity_constraint.dart @@ -1,32 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class VelocityConstraintPoint { - final Vector2 rA = new Vector2.zero(); - final Vector2 rB = new Vector2.zero(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); double normalImpulse = 0.0; double tangentImpulse = 0.0; double normalMass = 0.0; @@ -36,10 +12,10 @@ class VelocityConstraintPoint { class ContactVelocityConstraint { List points = - new List(Settings.maxManifoldPoints); - final Vector2 normal = new Vector2.zero(); - final Matrix2 normalMass = new Matrix2.zero(); - final Matrix2 K = new Matrix2.zero(); + List(Settings.maxManifoldPoints); + final Vector2 normal = Vector2.zero(); + final Matrix2 normalMass = Matrix2.zero(); + final Matrix2 K = Matrix2.zero(); int indexA = 0; int indexB = 0; double invMassA = 0.0, invMassB = 0.0; @@ -52,7 +28,7 @@ class ContactVelocityConstraint { ContactVelocityConstraint() { for (int i = 0; i < points.length; i++) { - points[i] = new VelocityConstraintPoint(); + points[i] = VelocityConstraintPoint(); } } } diff --git a/lib/src/dynamics/contacts/edge_and_circle_contact.dart b/lib/src/dynamics/contacts/edge_and_circle_contact.dart index 0489c4b..405ed47 100644 --- a/lib/src/dynamics/contacts/edge_and_circle_contact.dart +++ b/lib/src/dynamics/contacts/edge_and_circle_contact.dart @@ -1,40 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class EdgeAndCircleContact extends Contact { - EdgeAndCircleContact(IWorldPool argPool) : super(argPool); - - void init(Fixture fA, int indexA, Fixture fB, int indexB) { - super.init(fA, indexA, fB, indexB); + EdgeAndCircleContact(Fixture fA, int indexA, Fixture fB, int indexB) + : super(fA, indexA, fB, indexB) { assert(_fixtureA.getType() == ShapeType.EDGE); assert(_fixtureB.getType() == ShapeType.CIRCLE); } void evaluate(Manifold manifold, Transform xfA, Transform xfB) { - _pool.getCollision().collideEdgeAndCircle( + World.collision.collideEdgeAndCircle( manifold, _fixtureA.getShape() as EdgeShape, xfA, diff --git a/lib/src/dynamics/contacts/edge_and_polygon_contact.dart b/lib/src/dynamics/contacts/edge_and_polygon_contact.dart index 6a1a4ed..55a64c9 100644 --- a/lib/src/dynamics/contacts/edge_and_polygon_contact.dart +++ b/lib/src/dynamics/contacts/edge_and_polygon_contact.dart @@ -1,40 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class EdgeAndPolygonContact extends Contact { - EdgeAndPolygonContact(IWorldPool argPool) : super(argPool); - - void init(Fixture fA, int indexA, Fixture fB, int indexB) { - super.init(fA, indexA, fB, indexB); + EdgeAndPolygonContact(Fixture fA, int indexA, Fixture fB, int indexB) + : super(fA, indexA, fB, indexB) { assert(_fixtureA.getType() == ShapeType.EDGE); assert(_fixtureB.getType() == ShapeType.POLYGON); } void evaluate(Manifold manifold, Transform xfA, Transform xfB) { - _pool.getCollision().collideEdgeAndPolygon( + World.collision.collideEdgeAndPolygon( manifold, _fixtureA.getShape() as EdgeShape, xfA, diff --git a/lib/src/dynamics/contacts/polygon_and_circle_contact.dart b/lib/src/dynamics/contacts/polygon_and_circle_contact.dart index c16dba6..ce51152 100644 --- a/lib/src/dynamics/contacts/polygon_and_circle_contact.dart +++ b/lib/src/dynamics/contacts/polygon_and_circle_contact.dart @@ -1,40 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class PolygonAndCircleContact extends Contact { - PolygonAndCircleContact(IWorldPool argPool) : super(argPool); - - void init0(Fixture fixtureA, Fixture fixtureB) { - init(fixtureA, 0, fixtureB, 0); + PolygonAndCircleContact(Fixture fixtureA, Fixture fixtureB) + : super(fixtureA, 0, fixtureB, 0) { assert(_fixtureA.getType() == ShapeType.POLYGON); assert(_fixtureB.getType() == ShapeType.CIRCLE); } void evaluate(Manifold manifold, Transform xfA, Transform xfB) { - _pool.getCollision().collidePolygonAndCircle( + World.collision.collidePolygonAndCircle( manifold, _fixtureA.getShape() as PolygonShape, xfA, diff --git a/lib/src/dynamics/contacts/polygon_contact.dart b/lib/src/dynamics/contacts/polygon_contact.dart index 2ed2381..ccb9b87 100644 --- a/lib/src/dynamics/contacts/polygon_contact.dart +++ b/lib/src/dynamics/contacts/polygon_contact.dart @@ -1,42 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class PolygonContact extends Contact { - PolygonContact(IWorldPool argPool) : super(argPool) { - assert(_pool != null); - } - - void init0(Fixture fixtureA, Fixture fixtureB) { - init(fixtureA, 0, fixtureB, 0); + PolygonContact(Fixture fixtureA, Fixture fixtureB) + : super(fixtureA, 0, fixtureB, 0) { assert(_fixtureA.getType() == ShapeType.POLYGON); assert(_fixtureB.getType() == ShapeType.POLYGON); } void evaluate(Manifold manifold, Transform xfA, Transform xfB) { - _pool.getCollision().collidePolygons( + World.collision.collidePolygons( manifold, _fixtureA.getShape() as PolygonShape, xfA, diff --git a/lib/src/dynamics/contacts/position.dart b/lib/src/dynamics/contacts/position.dart index bac00ae..025ea55 100644 --- a/lib/src/dynamics/contacts/position.dart +++ b/lib/src/dynamics/contacts/position.dart @@ -1,30 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class Position { - final Vector2 c = new Vector2.zero(); + final Vector2 c = Vector2.zero(); double a = 0.0; } diff --git a/lib/src/dynamics/contacts/velocity.dart b/lib/src/dynamics/contacts/velocity.dart index 3e734c9..b2f290f 100644 --- a/lib/src/dynamics/contacts/velocity.dart +++ b/lib/src/dynamics/contacts/velocity.dart @@ -1,30 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class Velocity { - final Vector2 v = new Vector2.zero(); + final Vector2 v = Vector2.zero(); double w = 0.0; } diff --git a/lib/src/dynamics/filter.dart b/lib/src/dynamics/filter.dart index cd065d7..7f04b03 100644 --- a/lib/src/dynamics/filter.dart +++ b/lib/src/dynamics/filter.dart @@ -1,49 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * This holds contact filtering data. - */ +/// This holds contact filtering data. class Filter { - /** - * The collision category bits. Normally you would just set one bit. - */ + /// The collision category bits. Normally you would just set one bit. int categoryBits = 0x0001; - /** - * The collision mask bits. This states the categories that this - * shape would accept for collision. - */ + /// The collision mask bits. This states the categories that this + /// shape would accept for collision. int maskBits = 0xFFFF; - /** - * Collision groups allow a certain group of objects to never collide (negative) - * or always collide (positive). Zero means no collision group. Non-zero group - * filtering always wins against the mask bits. - */ + /// Collision groups allow a certain group of objects to never collide (negative) + /// or always collide (positive). Zero means no collision group. Non-zero group + /// filtering always wins against the mask bits. int groupIndex = 0; void set(Filter argOther) { diff --git a/lib/src/dynamics/fixture.dart b/lib/src/dynamics/fixture.dart index a11077e..5811469 100644 --- a/lib/src/dynamics/fixture.dart +++ b/lib/src/dynamics/fixture.dart @@ -1,38 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A fixture is used to attach a shape to a body for collision detection. A fixture inherits its - * transform from its parent. Fixtures hold additional non-geometric data such as friction, - * collision filters, etc. Fixtures are created via Body::CreateFixture. - * - * @warning you cannot reuse fixtures. - * - * @author daniel - */ +/// A fixture is used to attach a shape to a body for collision detection. A fixture inherits its +/// transform from its parent. Fixtures hold additional non-geometric data such as friction, +/// collision filters, etc. Fixtures are created via Body::CreateFixture. +/// +/// @warning you cannot reuse fixtures. class Fixture { double _density = 0.0; @@ -47,47 +19,37 @@ class Fixture { List _proxies; int _proxyCount = 0; - final Filter _filter = new Filter(); + final Filter _filter = Filter(); bool _isSensor = false; - /** - * Use this to store your application specific data. - */ + /// Use this to store your application specific data. Object userData; - /** - * Get the type of the child shape. You can use this to down cast to the concrete shape. - * - * @return the shape type. - */ + /// Get the type of the child shape. You can use this to down cast to the concrete shape. + /// + /// @return the shape type. ShapeType getType() => _shape.shapeType; - /** - * Get the child shape. You can modify the child shape, however you should not change the number - * of vertices because this will crash some collision caching mechanisms. - * - * @return - */ + /// Get the child shape. You can modify the child shape, however you should not change the number + /// of vertices because this will crash some collision caching mechanisms. + /// + /// @return Shape getShape() { return _shape; } - /** - * Is this fixture a sensor (non-solid)? - * - * @return the true if the shape is a sensor. - * @return - */ + /// Is this fixture a sensor (non-solid)? + /// + /// @return the true if the shape is a sensor. + /// @return bool isSensor() { return _isSensor; } - /** - * Set if this fixture is a sensor. - * - * @param sensor - */ + /// Set if this fixture is a sensor. + /// + /// @param sensor void setSensor(bool sensor) { if (sensor != _isSensor) { _body.setAwake(true); @@ -95,32 +57,26 @@ class Fixture { } } - /** - * Set the contact filtering data. This is an expensive operation and should not be called - * frequently. This will not update contacts until the next time step when either parent body is - * awake. This automatically calls refilter. - * - * @param filter - */ + /// Set the contact filtering data. This is an expensive operation and should not be called + /// frequently. This will not update contacts until the next time step when either parent body is + /// awake. This automatically calls refilter. + /// + /// @param filter void setFilterData(final Filter filter) { _filter.set(filter); refilter(); } - /** - * Get the contact filtering data. - * - * @return - */ + /// Get the contact filtering data. + /// + /// @return Filter getFilterData() { return _filter; } - /** - * Call this if you want to establish collision that was previously disabled by - * ContactFilter::ShouldCollide. - */ + /// Call this if you want to establish collision that was previously disabled by + /// ContactFilter::ShouldCollide. void refilter() { if (_body == null) { return; @@ -151,22 +107,18 @@ class Fixture { } } - /** - * Get the parent body of this fixture. This is NULL if the fixture is not attached. - * - * @return the parent body. - * @return - */ + /// Get the parent body of this fixture. This is NULL if the fixture is not attached. + /// + /// @return the parent body. + /// @return Body getBody() { return _body; } - /** - * Get the next fixture in the parent body's fixture list. - * - * @return the next shape. - * @return - */ + /// Get the next fixture in the parent body's fixture list. + /// + /// @return the next shape. + /// @return Fixture getNext() { return _next; } @@ -180,92 +132,72 @@ class Fixture { return _density; } - /** - * Test a point for containment in this fixture. This only works for convex shapes. - * - * @param p a point in world coordinates. - * @return - */ + /// Test a point for containment in this fixture. This only works for convex shapes. + /// + /// @param p a point in world coordinates. + /// @return bool testPoint(final Vector2 p) { return _shape.testPoint(_body._transform, p); } - /** - * Cast a ray against this shape. - * - * @param output the ray-cast results. - * @param input the ray-cast input parameters. - * @param output - * @param input - */ + /// Cast a ray against this shape. + /// + /// @param input the ray-cast input parameters. + /// @param output the ray-cast results. bool raycast(RayCastOutput output, RayCastInput input, int childIndex) { return _shape.raycast(output, input, _body._transform, childIndex); } - /** - * Get the mass data for this fixture. The mass data is based on the density and the shape. The - * rotational inertia is about the shape's origin. - * - * @return - */ + /// Get the mass data for this fixture. The mass data is based on the density and the shape. The + /// rotational inertia is about the shape's origin. + /// + /// @return void getMassData(MassData massData) { _shape.computeMass(massData, _density); } - /** - * Get the coefficient of friction. - * - * @return - */ + /// Get the coefficient of friction. + /// + /// @return double getFriction() { return _friction; } - /** - * Set the coefficient of friction. This will _not_ change the friction of existing contacts. - * - * @param friction - */ + /// Set the coefficient of friction. This will _not_ change the friction of existing contacts. + /// + /// @param friction void setFriction(double friction) { _friction = friction; } - /** - * Get the coefficient of restitution. - * - * @return - */ + /// Get the coefficient of restitution. + /// + /// @return double getRestitution() { return _restitution; } - /** - * Set the coefficient of restitution. This will _not_ change the restitution of existing - * contacts. - * - * @param restitution - */ + /// Set the coefficient of restitution. This will _not_ change the restitution of existing + /// contacts. + /// + /// @param restitution void setRestitution(double restitution) { _restitution = restitution; } - /** - * Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a more accurate - * AABB, compute it using the shape and the body transform. - * - * @return - */ + /// Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a more accurate + /// AABB, compute it using the shape and the body transform. + /// + /// @return AABB getAABB(int childIndex) { assert(childIndex >= 0 && childIndex < _proxyCount); return _proxies[childIndex].aabb; } - /** - * Compute the distance from this fixture. - * - * @param p a point in world coordinates. - * @return distance - */ + /// Compute the distance from this fixture. + /// + /// @param p a point in world coordinates. + /// @return distance double computeDistance(Vector2 p, int childIndex, Vector2 normalOut) { return _shape.computeDistanceToOut( _body._transform, p, childIndex, normalOut); @@ -291,9 +223,9 @@ class Fixture { // Reserve proxy space int childCount = _shape.getChildCount(); if (_proxies == null) { - _proxies = new List(childCount); + _proxies = List(childCount); for (int i = 0; i < childCount; i++) { - _proxies[i] = new FixtureProxy(); + _proxies[i] = FixtureProxy(); _proxies[i].fixture = null; _proxies[i].proxyId = BroadPhase.NULL_PROXY; } @@ -302,11 +234,11 @@ class Fixture { if (_proxies.length < childCount) { List old = _proxies; int newLen = Math.max(old.length * 2, childCount); - _proxies = new List(newLen); - BufferUtils.arraycopy(old, 0, _proxies, 0, old.length); + _proxies = List(newLen); + BufferUtils.arrayCopy(old, 0, _proxies, 0, old.length); for (int i = 0; i < newLen; i++) { if (i >= old.length) { - _proxies[i] = new FixtureProxy(); + _proxies[i] = FixtureProxy(); } _proxies[i].fixture = null; _proxies[i].proxyId = BroadPhase.NULL_PROXY; @@ -346,11 +278,9 @@ class Fixture { } } - /** - * Internal method - * - * @param broadPhase - */ + /// Internal method + /// + /// @param broadPhase void destroyProxies(BroadPhase broadPhase) { // Destroy proxies in the broad-phase. for (int i = 0; i < _proxyCount; ++i) { @@ -362,17 +292,15 @@ class Fixture { _proxyCount = 0; } - final AABB _pool1 = new AABB(); - final AABB _pool2 = new AABB(); - final Vector2 _displacement = new Vector2.zero(); - - /** - * Internal method - * - * @param broadPhase - * @param xf1 - * @param xf2 - */ + final AABB _pool1 = AABB(); + final AABB _pool2 = AABB(); + final Vector2 _displacement = Vector2.zero(); + + /// Internal method + /// + /// @param broadPhase + /// @param xf1 + /// @param xf2 void synchronize(BroadPhase broadPhase, final Transform transform1, final Transform transform2) { if (_proxyCount == 0) { diff --git a/lib/src/dynamics/fixture_def.dart b/lib/src/dynamics/fixture_def.dart index 2af7da0..9729fcf 100644 --- a/lib/src/dynamics/fixture_def.dart +++ b/lib/src/dynamics/fixture_def.dart @@ -1,152 +1,88 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A fixture definition is used to create a fixture. This class defines an abstract fixture - * definition. You can reuse fixture definitions safely. - */ +/// A fixture definition is used to create a fixture. This class defines an abstract fixture +/// definition. You can reuse fixture definitions safely. class FixtureDef { - /** - * The shape, this must be set. The shape will be cloned, so you can create the shape on the - * stack. - */ + /// The shape, this must be set. The shape will be cloned, so you can create the shape on the + /// stack. Shape shape = null; - /** - * Use this to store application specific fixture data. - */ + /// Use this to store application specific fixture data. Object userData; - /** - * The friction coefficient, usually in the range [0,1]. - */ + /// The friction coefficient, usually in the range [0,1]. double friction = 0.2; - /** - * The restitution (elasticity) usually in the range [0,1]. - */ + /// The restitution (elasticity) usually in the range [0,1]. double restitution = 0.0; - /** - * The density, usually in kg/m^2 - */ + /// The density, usually in kg/m^2 double density = 0.0; - /** - * A sensor shape collects contact information but never generates a collision response. - */ + /// A sensor shape collects contact information but never generates a collision response. bool isSensor = false; - /** - * Contact filtering data; - */ - Filter filter = new Filter(); + /// Contact filtering data; + Filter filter = Filter(); - /** - * The shape, this must be set. The shape will be cloned, so you can create the shape on the - * stack. - */ + /// The shape, this must be set. The shape will be cloned, so you can create the shape on the + /// stack. Shape getShape() { return shape; } - /** - * The shape, this must be set. The shape will be cloned, so you can create the shape on the - * stack. - */ + /// The shape, this must be set. The shape will be cloned, so you can create the shape on the + /// stack. void setShape(Shape shape) { this.shape = shape; } - /** - * Use this to store application specific fixture data. - */ + /// Use this to store application specific fixture data. Object getUserData() { return userData; } - /** - * Use this to store application specific fixture data. - */ + /// Use this to store application specific fixture data. void setUserData(Object userData) { this.userData = userData; } - /** - * The friction coefficient, usually in the range [0,1]. - */ + /// The friction coefficient, usually in the range [0,1]. double getFriction() { return friction; } - /** - * The friction coefficient, usually in the range [0,1]. - */ + /// The friction coefficient, usually in the range [0,1]. void setFriction(double friction) { this.friction = friction; } - /** - * The restitution (elasticity) usually in the range [0,1]. - */ + /// The restitution (elasticity) usually in the range [0,1]. double getRestitution() { return restitution; } - /** - * The restitution (elasticity) usually in the range [0,1]. - */ + /// The restitution (elasticity) usually in the range [0,1]. void setRestitution(double restitution) { this.restitution = restitution; } - /** - * The density, usually in kg/m^2 - */ + /// The density, usually in kg/m^2 double getDensity() { return density; } - /** - * The density, usually in kg/m^2 - */ + /// The density, usually in kg/m^2 void setDensity(double density) { this.density = density; } - /** - * Contact filtering data; - */ + /// Contact filtering data; Filter getFilter() { return filter; } - /** - * Contact filtering data; - */ + /// Contact filtering data; void setFilter(Filter filter) { this.filter = filter; } diff --git a/lib/src/dynamics/fixture_proxy.dart b/lib/src/dynamics/fixture_proxy.dart index 14ed4e5..82f6cb5 100644 --- a/lib/src/dynamics/fixture_proxy.dart +++ b/lib/src/dynamics/fixture_proxy.dart @@ -1,34 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * This proxy is used internally to connect fixtures to the broad-phase. - */ +/// This proxy is used internally to connect fixtures to the broad-phase. class FixtureProxy { - final AABB aabb = new AABB(); + final AABB aabb = AABB(); Fixture fixture; int childIndex = 0; int proxyId = 0; diff --git a/lib/src/dynamics/island.dart b/lib/src/dynamics/island.dart index 1a6e557..e06ee07 100644 --- a/lib/src/dynamics/island.dart +++ b/lib/src/dynamics/island.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; /* @@ -142,9 +118,7 @@ part of box2d; However, we can compute sin+cos of the same angle fast. */ -/** - * This is an internal class. - */ +/// This is an internal class. class Island { ContactListener _listener; @@ -163,9 +137,16 @@ class Island { int _contactCapacity = 0; int _jointCapacity = 0; + Island() { + _bodies = List(_bodyCapacity); + _contacts = List(_contactCapacity); + _joints = List(_jointCapacity); + _velocities = List(0); + _positions = List(0); + } + void init(int bodyCapacity, int contactCapacity, int jointCapacity, ContactListener listener) { - // System.out.println("Initializing Island"); _bodyCapacity = bodyCapacity; _contactCapacity = contactCapacity; _jointCapacity = jointCapacity; @@ -175,36 +156,28 @@ class Island { _listener = listener; - if (_bodies == null || _bodyCapacity > _bodies.length) { - _bodies = new List(_bodyCapacity); + if (_bodyCapacity > _bodies.length) { + _bodies = List(_bodyCapacity); } - if (_joints == null || _jointCapacity > _joints.length) { - _joints = new List(_jointCapacity); + + if (_contactCapacity > _contacts.length) { + _contacts = List(_contactCapacity); } - if (_contacts == null || _contactCapacity > _contacts.length) { - _contacts = new List(_contactCapacity); + + if (_jointCapacity > _joints.length) { + _joints = List(_jointCapacity); } - // dynamic array - if (_velocities == null || _bodyCapacity > _velocities.length) { - final List old = - _velocities == null ? new List(0) : _velocities; - _velocities = new List(_bodyCapacity); - BufferUtils.arraycopy(old, 0, _velocities, 0, old.length); - for (int i = old.length; i < _velocities.length; i++) { - _velocities[i] = new Velocity(); - } + if (_bodyCapacity > _velocities.length) { + _velocities = List.generate(_bodyCapacity, + (i) => _velocities.length > i ? _velocities[i] : Velocity(), + growable: false); } - // dynamic array - if (_positions == null || _bodyCapacity > _positions.length) { - final List old = - _positions == null ? new List(0) : _positions; - _positions = new List(_bodyCapacity); - BufferUtils.arraycopy(old, 0, _positions, 0, old.length); - for (int i = old.length; i < _positions.length; i++) { - _positions[i] = new Position(); - } + if (_bodyCapacity > _positions.length) { + _positions = List.generate(_bodyCapacity, + (i) => _positions.length > i ? _positions[i] : Position(), + growable: false); } } @@ -214,12 +187,11 @@ class Island { _jointCount = 0; } - final ContactSolver _contactSolver = new ContactSolver(); - final SolverData _solverData = new SolverData(); - final ContactSolverDef _solverDef = new ContactSolverDef(); + final ContactSolver _contactSolver = ContactSolver(); + final SolverData _solverData = SolverData(); + final ContactSolverDef _solverDef = ContactSolverDef(); void solve(Profile profile, TimeStep step, Vector2 gravity, bool allowSleep) { - // System.out.println("Solving Island"); double h = step.dt; // Integrate velocities and apply damping. Initialize the body state. @@ -237,7 +209,6 @@ class Island { if (b._bodyType == BodyType.DYNAMIC) { // Integrate velocities. - // v += h * (b._gravityScale * gravity + b._invMass * b._force); v.x += h * (b._gravityScale * gravity.x + b._invMass * b._force.x); v.y += h * (b._gravityScale * gravity.y + b._invMass * b._force.y); w += h * b._invI * b._torque; @@ -276,11 +247,9 @@ class Island { _solverDef.velocities = _velocities; _contactSolver.init(_solverDef); - // System.out.println("island init vel"); _contactSolver.initializeVelocityConstraints(); if (step.warmStarting) { - // System.out.println("island warm start"); _contactSolver.warmStart(); } @@ -288,7 +257,6 @@ class Island { _joints[i].initVelocityConstraints(_solverData); } - // System.out.println("island solving velocities"); for (int i = 0; i < step.velocityIterations; ++i) { for (int j = 0; j < _jointCount; ++j) { _joints[j].solveVelocityConstraints(_solverData); @@ -308,14 +276,14 @@ class Island { double w = _velocities[i].w; // Check for large velocities - double translationx = v.x * h; - double translationy = v.y * h; + double translationX = v.x * h; + double translationY = v.y * h; - if (translationx * translationx + translationy * translationy > + if (translationX * translationX + translationY * translationY > Settings.maxTranslationSquared) { double ratio = Settings.maxTranslation / Math.sqrt( - translationx * translationx + translationy * translationy); + translationX * translationX + translationY * translationY); v.x *= ratio; v.y *= ratio; } @@ -368,7 +336,7 @@ class Island { report(_contactSolver._velocityConstraints); if (allowSleep) { - double minSleepTime = double.MAX_FINITE; + double minSleepTime = double.maxFinite; final double linTolSqr = Settings.linearSleepTolerance * Settings.linearSleepTolerance; @@ -393,16 +361,13 @@ class Island { } if (minSleepTime >= Settings.timeToSleep && positionSolved) { - for (int i = 0; i < _bodyCount; ++i) { - Body b = _bodies[i]; - b.setAwake(false); - } + _bodies.forEach((b) => b?.setAwake(false)); } } } - final ContactSolver _toiContactSolver = new ContactSolver(); - final ContactSolverDef _toiSolverDef = new ContactSolverDef(); + final ContactSolver _toiContactSolver = ContactSolver(); + final ContactSolverDef _toiSolverDef = ContactSolverDef(); void solveTOI(TimeStep subStep, int toiIndexA, int toiIndexB) { assert(toiIndexA < _bodyCount); @@ -433,38 +398,6 @@ class Island { break; } } - // #if 0 - // // Is the new position really safe? - // for (int i = 0; i < _contactCount; ++i) - // { - // Contact* c = _contacts[i]; - // Fixture* fA = c.fixtureA; - // Fixture* fB = c.fixtureB; - // - // Body bA = fA.GetBody(); - // Body bB = fB.GetBody(); - // - // int indexA = c.GetChildIndexA(); - // int indexB = c.GetChildIndexB(); - // - // DistanceInput input; - // input.proxyA.Set(fA.GetShape(), indexA); - // input.proxyB.Set(fB.GetShape(), indexB); - // input.transformA = bA.GetTransform(); - // input.transformB = bB.GetTransform(); - // input.useRadii = false; - // - // DistanceOutput output; - // SimplexCache cache; - // cache.count = 0; - // Distance(&output, &cache, &input); - // - // if (output.distance == 0 || cache.count == 3) - // { - // cache.count += 0; - // } - // } - // #endif // Leap of faith to new safe state. _bodies[toiIndexA]._sweep.c0.x = _positions[toiIndexA].c.x; @@ -495,13 +428,13 @@ class Island { double w = _velocities[i].w; // Check for large velocities - double translationx = v.x * h; - double translationy = v.y * h; - if (translationx * translationx + translationy * translationy > + double translationX = v.x * h; + double translationY = v.y * h; + if (translationX * translationX + translationY * translationY > Settings.maxTranslationSquared) { double ratio = Settings.maxTranslation / Math.sqrt( - translationx * translationx + translationy * translationy); + translationX * translationX + translationY * translationY); v.scale(ratio); } @@ -554,7 +487,7 @@ class Island { _joints[_jointCount++] = joint; } - final ContactImpulse _impulse = new ContactImpulse(); + final ContactImpulse _impulse = ContactImpulse(); void report(List constraints) { if (_listener == null) { diff --git a/lib/src/dynamics/joints/constant_volume_joints.dart b/lib/src/dynamics/joints/constant_volume_joints.dart index 6a33e09..13d4528 100644 --- a/lib/src/dynamics/joints/constant_volume_joints.dart +++ b/lib/src/dynamics/joints/constant_volume_joints.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ConstantVolumeJoint extends Joint { @@ -50,13 +26,13 @@ class ConstantVolumeJoint extends Joint { ConstantVolumeJoint(World argWorld, ConstantVolumeJointDef def) : _bodies = def.bodies.toList(growable: false), - super(argWorld.getPool(), def) { + super(def) { _world = argWorld; if (def.bodies.length <= 2) { throw "You cannot create a constant volume joint with less than three _bodies."; } - _targetLengths = new Float64List(_bodies.length); + _targetLengths = Float64List(_bodies.length); for (int i = 0; i < _targetLengths.length; ++i) { final int next = (i == _targetLengths.length - 1) ? 0 : i + 1; double dist = (_bodies[i].worldCenter - _bodies[next].worldCenter).length; @@ -68,8 +44,8 @@ class ConstantVolumeJoint extends Joint { throw "Incorrect joint definition. Joints have to correspond to the _bodies"; } if (def.joints == null) { - final DistanceJointDef djd = new DistanceJointDef(); - _distanceJoints = new List(_bodies.length); + final DistanceJointDef djd = DistanceJointDef(); + _distanceJoints = List(_bodies.length); for (int i = 0; i < _targetLengths.length; ++i) { final int next = (i == _targetLengths.length - 1) ? 0 : i + 1; djd.frequencyHz = def.frequencyHz; // 20.0; @@ -83,9 +59,9 @@ class ConstantVolumeJoint extends Joint { _distanceJoints = def.joints.toList(); } - _normals = new List(_bodies.length); + _normals = List(_bodies.length); for (int i = 0; i < _normals.length; ++i) { - _normals[i] = new Vector2.zero(); + _normals[i] = Vector2.zero(); } } @@ -136,7 +112,7 @@ class ConstantVolumeJoint extends Joint { perimeter += dist; } - final Vector2 delta = pool.popVec2(); + final Vector2 delta = Vector2.zero(); double deltaArea = _targetVolume - getSolverArea(positions); double toExtrude = 0.5 * deltaArea / perimeter; // *relaxationFactor @@ -146,7 +122,6 @@ class ConstantVolumeJoint extends Joint { final int next = (i == _bodies.length - 1) ? 0 : i + 1; delta.setValues(toExtrude * (_normals[i].x + _normals[next].x), toExtrude * (_normals[i].y + _normals[next].y)); - // sumdeltax += dx; double normSqrd = delta.length2; if (normSqrd > Settings.maxLinearCorrection * Settings.maxLinearCorrection) { @@ -157,34 +132,25 @@ class ConstantVolumeJoint extends Joint { } positions[_bodies[next]._islandIndex].c.x += delta.x; positions[_bodies[next]._islandIndex].c.y += delta.y; - // _bodies[next]._linearVelocity.x += delta.x * step.inv_dt; - // _bodies[next]._linearVelocity.y += delta.y * step.inv_dt; } - pool.pushVec2(1); - // System.out.println(sumdeltax); return done; } void initVelocityConstraints(final SolverData step) { List velocities = step.velocities; List positions = step.positions; - final List d = pool.getVec2Array(_bodies.length); + final List d = List(_bodies.length); for (int i = 0; i < _bodies.length; ++i) { final int prev = (i == 0) ? _bodies.length - 1 : i - 1; final int next = (i == _bodies.length - 1) ? 0 : i + 1; - d[i].setFrom(positions[_bodies[next]._islandIndex].c); + d[i] = Vector2.copy(positions[_bodies[next]._islandIndex].c); d[i].sub(positions[_bodies[prev]._islandIndex].c); } if (step.step.warmStarting) { _impulse *= step.step.dtRatio; - // double lambda = -2.0f * crossMassSum / dotMassSum; - // System.out.println(crossMassSum + " " +dotMassSum); - // lambda = MathUtils.clamp(lambda, -Settings.maxLinearCorrection, - // Settings.maxLinearCorrection); - // _impulse = lambda; for (int i = 0; i < _bodies.length; ++i) { velocities[_bodies[i]._islandIndex].v.x += _bodies[i]._invMass * d[i].y * .5 * _impulse; @@ -206,22 +172,18 @@ class ConstantVolumeJoint extends Joint { List velocities = step.velocities; List positions = step.positions; - final List d = pool.getVec2Array(_bodies.length); + final List d = List(_bodies.length); for (int i = 0; i < _bodies.length; ++i) { final int prev = (i == 0) ? _bodies.length - 1 : i - 1; final int next = (i == _bodies.length - 1) ? 0 : i + 1; - d[i].setFrom(positions[_bodies[next]._islandIndex].c); + d[i] = Vector2.copy(positions[_bodies[next]._islandIndex].c); d[i].sub(positions[_bodies[prev]._islandIndex].c); dotMassSum += (d[i].length2) / _bodies[i].mass; crossMassSum += velocities[_bodies[i]._islandIndex].v.cross(d[i]); } double lambda = -2.0 * crossMassSum / dotMassSum; - // System.out.println(crossMassSum + " " +dotMassSum); - // lambda = MathUtils.clamp(lambda, -Settings.maxLinearCorrection, - // Settings.maxLinearCorrection); _impulse += lambda; - // System.out.println(_impulse); for (int i = 0; i < _bodies.length; ++i) { velocities[_bodies[i]._islandIndex].v.x += _bodies[i]._invMass * d[i].y * .5 * lambda; @@ -230,17 +192,19 @@ class ConstantVolumeJoint extends Joint { } } - /** No-op */ - void getAnchorA(Vector2 argOut) {} + /// No-op + @override + Vector2 getAnchorA() => Vector2.zero(); - /** No-op */ - void getAnchorB(Vector2 argOut) {} + /// No-op + @override + Vector2 getAnchorB() => Vector2.zero(); - /** No-op */ - void getReactionForce(double inv_dt, Vector2 argOut) {} + /// No-op + @override + Vector2 getReactionForce(double inv_dt) => Vector2.zero(); - /** No-op */ - double getReactionTorque(double inv_dt) { - return 0.0; - } + /// No-op + @override + double getReactionTorque(double inv_dt) => 0.0; } diff --git a/lib/src/dynamics/joints/constant_volume_joints_def.dart b/lib/src/dynamics/joints/constant_volume_joints_def.dart index ac4bc48..568dafe 100644 --- a/lib/src/dynamics/joints/constant_volume_joints_def.dart +++ b/lib/src/dynamics/joints/constant_volume_joints_def.dart @@ -1,50 +1,22 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Definition for a {@link ConstantVolumeJoint}, which connects a group a bodies together so they - * maintain a constant volume within them. - */ +/// Definition for a {@link ConstantVolumeJoint}, which connects a group a bodies together so they +/// maintain a constant volume within them. class ConstantVolumeJointDef extends JointDef { double frequencyHz = 0.0; double dampingRatio = 0.0; - List bodies = new List(); + List bodies = List(); List joints; ConstantVolumeJointDef() : super(JointType.CONSTANT_VOLUME) { collideConnected = false; } - /** - * Adds a body to the group - * - * @param argBody - */ + /// Adds a body to the group + /// + /// @param argBody void addBody(Body argBody) { bodies.add(argBody); if (bodies.length == 1) { @@ -55,14 +27,10 @@ class ConstantVolumeJointDef extends JointDef { } } - /** - * Adds a body and the pre-made distance joint. Should only be used for deserialization. - */ + /// Adds a body and the pre-made distance joint. Should only be used for deserialization. void addBodyAndJoint(Body argBody, DistanceJoint argJoint) { addBody(argBody); - if (joints == null) { - joints = new List(); - } + joints ??= List(); joints.add(argJoint); } } diff --git a/lib/src/dynamics/joints/distance_joint.dart b/lib/src/dynamics/joints/distance_joint.dart index 4926b4e..4e96cec 100644 --- a/lib/src/dynamics/joints/distance_joint.dart +++ b/lib/src/dynamics/joints/distance_joint.dart @@ -1,40 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -//C = norm(p2 - p1) - L -//u = (p2 - p1) / norm(p2 - p1) -//Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -//J = [-u -cross(r1, u) u cross(r2, u)] -//K = J * invM * JT -//= invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 - -/** - * A distance joint constrains two points on two bodies to remain at a fixed distance from each - * other. You can view this as a massless, rigid rod. - */ +/// A distance joint constrains two points on two bodies to remain at a fixed distance from each +/// other. You can view this as a massless, rigid rod. class DistanceJoint extends Joint { double _frequencyHz = 0.0; @@ -42,8 +9,6 @@ class DistanceJoint extends Joint { double _bias = 0.0; // Solver shared - final Vector2 _localAnchorA; - final Vector2 _localAnchorB; double _gamma = 0.0; double _impulse = 0.0; double _length = 0.0; @@ -51,51 +16,36 @@ class DistanceJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _u = new Vector2.zero(); - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _u = Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; double _mass = 0.0; - DistanceJoint(IWorldPool argWorld, final DistanceJointDef def) - : _localAnchorA = def.localAnchorA.clone(), - _localAnchorB = def.localAnchorB.clone(), - super(argWorld, def) { + DistanceJoint(final DistanceJointDef def) : super(def) { _length = def.length; _frequencyHz = def.frequencyHz; _dampingRatio = def.dampingRatio; } - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); + /// Get the reaction force given the inverse time step. Unit is N. + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2( + _impulse * _u.x * inv_dt, + _impulse * _u.y * inv_dt, + ); } - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - /** - * Get the reaction force given the inverse time step. Unit is N. - */ - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut.x = _impulse * _u.x * inv_dt; - argOut.y = _impulse * _u.y * inv_dt; - } - - /** - * Get the reaction torque given the inverse time step. Unit is N*m. This is always zero for a - * distance joint. - */ - - double getReactionTorque(double inv_dt) { - return 0.0; - } + /// Get the reaction torque given the inverse time step. Unit is N*m. This is always zero for a + /// distance joint. + @override + double getReactionTorque(double inv_dt) => 0.0; void initVelocityConstraints(final SolverData data) { _indexA = _bodyA._islandIndex; @@ -117,33 +67,27 @@ class DistanceJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); + final Rot qA = Rot(); + final Rot qB = Rot(); qA.setAngle(aA); qB.setAngle(aB); // use _u as temporary variable - Rot.mulToOutUnsafe( - qA, - _u - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - _rA); - Rot.mulToOutUnsafe( - qB, - _u - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); + _u + ..setFrom(localAnchorA) + ..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, _u)); + _u + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, _u)); _u ..setFrom(cB) ..add(_rB) ..sub(cA) ..sub(_rA); - pool.pushRot(2); - // Handle singularity. double length = _u.length; if (length > Settings.linearSlop) { @@ -165,7 +109,7 @@ class DistanceJoint extends Joint { double C = length - _length; // Frequency - double omega = 2.0 * Math.PI * _frequencyHz; + double omega = 2.0 * Math.pi * _frequencyHz; // Damping coefficient double d = 2.0 * _mass * _dampingRatio * omega; @@ -189,7 +133,7 @@ class DistanceJoint extends Joint { // Scale the impulse to support a variable time step. _impulse *= data.step.dtRatio; - Vector2 P = pool.popVec2(); + Vector2 P = Vector2.zero(); P ..setFrom(_u) ..scale(_impulse); @@ -201,14 +145,10 @@ class DistanceJoint extends Joint { vB.x += _invMassB * P.x; vB.y += _invMassB * P.y; wB += _invIB * _rB.cross(P); - - pool.pushVec2(1); } else { _impulse = 0.0; } -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; } @@ -218,8 +158,8 @@ class DistanceJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Vector2 vpA = pool.popVec2(); - final Vector2 vpB = pool.popVec2(); + final Vector2 vpA = Vector2.zero(); + final Vector2 vpB = Vector2.zero(); // Cdot = dot(u, v + cross(w, r)) _rA.scaleOrthogonalInto(wA, vpA); @@ -241,23 +181,19 @@ class DistanceJoint extends Joint { vB.y += _invMassB * Py; wB += _invIB * (_rB.x * Py - _rB.y * Px); -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(2); } bool solvePositionConstraints(final SolverData data) { if (_frequencyHz > 0.0) { return true; } - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); - final Vector2 u = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 u = Vector2.zero(); Vector2 cA = data.positions[_indexA].c; double aA = data.positions[_indexA].a; @@ -267,18 +203,14 @@ class DistanceJoint extends Joint { qA.setAngle(aA); qB.setAngle(aB); - Rot.mulToOutUnsafe( - qA, - u - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - u - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + u + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, u)); + u + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, u)); u ..setFrom(cB) ..add(rB) @@ -301,14 +233,9 @@ class DistanceJoint extends Joint { cB.y += _invMassB * Py; aB += _invIB * (rB.x * Py - rB.y * Px); -// data.positions[_indexA].c.set(cA); data.positions[_indexA].a = aA; -// data.positions[_indexB].c.set(cB); data.positions[_indexB].a = aB; - pool.pushVec2(3); - pool.pushRot(2); - return C.abs() < Settings.linearSlop; } } diff --git a/lib/src/dynamics/joints/distance_joint_def.dart b/lib/src/dynamics/joints/distance_joint_def.dart index 5fb90d1..a33a4bb 100644 --- a/lib/src/dynamics/joints/distance_joint_def.dart +++ b/lib/src/dynamics/joints/distance_joint_def.dart @@ -1,67 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero - * length of the distance joint. The definition uses local anchor points so that the initial - * configuration can violate the constraint slightly. This helps when saving and loading a game. - * - * @warning Do not use a zero or short length. - */ +/// Distance joint definition. This requires defining an anchor point on both bodies and the non-zero +/// length of the distance joint. The definition uses local anchor points so that the initial +/// configuration can violate the constraint slightly. This helps when saving and loading a game. +/// +/// @warning Do not use a zero or short length. class DistanceJointDef extends JointDef { - /** The local anchor point relative to body1's origin. */ - final Vector2 localAnchorA = new Vector2.zero(); - - /** The local anchor point relative to body2's origin. */ - final Vector2 localAnchorB = new Vector2.zero(); - - /** The equilibrium length between the anchor points. */ + /// The equilibrium length between the anchor points. double length = 1.0; - /** - * The mass-spring-damper frequency in Hertz. - */ + /// The mass-spring-damper frequency in Hertz. double frequencyHz = 0.0; - /** - * The damping ratio. 0 = no damping, 1 = critical damping. - */ + /// The damping ratio. 0 = no damping, 1 = critical damping. double dampingRatio = 0.0; DistanceJointDef() : super(JointType.DISTANCE); - /** - * Initialize the bodies, anchors, and length using the world anchors. - * - * @param b1 First body - * @param b2 Second body - * @param anchor1 World anchor on first body - * @param anchor2 World anchor on second body - */ + /// Initialize the bodies, anchors, and length using the world anchors. + /// + /// @param b1 First body + /// @param b2 Second body + /// @param anchor1 World anchor on first body + /// @param anchor2 World anchor on second body void initialize(final Body b1, final Body b2, final Vector2 anchor1, final Vector2 anchor2) { bodyA = b1; diff --git a/lib/src/dynamics/joints/friction_joint.dart b/lib/src/dynamics/joints/friction_joint.dart index 2027cdd..9a6850a 100644 --- a/lib/src/dynamics/joints/friction_joint.dart +++ b/lib/src/dynamics/joints/friction_joint.dart @@ -1,33 +1,6 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class FrictionJoint extends Joint { - final Vector2 _localAnchorA; - final Vector2 _localAnchorB; - // Solver shared final Vector2 _linearImpulse; double _angularImpulse = 0.0; @@ -37,46 +10,28 @@ class FrictionJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; - final Matrix2 _linearMass = new Matrix2.zero(); + final Matrix2 _linearMass = Matrix2.zero(); double _angularMass = 0.0; - FrictionJoint(IWorldPool argWorldPool, FrictionJointDef def) - : _localAnchorA = new Vector2.copy(def.localAnchorA), - _localAnchorB = new Vector2.copy(def.localAnchorB), - _linearImpulse = new Vector2.zero(), - super(argWorldPool, def) { + FrictionJoint(FrictionJointDef def) + : _linearImpulse = Vector2.zero(), + super(def) { _maxForce = def.maxForce; _maxTorque = def.maxTorque; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut - ..setFrom(_linearImpulse) - ..scale(inv_dt); + /// Get the reaction force given the inverse time step. Unit is N. + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2.copy(_linearImpulse)..scale(inv_dt); } double getReactionTorque(double inv_dt) { @@ -101,9 +56,7 @@ class FrictionJoint extends Joint { return _maxTorque; } - /** - * @see org.jbox2d.dynamics.joints.Joint#initVelocityConstraints(org.jbox2d.dynamics.TimeStep) - */ + /// @see org.jbox2d.dynamics.joints.Joint#initVelocityConstraints(org.jbox2d.dynamics.TimeStep) void initVelocityConstraints(final SolverData data) { _indexA = _bodyA._islandIndex; @@ -123,40 +76,27 @@ class FrictionJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Vector2 temp = pool.popVec2(); - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); + final Vector2 temp = Vector2.zero(); + final Rot qA = Rot(); + final Rot qB = Rot(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective mass matrix. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - _rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, temp)); double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - final Matrix2 K = pool.popMat22(); + final Matrix2 K = Matrix2.zero(); double a11 = mA + mB + iA * _rA.y * _rA.y + iB * _rB.y * _rB.y; double a21 = -iA * _rA.x * _rA.y - iB * _rB.x * _rB.y; double a12 = a21; @@ -176,7 +116,7 @@ class FrictionJoint extends Joint { _linearImpulse.scale(data.step.dtRatio); _angularImpulse *= data.step.dtRatio; - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); P.setFrom(_linearImpulse); temp @@ -190,23 +130,15 @@ class FrictionJoint extends Joint { ..scale(mB); vB.add(temp); wB += iB * (_rB.cross(P) + _angularImpulse); - - pool.pushVec2(1); } else { _linearImpulse.setZero(); _angularImpulse = 0.0; } -// data.velocities[_indexA].v.set(vA); if (data.velocities[_indexA].w != wA) { assert(data.velocities[_indexA].w != wA); } data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushRot(2); - pool.pushVec2(1); - pool.pushMat22(1); } void solveVelocityConstraints(final SolverData data) { @@ -237,8 +169,8 @@ class FrictionJoint extends Joint { // Solve linear friction { - final Vector2 Cdot = pool.popVec2(); - final Vector2 temp = pool.popVec2(); + final Vector2 Cdot = Vector2.zero(); + final Vector2 temp = Vector2.zero(); _rA.scaleOrthogonalInto(wA, temp); _rB.scaleOrthogonalInto(wB, Cdot); @@ -247,11 +179,11 @@ class FrictionJoint extends Joint { ..sub(vA) ..sub(temp); - final Vector2 impulse = pool.popVec2(); + final Vector2 impulse = Vector2.zero(); _linearMass.transformed(Cdot, impulse); impulse.negate(); - final Vector2 oldImpulse = pool.popVec2(); + final Vector2 oldImpulse = Vector2.zero(); oldImpulse.setFrom(_linearImpulse); _linearImpulse.add(impulse); @@ -279,16 +211,11 @@ class FrictionJoint extends Joint { wB += iB * _rB.cross(impulse); } -// data.velocities[_indexA].v.set(vA); if (data.velocities[_indexA].w != wA) { assert(data.velocities[_indexA].w != wA); } data.velocities[_indexA].w = wA; - -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(4); } bool solvePositionConstraints(final SolverData data) { diff --git a/lib/src/dynamics/joints/friction_joint_def.dart b/lib/src/dynamics/joints/friction_joint_def.dart index 8bb3441..3e3a963 100644 --- a/lib/src/dynamics/joints/friction_joint_def.dart +++ b/lib/src/dynamics/joints/friction_joint_def.dart @@ -1,68 +1,21 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Friction joint definition. - * - * @author Daniel Murphy - */ +/// Friction joint definition. class FrictionJointDef extends JointDef { - /** - * The local anchor point relative to bodyA's origin. - */ - final Vector2 localAnchorA; - - /** - * The local anchor point relative to bodyB's origin. - */ - final Vector2 localAnchorB; - - /** - * The maximum friction force in N. - */ + /// The maximum friction force in N. double maxForce = 0.0; - /** - * The maximum friction torque in N-m. - */ + /// The maximum friction torque in N-m. double maxTorque = 0.0; - FrictionJointDef() - : localAnchorA = new Vector2.zero(), - localAnchorB = new Vector2.zero(), - super(JointType.FRICTION); + FrictionJointDef() : super(JointType.FRICTION); - /** - * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world - * axis. - */ + /// Initialize the bodies, anchors, axis, and reference angle using the world anchor and world + /// axis. void initialize(Body bA, Body bB, Vector2 anchor) { bodyA = bA; bodyB = bB; - bA.getLocalPointToOut(anchor, localAnchorA); - bB.getLocalPointToOut(anchor, localAnchorB); + localAnchorA.setFrom(bA.getLocalPoint(anchor)); + localAnchorB.setFrom(bB.getLocalPoint(anchor)); } } diff --git a/lib/src/dynamics/joints/gear_joint.dart b/lib/src/dynamics/joints/gear_joint.dart index 521b621..c43405f 100644 --- a/lib/src/dynamics/joints/gear_joint.dart +++ b/lib/src/dynamics/joints/gear_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Gear Joint: @@ -43,18 +19,14 @@ part of box2d; //J = [ug cross(r, ug)] //K = J * invM * JT = invMass + invI * cross(r, ug)^2 -/** - * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic - * joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio * coordinate2 = - * constant The ratio can be negative or positive. If one joint is a revolute joint and the other - * joint is a prismatic joint, then the ratio will have units of length or units of 1/length. - * - * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 - * on those joints). - * @warning You have to manually destroy the gear joint if joint1 or joint2 is destroyed. - * @author Daniel Murphy - */ - +/// A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic +/// joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio * coordinate2 = +/// constant The ratio can be negative or positive. If one joint is a revolute joint and the other +/// joint is a prismatic joint, then the ratio will have units of length or units of 1/length. +/// +/// @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 +/// on those joints). +/// @warning You have to manually destroy the gear joint if joint1 or joint2 is destroyed. class GearJoint extends Joint { final Joint _joint1; final Joint _joint2; @@ -68,13 +40,11 @@ class GearJoint extends Joint { final Body _bodyD; // Solver shared - final Vector2 _localAnchorA = new Vector2.zero(); - final Vector2 _localAnchorB = new Vector2.zero(); - final Vector2 _localAnchorC = new Vector2.zero(); - final Vector2 _localAnchorD = new Vector2.zero(); + final Vector2 _localAnchorC = Vector2.zero(); + final Vector2 _localAnchorD = Vector2.zero(); - final Vector2 _localAxisC = new Vector2.zero(); - final Vector2 _localAxisD = new Vector2.zero(); + final Vector2 _localAxisC = Vector2.zero(); + final Vector2 _localAxisD = Vector2.zero(); double _referenceAngleA = 0.0; double _referenceAngleB = 0.0; @@ -86,24 +56,24 @@ class GearJoint extends Joint { // Solver temp int _indexA = 0, _indexB = 0, _indexC = 0, _indexD = 0; - final Vector2 _lcA = new Vector2.zero(), - _lcB = new Vector2.zero(), - _lcC = new Vector2.zero(), - _lcD = new Vector2.zero(); + final Vector2 _lcA = Vector2.zero(), + _lcB = Vector2.zero(), + _lcC = Vector2.zero(), + _lcD = Vector2.zero(); double _mA = 0.0, _mB = 0.0, _mC = 0.0, _mD = 0.0; double _iA = 0.0, _iB = 0.0, _iC = 0.0, _iD = 0.0; - final Vector2 _JvAC = new Vector2.zero(), _JvBD = new Vector2.zero(); + final Vector2 _JvAC = Vector2.zero(), _JvBD = Vector2.zero(); double _JwA = 0.0, _JwB = 0.0, _JwC = 0.0, _JwD = 0.0; double _mass = 0.0; - GearJoint(IWorldPool argWorldPool, GearJointDef def) + GearJoint(GearJointDef def) : _joint1 = def.joint1, _joint2 = def.joint2, _typeA = def.joint1.getType(), _typeB = def.joint2.getType(), _bodyC = def.joint1.getBodyA(), _bodyD = def.joint2.getBodyA(), - super(argWorldPool, def) { + super(def) { assert(_typeA == JointType.REVOLUTE || _typeA == JointType.PRISMATIC); assert(_typeB == JointType.REVOLUTE || _typeB == JointType.PRISMATIC); @@ -120,29 +90,28 @@ class GearJoint extends Joint { if (_typeA == JointType.REVOLUTE) { final revolute = def.joint1 as RevoluteJoint; - _localAnchorC.setFrom(revolute._localAnchorA); - _localAnchorA.setFrom(revolute._localAnchorB); + _localAnchorC.setFrom(revolute.localAnchorA); + localAnchorA.setFrom(revolute.localAnchorB); _referenceAngleA = revolute._referenceAngle; _localAxisC.setZero(); coordinateA = aA - aC - _referenceAngleA; } else { - Vector2 pA = pool.popVec2(); - Vector2 temp = pool.popVec2(); + Vector2 pA = Vector2.zero(); + Vector2 temp = Vector2.zero(); final prismatic = def.joint1 as PrismaticJoint; - _localAnchorC.setFrom(prismatic._localAnchorA); - _localAnchorA.setFrom(prismatic._localAnchorB); + _localAnchorC.setFrom(prismatic.localAnchorA); + localAnchorA.setFrom(prismatic.localAnchorB); _referenceAngleA = prismatic._referenceAngle; _localAxisC.setFrom(prismatic._localXAxisA); Vector2 pC = _localAnchorC; - Rot.mulToOutUnsafe(xfA.q, _localAnchorA, temp); temp + ..setFrom(Rot.mulVec2(xfA.q, localAnchorA)) ..add(xfA.p) ..sub(xfC.p); - Rot.mulTransUnsafeVec2(xfC.q, temp, pA); + pA.setFrom(Rot.mulTransVec2(xfC.q, temp)); coordinateA = (pA..sub(pC)).dot(_localAxisC); - pool.pushVec2(2); } _bodyB = _joint2.getBodyB(); @@ -155,51 +124,39 @@ class GearJoint extends Joint { if (_typeB == JointType.REVOLUTE) { final revolute = def.joint2 as RevoluteJoint; - _localAnchorD.setFrom(revolute._localAnchorA); - _localAnchorB.setFrom(revolute._localAnchorB); + _localAnchorD.setFrom(revolute.localAnchorA); + localAnchorB.setFrom(revolute.localAnchorB); _referenceAngleB = revolute._referenceAngle; _localAxisD.setZero(); coordinateB = aB - aD - _referenceAngleB; } else { - Vector2 pB = pool.popVec2(); - Vector2 temp = pool.popVec2(); + Vector2 pB = Vector2.zero(); + Vector2 temp = Vector2.zero(); final prismatic = def.joint2 as PrismaticJoint; - _localAnchorD.setFrom(prismatic._localAnchorA); - _localAnchorB.setFrom(prismatic._localAnchorB); + _localAnchorD.setFrom(prismatic.localAnchorA); + localAnchorB.setFrom(prismatic.localAnchorB); _referenceAngleB = prismatic._referenceAngle; _localAxisD.setFrom(prismatic._localXAxisA); Vector2 pD = _localAnchorD; - Rot.mulToOutUnsafe(xfB.q, _localAnchorB, temp); temp + ..setFrom(Rot.mulVec2(xfB.q, localAnchorB)) ..add(xfB.p) ..sub(xfD.p); - Rot.mulTransUnsafeVec2(xfD.q, temp, pB); + pB.setFrom(Rot.mulTransVec2(xfD.q, temp)); coordinateB = (pB..sub(pD)).dot(_localAxisD); - pool.pushVec2(2); } _ratio = def.ratio; - _constant = coordinateA + _ratio * coordinateB; - _impulse = 0.0; } - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut - ..setFrom(_JvAC) - ..scale(_impulse); - argOut.scale(inv_dt); + /// Get the reaction force given the inverse time step. Unit is N. + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2.copy(_JvAC)..scale(_impulse)..scale(inv_dt); } double getReactionTorque(double inv_dt) { @@ -253,10 +210,7 @@ class GearJoint extends Joint { Vector2 vD = data.velocities[_indexD].v; double wD = data.velocities[_indexD].w; - Rot qA = pool.popRot(), - qB = pool.popRot(), - qC = pool.popRot(), - qD = pool.popRot(); + Rot qA = Rot(), qB = Rot(), qC = Rot(), qD = Rot(); qA.setAngle(aA); qB.setAngle(aB); qC.setAngle(aC); @@ -264,7 +218,7 @@ class GearJoint extends Joint { _mass = 0.0; - Vector2 temp = pool.popVec2(); + Vector2 temp = Vector2.zero(); if (_typeA == JointType.REVOLUTE) { _JvAC.setZero(); @@ -272,25 +226,20 @@ class GearJoint extends Joint { _JwC = 1.0; _mass += _iA + _iC; } else { - Vector2 rC = pool.popVec2(); - Vector2 rA = pool.popVec2(); - Rot.mulToOutUnsafe(qC, _localAxisC, _JvAC); - Rot.mulToOutUnsafe( - qC, - temp - ..setFrom(_localAnchorC) - ..sub(_lcC), - rC); - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_lcA), - rA); + Vector2 rC = Vector2.zero(); + Vector2 rA = Vector2.zero(); + _JvAC.setFrom(Rot.mulVec2(qC, _localAxisC)); + temp + ..setFrom(_localAnchorC) + ..sub(_lcC); + rC.setFrom(Rot.mulVec2(qC, temp)); + temp + ..setFrom(localAnchorA) + ..sub(_lcA); + rA.setFrom(Rot.mulVec2(qA, temp)); _JwC = rC.cross(_JvAC); _JwA = rA.cross(_JvAC); _mass += _mC + _mA + _iC * _JwC * _JwC + _iA * _JwA * _JwA; - pool.pushVec2(2); } if (_typeB == JointType.REVOLUTE) { @@ -299,22 +248,18 @@ class GearJoint extends Joint { _JwD = _ratio; _mass += _ratio * _ratio * (_iB + _iD); } else { - Vector2 u = pool.popVec2(); - Vector2 rD = pool.popVec2(); - Vector2 rB = pool.popVec2(); - Rot.mulToOutUnsafe(qD, _localAxisD, u); - Rot.mulToOutUnsafe( - qD, - temp - ..setFrom(_localAnchorD) - ..sub(_lcD), - rD); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_lcB), - rB); + Vector2 u = Vector2.zero(); + Vector2 rD = Vector2.zero(); + Vector2 rB = Vector2.zero(); + u.setFrom(Rot.mulVec2(qD, _localAxisD)); + temp + ..setFrom(_localAnchorD) + ..sub(_lcD); + rD.setFrom(Rot.mulVec2(qD, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_lcB); + rB.setFrom(Rot.mulVec2(qB, temp)); _JvBD ..setFrom(u) ..scale(_ratio); @@ -322,7 +267,6 @@ class GearJoint extends Joint { _JwB = _ratio * rB.cross(u); _mass += _ratio * _ratio * (_mD + _mB) + _iD * _JwD * _JwD + _iB * _JwB * _JwB; - pool.pushVec2(3); } // Compute effective mass. @@ -347,16 +291,10 @@ class GearJoint extends Joint { } else { _impulse = 0.0; } - pool.pushVec2(1); - pool.pushRot(4); - // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; - // data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; - // data.velocities[_indexC].v = vC; data.velocities[_indexC].w = wC; - // data.velocities[_indexD].v = vD; data.velocities[_indexD].w = wD; } @@ -370,8 +308,8 @@ class GearJoint extends Joint { Vector2 vD = data.velocities[_indexD].v; double wD = data.velocities[_indexD].w; - Vector2 temp1 = pool.popVec2(); - Vector2 temp2 = pool.popVec2(); + Vector2 temp1 = Vector2.zero(); + Vector2 temp2 = Vector2.zero(); double Cdot = _JvAC.dot(temp1 ..setFrom(vA) ..sub(vC)) + @@ -379,7 +317,6 @@ class GearJoint extends Joint { ..setFrom(vB) ..sub(vD)); Cdot += (_JwA * wA - _JwC * wC) + (_JwB * wB - _JwD * wD); - pool.pushVec2(2); double impulse = -_mass * Cdot; _impulse += impulse; @@ -428,10 +365,7 @@ class GearJoint extends Joint { Vector2 cD = data.positions[_indexD].c; double aD = data.positions[_indexD].a; - Rot qA = pool.popRot(), - qB = pool.popRot(), - qC = pool.popRot(), - qD = pool.popRot(); + Rot qA = Rot(), qB = Rot(), qC = Rot(), qD = Rot(); qA.setAngle(aA); qB.setAngle(aB); qC.setAngle(aC); @@ -441,9 +375,9 @@ class GearJoint extends Joint { double coordinateA, coordinateB; - Vector2 temp = pool.popVec2(); - Vector2 JvAC = pool.popVec2(); - Vector2 JvBD = pool.popVec2(); + Vector2 temp = Vector2.zero(); + Vector2 JvAC = Vector2.zero(); + Vector2 JvBD = Vector2.zero(); double JwA, JwB, JwC, JwD; double mass = 0.0; @@ -455,23 +389,19 @@ class GearJoint extends Joint { coordinateA = aA - aC - _referenceAngleA; } else { - Vector2 rC = pool.popVec2(); - Vector2 rA = pool.popVec2(); - Vector2 pC = pool.popVec2(); - Vector2 pA = pool.popVec2(); - Rot.mulToOutUnsafe(qC, _localAxisC, JvAC); - Rot.mulToOutUnsafe( - qC, - temp - ..setFrom(_localAnchorC) - ..sub(_lcC), - rC); - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_lcA), - rA); + Vector2 rC = Vector2.zero(); + Vector2 rA = Vector2.zero(); + Vector2 pC = Vector2.zero(); + Vector2 pA = Vector2.zero(); + JvAC.setFrom(Rot.mulVec2(qC, _localAxisC)); + temp + ..setFrom(_localAnchorC) + ..sub(_lcC); + rC.setFrom(Rot.mulVec2(qC, temp)); + temp + ..setFrom(localAnchorA) + ..sub(_lcA); + rA.setFrom(Rot.mulVec2(qA, temp)); JwC = rC.cross(JvAC); JwA = rA.cross(JvAC); mass += _mC + _mA + _iC * JwC * JwC + _iA * JwA * JwA; @@ -479,15 +409,12 @@ class GearJoint extends Joint { pC ..setFrom(_localAnchorC) ..sub(_lcC); - Rot.mulTransUnsafeVec2( - qC, - temp - ..setFrom(rA) - ..add(cA) - ..sub(cC), - pA); + temp + ..setFrom(rA) + ..add(cA) + ..sub(cC); + pA.setFrom(Rot.mulTransVec2(qC, temp)); coordinateA = (pA..sub(pC)).dot(_localAxisC); - pool.pushVec2(4); } if (_typeB == JointType.REVOLUTE) { @@ -498,24 +425,20 @@ class GearJoint extends Joint { coordinateB = aB - aD - _referenceAngleB; } else { - Vector2 u = pool.popVec2(); - Vector2 rD = pool.popVec2(); - Vector2 rB = pool.popVec2(); - Vector2 pD = pool.popVec2(); - Vector2 pB = pool.popVec2(); - Rot.mulToOutUnsafe(qD, _localAxisD, u); - Rot.mulToOutUnsafe( - qD, - temp - ..setFrom(_localAnchorD) - ..sub(_lcD), - rD); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_lcB), - rB); + Vector2 u = Vector2.zero(); + Vector2 rD = Vector2.zero(); + Vector2 rB = Vector2.zero(); + Vector2 pD = Vector2.zero(); + Vector2 pB = Vector2.zero(); + u.setFrom(Rot.mulVec2(qD, _localAxisD)); + temp + ..setFrom(_localAnchorD) + ..sub(_lcD); + rD.setFrom(Rot.mulVec2(qD, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_lcB); + rB.setFrom(Rot.mulVec2(qB, temp)); JvBD ..setFrom(u) ..scale(_ratio); @@ -526,15 +449,12 @@ class GearJoint extends Joint { pD ..setFrom(_localAnchorD) ..sub(_lcD); - Rot.mulTransUnsafeVec2( - qD, - temp - ..setFrom(rB) - ..add(cB) - ..sub(cD), - pB); + temp + ..setFrom(rB) + ..add(cB) + ..sub(cD); + pB.setFrom(Rot.mulTransVec2(qD, pB)); coordinateB = (pB..sub(pD)).dot(_localAxisD); - pool.pushVec2(5); } double C = (coordinateA + _ratio * coordinateB) - _constant; @@ -543,8 +463,6 @@ class GearJoint extends Joint { if (mass > 0.0) { impulse = -C / mass; } - pool.pushVec2(3); - pool.pushRot(4); cA.x += (_mA * impulse) * JvAC.x; cA.y += (_mA * impulse) * JvAC.y; diff --git a/lib/src/dynamics/joints/gear_joint_def.dart b/lib/src/dynamics/joints/gear_joint_def.dart index 7755ca7..38690db 100644 --- a/lib/src/dynamics/joints/gear_joint_def.dart +++ b/lib/src/dynamics/joints/gear_joint_def.dart @@ -1,52 +1,17 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Gear joint definition. This definition requires two existing revolute or prismatic joints (any - * combination will work). The provided joints must attach a dynamic body to a static body. - * - * @author Daniel Murphy - */ - +/// Gear joint definition. This definition requires two existing revolute or prismatic joints (any +/// combination will work). The provided joints must attach a dynamic body to a static body. class GearJointDef extends JointDef { - /** - * The first revolute/prismatic joint attached to the gear joint. - */ + /// The first revolute/prismatic joint attached to the gear joint. Joint joint1; - /** - * The second revolute/prismatic joint attached to the gear joint. - */ + /// The second revolute/prismatic joint attached to the gear joint. Joint joint2; - /** - * Gear ratio. - * - * @see GearJoint - */ + /// Gear ratio. + /// + /// @see GearJoint double ratio = 0.0; GearJointDef() : super(JointType.GEAR); diff --git a/lib/src/dynamics/joints/jacobian.dart b/lib/src/dynamics/joints/jacobian.dart index c3e6481..4210333 100644 --- a/lib/src/dynamics/joints/jacobian.dart +++ b/lib/src/dynamics/joints/jacobian.dart @@ -1,31 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class Jacobian { - final Vector2 linearA = new Vector2.zero(); + final Vector2 linearA = Vector2.zero(); double angularA = 0.0; double angularB = 0.0; } diff --git a/lib/src/dynamics/joints/joint.dart b/lib/src/dynamics/joints/joint.dart index 3bd623d..d17e3f2 100644 --- a/lib/src/dynamics/joints/joint.dart +++ b/lib/src/dynamics/joints/joint.dart @@ -1,63 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * The base joint class. Joints are used to constrain two bodies together in various fashions. Some - * joints also feature limits and motors. - * - * @author Daniel Murphy - */ +/// The base joint class. Joints are used to constrain two bodies together in various fashions. Some +/// joints also feature limits and motors. abstract class Joint { static Joint create(World world, JointDef def) { - // Joint joint = null; switch (def.type) { case JointType.MOUSE: - return new MouseJoint(world.getPool(), def as MouseJointDef); + return MouseJoint(def as MouseJointDef); case JointType.DISTANCE: - return new DistanceJoint(world.getPool(), def as DistanceJointDef); + return DistanceJoint(def as DistanceJointDef); case JointType.PRISMATIC: - return new PrismaticJoint(world.getPool(), def as PrismaticJointDef); + return PrismaticJoint(def as PrismaticJointDef); case JointType.REVOLUTE: - return new RevoluteJoint(world.getPool(), def as RevoluteJointDef); + return RevoluteJoint(def as RevoluteJointDef); case JointType.WELD: - return new WeldJoint(world.getPool(), def as WeldJointDef); + return WeldJoint(def as WeldJointDef); case JointType.FRICTION: - return new FrictionJoint(world.getPool(), def as FrictionJointDef); + return FrictionJoint(def as FrictionJointDef); case JointType.WHEEL: - return new WheelJoint(world.getPool(), def as WheelJointDef); + return WheelJoint(def as WheelJointDef); case JointType.GEAR: - return new GearJoint(world.getPool(), def as GearJointDef); + return GearJoint(def as GearJointDef); case JointType.PULLEY: - return new PulleyJoint(world.getPool(), def as PulleyJointDef); + return PulleyJoint(def as PulleyJointDef); case JointType.CONSTANT_VOLUME: - return new ConstantVolumeJoint(world, def as ConstantVolumeJointDef); + return ConstantVolumeJoint(world, def as ConstantVolumeJointDef); case JointType.ROPE: - return new RopeJoint(world.getPool(), def as RopeJointDef); + return RopeJoint(def as RopeJointDef); case JointType.MOTOR: - return new MotorJoint(world.getPool(), def as MotorJointDef); + return MotorJoint(def as MotorJointDef); case JointType.UNKNOWN: default: return null; @@ -79,135 +50,103 @@ abstract class Joint { bool _islandFlag = false; bool _collideConnected = false; - Object _userData; - - IWorldPool pool; + final Vector2 localAnchorA; + final Vector2 localAnchorB; - // Cache here per time step to reduce cache misses. - // final Vec2 _localCenterA, _localCenterB; - // double _invMassA, _invIA; - // double _invMassB, _invIB; - - Joint(IWorldPool worldPool, JointDef def) : _type = def.type { + Joint(JointDef def) + : localAnchorA = def.localAnchorA, + localAnchorB = def.localAnchorB, + _type = def.type { assert(def.bodyA != def.bodyB); - pool = worldPool; _prev = null; _next = null; _bodyA = def.bodyA; _bodyB = def.bodyB; _collideConnected = def.collideConnected; _islandFlag = false; - _userData = def.userData; - _edgeA = new JointEdge(); + _edgeA = JointEdge(); _edgeA.joint = null; _edgeA.other = null; _edgeA.prev = null; _edgeA.next = null; - _edgeB = new JointEdge(); + _edgeB = JointEdge(); _edgeB.joint = null; _edgeB.other = null; _edgeB.prev = null; _edgeB.next = null; - - // _localCenterA = new Vec2(); - // _localCenterB = new Vec2(); } - /** - * get the type of the concrete joint. - * - * @return - */ + /// get the type of the concrete joint. + /// + /// @return JointType getType() { return _type; } - /** - * get the first body attached to this joint. - */ + /// get the first body attached to this joint. Body getBodyA() { return _bodyA; } - /** - * get the second body attached to this joint. - * - * @return - */ + /// Get the second body attached to this joint. + /// + /// @return Body getBodyB() { return _bodyB; } - /** - * get the anchor point on bodyA in world coordinates. - * - * @return - */ - void getAnchorA(Vector2 out); - - /** - * get the anchor point on bodyB in world coordinates. - * - * @return - */ - void getAnchorB(Vector2 out); - - /** - * get the reaction force on body2 at the joint anchor in Newtons. - * - * @param inv_dt - * @return - */ - void getReactionForce(double inv_dt, Vector2 out); - - /** - * get the reaction torque on body2 in N*m. - * - * @param inv_dt - * @return - */ + /// Get the anchor point on bodyA in world coordinates. + /// + /// @return + Vector2 getAnchorA() => _bodyA.getWorldPoint(localAnchorA); + + /// Get the anchor point on bodyB in world coordinates. + /// + /// @return + Vector2 getAnchorB() => _bodyB.getWorldPoint(localAnchorB); + + /// Get the reaction force on body2 at the joint anchor in Newtons. + /// + /// @param inv_dt + /// @return + Vector2 getReactionForce(double inv_dt); + + /// get the reaction torque on body2 in N*m. + /// + /// @param inv_dt + /// @return double getReactionTorque(double inv_dt); - /** - * get the next joint the world joint list. - */ + /// get the next joint the world joint list. Joint getNext() { return _next; } - /** - * Get collide connected. Note: modifying the collide connect flag won't work correctly because - * the flag is only checked when fixture AABBs begin to overlap. - */ + /// Get collide connected. Note: modifying the collide connect flag won't work correctly because + /// the flag is only checked when fixture AABBs begin to overlap. bool getCollideConnected() { return _collideConnected; } - /** - * Short-cut function to determine if either body is inactive. - * - * @return - */ + /// Short-cut function to determine if either body is inactive. + /// + /// @return bool isActive() { return _bodyA.isActive() && _bodyB.isActive(); } - /** Internal */ + /// Internal void initVelocityConstraints(SolverData data); - /** Internal */ + /// Internal void solveVelocityConstraints(SolverData data); - /** - * This returns true if the position errors are within tolerance. Internal. - */ + /// This returns true if the position errors are within tolerance. Internal. bool solvePositionConstraints(SolverData data); - /** - * Override to handle destruction of joint - */ + /// Override to handle destruction of joint void destructor() {} } diff --git a/lib/src/dynamics/joints/joint_def.dart b/lib/src/dynamics/joints/joint_def.dart index d478438..a84d73b 100644 --- a/lib/src/dynamics/joints/joint_def.dart +++ b/lib/src/dynamics/joints/joint_def.dart @@ -1,60 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Joint definitions are used to construct joints. - * @author Daniel Murphy - */ +/// Joint definitions are used to construct joints. class JointDef { + /// The local anchor point relative to body1's origin. + final Vector2 localAnchorA = Vector2.zero(); + + /// The local anchor point relative to body2's origin. + final Vector2 localAnchorB = Vector2.zero(); + JointDef(JointType type) { this.type = type; collideConnected = false; } - /** - * The joint type is set automatically for concrete joint types. - */ + + /// The joint type is set automatically for concrete joint types. JointType type; - /** - * Use this to attach application specific data to your joints. - */ + /// Use this to attach application specific data to your joints. Object userData; - /** - * The first attached body. - */ + /// The first attached body. Body bodyA; - /** - * The second attached body. - */ + /// The second attached body. Body bodyB; - /** - * Set this flag to true if the attached bodies should collide. - */ + /// Set this flag to true if the attached bodies should collide. bool collideConnected = false; } diff --git a/lib/src/dynamics/joints/joint_edge.dart b/lib/src/dynamics/joints/joint_edge.dart index 5fa95f5..58df2c7 100644 --- a/lib/src/dynamics/joints/joint_edge.dart +++ b/lib/src/dynamics/joints/joint_edge.dart @@ -1,55 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A joint edge is used to connect bodies and joints together - * in a joint graph where each body is a node and each joint - * is an edge. A joint edge belongs to a doubly linked list - * maintained in each attached body. Each joint has two joint - * nodes, one for each attached body. - * @author Daniel - */ +/// A joint edge is used to connect bodies and joints together +/// in a joint graph where each body is a node and each joint +/// is an edge. A joint edge belongs to a doubly linked list +/// maintained in each attached body. Each joint has two joint +/// nodes, one for each attached body. class JointEdge { - /** - * Provides quick access to the other body attached - */ + /// Provides quick access to the other body attached Body other = null; - /** - * the joint - */ + /// the joint Joint joint = null; - /** - * the previous joint edge in the body's joint list - */ + /// the previous joint edge in the body's joint list JointEdge prev = null; - /** - * the next joint edge in the body's joint list - */ + /// the next joint edge in the body's joint list JointEdge next = null; } diff --git a/lib/src/dynamics/joints/joint_type.dart b/lib/src/dynamics/joints/joint_type.dart index dd5a8dd..6dd459e 100644 --- a/lib/src/dynamics/joints/joint_type.dart +++ b/lib/src/dynamics/joints/joint_type.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; enum JointType { diff --git a/lib/src/dynamics/joints/limit_state.dart b/lib/src/dynamics/joints/limit_state.dart index 4b208c5..72a63ed 100644 --- a/lib/src/dynamics/joints/limit_state.dart +++ b/lib/src/dynamics/joints/limit_state.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; enum LimitState { INACTIVE, AT_LOWER, AT_UPPER, EQUAL } diff --git a/lib/src/dynamics/joints/motor_joint.dart b/lib/src/dynamics/joints/motor_joint.dart index 740bad9..6b6aad3 100644 --- a/lib/src/dynamics/joints/motor_joint.dart +++ b/lib/src/dynamics/joints/motor_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Point-to-point constraint @@ -36,17 +12,13 @@ part of box2d; //J = [0 0 -1 0 0 1] //K = invI1 + invI2 -/** - * A motor joint is used to control the relative motion between two bodies. A typical usage is to - * control the movement of a dynamic body with respect to the ground. - * - * @author dmurph - */ +/// A motor joint is used to control the relative motion between two bodies. A typical usage is to +/// control the movement of a dynamic body with respect to the ground. class MotorJoint extends Joint { // Solver shared - final Vector2 _linearOffset = new Vector2.zero(); + final Vector2 _linearOffset = Vector2.zero(); double _angularOffset = 0.0; - final Vector2 _linearImpulse = new Vector2.zero(); + final Vector2 _linearImpulse = Vector2.zero(); double _angularImpulse = 0.0; double _maxForce = 0.0; double _maxTorque = 0.0; @@ -55,20 +27,20 @@ class MotorJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); - final Vector2 _linearError = new Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); + final Vector2 _linearError = Vector2.zero(); double _angularError = 0.0; double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; - final Matrix2 _linearMass = new Matrix2.zero(); + final Matrix2 _linearMass = Matrix2.zero(); double _angularMass = 0.0; - MotorJoint(IWorldPool pool, MotorJointDef def) : super(pool, def) { + MotorJoint(MotorJointDef def) : super(def) { _linearOffset.setFrom(def.linearOffset); _angularOffset = def.angularOffset; @@ -79,27 +51,26 @@ class MotorJoint extends Joint { _correctionFactor = def.correctionFactor; } - void getAnchorA(Vector2 out) { - out.setFrom(_bodyA.position); + @override + Vector2 getAnchorA() { + return Vector2.copy(_bodyA.position); } - void getAnchorB(Vector2 out) { - out.setFrom(_bodyB.position); + @override + Vector2 getAnchorB() { + return Vector2.copy(_bodyB.position); } - void getReactionForce(double inv_dt, Vector2 out) { - out - ..setFrom(_linearImpulse) - ..scale(inv_dt); + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2.copy(_linearImpulse)..scale(inv_dt); } double getReactionTorque(double inv_dt) { return _angularImpulse * inv_dt; } - /** - * Set the target linear offset, in frame A, in meters. - */ + /// Set the target linear offset, in frame A, in meters. void setLinearOffset(Vector2 linearOffset) { if (linearOffset.x != _linearOffset.x || linearOffset.y != _linearOffset.y) { @@ -109,25 +80,19 @@ class MotorJoint extends Joint { } } - /** - * Get the target linear offset, in frame A, in meters. - */ + /// Get the target linear offset, in frame A, in meters. void getLinearOffsetOut(Vector2 out) { out.setFrom(_linearOffset); } - /** - * Get the target linear offset, in frame A, in meters. Do not modify. - */ + /// Get the target linear offset, in frame A, in meters. Do not modify. Vector2 getLinearOffset() { return _linearOffset; } - /** - * Set the target angular offset, in radians. - * - * @param angularOffset - */ + /// Set the target angular offset, in radians. + /// + /// @param angularOffset void setAngularOffset(double angularOffset) { if (angularOffset != _angularOffset) { _bodyA.setAwake(true); @@ -140,34 +105,26 @@ class MotorJoint extends Joint { return _angularOffset; } - /** - * Set the maximum friction force in N. - * - * @param force - */ + /// Set the maximum friction force in N. + /// + /// @param force void setMaxForce(double force) { assert(force >= 0.0); _maxForce = force; } - /** - * Get the maximum friction force in N. - */ + /// Get the maximum friction force in N. double getMaxForce() { return _maxForce; } - /** - * Set the maximum friction torque in N*m. - */ + /// Set the maximum friction torque in N*m. void setMaxTorque(double torque) { assert(torque >= 0.0); _maxTorque = torque; } - /** - * Get the maximum friction torque in N*m. - */ + /// Get the maximum friction torque in N*m. double getMaxTorque() { return _maxTorque; } @@ -192,10 +149,10 @@ class MotorJoint extends Joint { final Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); - Matrix2 K = pool.popMat22(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); + Matrix2 K = Matrix2.zero(); qA.setAngle(aA); qB.setAngle(aB); @@ -233,8 +190,7 @@ class MotorJoint extends Joint { _angularMass = 1.0 / _angularMass; } - // _linearError = cB + _rB - cA - _rA - b2Mul(qA, _linearOffset); - Rot.mulToOutUnsafe(qA, _linearOffset, temp); + temp.setFrom(Rot.mulVec2(qA, _linearOffset)); _linearError.x = cB.x + _rB.x - cA.x - _rA.x - temp.x; _linearError.y = cB.y + _rB.y - cA.y - _rA.y - temp.y; _angularError = aB - aA - _angularOffset; @@ -257,13 +213,7 @@ class MotorJoint extends Joint { _angularImpulse = 0.0; } - pool.pushVec2(1); - pool.pushMat22(1); - pool.pushRot(2); - - // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; - // data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } @@ -279,7 +229,7 @@ class MotorJoint extends Joint { double h = data.step.dt; double inv_h = data.step.inv_dt; - final Vector2 temp = pool.popVec2(); + final Vector2 temp = Vector2.zero(); // Solve angular friction { @@ -296,7 +246,7 @@ class MotorJoint extends Joint { wB += iB * impulse; } - final Vector2 Cdot = pool.popVec2(); + final Vector2 Cdot = Vector2.zero(); // Solve linear friction { @@ -316,7 +266,7 @@ class MotorJoint extends Joint { final Vector2 impulse = temp; _linearMass.transformed(Cdot, impulse); impulse.negate(); - final Vector2 oldImpulse = pool.popVec2(); + final Vector2 oldImpulse = Vector2.zero(); oldImpulse.setFrom(_linearImpulse); _linearImpulse.add(impulse); @@ -339,8 +289,6 @@ class MotorJoint extends Joint { wB += iB * (_rB.x * impulse.y - _rB.y * impulse.x); } - pool.pushVec2(3); - // data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); diff --git a/lib/src/dynamics/joints/motor_joint_def.dart b/lib/src/dynamics/joints/motor_joint_def.dart index 432c839..6de9ce6 100644 --- a/lib/src/dynamics/joints/motor_joint_def.dart +++ b/lib/src/dynamics/joints/motor_joint_def.dart @@ -1,58 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Motor joint definition. - * - * @author dmurph - */ +/// Motor joint definition. class MotorJointDef extends JointDef { - /** - * Position of bodyB minus the position of bodyA, in bodyA's frame, in meters. - */ - final Vector2 linearOffset = new Vector2.zero(); + /// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters. + final Vector2 linearOffset = Vector2.zero(); - /** - * The bodyB angle minus bodyA angle in radians. - */ + /// The bodyB angle minus bodyA angle in radians. double angularOffset = 0.0; - /** - * The maximum motor force in N. - */ + /// The maximum motor force in N. double maxForce = 1.0; - /** - * The maximum motor torque in N-m. - */ + /// The maximum motor torque in N-m. double maxTorque = 1.0; - /** - * Position correction factor in the range [0,1]. - */ + /// Position correction factor in the range [0,1]. double correctionFactor = 0.3; MotorJointDef() : super(JointType.MOTOR); @@ -61,7 +23,7 @@ class MotorJointDef extends JointDef { bodyA = bA; bodyB = bB; Vector2 xB = bodyB.position; - bodyA.getLocalPointToOut(xB, linearOffset); + linearOffset.setFrom(bodyA.getLocalPoint(xB)); double angleA = bodyA.getAngle(); double angleB = bodyB.getAngle(); diff --git a/lib/src/dynamics/joints/mouse_joint.dart b/lib/src/dynamics/joints/mouse_joint.dart index a45a188..3442370 100644 --- a/lib/src/dynamics/joints/mouse_joint.dart +++ b/lib/src/dynamics/joints/mouse_joint.dart @@ -1,67 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A mouse joint is used to make a point on a body track a specified world point. This a soft - * constraint with a maximum force. This allows the constraint to stretch and without applying huge - * forces. NOTE: this joint is not documented in the manual because it was developed to be used in - * the testbed. If you want to learn how to use the mouse joint, look at the testbed. - * - * @author Daniel - */ +/// A mouse joint is used to make a point on a body track a specified world point. This a soft +/// constraint with a maximum force. This allows the constraint to stretch and without applying huge +/// forces. NOTE: this joint is not documented in the manual because it was developed to be used in +/// the testbed. If you want to learn how to use the mouse joint, look at the testbed. class MouseJoint extends Joint { - final Vector2 _localAnchorB = new Vector2.zero(); - final Vector2 _targetA = new Vector2.zero(); + final Vector2 _targetA = Vector2.zero(); double _frequencyHz = 0.0; double _dampingRatio = 0.0; double _beta = 0.0; // Solver shared - final Vector2 _impulse = new Vector2.zero(); + final Vector2 _impulse = Vector2.zero(); double _maxForce = 0.0; double _gamma = 0.0; // Solver temp int _indexB = 0; - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassB = 0.0; double _invIB = 0.0; - final Matrix2 _mass = new Matrix2.zero(); - final Vector2 _C = new Vector2.zero(); + final Matrix2 _mass = Matrix2.zero(); + final Vector2 _C = Vector2.zero(); - MouseJoint(IWorldPool argWorld, MouseJointDef def) : super(argWorld, def) { + MouseJoint(MouseJointDef def) : super(def) { assert(MathUtils.vector2IsValid(def.target)); assert(def.maxForce >= 0); assert(def.frequencyHz >= 0); assert(def.dampingRatio >= 0); _targetA.setFrom(def.target); - Transform.mulTransToOutUnsafeVec2( - _bodyB._transform, _targetA, _localAnchorB); + localAnchorB.setFrom(Transform.mulTransVec2(_bodyB._transform, _targetA)); _maxForce = def.maxForce; _impulse.setZero(); @@ -70,18 +40,13 @@ class MouseJoint extends Joint { _dampingRatio = def.dampingRatio; } - void getAnchorA(Vector2 argOut) { - argOut.setFrom(_targetA); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); + @override + Vector2 getAnchorA() { + return Vector2.copy(_targetA); } - void getReactionForce(double invDt, Vector2 argOut) { - argOut - ..setFrom(_impulse) - ..scale(invDt); + Vector2 getReactionForce(double invDt) { + return Vector2.copy(_impulse)..scale(invDt); } double getReactionTorque(double invDt) { @@ -110,14 +75,14 @@ class MouseJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qB = pool.popRot(); + final Rot qB = Rot(); qB.setAngle(aB); double mass = _bodyB.mass; // Frequency - double omega = 2.0 * Math.PI * _frequencyHz; + double omega = 2.0 * Math.pi * _frequencyHz; // Damping coefficient double d = 2.0 * mass * _dampingRatio * omega; @@ -136,20 +101,18 @@ class MouseJoint extends Joint { } _beta = h * k * _gamma; - Vector2 temp = pool.popVec2(); + Vector2 temp = Vector2.zero(); // Compute the effective mass matrix. - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, temp)); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - final Matrix2 K = pool.popMat22(); + final Matrix2 K = Matrix2.zero(); double a11 = _invMassB + _invIB * _rB.y * _rB.y + _gamma; double a21 = -_invIB * _rB.x * _rB.y; double a12 = a21; @@ -177,12 +140,7 @@ class MouseJoint extends Joint { _impulse.setZero(); } -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(1); - pool.pushMat22(1); - pool.pushRot(1); } bool solvePositionConstraints(final SolverData data) { @@ -194,12 +152,12 @@ class MouseJoint extends Joint { double wB = data.velocities[_indexB].w; // Cdot = v + cross(w, r) - final Vector2 Cdot = pool.popVec2(); + final Vector2 Cdot = Vector2.zero(); _rB.scaleOrthogonalInto(wB, Cdot); Cdot.add(vB); - final Vector2 impulse = pool.popVec2(); - final Vector2 temp = pool.popVec2(); + final Vector2 impulse = Vector2.zero(); + final Vector2 temp = Vector2.zero(); temp ..setFrom(_impulse) @@ -224,9 +182,6 @@ class MouseJoint extends Joint { vB.y += _invMassB * impulse.y; wB += _invIB * _rB.cross(impulse); -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(3); } } diff --git a/lib/src/dynamics/joints/mouse_joint_def.dart b/lib/src/dynamics/joints/mouse_joint_def.dart index 08c12cb..4ac2c67 100644 --- a/lib/src/dynamics/joints/mouse_joint_def.dart +++ b/lib/src/dynamics/joints/mouse_joint_def.dart @@ -1,54 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. - * - * @author Daniel - */ +/// Mouse joint definition. This requires a world target point, tuning parameters, and the time step. class MouseJointDef extends JointDef { - /** - * The initial world target point. This is assumed to coincide with the body anchor initially. - */ - final Vector2 target = new Vector2.zero(); + /// The initial world target point. This is assumed to coincide with the body anchor initially. + final Vector2 target = Vector2.zero(); - /** - * The maximum constraint force that can be exerted to move the candidate body. Usually you will - * express as some multiple of the weight (multiplier * mass * gravity). - */ + /// The maximum constraint force that can be exerted to move the candidate body. Usually you will + /// express as some multiple of the weight (multiplier * mass * gravity). double maxForce = 0.0; - /** - * The response speed. - */ + /// The response speed. double frequencyHz = 5.0; - /** - * The damping ratio. 0 = no damping, 1 = critical damping. - */ + /// The damping ratio. 0 = no damping, 1 = critical damping. double dampingRatio = .7; MouseJointDef() : super(JointType.MOUSE); diff --git a/lib/src/dynamics/joints/prismatic_joint.dart b/lib/src/dynamics/joints/prismatic_joint.dart index ff5511d..a28af6f 100644 --- a/lib/src/dynamics/joints/prismatic_joint.dart +++ b/lib/src/dynamics/joints/prismatic_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Linear constraint (point-to-line) @@ -90,23 +66,19 @@ part of box2d; //Now compute impulse to be applied: //df = f2 - f1 -/** - * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in - * bodyA. Relative rotation is prevented. You can use a joint limit to restrict the range of motion - * and a joint motor to drive the motion or to model joint friction. - * - * @author Daniel - */ +/// A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in +/// bodyA. Relative rotation is prevented. You can use a joint limit to restrict the range of motion +/// and a joint motor to drive the motion or to model joint friction. class PrismaticJoint extends Joint { // Solver shared - final Vector2 _localAnchorA; - final Vector2 _localAnchorB; + final Vector2 localAnchorA; + final Vector2 localAnchorB; final Vector2 _localXAxisA; final Vector2 _localYAxisA; double _referenceAngle; // TODO(srdjan): Make fields below private. - final Vector3 _impulse = new Vector3.zero(); + final Vector3 _impulse = Vector3.zero(); double _motorImpulse = 0.0; double _lowerTranslation = 0.0; double _upperTranslation = 0.0; @@ -119,26 +91,26 @@ class PrismaticJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; - final Vector2 _axis = new Vector2.zero(); - final Vector2 _perp = new Vector2.zero(); + final Vector2 _axis = Vector2.zero(); + final Vector2 _perp = Vector2.zero(); double _s1 = 0.0, _s2 = 0.0; double _a1 = 0.0, _a2 = 0.0; - final Matrix3 _K = new Matrix3.zero(); + final Matrix3 _K = Matrix3.zero(); double _motorMass = 0.0; // effective mass for motor/limit translational constraint. - PrismaticJoint(IWorldPool argWorld, PrismaticJointDef def) - : _localAnchorA = new Vector2.copy(def.localAnchorA), - _localAnchorB = new Vector2.copy(def.localAnchorB), - _localXAxisA = new Vector2.copy(def.localAxisA)..normalize(), - _localYAxisA = new Vector2.zero(), - super(argWorld, def) { + PrismaticJoint(PrismaticJointDef def) + : localAnchorA = Vector2.copy(def.localAnchorA), + localAnchorB = Vector2.copy(def.localAnchorB), + _localXAxisA = Vector2.copy(def.localAxisA)..normalize(), + _localYAxisA = Vector2.zero(), + super(def) { _localXAxisA.scaleOrthogonalInto(1.0, _localYAxisA); _referenceAngle = def.referenceAngle; @@ -151,65 +123,47 @@ class PrismaticJoint extends Joint { _limitState = LimitState.INACTIVE; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - Vector2 temp = pool.popVec2(); + @override + Vector2 getReactionForce(double inv_dt) { + Vector2 temp = Vector2.zero(); temp ..setFrom(_axis) ..scale(_motorImpulse + _impulse.z); - argOut - ..setFrom(_perp) + Vector2 out = Vector2.copy(_perp) ..scale(_impulse.x) ..add(temp) ..scale(inv_dt); - pool.pushVec2(1); + return out; } double getReactionTorque(double inv_dt) { return inv_dt * _impulse.y; } - /** - * Get the current joint translation, usually in meters. - */ + /// Get the current joint translation, usually in meters. double getJointSpeed() { Body bA = _bodyA; Body bB = _bodyB; - Vector2 temp = pool.popVec2(); - Vector2 rA = pool.popVec2(); - Vector2 rB = pool.popVec2(); - Vector2 p1 = pool.popVec2(); - Vector2 p2 = pool.popVec2(); - Vector2 d = pool.popVec2(); - Vector2 axis = pool.popVec2(); - Vector2 temp2 = pool.popVec2(); - Vector2 temp3 = pool.popVec2(); + Vector2 temp = Vector2.zero(); + Vector2 rA = Vector2.zero(); + Vector2 rB = Vector2.zero(); + Vector2 p1 = Vector2.zero(); + Vector2 p2 = Vector2.zero(); + Vector2 d = Vector2.zero(); + Vector2 axis = Vector2.zero(); + Vector2 temp2 = Vector2.zero(); + Vector2 temp3 = Vector2.zero(); temp - ..setFrom(_localAnchorA) + ..setFrom(localAnchorA) ..sub(bA._sweep.localCenter); - Rot.mulToOutUnsafe(bA._transform.q, temp, rA); + rA.setFrom(Rot.mulVec2(bA._transform.q, temp)); temp - ..setFrom(_localAnchorB) + ..setFrom(localAnchorB) ..sub(bB._sweep.localCenter); - Rot.mulToOutUnsafe(bB._transform.q, temp, rB); + rB.setFrom(Rot.mulVec2(bB._transform.q, temp)); p1 ..setFrom(bA._sweep.c) @@ -221,7 +175,7 @@ class PrismaticJoint extends Joint { d ..setFrom(p2) ..sub(p1); - Rot.mulToOutUnsafe(bA._transform.q, _localXAxisA, axis); + axis.setFrom(Rot.mulVec2(bA._transform.q, _localXAxisA)); Vector2 vA = bA._linearVelocity; Vector2 vB = bB._linearVelocity; @@ -238,36 +192,29 @@ class PrismaticJoint extends Joint { ..sub(temp3); double speed = d.dot(temp) + axis.dot(temp2); - pool.pushVec2(9); - return speed; } double getJointTranslation() { - Vector2 pA = pool.popVec2(), pB = pool.popVec2(), axis = pool.popVec2(); - _bodyA.getWorldPointToOut(_localAnchorA, pA); - _bodyB.getWorldPointToOut(_localAnchorB, pB); - _bodyA.getWorldVectorToOutUnsafe(_localXAxisA, axis); + Vector2 pA = Vector2.zero(), pB = Vector2.zero(), axis = Vector2.zero(); + pA.setFrom(_bodyA.getWorldPoint(localAnchorA)); + pB.setFrom(_bodyB.getWorldPoint(localAnchorB)); + axis.setFrom(_bodyA.getWorldVector(_localXAxisA)); pB.sub(pA); double translation = pB.dot(axis); - pool.pushVec2(3); return translation; } - /** - * Is the joint limit enabled? - * - * @return - */ + /// Is the joint limit enabled? + /// + /// @return bool isLimitEnabled() { return _enableLimit; } - /** - * Enable/disable the joint limit. - * - * @param flag - */ + /// Enable/disable the joint limit. + /// + /// @param flag void enableLimit(bool flag) { if (flag != _enableLimit) { _bodyA.setAwake(true); @@ -277,30 +224,24 @@ class PrismaticJoint extends Joint { } } - /** - * Get the lower joint limit, usually in meters. - * - * @return - */ + /// Get the lower joint limit, usually in meters. + /// + /// @return double getLowerLimit() { return _lowerTranslation; } - /** - * Get the upper joint limit, usually in meters. - * - * @return - */ + /// Get the upper joint limit, usually in meters. + /// + /// @return double getUpperLimit() { return _upperTranslation; } - /** - * Set the joint limits, usually in meters. - * - * @param lower - * @param upper - */ + /// Set the joint limits, usually in meters. + /// + /// @param lower + /// @param upper void setLimits(double lower, double upper) { assert(lower <= upper); if (lower != _lowerTranslation || upper != _upperTranslation) { @@ -312,63 +253,51 @@ class PrismaticJoint extends Joint { } } - /** - * Is the joint motor enabled? - * - * @return - */ + /// Is the joint motor enabled? + /// + /// @return bool isMotorEnabled() { return _enableMotor; } - /** - * Enable/disable the joint motor. - * - * @param flag - */ + /// Enable/disable the joint motor. + /// + /// @param flag void enableMotor(bool flag) { _bodyA.setAwake(true); _bodyB.setAwake(true); _enableMotor = flag; } - /** - * Set the motor speed, usually in meters per second. - * - * @param speed - */ + /// Set the motor speed, usually in meters per second. + /// + /// @param speed void setMotorSpeed(double speed) { _bodyA.setAwake(true); _bodyB.setAwake(true); _motorSpeed = speed; } - /** - * Get the motor speed, usually in meters per second. - * - * @return - */ + /// Get the motor speed, usually in meters per second. + /// + /// @return double getMotorSpeed() { return _motorSpeed; } - /** - * Set the maximum motor force, usually in N. - * - * @param force - */ + /// Set the maximum motor force, usually in N. + /// + /// @param force void setMaxMotorForce(double force) { _bodyA.setAwake(true); _bodyB.setAwake(true); _maxMotorForce = force; } - /** - * Get the current motor force, usually in N. - * - * @param inv_dt - * @return - */ + /// Get the current motor force, usually in N. + /// + /// @param inv_dt + /// @return double getMotorForce(double inv_dt) { return _motorImpulse * inv_dt; } @@ -405,29 +334,25 @@ class PrismaticJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 d = pool.popVec2(); - final Vector2 temp = pool.popVec2(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 d = Vector2.zero(); + final Vector2 temp = Vector2.zero(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - d - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - d - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + d + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, d)); + d + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, d)); d ..setFrom(cB) ..sub(cA) @@ -439,7 +364,7 @@ class PrismaticJoint extends Joint { // Compute motor Jacobian and effective mass. { - Rot.mulToOutUnsafe(qA, _localXAxisA, _axis); + _axis.setFrom(Rot.mulVec2(qA, _localXAxisA)); temp ..setFrom(d) ..add(rA); @@ -454,7 +379,7 @@ class PrismaticJoint extends Joint { // Prismatic constraint. { - Rot.mulToOutUnsafe(qA, _localYAxisA, _perp); + _perp.setFrom(Rot.mulVec2(qA, _localYAxisA)); temp ..setFrom(d) @@ -510,7 +435,7 @@ class PrismaticJoint extends Joint { _impulse.scale(data.step.dtRatio); _motorImpulse *= data.step.dtRatio; - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); temp ..setFrom(_axis) ..scale(_motorImpulse + _impulse.z); @@ -531,8 +456,6 @@ class PrismaticJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * LB; - - pool.pushVec2(1); } else { _impulse.setZero(); _motorImpulse = 0.0; @@ -542,9 +465,6 @@ class PrismaticJoint extends Joint { data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushRot(2); - pool.pushVec2(4); } void solveVelocityConstraints(final SolverData data) { @@ -556,7 +476,7 @@ class PrismaticJoint extends Joint { double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - final Vector2 temp = pool.popVec2(); + final Vector2 temp = Vector2.zero(); // Solve linear motor constraint. if (_enableMotor && _limitState != LimitState.EQUAL) { @@ -571,7 +491,7 @@ class PrismaticJoint extends Joint { _motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); P ..setFrom(_axis) ..scale(impulse); @@ -585,17 +505,14 @@ class PrismaticJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * LB; - - pool.pushVec2(1); } - final Vector2 Cdot1 = pool.popVec2(); + final Vector2 Cdot1 = Vector2.zero(); temp ..setFrom(vB) ..sub(vA); Cdot1.x = _perp.dot(temp) + _s2 * wB - _s1 * wA; Cdot1.y = wB - wA; - // System.out.println(Cdot1); if (_enableLimit && _limitState != LimitState.INACTIVE) { // Solve prismatic and limit constraint in block form. @@ -605,11 +522,11 @@ class PrismaticJoint extends Joint { ..sub(vA); Cdot2 = _axis.dot(temp) + _a2 * wB - _a1 * wA; - final Vector3 Cdot = pool.popVec3(); + final Vector3 Cdot = Vector3.zero(); Cdot.setValues(Cdot1.x, Cdot1.y, Cdot2); - final Vector3 f1 = pool.popVec3(); - final Vector3 df = pool.popVec3(); + final Vector3 f1 = Vector3.zero(); + final Vector3 df = Vector3.zero(); f1.setFrom(_impulse); Matrix3.solve(_K, df, Cdot..negate()); @@ -625,8 +542,8 @@ class PrismaticJoint extends Joint { // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + // f1(1:2) - final Vector2 b = pool.popVec2(); - final Vector2 f2r = pool.popVec2(); + final Vector2 b = Vector2.zero(); + final Vector2 f2r = Vector2.zero(); temp ..setValues(_K.entry(0, 2), _K.entry(1, 2)) @@ -637,7 +554,7 @@ class PrismaticJoint extends Joint { ..sub(temp); Matrix3.solve2(_K, f2r, b); - f2r.add(new Vector2(f1.x, f1.y)); + f2r.add(Vector2(f1.x, f1.y)); _impulse.x = f2r.x; _impulse.y = f2r.y; @@ -645,7 +562,7 @@ class PrismaticJoint extends Joint { ..setFrom(_impulse) ..sub(f1); - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); temp ..setFrom(_axis) ..scale(df.z); @@ -664,19 +581,16 @@ class PrismaticJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * LB; - - pool.pushVec2(3); - pool.pushVec3(3); } else { // Limit is inactive, just solve the prismatic constraint in block form. - final Vector2 df = pool.popVec2(); + final Vector2 df = Vector2.zero(); Matrix3.solve2(_K, df, Cdot1..negate()); Cdot1.negate(); _impulse.x += df.x; _impulse.y += df.y; - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); P ..setFrom(_perp) ..scale(df.x); @@ -690,30 +604,26 @@ class PrismaticJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * LB; - - pool.pushVec2(2); } // data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(2); } bool solvePositionConstraints(final SolverData data) { - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); - final Vector2 d = pool.popVec2(); - final Vector2 axis = pool.popVec2(); - final Vector2 perp = pool.popVec2(); - final Vector2 temp = pool.popVec2(); - final Vector2 C1 = pool.popVec2(); - - final Vector3 impulse = pool.popVec3(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 d = Vector2.zero(); + final Vector2 axis = Vector2.zero(); + final Vector2 perp = Vector2.zero(); + final Vector2 temp = Vector2.zero(); + final Vector2 C1 = Vector2.zero(); + + final Vector3 impulse = Vector3.zero(); Vector2 cA = data.positions[_indexA].c; double aA = data.positions[_indexA].a; @@ -727,31 +637,27 @@ class PrismaticJoint extends Joint { double iA = _invIA, iB = _invIB; // Compute fresh Jacobians - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); d ..setFrom(cB) ..add(rB) ..sub(cA) ..sub(rA); - Rot.mulToOutUnsafe(qA, _localXAxisA, axis); + axis.setFrom(Rot.mulVec2(qA, _localXAxisA)); double a1 = (temp ..setFrom(d) ..add(rA)) .cross(axis); double a2 = rB.cross(axis); - Rot.mulToOutUnsafe(qA, _localYAxisA, perp); + perp.setFrom(Rot.mulVec2(qA, _localYAxisA)); double s1 = (temp ..setFrom(d) @@ -807,17 +713,15 @@ class PrismaticJoint extends Joint { double k23 = iA * a1 + iB * a2; double k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - final Matrix3 K = pool.popMat33(); + final Matrix3 K = Matrix3.zero(); K.setValues(k11, k12, k13, k12, k22, k23, k13, k23, k33); - final Vector3 C = pool.popVec3(); + final Vector3 C = Vector3.zero(); C.x = C1.x; C.y = C1.y; C.z = C2; Matrix3.solve(K, impulse, C..negate()); - pool.pushVec3(1); - pool.pushMat33(1); } else { double k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; double k12 = iA * s1 + iB * s2; @@ -826,7 +730,7 @@ class PrismaticJoint extends Joint { k22 = 1.0; } - final Matrix2 K = pool.popMat22(); + final Matrix2 K = Matrix2.zero(); K.setValues(k11, k12, k12, k22); // temp is impulse1 @@ -836,8 +740,6 @@ class PrismaticJoint extends Joint { impulse.x = temp.x; impulse.y = temp.y; impulse.z = 0.0; - - pool.pushMat22(1); } double Px = impulse.x * perp.x + impulse.z * axis.x; @@ -852,15 +754,9 @@ class PrismaticJoint extends Joint { cB.y += mB * Py; aB += iB * LB; - // data.positions[_indexA].c.set(cA); data.positions[_indexA].a = aA; - // data.positions[_indexB].c.set(cB); data.positions[_indexB].a = aB; - pool.pushVec2(7); - pool.pushVec3(1); - pool.pushRot(2); - return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; } diff --git a/lib/src/dynamics/joints/prismatic_joint_def.dart b/lib/src/dynamics/joints/prismatic_joint_def.dart index 8e64922..c604714 100644 --- a/lib/src/dynamics/joints/prismatic_joint_def.dart +++ b/lib/src/dynamics/joints/prismatic_joint_def.dart @@ -1,103 +1,47 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor - * point. The definition uses local anchor points and a local axis so that the initial configuration - * can violate the constraint slightly. The joint translation is zero when the local anchor points - * coincide in world space. Using local anchors and a local axis helps when saving and loading a - * game. - * - * @warning at least one body should by dynamic with a non-fixed rotation. - * @author Daniel - * - */ +/// Prismatic joint definition. This requires defining a line of motion using an axis and an anchor +/// point. The definition uses local anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero when the local anchor points +/// coincide in world space. Using local anchors and a local axis helps when saving and loading a +/// game. +/// +/// @warning at least one body should by dynamic with a non-fixed rotation. class PrismaticJointDef extends JointDef { - /** - * The local anchor point relative to body1's origin. - */ - final Vector2 localAnchorA = new Vector2.zero(); - - /** - * The local anchor point relative to body2's origin. - */ - final Vector2 localAnchorB = new Vector2.zero(); - - /** - * The local translation axis in body1. - */ - final Vector2 localAxisA = new Vector2(1.0, 0.0); + /// The local translation axis in body1. + final Vector2 localAxisA = Vector2(1.0, 0.0); - /** - * The constrained angle between the bodies: body2_angle - body1_angle. - */ + /// The constrained angle between the bodies: body2_angle - body1_angle. double referenceAngle = 0.0; - /** - * Enable/disable the joint limit. - */ + /// Enable/disable the joint limit. bool enableLimit = false; - /** - * The lower translation limit, usually in meters. - */ + /// The lower translation limit, usually in meters. double lowerTranslation = 0.0; - /** - * The upper translation limit, usually in meters. - */ + /// The upper translation limit, usually in meters. double upperTranslation = 0.0; - /** - * Enable/disable the joint motor. - */ + /// Enable/disable the joint motor. bool enableMotor = false; - /** - * The maximum motor torque, usually in N-m. - */ + /// The maximum motor torque, usually in N-m. double maxMotorForce = 0.0; - /** - * The desired motor speed in radians per second. - */ + /// The desired motor speed in radians per second. double motorSpeed = 0.0; PrismaticJointDef() : super(JointType.PRISMATIC); - /** - * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world - * axis. - */ + /// Initialize the bodies, anchors, axis, and reference angle using the world anchor and world + /// axis. void initialize(Body b1, Body b2, Vector2 anchor, Vector2 axis) { bodyA = b1; bodyB = b2; - bodyA.getLocalPointToOut(anchor, localAnchorA); - bodyB.getLocalPointToOut(anchor, localAnchorB); - bodyA.getLocalVectorToOut(axis, localAxisA); + localAnchorA.setFrom(bodyA.getLocalPoint(anchor)); + localAnchorB.setFrom(bodyB.getLocalPoint(anchor)); + localAxisA.setFrom(bodyA.getLocalVector(axis)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } } diff --git a/lib/src/dynamics/joints/pulley_joint.dart b/lib/src/dynamics/joints/pulley_joint.dart index 04089d6..6965dd9 100644 --- a/lib/src/dynamics/joints/pulley_joint.dart +++ b/lib/src/dynamics/joints/pulley_joint.dart @@ -1,49 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a - * ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by - * the ratio. Warning: the pulley joint can get a bit squirrelly by itself. They often work better - * when combined with prismatic joints. You should also cover the the anchor points with static - * shapes to prevent one side from going to zero length. - * - * @author Daniel Murphy - */ +/// The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a +/// ratio such that: length1 + ratio * length2 <= constant Yes, the force transmitted is scaled by +/// the ratio. Warning: the pulley joint can get a bit squirrelly by itself. They often work better +/// when combined with prismatic joints. You should also cover the the anchor points with static +/// shapes to prevent one side from going to zero length. class PulleyJoint extends Joint { static const double MIN_PULLEY_LENGTH = 2.0; - final Vector2 _groundAnchorA = new Vector2.zero(); - final Vector2 _groundAnchorB = new Vector2.zero(); + final Vector2 _groundAnchorA = Vector2.zero(); + final Vector2 _groundAnchorB = Vector2.zero(); double _lengthA = 0.0; double _lengthB = 0.0; // Solver shared - final Vector2 _localAnchorA = new Vector2.zero(); - final Vector2 _localAnchorB = new Vector2.zero(); double _constant = 0.0; double _ratio = 0.0; double _impulse = 0.0; @@ -51,24 +21,23 @@ class PulleyJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _uA = new Vector2.zero(); - final Vector2 _uB = new Vector2.zero(); - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _uA = Vector2.zero(); + final Vector2 _uB = Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; double _mass = 0.0; - PulleyJoint(IWorldPool argWorldPool, PulleyJointDef def) - : super(argWorldPool, def) { + PulleyJoint(PulleyJointDef def) : super(def) { _groundAnchorA.setFrom(def.groundAnchorA); _groundAnchorB.setFrom(def.groundAnchorB); - _localAnchorA.setFrom(def.localAnchorA); - _localAnchorB.setFrom(def.localAnchorB); + localAnchorA.setFrom(def.localAnchorA); + localAnchorB.setFrom(def.localAnchorB); assert(def.ratio != 0.0); _ratio = def.ratio; @@ -89,44 +58,24 @@ class PulleyJoint extends Joint { } double getCurrentLengthA() { - final Vector2 p = pool.popVec2(); - _bodyA.getWorldPointToOut(_localAnchorA, p); + final Vector2 p = Vector2.zero(); + p.setFrom(_bodyA.getWorldPoint(localAnchorA)); p.sub(_groundAnchorA); double length = p.length; - pool.pushVec2(1); return length; } double getCurrentLengthB() { - final Vector2 p = pool.popVec2(); - _bodyB.getWorldPointToOut(_localAnchorB, p); + final Vector2 p = Vector2.zero(); + p.setFrom(_bodyB.getWorldPoint(localAnchorB)); p.sub(_groundAnchorB); double length = p.length; - pool.pushVec2(1); return length; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut - ..setFrom(_uB) - ..scale(_impulse) - ..scale(inv_dt); + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2.copy(_uB)..scale(_impulse)..scale(inv_dt); } double getReactionTorque(double inv_dt) { @@ -141,26 +90,6 @@ class PulleyJoint extends Joint { return _groundAnchorB; } - double getLength1() { - final Vector2 p = pool.popVec2(); - _bodyA.getWorldPointToOut(_localAnchorA, p); - p.sub(_groundAnchorA); - - double len = p.length; - pool.pushVec2(1); - return len; - } - - double getLength2() { - final Vector2 p = pool.popVec2(); - _bodyB.getWorldPointToOut(_localAnchorB, p); - p.sub(_groundAnchorB); - - double len = p.length; - pool.pushVec2(1); - return len; - } - double getRatio() { return _ratio; } @@ -185,26 +114,22 @@ class PulleyJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - _rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, temp)); _uA ..setFrom(cA) @@ -248,8 +173,8 @@ class PulleyJoint extends Joint { _impulse *= data.step.dtRatio; // Warm starting. - final Vector2 PA = pool.popVec2(); - final Vector2 PB = pool.popVec2(); + final Vector2 PA = Vector2.zero(); + final Vector2 PB = Vector2.zero(); PA ..setFrom(_uA) @@ -264,18 +189,11 @@ class PulleyJoint extends Joint { vB.x += _invMassB * PB.x; vB.y += _invMassB * PB.y; wB += _invIB * _rB.cross(PB); - - pool.pushVec2(2); } else { _impulse = 0.0; } -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(1); - pool.pushRot(2); } void solveVelocityConstraints(final SolverData data) { @@ -284,10 +202,10 @@ class PulleyJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Vector2 vpA = pool.popVec2(); - final Vector2 vpB = pool.popVec2(); - final Vector2 PA = pool.popVec2(); - final Vector2 PB = pool.popVec2(); + final Vector2 vpA = Vector2.zero(); + final Vector2 vpB = Vector2.zero(); + final Vector2 PA = Vector2.zero(); + final Vector2 PB = Vector2.zero(); _rA.scaleOrthogonalInto(wA, vpA); vpA.add(vA); @@ -311,24 +229,20 @@ class PulleyJoint extends Joint { vB.y += _invMassB * PB.y; wB += _invIB * _rB.cross(PB); -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(4); } bool solvePositionConstraints(final SolverData data) { - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); - final Vector2 uA = pool.popVec2(); - final Vector2 uB = pool.popVec2(); - final Vector2 temp = pool.popVec2(); - final Vector2 PA = pool.popVec2(); - final Vector2 PB = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 uA = Vector2.zero(); + final Vector2 uB = Vector2.zero(); + final Vector2 temp = Vector2.zero(); + final Vector2 PA = Vector2.zero(); + final Vector2 PB = Vector2.zero(); Vector2 cA = data.positions[_indexA].c; double aA = data.positions[_indexA].a; @@ -337,19 +251,14 @@ class PulleyJoint extends Joint { qA.setAngle(aA); qB.setAngle(aB); - - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); uA ..setFrom(cA) @@ -407,14 +316,9 @@ class PulleyJoint extends Joint { cB.y += _invMassB * PB.y; aB += _invIB * rB.cross(PB); -// data.positions[_indexA].c.set(cA); data.positions[_indexA].a = aA; -// data.positions[_indexB].c.set(cB); data.positions[_indexB].a = aB; - pool.pushRot(2); - pool.pushVec2(7); - return linearError < Settings.linearSlop; } } diff --git a/lib/src/dynamics/joints/pulley_joint_def.dart b/lib/src/dynamics/joints/pulley_joint_def.dart index 1249066..1fe8e6f 100644 --- a/lib/src/dynamics/joints/pulley_joint_def.dart +++ b/lib/src/dynamics/joints/pulley_joint_def.dart @@ -1,86 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, and a - * pulley ratio. - * - * @author Daniel Murphy - */ +/// Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, and a +/// pulley ratio. class PulleyJointDef extends JointDef { - /** - * The first ground anchor in world coordinates. This point never moves. - */ - Vector2 groundAnchorA = new Vector2(-1.0, 1.0); - - /** - * The second ground anchor in world coordinates. This point never moves. - */ - Vector2 groundAnchorB = new Vector2(1.0, 1.0); - - /** - * The local anchor point relative to bodyA's origin. - */ - Vector2 localAnchorA = new Vector2(-1.0, 0.0); + /// The first ground anchor in world coordinates. This point never moves. + Vector2 groundAnchorA = Vector2(-1.0, 1.0); - /** - * The local anchor point relative to bodyB's origin. - */ - Vector2 localAnchorB = new Vector2(1.0, 0.0); + /// The second ground anchor in world coordinates. This point never moves. + Vector2 groundAnchorB = Vector2(1.0, 1.0); - /** - * The a reference length for the segment attached to bodyA. - */ + /// The a reference length for the segment attached to bodyA. double lengthA = 0.0; - /** - * The a reference length for the segment attached to bodyB. - */ + /// The a reference length for the segment attached to bodyB. double lengthB = 0.0; - /** - * The pulley ratio, used to simulate a block-and-tackle. - */ + /// The pulley ratio, used to simulate a block-and-tackle. double ratio = 1.0; PulleyJointDef() : super(JointType.PULLEY) { collideConnected = true; } - /** - * Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - */ + /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. void initialize(Body b1, Body b2, Vector2 ga1, Vector2 ga2, Vector2 anchor1, Vector2 anchor2, double r) { bodyA = b1; bodyB = b2; groundAnchorA = ga1; groundAnchorB = ga2; - localAnchorA = bodyA.getLocalPoint(anchor1); - localAnchorB = bodyB.getLocalPoint(anchor2); + localAnchorA.setFrom(bodyA.getLocalPoint(anchor1)); + localAnchorB.setFrom(bodyB.getLocalPoint(anchor2)); Vector2 d1 = anchor1 - ga1; lengthA = d1.length; Vector2 d2 = anchor2 - ga2; diff --git a/lib/src/dynamics/joints/revolute_joint.dart b/lib/src/dynamics/joints/revolute_joint.dart index 0d37d1c..b2d0d0c 100644 --- a/lib/src/dynamics/joints/revolute_joint.dart +++ b/lib/src/dynamics/joints/revolute_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Point-to-point constraint //C = p2 - p1 @@ -36,20 +12,16 @@ part of box2d; //J = [0 0 -1 0 0 1] //K = invI1 + invI2 -/** - * A revolute joint constrains two bodies to share a common point while they are free to rotate - * about the point. The relative rotation about the shared point is the joint angle. You can limit - * the relative rotation with a joint limit that specifies a lower and upper angle. You can use a - * motor to drive the relative rotation about the shared point. A maximum motor torque is provided - * so that infinite forces are not generated. - * - * @author Daniel Murphy - */ +/// A revolute joint constrains two bodies to share a common point while they are free to rotate +/// about the point. The relative rotation about the shared point is the joint angle. You can limit +/// the relative rotation with a joint limit that specifies a lower and upper angle. You can use a +/// motor to drive the relative rotation about the shared point. A maximum motor torque is provided +/// so that infinite forces are not generated. class RevoluteJoint extends Joint { // Solver shared - final Vector2 _localAnchorA = new Vector2.zero(); - final Vector2 _localAnchorB = new Vector2.zero(); - final Vector3 _impulse = new Vector3.zero(); + final Vector2 localAnchorA = Vector2.zero(); + final Vector2 localAnchorB = Vector2.zero(); + final Vector3 _impulse = Vector3.zero(); double _motorImpulse = 0.0; bool _enableMotor = false; @@ -64,23 +36,22 @@ class RevoluteJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; final Matrix3 _mass = - new Matrix3.zero(); // effective mass for point-to-point constraint. + Matrix3.zero(); // effective mass for point-to-point constraint. double _motorMass = 0.0; // effective mass for motor/limit angular constraint. LimitState _limitState = LimitState.INACTIVE; - RevoluteJoint(IWorldPool argWorld, RevoluteJointDef def) - : super(argWorld, def) { - _localAnchorA.setFrom(def.localAnchorA); - _localAnchorB.setFrom(def.localAnchorB); + RevoluteJoint(RevoluteJointDef def) : super(def) { + localAnchorA.setFrom(def.localAnchorA); + localAnchorB.setFrom(def.localAnchorB); _referenceAngle = def.referenceAngle; _lowerAngle = def.lowerAngle; @@ -110,35 +81,22 @@ class RevoluteJoint extends Joint { double aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - _rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, temp)); double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; @@ -189,7 +147,7 @@ class RevoluteJoint extends Joint { } if (data.step.warmStarting) { - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); // Scale impulses to support a variable time step. _impulse.x *= data.step.dtRatio; _impulse.y *= data.step.dtRatio; @@ -205,7 +163,6 @@ class RevoluteJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * (_rB.cross(P) + _motorImpulse + _impulse.z); - pool.pushVec2(1); } else { _impulse.setZero(); _motorImpulse = 0.0; @@ -214,9 +171,6 @@ class RevoluteJoint extends Joint { data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(1); - pool.pushRot(2); } void solveVelocityConstraints(final SolverData data) { @@ -245,14 +199,14 @@ class RevoluteJoint extends Joint { wA -= iA * impulse; wB += iB * impulse; } - final Vector2 temp = pool.popVec2(); + final Vector2 temp = Vector2.zero(); // Solve limit constraint. if (_enableLimit && _limitState != LimitState.INACTIVE && fixedRotation == false) { - final Vector2 Cdot1 = pool.popVec2(); - final Vector3 Cdot = pool.popVec3(); + final Vector2 Cdot1 = Vector2.zero(); + final Vector3 Cdot = Vector3.zero(); // Solve point-to-point constraint _rA.scaleOrthogonalInto(wA, temp); @@ -264,7 +218,7 @@ class RevoluteJoint extends Joint { double Cdot2 = wB - wA; Cdot.setValues(Cdot1.x, Cdot1.y, Cdot2); - Vector3 impulse = pool.popVec3(); + Vector3 impulse = Vector3.zero(); Matrix3.solve(_mass, impulse, Cdot); impulse.negate(); @@ -273,7 +227,7 @@ class RevoluteJoint extends Joint { } else if (_limitState == LimitState.AT_LOWER) { double newImpulse = _impulse.z + impulse.z; if (newImpulse < 0.0) { - final Vector2 rhs = pool.popVec2(); + final Vector2 rhs = Vector2.zero(); rhs ..setValues(_mass.entry(0, 2), _mass.entry(1, 2)) ..scale(_impulse.z) @@ -285,14 +239,13 @@ class RevoluteJoint extends Joint { _impulse.x += temp.x; _impulse.y += temp.y; _impulse.z = 0.0; - pool.pushVec2(1); } else { _impulse.add(impulse); } } else if (_limitState == LimitState.AT_UPPER) { double newImpulse = _impulse.z + impulse.z; if (newImpulse > 0.0) { - final Vector2 rhs = pool.popVec2(); + final Vector2 rhs = Vector2.zero(); rhs ..setValues(_mass.entry(0, 2), _mass.entry(1, 2)) ..scale(_impulse.z) @@ -304,12 +257,11 @@ class RevoluteJoint extends Joint { _impulse.x += temp.x; _impulse.y += temp.y; _impulse.z = 0.0; - pool.pushVec2(1); } else { _impulse.add(impulse); } } - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); P.setValues(impulse.x, impulse.y); @@ -320,13 +272,10 @@ class RevoluteJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * (_rB.cross(P) + impulse.z); - - pool.pushVec2(2); - pool.pushVec3(2); } else { // Solve point-to-point constraint - Vector2 Cdot = pool.popVec2(); - Vector2 impulse = pool.popVec2(); + Vector2 Cdot = Vector2.zero(); + Vector2 impulse = Vector2.zero(); _rA.scaleOrthogonalInto(wA, temp); _rB.scaleOrthogonalInto(wB, Cdot); @@ -346,21 +295,17 @@ class RevoluteJoint extends Joint { vB.x += mB * impulse.x; vB.y += mB * impulse.y; wB += iB * _rB.cross(impulse); - - pool.pushVec2(2); } // data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(1); } bool solvePositionConstraints(final SolverData data) { - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); + final Rot qA = Rot(); + final Rot qB = Rot(); Vector2 cA = data.positions[_indexA].c; double aA = data.positions[_indexA].a; Vector2 cB = data.positions[_indexB].c; @@ -413,41 +358,38 @@ class RevoluteJoint extends Joint { qA.setAngle(aA); qB.setAngle(aB); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); - final Vector2 C = pool.popVec2(); - final Vector2 impulse = pool.popVec2(); - - Rot.mulToOutUnsafe( - qA, - C - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - C - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); - C + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 temp = Vector2.zero(); + final Vector2 impulse = Vector2.zero(); + + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); + + temp ..setFrom(cB) ..add(rB) ..sub(cA) ..sub(rA); - positionError = C.length; + positionError = temp.length; double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - final Matrix2 K = pool.popMat22(); + final Matrix2 K = Matrix2.zero(); double a11 = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; double a21 = -iA * rA.x * rA.y - iB * rB.x * rB.y; double a12 = a21; double a22 = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; K.setValues(a11, a21, a12, a22); - Matrix2.solve(K, impulse, C); + Matrix2.solve(K, impulse, temp); impulse.negate(); cA.x -= mA * impulse.x; @@ -457,45 +399,21 @@ class RevoluteJoint extends Joint { cB.x += mB * impulse.x; cB.y += mB * impulse.y; aB += iB * rB.cross(impulse); - - pool.pushVec2(4); - pool.pushMat22(1); } - // data.positions[_indexA].c.set(cA); data.positions[_indexA].a = aA; - // data.positions[_indexB].c.set(cB); data.positions[_indexB].a = aB; - pool.pushRot(2); - return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - double getReferenceAngle() { return _referenceAngle; } - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut - ..setValues(_impulse.x, _impulse.y) - ..scale(inv_dt); + @override + Vector2 getReactionForce(double inv_dt) { + return Vector2(_impulse.x, _impulse.y)..scale(inv_dt); } double getReactionTorque(double inv_dt) { diff --git a/lib/src/dynamics/joints/revolute_joint_def.dart b/lib/src/dynamics/joints/revolute_joint_def.dart index 35b9922..9dc4cdd 100644 --- a/lib/src/dynamics/joints/revolute_joint_def.dart +++ b/lib/src/dynamics/joints/revolute_joint_def.dart @@ -1,100 +1,48 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Revolute joint definition. This requires defining an anchor point where the bodies are joined. - * The definition uses local anchor points so that the initial configuration can violate the - * constraint slightly. You also need to specify the initial relative angle for joint limits. This - * helps when saving and loading a game. The local anchor points are measured from the body's origin - * rather than the center of mass because:
- *
    - *
  • you might not know where the center of mass will be.
  • - *
  • if you add/remove shapes from a body and recompute the mass, the joints will be broken.
  • - *
- */ +/// Revolute joint definition. This requires defining an anchor point where the bodies are joined. +/// The definition uses local anchor points so that the initial configuration can violate the +/// constraint slightly. You also need to specify the initial relative angle for joint limits. This +/// helps when saving and loading a game. The local anchor points are measured from the body's origin +/// rather than the center of mass because:
+///
    +///
  • you might not know where the center of mass will be.
  • +///
  • if you add/remove shapes from a body and recompute the mass, the joints will be broken.
  • +///
class RevoluteJointDef extends JointDef { - /** - * The local anchor point relative to body1's origin. - */ - Vector2 localAnchorA = new Vector2.zero(); - - /** - * The local anchor point relative to body2's origin. - */ - Vector2 localAnchorB = new Vector2.zero(); - - /** - * The body2 angle minus body1 angle in the reference state (radians). - */ + /// The body2 angle minus body1 angle in the reference state (radians). double referenceAngle = 0.0; - /** - * A flag to enable joint limits. - */ + /// A flag to enable joint limits. bool enableLimit = false; - /** - * The lower angle for the joint limit (radians). - */ + /// The lower angle for the joint limit (radians). double lowerAngle = 0.0; - /** - * The upper angle for the joint limit (radians). - */ + /// The upper angle for the joint limit (radians). double upperAngle = 0.0; - /** - * A flag to enable the joint motor. - */ + /// A flag to enable the joint motor. bool enableMotor = false; - /** - * The desired motor speed. Usually in radians per second. - */ + /// The desired motor speed. Usually in radians per second. double motorSpeed = 0.0; - /** - * The maximum motor torque used to achieve the desired motor speed. Usually in N-m. - */ + /// The maximum motor torque used to achieve the desired motor speed. Usually in N-m. double maxMotorTorque = 0.0; RevoluteJointDef() : super(JointType.REVOLUTE); - /** - * Initialize the bodies, anchors, and reference angle using the world anchor. - * - * @param b1 - * @param b2 - * @param anchor - */ + /// Initialize the bodies, anchors, and reference angle using the world anchor. + /// + /// @param b1 + /// @param b2 + /// @param anchor void initialize(final Body b1, final Body b2, final Vector2 anchor) { bodyA = b1; bodyB = b2; - bodyA.getLocalPointToOut(anchor, localAnchorA); - bodyB.getLocalPointToOut(anchor, localAnchorB); + localAnchorA.setFrom(bodyA.getLocalPoint(anchor)); + localAnchorB.setFrom(bodyB.getLocalPoint(anchor)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } } diff --git a/lib/src/dynamics/joints/rope_joint.dart b/lib/src/dynamics/joints/rope_joint.dart index adb422b..f2a5a38 100644 --- a/lib/src/dynamics/joints/rope_joint.dart +++ b/lib/src/dynamics/joints/rope_joint.dart @@ -1,42 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A rope joint enforces a maximum distance between two points on two bodies. It has no other - * effect. Warning: if you attempt to change the maximum length during the simulation you will get - * some non-physical behavior. A model that would allow you to dynamically modify the length would - * have some sponginess, so I chose not to implement it that way. See DistanceJoint if you want to - * dynamically control length. - * - * @author Daniel Murphy - */ +/// A rope joint enforces a maximum distance between two points on two bodies. It has no other +/// effect. Warning: if you attempt to change the maximum length during the simulation you will get +/// some non-physical behavior. A model that would allow you to dynamically modify the length would +/// have some sponginess, so I chose not to implement it that way. See DistanceJoint if you want to +/// dynamically control length. class RopeJoint extends Joint { // Solver shared - final Vector2 _localAnchorA = new Vector2.zero(); - final Vector2 _localAnchorB = new Vector2.zero(); + final Vector2 localAnchorA = Vector2.zero(); + final Vector2 localAnchorB = Vector2.zero(); double _maxLength = 0.0; double _length = 0.0; double _impulse = 0.0; @@ -44,11 +16,11 @@ class RopeJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _u = new Vector2.zero(); - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _u = Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; @@ -56,9 +28,9 @@ class RopeJoint extends Joint { double _mass = 0.0; LimitState _state = LimitState.INACTIVE; - RopeJoint(IWorldPool worldPool, RopeJointDef def) : super(worldPool, def) { - _localAnchorA.setFrom(def.localAnchorA); - _localAnchorB.setFrom(def.localAnchorB); + RopeJoint(RopeJointDef def) : super(def) { + localAnchorA.setFrom(def.localAnchorA); + localAnchorB.setFrom(def.localAnchorB); _maxLength = def.maxLength; } @@ -83,26 +55,22 @@ class RopeJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - _rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - _rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + _rB.setFrom(Rot.mulVec2(qB, temp)); _u ..setFrom(cB) @@ -125,8 +93,6 @@ class RopeJoint extends Joint { _u.setZero(); _mass = 0.0; _impulse = 0.0; - pool.pushRot(2); - pool.pushVec2(1); return; } @@ -155,12 +121,7 @@ class RopeJoint extends Joint { _impulse = 0.0; } - pool.pushRot(2); - pool.pushVec2(1); - - // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; - // data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } @@ -170,10 +131,9 @@ class RopeJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - // Cdot = dot(u, v + cross(w, r)) - Vector2 vpA = pool.popVec2(); - Vector2 vpB = pool.popVec2(); - Vector2 temp = pool.popVec2(); + Vector2 vpA = Vector2.zero(); + Vector2 vpB = Vector2.zero(); + Vector2 temp = Vector2.zero(); _rA.scaleOrthogonalInto(wA, vpA); vpA.add(vA); @@ -192,7 +152,7 @@ class RopeJoint extends Joint { double impulse = -_mass * Cdot; double oldImpulse = _impulse; - _impulse = Math.min(0.0, _impulse + impulse); + _impulse = Math.min(0.0, _impulse + impulse); impulse = _impulse - oldImpulse; double Px = impulse * _u.x; @@ -204,8 +164,6 @@ class RopeJoint extends Joint { vB.y += _invMassB * Py; wB += _invIB * (_rB.x * Py - _rB.y * Px); - pool.pushVec2(3); - // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; // data.velocities[_indexB].v = vB; @@ -218,29 +176,26 @@ class RopeJoint extends Joint { Vector2 cB = data.positions[_indexB].c; double aB = data.positions[_indexB].a; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 u = pool.popVec2(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 u = Vector2.zero(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); + u ..setFrom(cB) ..add(rB) @@ -248,11 +203,11 @@ class RopeJoint extends Joint { ..sub(rA); double length = u.normalize(); - double C = length - _maxLength; + double c = length - _maxLength; - C = MathUtils.clampDouble(C, 0.0, Settings.maxLinearCorrection); + c = MathUtils.clampDouble(c, 0.0, Settings.maxLinearCorrection); - double impulse = -_mass * C; + double impulse = -_mass * c; double Px = impulse * u.x; double Py = impulse * u.y; @@ -263,44 +218,20 @@ class RopeJoint extends Joint { cB.y += _invMassB * Py; aB += _invIB * (rB.x * Py - rB.y * Px); - pool.pushRot(2); - pool.pushVec2(4); - - // data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; - // data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return length - _maxLength < Settings.linearSlop; } - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut - ..setFrom(_u) - ..scale(inv_dt) - ..scale(_impulse); + Vector2 getReactionForce(double inv_dt) { + return Vector2.copy(_u)..scale(inv_dt)..scale(_impulse); } double getReactionTorque(double inv_dt) { return 0.0; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - double getMaxLength() { return _maxLength; } diff --git a/lib/src/dynamics/joints/rope_joint_def.dart b/lib/src/dynamics/joints/rope_joint_def.dart index 69daead..ad4e426 100644 --- a/lib/src/dynamics/joints/rope_joint_def.dart +++ b/lib/src/dynamics/joints/rope_joint_def.dart @@ -1,50 +1,10 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Rope joint definition. This requires two body anchor points and a maximum lengths. Note: by - * default the connected objects will not collide. see collideConnected in b2JointDef. - * - * @author Daniel Murphy - */ +/// Rope joint definition. This requires two body anchor points and a maximum lengths. Note: by +/// default the connected objects will not collide. see collideConnected in b2JointDef. class RopeJointDef extends JointDef { - /** - * The local anchor point relative to bodyA's origin. - */ - final Vector2 localAnchorA = new Vector2.zero(); - - /** - * The local anchor point relative to bodyB's origin. - */ - final Vector2 localAnchorB = new Vector2.zero(); - - /** - * The maximum length of the rope. Warning: this must be larger than b2_linearSlop or the joint - * will have no effect. - */ + /// The maximum length of the rope. Warning: this must be larger than b2_linearSlop or the joint + /// will have no effect. double maxLength = 0.0; RopeJointDef() : super(JointType.ROPE) { diff --git a/lib/src/dynamics/joints/weld_joint.dart b/lib/src/dynamics/joints/weld_joint.dart index 08c33ea..f69a85e 100644 --- a/lib/src/dynamics/joints/weld_joint.dart +++ b/lib/src/dynamics/joints/weld_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Point-to-point constraint @@ -38,20 +14,16 @@ part of box2d; //J = [0 0 -1 0 0 1] //K = invI1 + invI2 -/** - * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the - * island constraint solver is approximate. - * - * @author Daniel Murphy - */ +/// A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the +/// island constraint solver is approximate. class WeldJoint extends Joint { double _frequencyHz = 0.0; double _dampingRatio = 0.0; double _bias = 0.0; // Solver shared - final Vector2 _localAnchorA; - final Vector2 _localAnchorB; + final Vector2 localAnchorA; + final Vector2 localAnchorB; double _referenceAngle = 0.0; double _gamma = 0.0; final Vector3 _impulse; @@ -59,21 +31,21 @@ class WeldJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _rA = new Vector2.zero(); - final Vector2 _rB = new Vector2.zero(); - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _rA = Vector2.zero(); + final Vector2 _rB = Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; - final Matrix3 _mass = new Matrix3.zero(); + final Matrix3 _mass = Matrix3.zero(); - WeldJoint(IWorldPool argWorld, WeldJointDef def) - : _localAnchorA = new Vector2.copy(def.localAnchorA), - _localAnchorB = new Vector2.copy(def.localAnchorB), - _impulse = new Vector3.zero(), - super(argWorld, def) { + WeldJoint(WeldJointDef def) + : localAnchorA = Vector2.copy(def.localAnchorA), + localAnchorB = Vector2.copy(def.localAnchorB), + _impulse = Vector3.zero(), + super(def) { _referenceAngle = def.referenceAngle; _frequencyHz = def.frequencyHz; _dampingRatio = def.dampingRatio; @@ -83,25 +55,8 @@ class WeldJoint extends Joint { return _referenceAngle; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - argOut.setValues(_impulse.x, _impulse.y); - argOut.scale(inv_dt); + Vector2 getReactionForce(double inv_dt) { + return Vector2(_impulse.x, _impulse.y)..scale(inv_dt); } double getReactionTorque(double inv_dt) { @@ -128,22 +83,19 @@ class WeldJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. + final temp = Vector2.copy(localAnchorA)..sub(_localCenterA); + _rA.setFrom(Rot.mulVec2(qA, temp)); temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA); - Rot.mulToOutUnsafe(qA, temp, _rA); - temp - ..setFrom(_localAnchorB) + ..setFrom(localAnchorB) ..sub(_localCenterB); - Rot.mulToOutUnsafe(qB, temp, _rB); + _rB.setFrom(Rot.mulVec2(qB, temp)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] @@ -157,7 +109,7 @@ class WeldJoint extends Joint { double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - final Matrix3 K = pool.popMat33(); + final Matrix3 K = Matrix3.zero(); double ex_x = mA + mB + _rA.y * _rA.y * iA + _rB.y * _rB.y * iB; double ey_x = -_rA.y * _rA.x * iA - _rB.y * _rB.x * iB; @@ -180,7 +132,7 @@ class WeldJoint extends Joint { double C = aB - aA - _referenceAngle; // Frequency - double omega = 2.0 * Math.PI * _frequencyHz; + double omega = 2.0 * Math.pi * _frequencyHz; // Damping coefficient double d = 2.0 * m * _dampingRatio * omega; @@ -203,11 +155,10 @@ class WeldJoint extends Joint { } if (data.step.warmStarting) { - final Vector2 P = pool.popVec2(); // Scale impulses to support a variable time step. _impulse.scale(data.step.dtRatio); - P.setValues(_impulse.x, _impulse.y); + final Vector2 P = Vector2(_impulse.x, _impulse.y); vA.x -= mA * P.x; vA.y -= mA * P.y; @@ -216,19 +167,12 @@ class WeldJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * (_rB.cross(P) + _impulse.z); - pool.pushVec2(1); } else { _impulse.setZero(); } -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(1); - pool.pushRot(2); - pool.pushMat33(1); } void solveVelocityConstraints(final SolverData data) { @@ -240,9 +184,9 @@ class WeldJoint extends Joint { double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - final Vector2 Cdot1 = pool.popVec2(); - final Vector2 P = pool.popVec2(); - final Vector2 temp = pool.popVec2(); + final Vector2 Cdot1 = Vector2.zero(); + final Vector2 P = Vector2.zero(); + final Vector2 temp = Vector2.zero(); if (_frequencyHz > 0.0) { double Cdot2 = wB - wA; @@ -260,9 +204,8 @@ class WeldJoint extends Joint { ..sub(vA) ..sub(temp); + P.setFrom(MathUtils.matrix3Mul22(_mass, Cdot1)..negate()); final Vector2 impulse1 = P; - MathUtils.matrix3Mul22ToOutUnsafe(_mass, Cdot1, impulse1); - impulse1.negate(); _impulse.x += impulse1.x; _impulse.y += impulse1.y; @@ -283,13 +226,9 @@ class WeldJoint extends Joint { ..sub(temp); double Cdot2 = wB - wA; - final Vector3 Cdot = pool.popVec3(); - Cdot.setValues(Cdot1.x, Cdot1.y, Cdot2); - - final Vector3 impulse = pool.popVec3(); - MathUtils.matrix3MulToOutUnsafe(_mass, Cdot, impulse); + final Vector3 Cdot = Vector3(Cdot1.x, Cdot1.y, Cdot2); + final Vector3 impulse = MathUtils.matrix3Mul(_mass, Cdot)..negate(); - impulse.negate(); _impulse.add(impulse); P.setValues(impulse.x, impulse.y); @@ -301,16 +240,10 @@ class WeldJoint extends Joint { vB.x += mB * P.x; vB.y += mB * P.y; wB += iB * (_rB.cross(P) + impulse.z); - - pool.pushVec3(2); } -// data.velocities[_indexA].v.set(vA); data.velocities[_indexA].w = wA; -// data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; - - pool.pushVec2(3); } bool solvePositionConstraints(final SolverData data) { @@ -318,11 +251,8 @@ class WeldJoint extends Joint { double aA = data.positions[_indexA].a; Vector2 cB = data.positions[_indexB].c; double aB = data.positions[_indexB].a; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); - final Vector2 rA = pool.popVec2(); - final Vector2 rB = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); qA.setAngle(aA); qB.setAngle(aB); @@ -330,17 +260,17 @@ class WeldJoint extends Joint { double mA = _invMassA, mB = _invMassB; double iA = _invIA, iB = _invIB; - temp.setFrom(_localAnchorA); - temp.sub(_localCenterA); - Rot.mulToOutUnsafe(qA, temp, rA); - temp.setFrom(_localAnchorB); - temp.sub(_localCenterB); - Rot.mulToOutUnsafe(qB, temp, rB); + final Vector2 temp = Vector2.copy(localAnchorA)..sub(_localCenterA); + final Vector2 rA = Vector2.copy(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + final Vector2 rB = Vector2.copy(Rot.mulVec2(qB, temp)); double positionError, angularError; - final Matrix3 K = pool.popMat33(); - final Vector2 C1 = pool.popVec2(); - final Vector2 P = pool.popVec2(); + final Matrix3 K = Matrix3.zero(); + final Vector2 C1 = Vector2.zero(); + final Vector2 P = Vector2.zero(); double ex_x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; double ey_x = -rA.y * rA.x * iA - rB.y * rB.x * iB; @@ -385,9 +315,8 @@ class WeldJoint extends Joint { positionError = C1.length; angularError = C2.abs(); - final Vector3 C = pool.popVec3(); - final Vector3 impulse = pool.popVec3(); - C.setValues(C1.x, C1.y, C2); + final Vector3 C = Vector3(C1.x, C1.y, C2); + final Vector3 impulse = Vector3.zero(); Matrix3.solve(K, impulse, C); impulse.negate(); @@ -400,18 +329,11 @@ class WeldJoint extends Joint { cB.x += mB * P.x; cB.y += mB * P.y; aB += iB * (rB.cross(P) + impulse.z); - pool.pushVec3(2); } -// data.positions[_indexA].c.set(cA); data.positions[_indexA].a = aA; -// data.positions[_indexB].c.set(cB); data.positions[_indexB].a = aB; - pool.pushVec2(5); - pool.pushRot(2); - pool.pushMat33(1); - return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } diff --git a/lib/src/dynamics/joints/weld_joint_def.dart b/lib/src/dynamics/joints/weld_joint_def.dart index 9d02d79..15b0169 100644 --- a/lib/src/dynamics/joints/weld_joint_def.dart +++ b/lib/src/dynamics/joints/weld_joint_def.dart @@ -1,69 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class WeldJointDef extends JointDef { - /** - * The local anchor point relative to body1's origin. - */ - final Vector2 localAnchorA = new Vector2.zero(); - - /** - * The local anchor point relative to body2's origin. - */ - final Vector2 localAnchorB = new Vector2.zero(); - - /** - * The body2 angle minus body1 angle in the reference state (radians). - */ + /// The body2 angle minus body1 angle in the reference state (radians). double referenceAngle = 0.0; - /** - * The mass-spring-damper frequency in Hertz. Rotation only. Disable softness with a value of 0. - */ + /// The mass-spring-damper frequency in Hertz. Rotation only. Disable softness with a value of 0. double frequencyHz = 0.0; - /** - * The damping ratio. 0 = no damping, 1 = critical damping. - */ + /// The damping ratio. 0 = no damping, 1 = critical damping. double dampingRatio = 0.0; WeldJointDef() : super(JointType.WELD); - /** - * Initialize the bodies, anchors, and reference angle using a world anchor point. - * - * @param bA - * @param bB - * @param anchor - */ + /// Initialize the bodies, anchors, and reference angle using a world anchor point. + /// + /// @param bA + /// @param bB + /// @param anchor void initialize(Body bA, Body bB, Vector2 anchor) { bodyA = bA; bodyB = bB; - bodyA.getLocalPointToOut(anchor, localAnchorA); - bodyB.getLocalPointToOut(anchor, localAnchorB); + localAnchorA.setFrom(bodyA.getLocalPoint(anchor)); + localAnchorB.setFrom(bodyB.getLocalPoint(anchor)); referenceAngle = bodyB.getAngle() - bodyA.getAngle(); } } diff --git a/lib/src/dynamics/joints/wheel_joint.dart b/lib/src/dynamics/joints/wheel_joint.dart index 3c36602..3c7321a 100644 --- a/lib/src/dynamics/joints/wheel_joint.dart +++ b/lib/src/dynamics/joints/wheel_joint.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; //Linear constraint (point-to-line) @@ -40,24 +16,20 @@ part of box2d; //Cdot = wB - wA //J = [0 0 -1 0 0 1] -/** - * A wheel joint. This joint provides two degrees of freedom: translation along an axis fixed in - * bodyA and rotation in the plane. You can use a joint limit to restrict the range of motion and a - * joint motor to drive the rotation or to model rotational friction. This joint is designed for - * vehicle suspensions. - * - * @author Daniel Murphy - */ +/// A wheel joint. This joint provides two degrees of freedom: translation along an axis fixed in +/// bodyA and rotation in the plane. You can use a joint limit to restrict the range of motion and a +/// joint motor to drive the rotation or to model rotational friction. This joint is designed for +/// vehicle suspensions. class WheelJoint extends Joint { // TODO(srdjan): make fields private. double _frequencyHz = 0.0; double _dampingRatio = 0.0; // Solver shared - final Vector2 _localAnchorA = new Vector2.zero(); - final Vector2 _localAnchorB = new Vector2.zero(); - final Vector2 _localXAxisA = new Vector2.zero(); - final Vector2 _localYAxisA = new Vector2.zero(); + final Vector2 localAnchorA = Vector2.zero(); + final Vector2 localAnchorB = Vector2.zero(); + final Vector2 _localXAxisA = Vector2.zero(); + final Vector2 _localYAxisA = Vector2.zero(); double _impulse = 0.0; double _motorImpulse = 0.0; @@ -70,15 +42,15 @@ class WheelJoint extends Joint { // Solver temp int _indexA = 0; int _indexB = 0; - final Vector2 _localCenterA = new Vector2.zero(); - final Vector2 _localCenterB = new Vector2.zero(); + final Vector2 _localCenterA = Vector2.zero(); + final Vector2 _localCenterB = Vector2.zero(); double _invMassA = 0.0; double _invMassB = 0.0; double _invIA = 0.0; double _invIB = 0.0; - final Vector2 _ax = new Vector2.zero(); - final Vector2 _ay = new Vector2.zero(); + final Vector2 _ax = Vector2.zero(); + final Vector2 _ay = Vector2.zero(); double _sAx = 0.0, _sBx = 0.0; double _sAy = 0.0, _sBy = 0.0; @@ -89,9 +61,9 @@ class WheelJoint extends Joint { double _bias = 0.0; double _gamma = 0.0; - WheelJoint(IWorldPool argPool, WheelJointDef def) : super(argPool, def) { - _localAnchorA.setFrom(def.localAnchorA); - _localAnchorB.setFrom(def.localAnchorB); + WheelJoint(WheelJointDef def) : super(def) { + localAnchorA.setFrom(def.localAnchorA); + localAnchorB.setFrom(def.localAnchorB); _localXAxisA.setFrom(def.localAxisA); _localXAxisA.scaleOrthogonalInto(1.0, _localYAxisA); @@ -106,33 +78,17 @@ class WheelJoint extends Joint { _dampingRatio = def.dampingRatio; } - Vector2 getLocalAnchorA() { - return _localAnchorA; - } - - Vector2 getLocalAnchorB() { - return _localAnchorB; - } - - void getAnchorA(Vector2 argOut) { - _bodyA.getWorldPointToOut(_localAnchorA, argOut); - } - - void getAnchorB(Vector2 argOut) { - _bodyB.getWorldPointToOut(_localAnchorB, argOut); - } - - void getReactionForce(double inv_dt, Vector2 argOut) { - final Vector2 temp = pool.popVec2(); + Vector2 getReactionForce(double inv_dt) { + final Vector2 temp = Vector2.zero(); temp ..setFrom(_ay) ..scale(_impulse); - argOut + final Vector2 result = Vector2.copy(_ax) ..setFrom(_ax) ..scale(_springImpulse) ..add(temp) ..scale(inv_dt); - pool.pushVec2(1); + return result; } double getReactionTorque(double inv_dt) { @@ -143,20 +99,19 @@ class WheelJoint extends Joint { Body b1 = _bodyA; Body b2 = _bodyB; - Vector2 p1 = pool.popVec2(); - Vector2 p2 = pool.popVec2(); - Vector2 axis = pool.popVec2(); - b1.getWorldPointToOut(_localAnchorA, p1); - b2.getWorldPointToOut(_localAnchorA, p2); + Vector2 p1 = Vector2.zero(); + Vector2 p2 = Vector2.zero(); + Vector2 axis = Vector2.zero(); + p1.setFrom(b1.getWorldPoint(localAnchorA)); + p2.setFrom(b2.getWorldPoint(localAnchorA)); p2.sub(p1); - b1.getWorldVectorToOut(_localXAxisA, axis); + axis.setFrom(b1.getWorldVector(_localXAxisA)); double translation = p2.dot(axis); - pool.pushVec2(3); return translation; } - /** For serialization */ + /// For serialization Vector2 getLocalAxisA() { return _localXAxisA; } @@ -201,9 +156,9 @@ class WheelJoint extends Joint { // pooling // TODO(srdjan): Make fields private. - final Vector2 rA = new Vector2.zero(); - final Vector2 rB = new Vector2.zero(); - final Vector2 d = new Vector2.zero(); + final Vector2 rA = Vector2.zero(); + final Vector2 rB = Vector2.zero(); + final Vector2 d = Vector2.zero(); void initVelocityConstraints(SolverData data) { _indexA = _bodyA._islandIndex; @@ -228,26 +183,23 @@ class WheelJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); // Compute the effective masses. - Rot.mulToOutUnsafe( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOutUnsafe( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); + d ..setFrom(cB) ..add(rB) @@ -256,7 +208,7 @@ class WheelJoint extends Joint { // Point to line constraint { - Rot.mulToOut(qA, _localYAxisA, _ay); + _ay.setFrom(Rot.mulVec2(qA, _localYAxisA)); _sAy = (temp ..setFrom(d) ..add(rA)) @@ -275,7 +227,7 @@ class WheelJoint extends Joint { _bias = 0.0; _gamma = 0.0; if (_frequencyHz > 0.0) { - Rot.mulToOut(qA, _localXAxisA, _ax); + _ax.setFrom(Rot.mulVec2(qA, _localXAxisA)); _sAx = (temp ..setFrom(d) ..add(rA)) @@ -290,7 +242,7 @@ class WheelJoint extends Joint { double C = d.dot(_ax); // Frequency - double omega = 2.0 * Math.PI * _frequencyHz; + double omega = 2.0 * Math.pi * _frequencyHz; // Damping coefficient double dd = 2.0 * _springMass * _dampingRatio * omega; @@ -328,7 +280,7 @@ class WheelJoint extends Joint { } if (data.step.warmStarting) { - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); // Account for variable time step. _impulse *= data.step.dtRatio; _springImpulse *= data.step.dtRatio; @@ -346,18 +298,13 @@ class WheelJoint extends Joint { vB.x += _invMassB * P.x; vB.y += _invMassB * P.y; wB += _invIB * LB; - pool.pushVec2(1); } else { _impulse = 0.0; _springImpulse = 0.0; _motorImpulse = 0.0; } - pool.pushRot(2); - pool.pushVec2(1); - // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; - // data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } @@ -370,8 +317,8 @@ class WheelJoint extends Joint { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; - final Vector2 temp = pool.popVec2(); - final Vector2 P = pool.popVec2(); + final Vector2 temp = Vector2.zero(); + final Vector2 P = Vector2.zero(); // Solve spring constraint { @@ -435,7 +382,6 @@ class WheelJoint extends Joint { vB.y += mB * P.y; wB += iB * LB; } - pool.pushVec2(2); // data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; @@ -449,33 +395,30 @@ class WheelJoint extends Joint { Vector2 cB = data.positions[_indexB].c; double aB = data.positions[_indexB].a; - final Rot qA = pool.popRot(); - final Rot qB = pool.popRot(); - final Vector2 temp = pool.popVec2(); + final Rot qA = Rot(); + final Rot qB = Rot(); + final Vector2 temp = Vector2.zero(); qA.setAngle(aA); qB.setAngle(aB); - Rot.mulToOut( - qA, - temp - ..setFrom(_localAnchorA) - ..sub(_localCenterA), - rA); - Rot.mulToOut( - qB, - temp - ..setFrom(_localAnchorB) - ..sub(_localCenterB), - rB); + temp + ..setFrom(localAnchorA) + ..sub(_localCenterA); + rA.setFrom(Rot.mulVec2(qA, temp)); + temp + ..setFrom(localAnchorB) + ..sub(_localCenterB); + rB.setFrom(Rot.mulVec2(qB, temp)); + d ..setFrom(cB) ..sub(cA) ..add(rB) ..sub(rA); - Vector2 ay = pool.popVec2(); - Rot.mulToOut(qA, _localYAxisA, ay); + Vector2 ay = Vector2.zero(); + ay.setFrom(Rot.mulVec2(qA, _localYAxisA)); double sAy = (temp ..setFrom(d) @@ -495,7 +438,7 @@ class WheelJoint extends Joint { impulse = 0.0; } - final Vector2 P = pool.popVec2(); + final Vector2 P = Vector2.zero(); P.x = impulse * ay.x; P.y = impulse * ay.y; double LA = impulse * sAy; @@ -508,11 +451,7 @@ class WheelJoint extends Joint { cB.y += _invMassB * P.y; aB += _invIB * LB; - pool.pushVec2(3); - pool.pushRot(2); - // data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; - // data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return C.abs() <= Settings.linearSlop; diff --git a/lib/src/dynamics/joints/wheel_joint_def.dart b/lib/src/dynamics/joints/wheel_joint_def.dart index 65d4b8e..8dff298 100644 --- a/lib/src/dynamics/joints/wheel_joint_def.dart +++ b/lib/src/dynamics/joints/wheel_joint_def.dart @@ -1,77 +1,27 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Wheel joint definition. This requires defining a line of motion using an axis and an anchor - * point. The definition uses local anchor points and a local axis so that the initial configuration - * can violate the constraint slightly. The joint translation is zero when the local anchor points - * coincide in world space. Using local anchors and a local axis helps when saving and loading a - * game. - * - * @author Daniel Murphy - */ +/// Wheel joint definition. This requires defining a line of motion using an axis and an anchor +/// point. The definition uses local anchor points and a local axis so that the initial configuration +/// can violate the constraint slightly. The joint translation is zero when the local anchor points +/// coincide in world space. Using local anchors and a local axis helps when saving and loading a +/// game. class WheelJointDef extends JointDef { - /** - * The local anchor point relative to body1's origin. - */ - final Vector2 localAnchorA = new Vector2.zero(); - - /** - * The local anchor point relative to body2's origin. - */ - final Vector2 localAnchorB = new Vector2.zero(); - - /** - * The local translation axis in body1. - */ - final Vector2 localAxisA = new Vector2.zero(); + /// The local translation axis in body1. + final Vector2 localAxisA = Vector2.zero(); - /** - * Enable/disable the joint motor. - */ + /// Enable/disable the joint motor. bool enableMotor = false; - /** - * The maximum motor torque, usually in N-m. - */ + /// The maximum motor torque, usually in N-m. double maxMotorTorque = 0.0; - /** - * The desired motor speed in radians per second. - */ + /// The desired motor speed in radians per second. double motorSpeed = 0.0; - /** - * Suspension frequency, zero indicates no suspension - */ + /// Suspension frequency, zero indicates no suspension double frequencyHz = 0.0; - /** - * Suspension damping ratio, one indicates critical damping - */ + /// Suspension damping ratio, one indicates critical damping double dampingRatio = 0.0; WheelJointDef() : super(JointType.WHEEL) { @@ -81,8 +31,8 @@ class WheelJointDef extends JointDef { void initialize(Body b1, Body b2, Vector2 anchor, Vector2 axis) { bodyA = b1; bodyB = b2; - b1.getLocalPointToOut(anchor, localAnchorA); - b2.getLocalPointToOut(anchor, localAnchorB); - bodyA.getLocalVectorToOut(axis, localAxisA); + localAnchorA.setFrom(b1.getLocalPoint(anchor)); + localAnchorB.setFrom(b2.getLocalPoint(anchor)); + localAxisA.setFrom(bodyA.getLocalVector(axis)); } } diff --git a/lib/src/dynamics/profile.dart b/lib/src/dynamics/profile.dart index a096590..f6ac203 100644 --- a/lib/src/dynamics/profile.dart +++ b/lib/src/dynamics/profile.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ProfileEntry { @@ -32,8 +8,8 @@ class ProfileEntry { double longAvg = 0.0; double shortAvg = 0.0; - double min = double.MAX_FINITE; - double max = -double.MAX_FINITE; + double min = double.maxFinite; + double max = -double.maxFinite; double _accum = 0.0; void record(double value) { @@ -61,16 +37,16 @@ class ProfileEntry { } class Profile { - final ProfileEntry step = new ProfileEntry(); - final ProfileEntry stepInit = new ProfileEntry(); - final ProfileEntry collide = new ProfileEntry(); - final ProfileEntry solveParticleSystem = new ProfileEntry(); - final ProfileEntry solve = new ProfileEntry(); - final ProfileEntry solveInit = new ProfileEntry(); - final ProfileEntry solveVelocity = new ProfileEntry(); - final ProfileEntry solvePosition = new ProfileEntry(); - final ProfileEntry broadphase = new ProfileEntry(); - final ProfileEntry solveTOI = new ProfileEntry(); + final ProfileEntry step = ProfileEntry(); + final ProfileEntry stepInit = ProfileEntry(); + final ProfileEntry collide = ProfileEntry(); + final ProfileEntry solveParticleSystem = ProfileEntry(); + final ProfileEntry solve = ProfileEntry(); + final ProfileEntry solveInit = ProfileEntry(); + final ProfileEntry solveVelocity = ProfileEntry(); + final ProfileEntry solvePosition = ProfileEntry(); + final ProfileEntry broadphase = ProfileEntry(); + final ProfileEntry solveTOI = ProfileEntry(); void toDebugStrings(List strings) { strings.add("Profile:"); diff --git a/lib/src/dynamics/solver_data.dart b/lib/src/dynamics/solver_data.dart index 6250c94..88824ba 100644 --- a/lib/src/dynamics/solver_data.dart +++ b/lib/src/dynamics/solver_data.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class SolverData { diff --git a/lib/src/dynamics/time_step.dart b/lib/src/dynamics/time_step.dart index ee26b31..5ba835b 100644 --- a/lib/src/dynamics/time_step.dart +++ b/lib/src/dynamics/time_step.dart @@ -1,40 +1,14 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * This is an internal structure. - */ +/// This is an internal structure. class TimeStep { - /** time step */ + /// time step double dt = 0.0; - /** inverse time step (0 if dt == 0). */ + /// inverse time step (0 if dt == 0). double inv_dt = 0.0; - /** dt * inv_dt0 */ + /// dt * inv_dt0 double dtRatio = 0.0; int velocityIterations = 0; diff --git a/lib/src/dynamics/world.dart b/lib/src/dynamics/world.dart index 644808d..382003b 100644 --- a/lib/src/dynamics/world.dart +++ b/lib/src/dynamics/world.dart @@ -1,33 +1,7 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * The world class manages all physics entities, dynamic simulation, and asynchronous queries. The - * world also contains efficient memory management facilities. - */ +/// The world class manages all physics entities, dynamic simulation, and asynchronous queries. The +/// world also contains efficient memory management facilities. class World { static const int WORLD_POOL_SIZE = 100; static const int WORLD_POOL_CONTAINER_SIZE = 10; @@ -36,6 +10,11 @@ class World { static const int LOCKED = 0x0002; static const int CLEAR_FORCES = 0x0004; + // TODO.spydon: Don't have these fields as static + static final Distance distance = Distance(); + static final Collision collision = Collision(); + static final TimeOfImpact toi = TimeOfImpact(); + int _flags = 0; ContactManager _contactManager; @@ -54,12 +33,8 @@ class World { ParticleDestructionListener _particleDestructionListener; DebugDraw debugDraw; - final IWorldPool _pool; - - /** - * This is used to compute the time step ratio to support a variable time step. - */ - double _inv_dt0 = 0.0; + /// This is used to compute the time step ratio to support a variable time step. + double _invDt0 = 0.0; // these are for debugging the solver bool _warmStarting = false; @@ -72,46 +47,13 @@ class World { ParticleSystem _particleSystem; - static List> _create2D(int a, int b) { - var res = new List>(a); - for (int i = 0; i < a; i++) { - res[i] = new List(b); - } - return res; - } - - List> contactStacks = - _create2D(ShapeType.values.length, ShapeType.values.length); - - /** - * Construct a world object. - * - * @param gravity the world gravity vector. - */ - factory World.withGravity(Vector2 gravity) { - var w = new World.withPool(gravity, - new DefaultWorldPool(WORLD_POOL_SIZE, WORLD_POOL_CONTAINER_SIZE)); - return w; - } - - /** - * Construct a world object. - * - * @param gravity the world gravity vector. - */ - factory World.withPool(Vector2 gravity, IWorldPool pool) { - var w = new World.withPoolAndStrategy(gravity, pool, new DynamicTree()); - return w; - } - - factory World.withPoolAndStrategy( - Vector2 gravity, IWorldPool pool, BroadPhaseStrategy strategy) { - var w = new World(gravity, pool, new DefaultBroadPhaseBuffer(strategy)); - return w; - } - - World(Vector2 gravity, this._pool, BroadPhase broadPhase) - : _gravity = new Vector2.copy(gravity) { + /// Construct a world object. + /// + /// @param gravity the world gravity vector. + /// @param broadPhase what type of broad phase strategy that should be used. + World([Vector2 gravity, BroadPhase broadPhase]) + : _gravity = Vector2.copy(gravity ?? Vector2.zero()) { + broadPhase ??= DefaultBroadPhaseBuffer(DynamicTree()); _destructionListener = null; debugDraw = null; @@ -130,14 +72,14 @@ class World { _flags = CLEAR_FORCES; - _inv_dt0 = 0.0; + _invDt0 = 0.0; - _contactManager = new ContactManager(this, broadPhase); - _profile = new Profile(); + _contactManager = ContactManager(this, broadPhase); + _profile = Profile(); - _particleSystem = new ParticleSystem(this); + _particleSystem = ParticleSystem(this); - _initializeRegisters(); + //_initializeRegisters(); } void setAllowSleep(bool flag) { @@ -165,36 +107,6 @@ class World { return _allowSleep; } - void _addType( - IDynamicStack creator, ShapeType type1, ShapeType type2) { - ContactRegister register = new ContactRegister(); - register.creator = creator; - register.primary = true; - contactStacks[type1.index][type2.index] = register; - - if (type1 != type2) { - ContactRegister register2 = new ContactRegister(); - register2.creator = creator; - register2.primary = false; - contactStacks[type2.index][type1.index] = register2; - } - } - - void _initializeRegisters() { - _addType(_pool.getCircleContactStack(), ShapeType.CIRCLE, ShapeType.CIRCLE); - _addType( - _pool.getPolyCircleContactStack(), ShapeType.POLYGON, ShapeType.CIRCLE); - _addType(_pool.getPolyContactStack(), ShapeType.POLYGON, ShapeType.POLYGON); - _addType( - _pool.getEdgeCircleContactStack(), ShapeType.EDGE, ShapeType.CIRCLE); - _addType( - _pool.getEdgePolyContactStack(), ShapeType.EDGE, ShapeType.POLYGON); - _addType( - _pool.getChainCircleContactStack(), ShapeType.CHAIN, ShapeType.CIRCLE); - _addType( - _pool.getChainPolyContactStack(), ShapeType.CHAIN, ShapeType.POLYGON); - } - DestructionListener getDestructionListener() { return _destructionListener; } @@ -207,102 +119,48 @@ class World { _particleDestructionListener = listener; } - Contact popContact( - Fixture fixtureA, int indexA, Fixture fixtureB, int indexB) { - final ShapeType type1 = fixtureA.getType(); - final ShapeType type2 = fixtureB.getType(); - - final ContactRegister reg = contactStacks[type1.index][type2.index]; - if (reg != null) { - if (reg.primary) { - Contact c = reg.creator.pop(); - c.init(fixtureA, indexA, fixtureB, indexB); - return c; - } else { - Contact c = reg.creator.pop(); - c.init(fixtureB, indexB, fixtureA, indexA); - return c; - } - } else { - return null; - } - } - - void pushContact(Contact contact) { - Fixture fixtureA = contact.fixtureA; - Fixture fixtureB = contact.fixtureB; - - if (contact._manifold.pointCount > 0 && - !fixtureA.isSensor() && - !fixtureB.isSensor()) { - fixtureA.getBody().setAwake(true); - fixtureB.getBody().setAwake(true); - } - - ShapeType type1 = fixtureA.getType(); - ShapeType type2 = fixtureB.getType(); - - IDynamicStack creator = - contactStacks[type1.index][type2.index].creator; - creator.push(contact); - } - - IWorldPool getPool() { - return _pool; - } - - /** - * Register a destruction listener. The listener is owned by you and must remain in scope. - * - * @param listener - */ + /// Register a destruction listener. The listener is owned by you and must remain in scope. + /// + /// @param listener void setDestructionListener(DestructionListener listener) { _destructionListener = listener; } - /** - * Register a contact filter to provide specific control over collision. Otherwise the default - * filter is used (_defaultFilter). The listener is owned by you and must remain in scope. - * - * @param filter - */ + /// Register a contact filter to provide specific control over collision. Otherwise the default + /// filter is used (_defaultFilter). The listener is owned by you and must remain in scope. + /// + /// @param filter void setContactFilter(ContactFilter filter) { _contactManager.contactFilter = filter; } - /** - * Register a contact event listener. The listener is owned by you and must remain in scope. - * - * @param listener - */ + /// Register a contact event listener. The listener is owned by you and must remain in scope. + /// + /// @param listener void setContactListener(ContactListener listener) { _contactManager.contactListener = listener; } - /** - * Register a routine for debug drawing. The debug draw functions are called inside with - * World.DrawDebugData method. The debug draw object is owned by you and must remain in scope. - * - * @param debugDraw - */ + /// Register a routine for debug drawing. The debug draw functions are called inside with + /// World.DrawDebugData method. The debug draw object is owned by you and must remain in scope. + /// + /// @param debugDraw void setDebugDraw(DebugDraw debugDraw) { debugDraw = debugDraw; } - /** - * create a rigid body given a definition. No reference to the definition is retained. - * - * @warning This function is locked during callbacks. - * @param def - * @return - */ + /// create a rigid body given a definition. No reference to the definition is retained. + /// + /// @warning This function is locked during callbacks. + /// @param def + /// @return Body createBody(BodyDef def) { assert(isLocked() == false); if (isLocked()) { return null; } // TODO djm pooling - Body b = new Body(def, this); + Body b = Body(def, this); // add to world doubly linked list b._prev = null; @@ -316,14 +174,11 @@ class World { return b; } - /** - * destroy a rigid body given a definition. No reference to the definition is retained. This - * function is locked during callbacks. - * - * @warning This automatically deletes all associated shapes and joints. - * @warning This function is locked during callbacks. - * @param body - */ + /// Destroys a rigid body given a definition. No reference to the definition is retained. This + /// function is locked during callbacks. + /// + /// @warning This automatically deletes all associated shapes and joints. + /// @warning This function is locked during callbacks. void destroyBody(Body body) { assert(_bodyCount > 0); assert(isLocked() == false); @@ -390,14 +245,10 @@ class World { // TODO djm recycle body } - /** - * create a joint to constrain bodies together. No reference to the definition is retained. This - * may cause the connected bodies to cease colliding. - * - * @warning This function is locked during callbacks. - * @param def - * @return - */ + /// create a joint to constrain bodies together. No reference to the definition is retained. + /// This may cause the connected bodies to cease colliding. + /// + /// @warning This function is locked during callbacks. Joint createJoint(JointDef def) { assert(isLocked() == false); if (isLocked()) { @@ -456,12 +307,10 @@ class World { return j; } - /** - * destroy a joint. This may cause the connected bodies to begin colliding. - * - * @warning This function is locked during callbacks. - * @param joint - */ + /// destroy a joint. This may cause the connected bodies to begin colliding. + /// + /// @warning This function is locked during callbacks. + /// @param joint void destroyJoint(Joint j) { assert(isLocked() == false); if (isLocked()) { @@ -545,24 +394,20 @@ class World { // djm pooling // TODO(srdjan): Make fields private. - final TimeStep step = new TimeStep(); - final Timer stepTimer = new Timer(); - final Timer tempTimer = new Timer(); - - /** - * Take a time step. This performs collision detection, integration, and constraint solution. - * - * @param timeStep the amount of time to simulate, this should not vary. - * @param velocityIterations for the velocity constraint solver. - * @param positionIterations for the position constraint solver. - */ + final TimeStep step = TimeStep(); + final Timer stepTimer = Timer(); + final Timer tempTimer = Timer(); + + /// Take a time step. This performs collision detection, integration, and constraint solution. + /// + /// @param timeStep the amount of time to simulate, this should not vary. + /// @param velocityIterations for the velocity constraint solver. + /// @param positionIterations for the position constraint solver. void stepDt(double dt, int velocityIterations, int positionIterations) { stepTimer.reset(); tempTimer.reset(); - // log.debug("Starting step"); // If new fixtures were added, we need to find the new contacts. if ((_flags & NEW_FIXTURE) == NEW_FIXTURE) { - // log.debug("There's a new fixture, lets look for new contacts"); _contactManager.findNewContacts(); _flags &= ~NEW_FIXTURE; } @@ -578,7 +423,7 @@ class World { step.inv_dt = 0.0; } - step.dtRatio = _inv_dt0 * dt; + step.dtRatio = _invDt0 * dt; step.warmStarting = _warmStarting; _profile.stepInit.record(tempTimer.getMilliseconds()); @@ -606,7 +451,7 @@ class World { } if (step.dt > 0.0) { - _inv_dt0 = step.inv_dt; + _invDt0 = step.inv_dt; } if ((_flags & CLEAR_FORCES) == CLEAR_FORCES) { @@ -614,18 +459,15 @@ class World { } _flags &= ~LOCKED; - // log.debug("ending step"); _profile.step.record(stepTimer.getMilliseconds()); } - /** - * Call this after you are done with time steps to clear the forces. You normally call this after - * each call to Step, unless you are performing sub-steps. By default, forces will be - * automatically cleared, so you don't need to call this function. - * - * @see setAutoClearForces - */ + /// Call this after you are done with time steps to clear the forces. You normally call this after + /// each call to Step, unless you are performing sub-steps. By default, forces will be + /// automatically cleared, so you don't need to call this function. + /// + /// @see setAutoClearForces void clearForces() { for (Body body = bodyList; body != null; body = body.getNext()) { body._force.setZero(); @@ -633,15 +475,12 @@ class World { } } - final Color3i color = new Color3i.zero(); - final Transform xf = new Transform.zero(); - final Vector2 cA = new Vector2.zero(); - final Vector2 cB = new Vector2.zero(); - final Vec2Array avs = new Vec2Array(); + final Color3i color = Color3i.zero(); + final Transform xf = Transform.zero(); + final Vector2 cA = Vector2.zero(); + final Vector2 cB = Vector2.zero(); - /** - * Call this to draw shapes and other debug draw data. - */ + /// Call this to draw shapes and other debug draw data. void drawDebugData() { if (debugDraw == null) { return; @@ -688,8 +527,8 @@ class World { c = c.getNext()) { Fixture fixtureA = c.fixtureA; Fixture fixtureB = c.fixtureB; - fixtureA.getAABB(c.getChildIndexA()).getCenterToOut(cA); - fixtureB.getAABB(c.getChildIndexB()).getCenterToOut(cB); + cA.setFrom(fixtureA.getAABB(c.getChildIndexA()).getCenter()); + cB.setFrom(fixtureB.getAABB(c.getChildIndexB()).getCenter()); debugDraw.drawSegment(cA, cB, color); } } @@ -707,7 +546,7 @@ class World { FixtureProxy proxy = f._proxies[i]; AABB aabb = _contactManager.broadPhase.getFatAABB(proxy.proxyId); if (aabb != null) { - List vs = avs.get(4); + List vs = List(4); vs[0].setValues(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].setValues(aabb.upperBound.x, aabb.lowerBound.y); vs[2].setValues(aabb.upperBound.x, aabb.upperBound.y); @@ -720,7 +559,7 @@ class World { } if ((flags & DebugDraw.CENTER_OF_MASS_BIT) != 0) { - final Color3i xfColor = new Color3i(255, 0, 0); + final Color3i xfColor = Color3i(255, 0, 0); for (Body b = bodyList; b != null; b = b.getNext()) { xf.set(b._transform); xf.p.setFrom(b.worldCenter); @@ -735,27 +574,23 @@ class World { debugDraw.flush(); } - final WorldQueryWrapper wqwrapper = new WorldQueryWrapper(); + final WorldQueryWrapper wqwrapper = WorldQueryWrapper(); - /** - * Query the world for all fixtures that potentially overlap the provided AABB. - * - * @param callback a user implemented callback class. - * @param aabb the query box. - */ + /// Query the world for all fixtures that potentially overlap the provided AABB. + /// + /// @param callback a user implemented callback class. + /// @param aabb the query box. void queryAABB(QueryCallback callback, AABB aabb) { wqwrapper.broadPhase = _contactManager.broadPhase; wqwrapper.callback = callback; _contactManager.broadPhase.query(wqwrapper, aabb); } - /** - * Query the world for all fixtures and particles that potentially overlap the provided AABB. - * - * @param callback a user implemented callback class. - * @param particleCallback callback for particles. - * @param aabb the query box. - */ + /// Query the world for all fixtures and particles that potentially overlap the provided AABB. + /// + /// @param callback a user implemented callback class. + /// @param particleCallback callback for particles. + /// @param aabb the query box. void queryAABBTwoCallbacks(QueryCallback callback, ParticleQueryCallback particleCallback, AABB aabb) { wqwrapper.broadPhase = _contactManager.broadPhase; @@ -764,28 +599,24 @@ class World { _particleSystem.queryAABB(particleCallback, aabb); } - /** - * Query the world for all particles that potentially overlap the provided AABB. - * - * @param particleCallback callback for particles. - * @param aabb the query box. - */ + /// Query the world for all particles that potentially overlap the provided AABB. + /// + /// @param particleCallback callback for particles. + /// @param aabb the query box. void queryAABBParticle(ParticleQueryCallback particleCallback, AABB aabb) { _particleSystem.queryAABB(particleCallback, aabb); } - final WorldRayCastWrapper wrcwrapper = new WorldRayCastWrapper(); - final RayCastInput input = new RayCastInput(); + final WorldRayCastWrapper wrcwrapper = WorldRayCastWrapper(); + final RayCastInput input = RayCastInput(); - /** - * 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 ray-cast ignores shapes that contain the - * starting point. - * - * @param callback a user implemented callback class. - * @param point1 the ray starting point - * @param point2 the ray ending point - */ + /// 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 ray-cast ignores shapes that contain the + /// starting point. + /// + /// @param callback a user implemented callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point void raycast(RayCastCallback callback, Vector2 point1, Vector2 point2) { wrcwrapper.broadPhase = _contactManager.broadPhase; wrcwrapper.callback = callback; @@ -795,16 +626,14 @@ class World { _contactManager.broadPhase.raycast(wrcwrapper, input); } - /** - * Ray-cast the world for all fixtures and particles in the path of the ray. Your callback - * controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes - * that contain the starting point. - * - * @param callback a user implemented callback class. - * @param particleCallback the particle callback class. - * @param point1 the ray starting point - * @param point2 the ray ending point - */ + /// Ray-cast the world for all fixtures and particles in the path of the ray. Your callback + /// controls whether you get the closest point, any point, or n-points. The ray-cast ignores shapes + /// that contain the starting point. + /// + /// @param callback a user implemented callback class. + /// @param particleCallback the particle callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point void raycastTwoCallBacks( RayCastCallback callback, ParticleRaycastCallback particleCallback, @@ -819,108 +648,68 @@ class World { _particleSystem.raycast(particleCallback, point1, point2); } - /** - * Ray-cast the world for all particles in the path of the ray. Your callback controls whether you - * get the closest point, any point, or n-points. - * - * @param particleCallback the particle callback class. - * @param point1 the ray starting point - * @param point2 the ray ending point - */ + /// Ray-cast the world for all particles in the path of the ray. Your callback controls whether you + /// get the closest point, any point, or n-points. + /// + /// @param particleCallback the particle callback class. + /// @param point1 the ray starting point + /// @param point2 the ray ending point void raycastParticle(ParticleRaycastCallback particleCallback, Vector2 point1, Vector2 point2) { _particleSystem.raycast(particleCallback, point1, point2); } - /** - * 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 the list. - * - * @return the head of the world contact list. - * @warning contacts are created and destroyed in the middle of a time step. Use ContactListener - * to avoid missing contacts. - */ + /// 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 the list. + /// + /// @return the head of the world contact list. + /// @warning contacts are created and destroyed in the middle of a time step. Use ContactListener + /// to avoid missing contacts. Contact getContactList() { return _contactManager.contactList; } - /** - * Get the number of broad-phase proxies. - * - * @return - */ + /// Get the number of broad-phase proxies. int getProxyCount() { return _contactManager.broadPhase.getProxyCount(); } - /** - * Get the number of contacts (each may have 0 or more contact points). - * - * @return - */ + /// Get the number of contacts (each may have 0 or more contact points). int getContactCount() { return _contactManager.contactCount; } - /** - * Gets the height of the dynamic tree - * - * @return - */ + /// Gets the height of the dynamic tree int getTreeHeight() { return _contactManager.broadPhase.getTreeHeight(); } - /** - * Gets the balance of the dynamic tree - * - * @return - */ + /// Gets the balance of the dynamic tree int getTreeBalance() { return _contactManager.broadPhase.getTreeBalance(); } - /** - * Gets the quality of the dynamic tree - * - * @return - */ + /// Gets the quality of the dynamic tree double getTreeQuality() { return _contactManager.broadPhase.getTreeQuality(); } - /** - * Change the global gravity vector. - * - * @param gravity - */ + /// Change the global gravity vector. void setGravity(Vector2 gravity) { _gravity.setFrom(gravity); } - /** - * Get the global gravity vector. - * - * @return - */ + /// Get the global gravity vector. Vector2 getGravity() { return _gravity; } - /** - * Is the world locked (in the middle of a time step). - * - * @return - */ + /// Is the world locked (in the middle of a time step). bool isLocked() { return (_flags & LOCKED) == LOCKED; } - /** - * Set flag to control automatic clearing of forces after each time step. - * - * @param flag - */ + /// Set flag to control automatic clearing of forces after each time step. void setAutoClearForces(bool flag) { if (flag) { _flags |= CLEAR_FORCES; @@ -929,19 +718,15 @@ class World { } } - /** - * Get the flag that controls automatic clearing of forces after each time step. - * - * @return - */ + /// Get the flag that controls automatic clearing of forces after each time step. bool getAutoClearForces() { return (_flags & CLEAR_FORCES) == CLEAR_FORCES; } - final Island island = new Island(); - List stack = - new List(10); // TODO djm find a good initial stack number; - final Timer broadphaseTimer = new Timer(); + final Island island = Island(); + // TODO djm find a good initial stack number; + List stack = List(10); + final Timer broadphaseTimer = Timer(); void solve(TimeStep step) { _profile.solveInit.startAccum(); @@ -971,7 +756,7 @@ class World { // Build and simulate all awake islands. int stackSize = _bodyCount; if (stack.length < stackSize) { - stack = new List(stackSize); + stack = List(stackSize); } for (Body seed = bodyList; seed != null; seed = seed._next) { if ((seed._flags & Body.ISLAND_FLAG) == Body.ISLAND_FLAG) { @@ -1106,13 +891,13 @@ class World { _profile.broadphase.record(broadphaseTimer.getMilliseconds()); } - final Island toiIsland = new Island(); - final TOIInput toiInput = new TOIInput(); - final TOIOutput toiOutput = new TOIOutput(); - final TimeStep subStep = new TimeStep(); - final List tempBodies = new List(2); - final Sweep backup1 = new Sweep(); - final Sweep backup2 = new Sweep(); + final Island toiIsland = Island(); + final TOIInput toiInput = TOIInput(); + final TOIOutput toiOutput = TOIOutput(); + final TimeStep subStep = TimeStep(); + final List tempBodies = List(2); + final Sweep backup1 = Sweep(); + final Sweep backup2 = Sweep(); void solveTOI(final TimeStep step) { final Island island = toiIsland; @@ -1210,7 +995,7 @@ class World { input.sweepB.set(bB._sweep); input.tMax = 1.0; - _pool.getTimeOfImpact().timeOfImpact(toiOutput, input); + toi.timeOfImpact(toiOutput, input); // Beta is the fraction of the remaining portion of the . double beta = toiOutput.t; @@ -1402,10 +1187,8 @@ class World { Transform xf2 = bodyB._transform; Vector2 x1 = xf1.p; Vector2 x2 = xf2.p; - Vector2 p1 = _pool.popVec2(); - Vector2 p2 = _pool.popVec2(); - joint.getAnchorA(p1); - joint.getAnchorB(p2); + Vector2 p1 = Vector2.copy(joint.getAnchorA()); + Vector2 p2 = Vector2.copy(joint.getAnchorB()); color.setFromRGBd(0.5, 0.8, 0.8); @@ -1439,7 +1222,6 @@ class World { debugDraw.drawSegment(p1, p2, color); debugDraw.drawSegment(x2, p2, color); } - _pool.pushVec2(2); } // NOTE this corresponds to the liquid test, so the debugdraw can draw @@ -1447,15 +1229,14 @@ class World { static int LIQUID_INT = 1234598372; double liquidLength = .12; double averageLinearVel = -1.0; - final Vector2 liquidOffset = new Vector2.zero(); - final Vector2 circCenterMoved = new Vector2.zero(); - final Color3i liquidColor = new Color3i.fromRGBd(.4, .4, 1.0); + final Vector2 liquidOffset = Vector2.zero(); + final Vector2 circCenterMoved = Vector2.zero(); + final Color3i liquidColor = Color3i.fromRGBd(.4, .4, 1.0); - final Vector2 center = new Vector2.zero(); - final Vector2 axis = new Vector2.zero(); - final Vector2 v1 = new Vector2.zero(); - final Vector2 v2 = new Vector2.zero(); - final Vec2Array tlvertices = new Vec2Array(); + final Vector2 center = Vector2.zero(); + final Vector2 axis = Vector2.zero(); + final Vector2 v1 = Vector2.zero(); + final Vector2 v2 = Vector2.zero(); void drawShape(Fixture fixture, Transform xf, Color3i color, bool wireframe) { switch (fixture.getType()) { @@ -1463,8 +1244,7 @@ class World { { final circle = fixture.getShape() as CircleShape; - // Vec2 center = Mul(xf, circle.m_p); - Transform.mulToOutUnsafeVec2(xf, circle.p, center); + center.setFrom(Transform.mulVec2(xf, circle.position)); double radius = circle.radius; xf.q.getXAxis(axis); @@ -1498,11 +1278,10 @@ class World { final poly = fixture.getShape() as PolygonShape; int vertexCount = poly.count; assert(vertexCount <= Settings.maxPolygonVertices); - List vertices = tlvertices.get(Settings.maxPolygonVertices); + List vertices = List(Settings.maxPolygonVertices); for (int i = 0; i < vertexCount; ++i) { - // vertices[i] = Mul(xf, poly.m_vertices[i]); - Transform.mulToOutUnsafeVec2(xf, poly.vertices[i], vertices[i]); + vertices[i] = Transform.mulVec2(xf, poly.vertices[i]); } if (wireframe) { debugDraw.drawPolygon(vertices, vertexCount, color); @@ -1514,8 +1293,8 @@ class World { case ShapeType.EDGE: { final edge = fixture.getShape() as EdgeShape; - Transform.mulToOutUnsafeVec2(xf, edge.vertex1, v1); - Transform.mulToOutUnsafeVec2(xf, edge.vertex2, v2); + v1.setFrom(Transform.mulVec2(xf, edge.vertex1)); + v2.setFrom(Transform.mulVec2(xf, edge.vertex2)); debugDraw.drawSegment(v1, v2, color); } break; @@ -1525,9 +1304,9 @@ class World { int count = chain._count; List vertices = chain._vertices; - Transform.mulToOutUnsafeVec2(xf, vertices[0], v1); + v1.setFrom(Transform.mulVec2(xf, vertices[0])); for (int i = 1; i < count; ++i) { - Transform.mulToOutUnsafeVec2(xf, vertices[i], v2); + v2.setFrom(Transform.mulVec2(xf, vertices[i])); debugDraw.drawSegment(v1, v2, color); debugDraw.drawCircle(v1, 0.05, color); v1.setFrom(v2); @@ -1560,15 +1339,13 @@ class World { } } - /** - * Create a particle whose properties have been defined. No reference to the definition is - * retained. A simulation step must occur before it's possible to interact with a newly created - * particle. For example, DestroyParticleInShape() will not destroy a particle until Step() has - * been called. - * - * @warning This function is locked during callbacks. - * @return the index of the particle. - */ + /// Create a particle whose properties have been defined. No reference to the definition is + /// retained. A simulation step must occur before it's possible to interact with a newly created + /// particle. For example, DestroyParticleInShape() will not destroy a particle until Step() has + /// been called. + /// + /// @warning This function is locked during callbacks. + /// @return the index of the particle. int createParticle(ParticleDef def) { assert(isLocked() == false); if (isLocked()) { @@ -1578,50 +1355,42 @@ class World { return p; } - /** - * Destroy a particle. The particle is removed after the next step. - * - * @param index - */ + /// Destroy a particle. The particle is removed after the next step. + /// + /// @param index void destroyParticle(int index) { destroyParticleFlag(index, false); } - /** - * Destroy a particle. The particle is removed after the next step. - * - * @param Index of the particle to destroy. - * @param Whether to call the destruction listener just before the particle is destroyed. - */ + /// Destroy a particle. The particle is removed after the next step. + /// + /// @param Index of the particle to destroy. + /// @param Whether to call the destruction listener just before the particle is destroyed. void destroyParticleFlag(int index, bool callDestructionListener) { _particleSystem.destroyParticle(index, callDestructionListener); } - /** - * Destroy particles inside a shape without enabling the destruction callback for destroyed - * particles. This function is locked during callbacks. For more information see - * DestroyParticleInShape(Shape&, Transform&,bool). - * - * @param Shape which encloses particles that should be destroyed. - * @param Transform applied to the shape. - * @warning This function is locked during callbacks. - * @return Number of particles destroyed. - */ + /// Destroy particles inside a shape without enabling the destruction callback for destroyed + /// particles. This function is locked during callbacks. For more information see + /// DestroyParticleInShape(Shape&, Transform&,bool). + /// + /// @param Shape which encloses particles that should be destroyed. + /// @param Transform applied to the shape. + /// @warning This function is locked during callbacks. + /// @return Number of particles destroyed. int destroyParticlesInShape(Shape shape, Transform xf) { return destroyParticlesInShapeFlag(shape, xf, false); } - /** - * Destroy particles inside a shape. This function is locked during callbacks. In addition, this - * function immediately destroys particles in the shape in contrast to DestroyParticle() which - * defers the destruction until the next simulation step. - * - * @param Shape which encloses particles that should be destroyed. - * @param Transform applied to the shape. - * @param Whether to call the world b2DestructionListener for each particle destroyed. - * @warning This function is locked during callbacks. - * @return Number of particles destroyed. - */ + /// Destroy particles inside a shape. This function is locked during callbacks. In addition, this + /// function immediately destroys particles in the shape in contrast to DestroyParticle() which + /// defers the destruction until the next simulation step. + /// + /// @param Shape which encloses particles that should be destroyed. + /// @param Transform applied to the shape. + /// @param Whether to call the world b2DestructionListener for each particle destroyed. + /// @warning This function is locked during callbacks. + /// @return Number of particles destroyed. int destroyParticlesInShapeFlag( Shape shape, Transform xf, bool callDestructionListener) { assert(isLocked() == false); @@ -1632,12 +1401,10 @@ class World { shape, xf, callDestructionListener); } - /** - * Create a particle group whose properties have been defined. No reference to the definition is - * retained. - * - * @warning This function is locked during callbacks. - */ + /// Create a particle group whose properties have been defined. No reference to the definition is + /// retained. + /// + /// @warning This function is locked during callbacks. ParticleGroup createParticleGroup(ParticleGroupDef def) { assert(isLocked() == false); if (isLocked()) { @@ -1647,13 +1414,11 @@ class World { return g; } - /** - * Join two particle groups. - * - * @param the first group. Expands to encompass the second group. - * @param the second group. It is destroyed. - * @warning This function is locked during callbacks. - */ + /// Join two particle groups. + /// + /// @param the first group. Expands to encompass the second group. + /// @param the second group. It is destroyed. + /// @warning This function is locked during callbacks. void joinParticleGroups(ParticleGroup groupA, ParticleGroup groupB) { assert(isLocked() == false); if (isLocked()) { @@ -1662,13 +1427,11 @@ class World { _particleSystem.joinParticleGroups(groupA, groupB); } - /** - * Destroy particles in a group. This function is locked during callbacks. - * - * @param The particle group to destroy. - * @param Whether to call the world b2DestructionListener for each particle is destroyed. - * @warning This function is locked during callbacks. - */ + /// Destroy particles in a group. This function is locked during callbacks. + /// + /// @param The particle group to destroy. + /// @param Whether to call the world b2DestructionListener for each particle is destroyed. + /// @warning This function is locked during callbacks. void destroyParticlesInGroupFlag( ParticleGroup group, bool callDestructionListener) { assert(isLocked() == false); @@ -1678,144 +1441,114 @@ class World { _particleSystem.destroyParticlesInGroup(group, callDestructionListener); } - /** - * Destroy particles in a group without enabling the destruction callback for destroyed particles. - * This function is locked during callbacks. - * - * @param The particle group to destroy. - * @warning This function is locked during callbacks. - */ + /// Destroy particles in a group without enabling the destruction callback for destroyed particles. + /// This function is locked during callbacks. + /// + /// @param The particle group to destroy. + /// @warning This function is locked during callbacks. void destroyParticlesInGroup(ParticleGroup group) { destroyParticlesInGroupFlag(group, false); } - /** - * Get the world particle group list. With the returned group, use ParticleGroup::GetNext to get - * the next group in the world list. A NULL group indicates the end of the list. - * - * @return the head of the world particle group list. - */ + /// Get the world particle group list. With the returned group, use ParticleGroup::GetNext to get + /// the next group in the world list. A NULL group indicates the end of the list. + /// + /// @return the head of the world particle group list. List getParticleGroupList() { return _particleSystem.getParticleGroupList(); } - /** - * Get the number of particle groups. - * - * @return - */ + /// Get the number of particle groups. + /// + /// @return int getParticleGroupCount() { return _particleSystem.getParticleGroupCount(); } - /** - * Get the number of particles. - * - * @return - */ + /// Get the number of particles. + /// + /// @return int getParticleCount() { return _particleSystem.getParticleCount(); } - /** - * Get the maximum number of particles. - * - * @return - */ + /// Get the maximum number of particles. + /// + /// @return int getParticleMaxCount() { return _particleSystem.getParticleMaxCount(); } - /** - * Set the maximum number of particles. - * - * @param count - */ + /// Set the maximum number of particles. + /// + /// @param count void setParticleMaxCount(int count) { _particleSystem.setParticleMaxCount(count); } - /** - * Change the particle density. - * - * @param density - */ + /// Change the particle density. + /// + /// @param density void setParticleDensity(double density) { _particleSystem.setParticleDensity(density); } - /** - * Get the particle density. - * - * @return - */ + /// Get the particle density. + /// + /// @return double getParticleDensity() { return _particleSystem.getParticleDensity(); } - /** - * Change the particle gravity scale. Adjusts the effect of the global gravity vector on - * particles. Default value is 1.0. - * - * @param gravityScale - */ + /// Change the particle gravity scale. Adjusts the effect of the global gravity vector on + /// particles. Default value is 1.0. + /// + /// @param gravityScale void setParticleGravityScale(double gravityScale) { _particleSystem.setParticleGravityScale(gravityScale); } - /** - * Get the particle gravity scale. - * - * @return - */ + /// Get the particle gravity scale. + /// + /// @return double getParticleGravityScale() { return _particleSystem.getParticleGravityScale(); } - /** - * Damping is used to reduce the velocity of particles. The damping parameter can be larger than - * 1.0 but the damping effect becomes sensitive to the time step when the damping parameter is - * large. - * - * @param damping - */ + /// Damping is used to reduce the velocity of particles. The damping parameter can be larger than + /// 1.0 but the damping effect becomes sensitive to the time step when the damping parameter is + /// large. + /// + /// @param damping void setParticleDamping(double damping) { _particleSystem.setParticleDamping(damping); } - /** - * Get damping for particles - * - * @return - */ + /// Get damping for particles + /// + /// @return double getParticleDamping() { return _particleSystem.getParticleDamping(); } - /** - * Change the particle radius. You should set this only once, on world start. If you change the - * radius during execution, existing particles may explode, shrink, or behave unexpectedly. - * - * @param radius - */ + /// Change the particle radius. You should set this only once, on world start. If you change the + /// radius during execution, existing particles may explode, shrink, or behave unexpectedly. + /// + /// @param radius void setParticleRadius(double radius) { _particleSystem.setParticleRadius(radius); } - /** - * Get the particle radius. - * - * @return - */ + /// Get the particle radius. + /// + /// @return double getParticleRadius() { return _particleSystem.getParticleRadius(); } - /** - * Get the particle data. @return the pointer to the head of the particle data. - * - * @return - */ + /// Get the particle data. @return the pointer to the head of the particle data. + /// + /// @return List getParticleFlagsBuffer() { return _particleSystem.getParticleFlagsBuffer(); } @@ -1840,12 +1573,10 @@ class World { return _particleSystem.getParticleUserDataBuffer(); } - /** - * Set a buffer for particle data. - * - * @param buffer is a pointer to a block of memory. - * @param size is the number of values in the block. - */ + /// Set a buffer for particle data. + /// + /// @param buffer is a pointer to a block of memory. + /// @param size is the number of values in the block. void setParticleFlagsBuffer(List buffer, int capacity) { _particleSystem.setParticleFlagsBuffer(buffer, capacity); } @@ -1866,11 +1597,9 @@ class World { _particleSystem.setParticleUserDataBuffer(buffer, capacity); } - /** - * Get contacts between particles - * - * @return - */ + /// Get contacts between particles + /// + /// @return List getParticleContacts() { return _particleSystem.contactBuffer; } @@ -1879,11 +1608,9 @@ class World { return _particleSystem.contactCount; } - /** - * Get contacts between particles and bodies - * - * @return - */ + /// Get contacts between particles and bodies + /// + /// @return List getParticleBodyContacts() { return _particleSystem.bodyContactBuffer; } @@ -1892,11 +1619,9 @@ class World { return _particleSystem.bodyContactCount; } - /** - * Compute the kinetic energy that can be lost by damping force - * - * @return - */ + /// Compute the kinetic energy that can be lost by damping force + /// + /// @return double computeParticleCollisionEnergy() { return _particleSystem.computeParticleCollisionEnergy(); } @@ -1921,9 +1646,9 @@ class WorldQueryWrapper implements TreeCallback { class WorldRayCastWrapper implements TreeRayCastCallback { // djm pooling - final RayCastOutput _output = new RayCastOutput(); - final Vector2 _temp = new Vector2.zero(); - final Vector2 _point = new Vector2.zero(); + final RayCastOutput _output = RayCastOutput(); + final Vector2 _temp = Vector2.zero(); + final Vector2 _point = Vector2.zero(); double raycastCallback(RayCastInput input, int nodeId) { final userData = broadPhase.getUserData(nodeId) as FixtureProxy; diff --git a/lib/src/math_utils.dart b/lib/src/math_utils.dart index 7f4eae0..c60953b 100644 --- a/lib/src/math_utils.dart +++ b/lib/src/math_utils.dart @@ -1,58 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d.math_utils; import 'dart:math' as Math; import 'vector_math.dart'; -const double TWOPI = Math.PI * 2.0; +const double TWOPI = Math.pi * 2.0; double distanceSquared(Vector2 v1, Vector2 v2) => v1.distanceToSquared(v2); double distance(Vector2 v1, Vector2 v2) => v1.distanceTo(v2); -/** Returns the closest value to 'a' that is in between 'low' and 'high' */ +/// Returns the closest value to 'a' that is in between 'low' and 'high' double clampDouble(final double a, final double low, final double high) => - Math.max(low, Math.min(a, high)); + Math.max(low, Math.min(a, high)); Vector2 clampVec2(final Vector2 a, final Vector2 low, final Vector2 high) { - final Vector2 min = new Vector2.zero(); - min.x = a.x < high.x ? a.x : high.x; - min.y = a.y < high.y ? a.y : high.y; - min.x = low.x > min.x ? low.x : min.x; - min.y = low.y > min.y ? low.y : min.y; - return min; + return Vector2( + Math.max(low.x, Math.min(a.x, high.x)), + Math.max(low.y, Math.min(a.y, high.y)), + ); } -/** - * Given a value within the range specified by [fromMin] and [fromMax], - * returns a value with the same relative position in the range specified - * from [toMin] and [toMax]. For example, given a [val] of 2 in the - * "from range" of 0-4, and a "to range" of 10-20, would return 15. - */ +/// Given a value within the range specified by [fromMin] and [fromMax], +/// returns a value with the same relative position in the range specified +/// from [toMin] and [toMax]. For example, given a [val] of 2 in the +/// "from range" of 0-4, and a "to range" of 10-20, would return 15. double translateAndScale( double val, double fromMin, double fromMax, double toMin, double toMax) { final double mult = (val - fromMin) / (fromMax - fromMin); @@ -61,14 +33,12 @@ double translateAndScale( } bool approxEquals(num expected, num actual, [num tolerance = null]) { - if (tolerance == null) { - tolerance = (expected / 1e4).abs(); - } + tolerance ??= (expected / 1e4).abs(); return ((expected - actual).abs() <= tolerance); } Vector2 crossDblVec2(double s, Vector2 a) { - return new Vector2(-s * a.y, s * a.x); + return Vector2(-s * a.y, s * a.x); } bool vector2Equals(Vector2 a, Vector2 b) { @@ -82,17 +52,17 @@ bool vector2IsValid(Vector2 v) { return !v.x.isNaN && !v.x.isInfinite && !v.y.isNaN && !v.y.isInfinite; } -void matrix3MulToOutUnsafe(Matrix3 A, Vector3 v, Vector3 out) { - assert(out != v); - out.x = v.x * A.entry(0, 0) + v.y * A.entry(0, 1) + v.z * A.entry(0, 2); - out.y = v.x * A.entry(1, 0) + v.y * A.entry(1, 1) + v.z * A.entry(1, 2); - out.z = v.x * A.entry(2, 0) + v.y * A.entry(2, 1) + v.z * A.entry(2, 2); +Vector3 matrix3Mul(Matrix3 A, Vector3 v) { + final x = v.x * A.entry(0, 0) + v.y * A.entry(0, 1) + v.z * A.entry(0, 2); + final y = v.x * A.entry(1, 0) + v.y * A.entry(1, 1) + v.z * A.entry(1, 2); + final z = v.x * A.entry(2, 0) + v.y * A.entry(2, 1) + v.z * A.entry(2, 2); + return Vector3(x, y, z); } -void matrix3Mul22ToOutUnsafe(Matrix3 A, Vector2 v, Vector2 out) { - assert(v != out); - out.y = A.entry(1, 0) * v.x + A.entry(1, 1) * v.y; - out.x = A.entry(0, 0) * v.x + A.entry(0, 1) * v.y; +Vector2 matrix3Mul22(Matrix3 A, Vector2 v) { + final y = A.entry(1, 0) * v.x + A.entry(1, 1) * v.y; + final x = A.entry(0, 0) * v.x + A.entry(0, 1) * v.y; + return Vector2(x, y); } void matrix3GetInverse22(Matrix3 m, Matrix3 M) { @@ -117,7 +87,7 @@ void matrix3GetInverse22(Matrix3 m, Matrix3 M) { M.setValues(ex_x, ex_y, ex_z, ey_x, ey_y, ey_z, ez_x, ez_y, ez_z); } -// / Returns the zero matrix if singular. +/// Returns the zero matrix if singular. void matrix3GetSymInverse33(Matrix3 m, Matrix3 M) { double bx = m.entry(1, 1) * m.entry(2, 2) - m.entry(2, 1) * m.entry(1, 2); double by = m.entry(2, 1) * m.entry(0, 2) - m.entry(0, 1) * m.entry(2, 2); diff --git a/lib/src/particle/particle_body_contact.dart b/lib/src/particle/particle_body_contact.dart index 2066e9b..53181d2 100644 --- a/lib/src/particle/particle_body_contact.dart +++ b/lib/src/particle/particle_body_contact.dart @@ -1,38 +1,18 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleBodyContact { - /** Index of the particle making contact. */ + /// Index of the particle making contact. int index = 0; - /** The body making contact. */ + + /// The body making contact. Body body; - /** Weight of the contact. A value between 0.0f and 1.0f. */ + + /// Weight of the contact. A value between 0.0f and 1.0f. double weight = 0.0; - /** The normalized direction from the particle to the body. */ - final Vector2 normal = new Vector2.zero(); - /** The effective mass used in calculating force. */ + + /// The normalized direction from the particle to the body. + final Vector2 normal = Vector2.zero(); + + /// The effective mass used in calculating force. double mass = 0.0; } diff --git a/lib/src/particle/particle_color.dart b/lib/src/particle/particle_color.dart index a8ca488..48716af 100644 --- a/lib/src/particle/particle_color.dart +++ b/lib/src/particle/particle_color.dart @@ -1,36 +1,8 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * Small color object for each particle - * - * @author dmurph - */ +/// Small color object for each particle class ParticleColor { - Int8List _data = new Int8List(4); + Int8List _data = Int8List(4); void set r(int v) { _data[0] = v; diff --git a/lib/src/particle/particle_contact.dart b/lib/src/particle/particle_contact.dart index 979c293..81fe3bf 100644 --- a/lib/src/particle/particle_contact.dart +++ b/lib/src/particle/particle_contact.dart @@ -1,37 +1,16 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleContact { - /** Indices of the respective particles making contact. */ + /// Indices of the respective particles making contact. int indexA = 0; int indexB = 0; - /** The logical sum of the particle behaviors that have been set. */ + + /// The logical sum of the particle behaviors that have been set. int flags = 0; - /** Weight of the contact. A value between 0.0f and 1.0f. */ + + /// Weight of the contact. A value between 0.0f and 1.0f. double weight = 0.0; - /** The normalized direction from A to B. */ - final Vector2 normal = new Vector2.zero(); + + /// The normalized direction from A to B. + final Vector2 normal = Vector2.zero(); } diff --git a/lib/src/particle/particle_def.dart b/lib/src/particle/particle_def.dart index 52606a0..b8746d6 100644 --- a/lib/src/particle/particle_def.dart +++ b/lib/src/particle/particle_def.dart @@ -1,46 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleDef { - /** - * Specifies the type of particle. A particle may be more than one type. Multiple types are - * chained by logical sums, for example: pd.flags = ParticleType.b2_elasticParticle | - * ParticleType.b2_viscousParticle. - */ + /// Specifies the type of particle. A particle may be more than one type. Multiple types are + /// chained by logical sums, for example: pd.flags = ParticleType.b2_elasticParticle | + /// ParticleType.b2_viscousParticle. int flags = 0; - /** The world position of the particle. */ - final Vector2 position = new Vector2.zero(); + /// The world position of the particle. + final Vector2 position = Vector2.zero(); - /** The linear velocity of the particle in world co-ordinates. */ - final Vector2 velocity = new Vector2.zero(); + /// The linear velocity of the particle in world co-ordinates. + final Vector2 velocity = Vector2.zero(); - /** The color of the particle. */ + /// The color of the particle. ParticleColor color; - /** Use this to store application-specific body data. */ + /// Use this to store application-specific body data. Object userData; } diff --git a/lib/src/particle/particle_group.dart b/lib/src/particle/particle_group.dart index 5f4bdb1..7f667e1 100644 --- a/lib/src/particle/particle_group.dart +++ b/lib/src/particle/particle_group.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleGroup { @@ -36,10 +12,10 @@ class ParticleGroup { int _timestamp = 0; double _mass = 0.0; double _inertia = 0.0; - final Vector2 _center = new Vector2.zero(); - final Vector2 _linearVelocity = new Vector2.zero(); + final Vector2 _center = Vector2.zero(); + final Vector2 _linearVelocity = Vector2.zero(); double _angularVelocity = 0.0; - final Transform _transform = new Transform.zero(); + final Transform _transform = Transform.zero(); bool _destroyAutomatically = false; bool _toBeDestroyed = false; diff --git a/lib/src/particle/particle_group_def.dart b/lib/src/particle/particle_group_def.dart index 84e3b36..8a97e5f 100644 --- a/lib/src/particle/particle_group_def.dart +++ b/lib/src/particle/particle_group_def.dart @@ -1,73 +1,41 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * A particle group definition holds all the data needed to construct a particle group. You can - * safely re-use these definitions. - */ +/// A particle group definition holds all the data needed to construct a particle group. You can +/// safely re-use these definitions. class ParticleGroupDef { - /** The particle-behavior flags. */ + /// The particle-behavior flags. int flags = 0; - /** The group-construction flags. */ + /// The group-construction flags. int groupFlags = 0; - /** - * The world position of the group. Moves the group's shape a distance equal to the value of - * position. - */ - final Vector2 position = new Vector2.zero(); + /// The world position of the group. Moves the group's shape a distance equal to the value of + /// position. + final Vector2 position = Vector2.zero(); - /** - * The world angle of the group in radians. Rotates the shape by an angle equal to the value of - * angle. - */ + /// The world angle of the group in radians. Rotates the shape by an angle equal to the value of + /// angle. double angle = 0.0; - /** The linear velocity of the group's origin in world co-ordinates. */ - final Vector2 linearVelocity = new Vector2.zero(); + /// The linear velocity of the group's origin in world co-ordinates. + final Vector2 linearVelocity = Vector2.zero(); - /** The angular velocity of the group. */ + /// The angular velocity of the group. double angularVelocity = 0.0; - /** The color of all particles in the group. */ + /// The color of all particles in the group. ParticleColor color; - /** - * The strength of cohesion among the particles in a group with flag b2_elasticParticle or - * b2_springParticle. - */ + /// The strength of cohesion among the particles in a group with flag b2_elasticParticle or + /// b2_springParticle. double strength = 1.0; - /** Shape containing the particle group. */ + /// Shape containing the particle group. Shape shape; - /** If true, destroy the group automatically after its last particle has been destroyed. */ + /// If true, destroy the group automatically after its last particle has been destroyed. bool destroyAutomatically = true; - /** Use this to store application-specific group data. */ + /// Use this to store application-specific group data. Object userData; } diff --git a/lib/src/particle/particle_group_type.dart b/lib/src/particle/particle_group_type.dart index b7152f9..a78af3f 100644 --- a/lib/src/particle/particle_group_type.dart +++ b/lib/src/particle/particle_group_type.dart @@ -1,32 +1,9 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleGroupType { - /** resists penetration */ + /// resists penetration static const int b2_solidParticleGroup = 1 << 0; - /** keeps its shape */ + + /// keeps its shape static const int b2_rigidParticleGroup = 1 << 1; } diff --git a/lib/src/particle/particle_system.dart b/lib/src/particle/particle_system.dart index cfe6dd0..0656ff7 100644 --- a/lib/src/particle/particle_system.dart +++ b/lib/src/particle/particle_system.dart @@ -1,27 +1,3 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; class ParticleBuffer { @@ -38,7 +14,7 @@ class ParticleBufferInt { int userSuppliedCapacity; } -/** Connection between two particles */ +/// Connection between two particles class PsPair { int indexA = 0; int indexB = 0; @@ -47,18 +23,16 @@ class PsPair { double distance = 0.0; } -/** Connection between three particles */ +/// Connection between three particles class PsTriad { int indexA = 0, indexB = 0, indexC = 0; int flags = 0; double strength = 0.0; - final Vector2 pa = new Vector2.zero(), - pb = new Vector2.zero(), - pc = new Vector2.zero(); + final Vector2 pa = Vector2.zero(), pb = Vector2.zero(), pc = Vector2.zero(); double ka = 0.0, kb = 0.0, kc = 0.0, s = 0.0; } -/** Used for detecting particle contacts */ +/// Used for detecting particle contacts class PsProxy implements Comparable { int index = 0; int tag = 0; @@ -126,10 +100,10 @@ class DestroyParticlesInShapeCallback implements ParticleQueryCallback { class UpdateBodyContactsCallback implements QueryCallback { ParticleSystem system; - final Vector2 _tempVec = new Vector2.zero(); + final Vector2 _tempVec = Vector2.zero(); static ParticleBodyContact allocParticleBodyContact() => - new ParticleBodyContact(); + ParticleBodyContact(); bool reportFixture(Fixture fixture) { if (fixture.isSensor()) { @@ -211,11 +185,11 @@ class UpdateBodyContactsCallback implements QueryCallback { } } -PsTriad allocPsTriad() => new PsTriad(); +PsTriad allocPsTriad() => PsTriad(); // Callback used with VoronoiDiagram. class CreateParticleGroupCallback implements VoronoiDiagramCallback { - void callback(int a, int b, int c) { + void call(int a, int b, int c) { final Vector2 pa = system.positionBuffer.data[a]; final Vector2 pb = system.positionBuffer.data[b]; final Vector2 pc = system.positionBuffer.data[c]; @@ -270,7 +244,7 @@ class CreateParticleGroupCallback implements VoronoiDiagramCallback { // Callback used with VoronoiDiagram. class JoinParticleGroupsCallback implements VoronoiDiagramCallback { - void callback(int a, int b, int c) { + void call(int a, int b, int c) { // Create a triad if it will contain particles from both groups. int countA = ((a < groupB._firstIndex) ? 1 : 0) + ((b < groupB._firstIndex) ? 1 : 0) + @@ -336,10 +310,8 @@ class SolveCollisionCallback implements QueryCallback { ParticleSystem system; TimeStep step; - final RayCastInput input = new RayCastInput(); - final RayCastOutput output = new RayCastOutput(); - final Vector2 tempVec = new Vector2.zero(); - final Vector2 tempVec2 = new Vector2.zero(); + final RayCastInput input = RayCastInput(); + final RayCastOutput output = RayCastOutput(); bool reportFixture(Fixture fixture) { if (fixture.isSensor()) { @@ -377,20 +349,20 @@ class SolveCollisionCallback implements QueryCallback { aabblowerBoundy <= ap.y && ap.y <= aabbupperBoundy) { Vector2 av = system.velocityBuffer.data[a]; - final Vector2 temp = tempVec; - Transform.mulTransToOutUnsafeVec2(body._xf0, ap, temp); - Transform.mulToOutUnsafeVec2(body._transform, temp, input.p1); + final Vector2 temp = Transform.mulTransVec2(body._xf0, ap); + input.p1.setFrom(Transform.mulVec2(body._transform, temp)); input.p2.x = ap.x + step.dt * av.x; input.p2.y = ap.y + step.dt * av.y; input.maxFraction = 1.0; if (fixture.raycast(output, input, childIndex)) { - final Vector2 p = tempVec; - p.x = (1 - output.fraction) * input.p1.x + - output.fraction * input.p2.x + - Settings.linearSlop * output.normal.x; - p.y = (1 - output.fraction) * input.p1.y + - output.fraction * input.p2.y + - Settings.linearSlop * output.normal.y; + final Vector2 p = Vector2( + (1 - output.fraction) * input.p1.x + + output.fraction * input.p2.x + + Settings.linearSlop * output.normal.x, + (1 - output.fraction) * input.p1.y + + output.fraction * input.p2.y + + Settings.linearSlop * output.normal.y, + ); final double vx = step.inv_dt * (p.x - ap.x); final double vy = step.inv_dt * (p.y - ap.y); @@ -401,9 +373,7 @@ class SolveCollisionCallback implements QueryCallback { final double ay = particleMass * (av.y - vy); Vector2 b = output.normal; final double fdn = ax * b.x + ay * b.y; - final Vector2 f = tempVec2; - f.x = fdn * b.x; - f.y = fdn * b.y; + final Vector2 f = Vector2(fdn * b.x, fdn * b.y); body.applyLinearImpulse(f, p, true); } } @@ -436,11 +406,13 @@ class ParticleSystemTest { } class ParticleSystem { - /** All particle types that require creating pairs */ + /// All particle types that require creating pairs static const int k_pairFlags = ParticleType.b2_springParticle; - /** All particle types that require creating triads */ + + /// All particle types that require creating triads static const int k_triadFlags = ParticleType.b2_elasticParticle; - /** All particle types that require computing depth */ + + /// All particle types that require computing depth static const int k_noPressureFlags = ParticleType.b2_powderParticle; static const int xTruncBits = 12; @@ -527,11 +499,11 @@ class ParticleSystem { World world; - static Vector2 allocVec2() => new Vector2.zero(); - static Object allocObject() => new Object(); - static ParticleColor allocParticleColor() => new ParticleColor(); - static ParticleGroup allocParticleGroup() => new ParticleGroup(); - static PsProxy allocPsProxy() => new PsProxy(); + static Vector2 allocVec2() => Vector2.zero(); + static Object allocObject() => Object(); + static ParticleColor allocParticleColor() => ParticleColor(); + static ParticleGroup allocParticleGroup() => ParticleGroup(); + static PsProxy allocPsProxy() => PsProxy(); ParticleSystem(World world) { world = world; @@ -547,11 +519,11 @@ class ParticleSystem { ejectionStrength = 0.5; colorMixingStrength = 0.5; - flagsBuffer = new ParticleBufferInt(); - positionBuffer = new ParticleBuffer(allocVec2); - velocityBuffer = new ParticleBuffer(allocVec2); - colorBuffer = new ParticleBuffer(allocParticleColor); - userDataBuffer = new ParticleBuffer(allocObject); + flagsBuffer = ParticleBufferInt(); + positionBuffer = ParticleBuffer(allocVec2); + velocityBuffer = ParticleBuffer(allocVec2); + colorBuffer = ParticleBuffer(allocParticleColor); + userDataBuffer = ParticleBuffer(allocObject); } int createParticle(ParticleDef def) { @@ -647,7 +619,7 @@ class ParticleSystem { List requestParticleBuffer(List buffer, T allocClosure()) { if (buffer == null) { - buffer = new List(internalAllocatedCapacity); + buffer = List(internalAllocatedCapacity); for (int i = 0; i < internalAllocatedCapacity; i++) { try { buffer[i] = allocClosure(); @@ -661,7 +633,7 @@ class ParticleSystem { Float64List requestParticleBufferFloat64(Float64List buffer) { if (buffer == null) { - buffer = new Float64List(internalAllocatedCapacity); + buffer = Float64List(internalAllocatedCapacity); } return buffer; } @@ -674,9 +646,9 @@ class ParticleSystem { flagsBuffer.data[index] |= flags; } - final AABB _temp = new AABB(); + final AABB _temp = AABB(); final DestroyParticlesInShapeCallback _dpcallback = - new DestroyParticlesInShapeCallback(); + DestroyParticlesInShapeCallback(); int destroyParticlesInShape( Shape shape, Transform xf, bool callDestructionListener) { @@ -693,13 +665,13 @@ class ParticleSystem { } } - final AABB _temp2 = new AABB(); - final Vector2 _tempVec = new Vector2.zero(); - final Transform _tempTransform = new Transform.zero(); - final Transform _tempTransform2 = new Transform.zero(); + final AABB _temp2 = AABB(); + final Vector2 _tempVec = Vector2.zero(); + final Transform _tempTransform = Transform.zero(); + final Transform _tempTransform2 = Transform.zero(); CreateParticleGroupCallback _createParticleGroupCallback = - new CreateParticleGroupCallback(); - final ParticleDef _tempParticleDef = new ParticleDef(); + CreateParticleGroupCallback(); + final ParticleDef _tempParticleDef = ParticleDef(); ParticleGroup createParticleGroup(ParticleGroupDef groupDef) { double stride = getParticleStride(); @@ -738,7 +710,7 @@ class ParticleSystem { p.x = x; p.y = y; if (shape.testPoint(identity, p)) { - Transform.mulToOutVec2(transform, p, p); + p.setFrom(Transform.mulVec2(transform, p)); particleDef.position.x = p.x; particleDef.position.y = p.y; p.sub(groupDef.position); @@ -752,7 +724,7 @@ class ParticleSystem { } int lastIndex = count; - ParticleGroup group = new ParticleGroup(); + ParticleGroup group = ParticleGroup(); group._system = this; group._firstIndex = firstIndex; group._lastIndex = lastIndex; @@ -805,7 +777,7 @@ class ParticleSystem { } } if ((groupDef.flags & k_triadFlags) != 0) { - VoronoiDiagram diagram = new VoronoiDiagram(lastIndex - firstIndex); + VoronoiDiagram diagram = VoronoiDiagram(lastIndex - firstIndex); for (int i = firstIndex; i < lastIndex; i++) { diagram.addGenerator(positionBuffer.data[i], i); } @@ -822,7 +794,7 @@ class ParticleSystem { return group; } - static PsPair allocPsPair() => new PsPair(); + static PsPair allocPsPair() => PsPair(); void joinParticleGroups(ParticleGroup groupA, ParticleGroup groupB) { assert(groupA != groupB); @@ -873,14 +845,14 @@ class ParticleSystem { } if ((particleFlags & k_triadFlags) != 0) { VoronoiDiagram diagram = - new VoronoiDiagram(groupB._lastIndex - groupA._firstIndex); + VoronoiDiagram(groupB._lastIndex - groupA._firstIndex); for (int i = groupA._firstIndex; i < groupB._lastIndex; i++) { if ((flagsBuffer.data[i] & ParticleType.b2_zombieParticle) == 0) { diagram.addGenerator(positionBuffer.data[i], i); } } diagram.generate(getParticleStride() / 2); - JoinParticleGroupsCallback callback = new JoinParticleGroupsCallback(); + JoinParticleGroupsCallback callback = JoinParticleGroupsCallback(); callback.system = this; callback.groupA = groupA; callback.groupB = groupB; @@ -947,7 +919,7 @@ class ParticleSystem { depthBuffer = requestParticleBufferFloat64(depthBuffer); for (int i = group._firstIndex; i < group._lastIndex; i++) { double w = accumulationBuffer[i]; - depthBuffer[i] = w < 0.8 ? 0.0 : double.MAX_FINITE; + depthBuffer[i] = w < 0.8 ? 0.0 : double.maxFinite; } int interationCount = group.getParticleCount(); for (int t = 0; t < interationCount; t++) { @@ -981,7 +953,7 @@ class ParticleSystem { } for (int i = group._firstIndex; i < group._lastIndex; i++) { double p = depthBuffer[i]; - if (p < double.MAX_FINITE) { + if (p < double.maxFinite) { depthBuffer[i] *= particleDiameter; } else { depthBuffer[i] = 0.0; @@ -989,7 +961,7 @@ class ParticleSystem { } } - static ParticleContact allocParticleContact() => new ParticleContact(); + static ParticleContact allocParticleContact() => ParticleContact(); void addContact(int a, int b) { assert(a != b); @@ -1009,7 +981,7 @@ class ParticleSystem { contactBuffer, oldCapacity, newCapacity, allocParticleContact); contactCapacity = newCapacity; } - double invD = d2 != 0 ? Math.sqrt(1 / d2) : double.MAX_FINITE; + double invD = d2 != 0 ? Math.sqrt(1 / d2) : double.maxFinite; ParticleContact contact = contactBuffer[contactCount]; contact.indexA = a; contact.indexB = b; @@ -1073,15 +1045,14 @@ class ParticleSystem { } } - final UpdateBodyContactsCallback _ubccallback = - new UpdateBodyContactsCallback(); + final UpdateBodyContactsCallback _ubccallback = UpdateBodyContactsCallback(); void updateBodyContacts() { final AABB aabb = _temp; - aabb.lowerBound.x = double.MAX_FINITE; - aabb.lowerBound.y = double.MAX_FINITE; - aabb.upperBound.x = -double.MAX_FINITE; - aabb.upperBound.y = -double.MAX_FINITE; + aabb.lowerBound.x = double.maxFinite; + aabb.lowerBound.y = double.maxFinite; + aabb.upperBound.x = -double.maxFinite; + aabb.upperBound.y = -double.maxFinite; for (int i = 0; i < count; i++) { Vector2 p = positionBuffer.data[i]; Vector2.min(aabb.lowerBound, p, aabb.lowerBound); @@ -1097,16 +1068,16 @@ class ParticleSystem { world.queryAABB(_ubccallback, aabb); } - SolveCollisionCallback _sccallback = new SolveCollisionCallback(); + SolveCollisionCallback _sccallback = SolveCollisionCallback(); void solveCollision(TimeStep step) { final AABB aabb = _temp; final Vector2 lowerBound = aabb.lowerBound; final Vector2 upperBound = aabb.upperBound; - lowerBound.x = double.MAX_FINITE; - lowerBound.y = double.MAX_FINITE; - upperBound.x = -double.MAX_FINITE; - upperBound.y = -double.MAX_FINITE; + lowerBound.x = double.maxFinite; + lowerBound.y = double.maxFinite; + upperBound.x = -double.maxFinite; + upperBound.y = -double.maxFinite; for (int i = 0; i < count; i++) { final Vector2 v = velocityBuffer.data[i]; final Vector2 p1 = positionBuffer.data[i]; @@ -1159,7 +1130,7 @@ class ParticleSystem { double v2 = v.x * v.x + v.y * v.y; if (v2 > criticalVelocytySquared) { double a = v2 == 0 - ? double.MAX_FINITE + ? double.maxFinite : Math.sqrt(criticalVelocytySquared / v2); v.x *= a; v.y *= a; @@ -1339,17 +1310,14 @@ class ParticleSystem { void solveWall(TimeStep step) { for (int i = 0; i < count; i++) { if ((flagsBuffer.data[i] & ParticleType.b2_wallParticle) != 0) { - final Vector2 r = velocityBuffer.data[i]; - r.x = 0.0; - r.y = 0.0; + velocityBuffer.data[i].setFrom(Vector2.zero()); } } } - final Vector2 _tempVec2 = new Vector2.zero(); - final Rot _tempRot = new Rot(); - final Transform _tempXf = new Transform.zero(); - final Transform _tempXf2 = new Transform.zero(); + final Rot _tempRot = Rot(); + final Transform _tempXf = Transform.zero(); + final Transform _tempXf2 = Transform.zero(); void solveRigid(final TimeStep step) { for (ParticleGroup group = groupList; @@ -1358,26 +1326,26 @@ class ParticleSystem { if ((group._groupFlags & ParticleGroupType.b2_rigidParticleGroup) != 0) { group.updateStatistics(); Vector2 temp = _tempVec; - Vector2 cross = _tempVec2; Rot rotation = _tempRot; rotation.setAngle(step.dt * group._angularVelocity); - Rot.mulToOutUnsafe(rotation, group._center, cross); + Vector2 cross = Rot.mulVec2(rotation, group._center); temp ..setFrom(group._linearVelocity) ..scale(step.dt) ..add(group._center) ..sub(cross); _tempXf.p.setFrom(temp); - _tempXf.q.set(rotation); - Transform.mulToOut(_tempXf, group._transform, group._transform); + _tempXf.q.setFrom(rotation); + group._transform.set(Transform.mul(_tempXf, group._transform)); final Transform velocityTransform = _tempXf2; velocityTransform.p.x = step.inv_dt * _tempXf.p.x; velocityTransform.p.y = step.inv_dt * _tempXf.p.y; velocityTransform.q.s = step.inv_dt * _tempXf.q.s; velocityTransform.q.c = step.inv_dt * (_tempXf.q.c - 1); for (int i = group._firstIndex; i < group._lastIndex; i++) { - Transform.mulToOutUnsafeVec2(velocityTransform, - positionBuffer.data[i], velocityBuffer.data[i]); + velocityBuffer.data[i].setFrom( + Transform.mulVec2(velocityTransform, positionBuffer.data[i]), + ); } } } @@ -1402,7 +1370,7 @@ class ParticleSystem { double rs = oa.cross(pa) + ob.cross(pb) + oc.cross(pc); double rc = oa.dot(pa) + ob.dot(pb) + oc.dot(pc); double r2 = rs * rs + rc * rc; - double invR = r2 == 0 ? double.MAX_FINITE : Math.sqrt(1.0 / r2); + double invR = r2 == 0 ? double.maxFinite : Math.sqrt(1.0 / r2); rs *= invR; rc *= invR; final double strength = elasticStrength_ * triad.strength; @@ -1438,7 +1406,7 @@ class ParticleSystem { final double dy = pb.y - pa.y; double r0 = pair.distance; double r1 = Math.sqrt(dx * dx + dy * dy); - if (r1 == 0) r1 = double.MAX_FINITE; + if (r1 == 0) r1 = double.maxFinite; double strength = springStrength_ * pair.strength; final double fx = strength * (r0 - r1) / r1 * dx; final double fy = strength * (r0 - r1) / r1 * dy; @@ -1658,7 +1626,7 @@ class ParticleSystem { void solveZombie() { // removes particles with zombie flag int newCount = 0; - List newIndices = BufferUtils.allocClearIntList(count); + List newIndices = BufferUtils.intList(count); for (int i = 0; i < count; i++) { int flags = flagsBuffer.data[i]; if ((flags & ParticleType.b2_zombieParticle) != 0) { @@ -1847,7 +1815,7 @@ class ParticleSystem { } } - final NewIndices _newIndices = new NewIndices(); + final NewIndices _newIndices = NewIndices(); void RotateBuffer(int start, int mid, int end) { // move the particles assigned to the given group toward the end of array @@ -2131,11 +2099,9 @@ class ParticleSystem { } } - /** - * @param callback - * @param point1 - * @param point2 - */ + /// @param callback + /// @param point1 + /// @param point2 void raycast(ParticleRaycastCallback callback, final Vector2 point1, final Vector2 point2) { if (proxyCount == 0) { @@ -2158,7 +2124,7 @@ class ParticleSystem { final double vx = point2.x - point1.x; final double vy = point2.y - point1.y; double v2 = vx * vx + vy * vy; - if (v2 == 0) v2 = double.MAX_FINITE; + if (v2 == 0) v2 = double.maxFinite; for (int proxy = firstProxy; proxy < lastProxy; ++proxy) { int i = proxyBuffer[proxy].index; final Vector2 posI = positionBuffer.data[i]; @@ -2184,9 +2150,7 @@ class ParticleSystem { _tempVec.x = px + t * vx; _tempVec.y = py + t * vy; n.normalize(); - final Vector2 point = _tempVec2; - point.x = point1.x + t * vx; - point.y = point1.y + t * vy; + final Vector2 point = Vector2(point1.x + t * vx, point1.y + t * vy); double f = callback.reportParticle(i, point, n, t); fraction = Math.min(fraction, f); if (fraction <= 0) { diff --git a/lib/src/particle/particle_type.dart b/lib/src/particle/particle_type.dart index 32c3a9a..ce9da10 100644 --- a/lib/src/particle/particle_type.dart +++ b/lib/src/particle/particle_type.dart @@ -1,52 +1,33 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; -/** - * The particle type. Can be combined with | operator. Zero means liquid. - * - * @author dmurph - */ +/// The particle type. Can be combined with | operator. Zero means liquid. class ParticleType { static const int b2_waterParticle = 0; - /** removed after next step */ + + /// removed after next step static const int b2_zombieParticle = 1 << 1; - /** zero velocity */ + + /// zero velocity static const int b2_wallParticle = 1 << 2; - /** with restitution from stretching */ + + /// with restitution from stretching static const int b2_springParticle = 1 << 3; - /** with restitution from deformation */ + + /// with restitution from deformation static const int b2_elasticParticle = 1 << 4; - /** with viscosity */ + + /// with viscosity static const int b2_viscousParticle = 1 << 5; - /** without isotropic pressure */ + + /// without isotropic pressure static const int b2_powderParticle = 1 << 6; - /** with surface tension */ + + /// with surface tension static const int b2_tensileParticle = 1 << 7; - /** mixing color between contacting particles */ + + /// mixing color between contacting particles static const int b2_colorMixingParticle = 1 << 8; - /** call b2DestructionListener on destruction */ + + /// call b2DestructionListener on destruction static const int b2_destructionListener = 1 << 9; } diff --git a/lib/src/particle/stack_queue.dart b/lib/src/particle/stack_queue.dart deleted file mode 100644 index 6d24862..0000000 --- a/lib/src/particle/stack_queue.dart +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -class StackQueue { - List _buffer; - int _front = 0; - int _back = 0; - int _end = 0; - - StackQueue() {} - - void reset(List buffer) { - _buffer = buffer; - _front = 0; - _back = 0; - _end = buffer.length; - } - - void push(T task) { - if (_back >= _end) { - BufferUtils.arraycopy(_buffer, _front, _buffer, 0, _back - _front); - _back -= _front; - _front = 0; - if (_back >= _end) { - return; - } - } - _buffer[_back++] = task; - } - - T pop() { - assert(_front < _back); - return _buffer[_front++]; - } - - bool empty() { - return _front >= _back; - } - - T front() { - return _buffer[_front]; - } -} diff --git a/lib/src/particle/voronoi_diagram.dart b/lib/src/particle/voronoi_diagram.dart index b09358c..6de7a7f 100644 --- a/lib/src/particle/voronoi_diagram.dart +++ b/lib/src/particle/voronoi_diagram.dart @@ -1,35 +1,11 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - part of box2d; abstract class VoronoiDiagramCallback { - void callback(int aTag, int bTag, int cTag); + void call(int aTag, int bTag, int cTag); } class VoronoiGenerator { - final Vector2 center = new Vector2.zero(); + final Vector2 center = Vector2.zero(); int tag = 0; } @@ -55,13 +31,6 @@ class VoronoiDiagramTask { } } -class VoronoiDiagramTaskMutableStack extends MutableStack { - VoronoiDiagramTaskMutableStack(int size) : super(size); - VoronoiDiagramTask newInstance() { - return new VoronoiDiagramTask.zero(); - } -} - class VoronoiDiagram { List _generatorBuffer; int _generatorCount = 0; @@ -70,10 +39,8 @@ class VoronoiDiagram { List _diagram; VoronoiDiagram(int generatorCapacity) { - _generatorBuffer = new List(generatorCapacity); - for (int i = 0; i < generatorCapacity; i++) { - _generatorBuffer[i] = new VoronoiGenerator(); - } + _generatorBuffer = + List.filled(generatorCapacity, VoronoiGenerator()); _generatorCount = 0; _countX = 0; _countY = 0; @@ -90,10 +57,10 @@ class VoronoiDiagram { VoronoiGenerator d = _diagram[i + 1 + _countX]; if (b != c) { if (a != b && a != c) { - callback.callback(a.tag, b.tag, c.tag); + callback.call(a.tag, b.tag, c.tag); } if (d != b && d != c) { - callback.callback(b.tag, d.tag, c.tag); + callback.call(b.tag, d.tag, c.tag); } } } @@ -107,21 +74,20 @@ class VoronoiDiagram { g.tag = tag; } - final Vector2 _lower = new Vector2.zero(); - final Vector2 _upper = new Vector2.zero(); - MutableStack _taskPool = - new VoronoiDiagramTaskMutableStack(50); + final Vector2 _lower = Vector2.zero(); + final Vector2 _upper = Vector2.zero(); + final ListQueue _taskPool = + ListQueue(50); - final StackQueue _queue = - new StackQueue(); + final ListQueue _queue = ListQueue(); void generate(double radius) { assert(_diagram == null); double inverseRadius = 1 / radius; - _lower.x = double.MAX_FINITE; - _lower.y = double.MAX_FINITE; - _upper.x = -double.MAX_FINITE; - _upper.y = -double.MAX_FINITE; + _lower.x = double.maxFinite; + _lower.y = double.maxFinite; + _upper.x = -double.maxFinite; + _upper.y = -double.maxFinite; for (int k = 0; k < _generatorCount; k++) { VoronoiGenerator g = _generatorBuffer[k]; Vector2.min(_lower, g.center, _lower); @@ -129,18 +95,18 @@ class VoronoiDiagram { } _countX = 1 + (inverseRadius * (_upper.x - _lower.x)).toInt(); _countY = 1 + (inverseRadius * (_upper.y - _lower.y)).toInt(); - _diagram = new List(_countX * _countY); - _queue.reset(new List(4 * _countX * _countX)); + _diagram = List(_countX * _countY); + _queue.clear(); for (int k = 0; k < _generatorCount; k++) { VoronoiGenerator g = _generatorBuffer[k]; g.center.x = inverseRadius * (g.center.x - _lower.x); g.center.y = inverseRadius * (g.center.y - _lower.y); int x = Math.max(0, Math.min(g.center.x.toInt(), _countX - 1)); int y = Math.max(0, Math.min(g.center.y.toInt(), _countY - 1)); - _queue.push(_taskPool.pop().set(x, y, x + y * _countX, g)); + _queue.addFirst(_taskPool.removeFirst().set(x, y, x + y * _countX, g)); } - while (!_queue.empty()) { - VoronoiDiagramTask front = _queue.pop(); + while (_queue.isNotEmpty) { + VoronoiDiagramTask front = _queue.removeFirst(); int x = front._x; int y = front._y; int i = front._i; @@ -148,19 +114,21 @@ class VoronoiDiagram { if (_diagram[i] == null) { _diagram[i] = g; if (x > 0) { - _queue.push(_taskPool.pop().set(x - 1, y, i - 1, g)); + _queue.addFirst(_taskPool.removeFirst().set(x - 1, y, i - 1, g)); } if (y > 0) { - _queue.push(_taskPool.pop().set(x, y - 1, i - _countX, g)); + _queue + .addFirst(_taskPool.removeFirst().set(x, y - 1, i - _countX, g)); } if (x < _countX - 1) { - _queue.push(_taskPool.pop().set(x + 1, y, i + 1, g)); + _queue.addFirst(_taskPool.removeFirst().set(x + 1, y, i + 1, g)); } if (y < _countY - 1) { - _queue.push(_taskPool.pop().set(x, y + 1, i + _countX, g)); + _queue + .addFirst(_taskPool.removeFirst().set(x, y + 1, i + _countX, g)); } } - _taskPool.push(front); + _taskPool.addFirst(front); } int maxIteration = _countX + _countY; for (int iteration = 0; iteration < maxIteration; iteration++) { @@ -170,8 +138,8 @@ class VoronoiDiagram { VoronoiGenerator a = _diagram[i]; VoronoiGenerator b = _diagram[i + 1]; if (a != b) { - _queue.push(_taskPool.pop().set(x, y, i, b)); - _queue.push(_taskPool.pop().set(x + 1, y, i + 1, a)); + _queue.addFirst(_taskPool.removeFirst().set(x, y, i, b)); + _queue.addFirst(_taskPool.removeFirst().set(x + 1, y, i + 1, a)); } } } @@ -181,14 +149,15 @@ class VoronoiDiagram { VoronoiGenerator a = _diagram[i]; VoronoiGenerator b = _diagram[i + _countX]; if (a != b) { - _queue.push(_taskPool.pop().set(x, y, i, b)); - _queue.push(_taskPool.pop().set(x, y + 1, i + _countX, a)); + _queue.addFirst(_taskPool.removeFirst().set(x, y, i, b)); + _queue.addFirst( + _taskPool.removeFirst().set(x, y + 1, i + _countX, a)); } } } bool updated = false; - while (!_queue.empty()) { - VoronoiDiagramTask front = _queue.pop(); + while (_queue.isNotEmpty) { + VoronoiDiagramTask front = _queue.removeFirst(); int x = front._x; int y = front._y; int i = front._i; @@ -205,21 +174,23 @@ class VoronoiDiagram { if (a2 > b2) { _diagram[i] = b; if (x > 0) { - _queue.push(_taskPool.pop().set(x - 1, y, i - 1, b)); + _queue.addFirst(_taskPool.removeFirst().set(x - 1, y, i - 1, b)); } if (y > 0) { - _queue.push(_taskPool.pop().set(x, y - 1, i - _countX, b)); + _queue.addFirst( + _taskPool.removeFirst().set(x, y - 1, i - _countX, b)); } if (x < _countX - 1) { - _queue.push(_taskPool.pop().set(x + 1, y, i + 1, b)); + _queue.addFirst(_taskPool.removeFirst().set(x + 1, y, i + 1, b)); } if (y < _countY - 1) { - _queue.push(_taskPool.pop().set(x, y + 1, i + _countX, b)); + _queue.addFirst( + _taskPool.removeFirst().set(x, y + 1, i + _countX, b)); } updated = true; } } - _taskPool.push(front); + _taskPool.addFirst(front); } if (!updated) { break; diff --git a/lib/src/pooling/arrays/float_array.dart b/lib/src/pooling/arrays/float_array.dart deleted file mode 100644 index 2e7941a..0000000 --- a/lib/src/pooling/arrays/float_array.dart +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; diff --git a/lib/src/pooling/arrays/generator_array.dart b/lib/src/pooling/arrays/generator_array.dart deleted file mode 100644 index 2e7941a..0000000 --- a/lib/src/pooling/arrays/generator_array.dart +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; diff --git a/lib/src/pooling/arrays/int_array.dart b/lib/src/pooling/arrays/int_array.dart deleted file mode 100644 index 68332d0..0000000 --- a/lib/src/pooling/arrays/int_array.dart +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -class IntArray { - final HashMap> _map = new HashMap>(); - - List get(int argLength) { - assert(argLength > 0); - - if (!_map.containsKey(argLength)) { - _map[argLength] = getInitializedArray(argLength); - } - - assert(_map[argLength].length == - argLength); // : "Array not built of correct length"; - return _map[argLength]; - } - - List getInitializedArray(int argLength) { - return BufferUtils.allocClearIntList(argLength); - } -} diff --git a/lib/src/pooling/arrays/vec2_array.dart b/lib/src/pooling/arrays/vec2_array.dart deleted file mode 100644 index 78f8fe8..0000000 --- a/lib/src/pooling/arrays/vec2_array.dart +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -class Vec2Array { - final HashMap> _map = new HashMap>(); - - List get(int argLength) { - assert(argLength > 0); - - if (!_map.containsKey(argLength)) { - _map[argLength] = getInitializedArray(argLength); - } - - assert(_map[argLength].length == - argLength); // : "Array not built of correct length"; - return _map[argLength]; - } - - List getInitializedArray(int argLength) { - final List ray = new List(argLength); - for (int i = 0; i < ray.length; i++) { - ray[i] = new Vector2.zero(); - } - return ray; - } -} diff --git a/lib/src/pooling/idynamic_stack.dart b/lib/src/pooling/idynamic_stack.dart deleted file mode 100644 index cff1bc2..0000000 --- a/lib/src/pooling/idynamic_stack.dart +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -abstract class IDynamicStack { - /** - * Pops an item off the stack - * @return - */ - E pop(); - - /** - * Pushes an item back on the stack - * @param argObject - */ - void push(E argObject); -} diff --git a/lib/src/pooling/iordered_stack.dart b/lib/src/pooling/iordered_stack.dart deleted file mode 100644 index 2d91fda..0000000 --- a/lib/src/pooling/iordered_stack.dart +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -abstract class IOrderedStack { - /** - * Returns the next object in the pool - * @return - */ - E pop(); - - /** - * Returns the next 'argNum' objects in the pool - * in an array - * @param argNum - * @return an array containing the next pool objects in - * items 0-argNum. Array length and uniqueness not - * guaranteed. - */ - List popSome(int argNum); - - /** - * Tells the stack to take back the last 'argNum' items - * @param argNum - */ - void push(int argNum); -} diff --git a/lib/src/pooling/iworld_pool.dart b/lib/src/pooling/iworld_pool.dart deleted file mode 100644 index 5ab1eba..0000000 --- a/lib/src/pooling/iworld_pool.dart +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -abstract class IWorldPool { - IDynamicStack getPolyContactStack(); - - IDynamicStack getCircleContactStack(); - - IDynamicStack getPolyCircleContactStack(); - - IDynamicStack getEdgeCircleContactStack(); - - IDynamicStack getEdgePolyContactStack(); - - IDynamicStack getChainCircleContactStack(); - - IDynamicStack getChainPolyContactStack(); - - Vector2 popVec2(); - - List popVec2Some(int num); - - void pushVec2(int num); - - Vector3 popVec3(); - - List popVec3Some(int num); - - void pushVec3(int num); - - Matrix2 popMat22(); - - List popMat22Some(int num); - - void pushMat22(int num); - - Matrix3 popMat33(); - - void pushMat33(int num); - - AABB popAABB(); - - List popAABBSome(int num); - - void pushAABB(int num); - - Rot popRot(); - - void pushRot(int num); - - Collision getCollision(); - - TimeOfImpact getTimeOfImpact(); - - Distance getDistance(); - - Float64List getFloatArray(int argLength); - - List getIntArray(int argLength); - - List getVec2Array(int argLength); -} diff --git a/lib/src/pooling/normal/circle_stack.dart b/lib/src/pooling/normal/circle_stack.dart deleted file mode 100644 index 2e7941a..0000000 --- a/lib/src/pooling/normal/circle_stack.dart +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; diff --git a/lib/src/pooling/normal/default_world_pool.dart b/lib/src/pooling/normal/default_world_pool.dart deleted file mode 100644 index a4d4084..0000000 --- a/lib/src/pooling/normal/default_world_pool.dart +++ /dev/null @@ -1,312 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -/** - * Provides object pooling for all objects used in the engine. Objects retrieved from here should - * only be used temporarily, and then pushed back (with the exception of arrays). - */ - -class OrderedStackVec2 extends OrderedStack { - OrderedStackVec2(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - Vector2 newInstance() => new Vector2.zero(); -} - -class OrderedStackVec3 extends OrderedStack { - OrderedStackVec3(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - Vector3 newInstance() => new Vector3.zero(); -} - -class OrderedStackMat22 extends OrderedStack { - OrderedStackMat22(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - Matrix2 newInstance() => new Matrix2.zero(); -} - -class OrderedStackMat33 extends OrderedStack { - OrderedStackMat33(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - Matrix3 newInstance() => new Matrix3.zero(); -} - -class OrderedStackAABB extends OrderedStack { - OrderedStackAABB(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - AABB newInstance() => new AABB(); -} - -class OrderedStackRot extends OrderedStack { - OrderedStackRot(int argStackSize, int argContainerSize) - : super(argStackSize, argContainerSize); - Rot newInstance() => new Rot(); -} - -abstract class MutableStackWithPool extends MutableStack { - IWorldPool _pool; - MutableStackWithPool(this._pool, int argInitSize) : super(argInitSize); -} - -class MutableStackPolygonContact extends MutableStackWithPool { - MutableStackPolygonContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - PolygonContact newInstance() => new PolygonContact(_pool); -} - -class MutableStackCircleContact extends MutableStackWithPool { - MutableStackCircleContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - CircleContact newInstance() => new CircleContact(_pool); -} - -class MutableStackPolygonAndCircleContact - extends MutableStackWithPool { - MutableStackPolygonAndCircleContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - PolygonAndCircleContact newInstance() => new PolygonAndCircleContact(_pool); -} - -class MutableStackEdgeAndCircleContact - extends MutableStackWithPool { - MutableStackEdgeAndCircleContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - EdgeAndCircleContact newInstance() => new EdgeAndCircleContact(_pool); -} - -class MutableStackEdgeAndPolygonContact - extends MutableStackWithPool { - MutableStackEdgeAndPolygonContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - EdgeAndPolygonContact newInstance() => new EdgeAndPolygonContact(_pool); -} - -class MutableStackChainAndCircleContact - extends MutableStackWithPool { - MutableStackChainAndCircleContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - ChainAndCircleContact newInstance() => new ChainAndCircleContact(_pool); -} - -class MutableStackChainAndPolygonContact - extends MutableStackWithPool { - MutableStackChainAndPolygonContact(IWorldPool pool, int argInitSize) - : super(pool, argInitSize); - ChainAndPolygonContact newInstance() => new ChainAndPolygonContact(_pool); -} - -class DefaultWorldPool implements IWorldPool { - final OrderedStack _vecs; - final OrderedStack _vec3s; - final OrderedStack _mats; - final OrderedStack _mat33s; - final OrderedStack _aabbs; - final OrderedStack _rots; - - final HashMap _afloats = new HashMap(); - final HashMap> _aints = new HashMap>(); - final HashMap> _avecs = new HashMap>(); - - IWorldPool _world; - - IWorldPool get world => _world; - - MutableStackWithPool _pcstack; - MutableStackWithPool _ccstack; - MutableStackWithPool _cpstack; - MutableStackWithPool _ecstack; - MutableStackWithPool _epstack; - MutableStackWithPool _chcstack; - MutableStackWithPool _chpstack; - - Collision _collision; - TimeOfImpact _toi; - final Distance _dist; - - DefaultWorldPool(int argSize, int argContainerSize) - : _vecs = new OrderedStackVec2(argSize, argContainerSize), - _vec3s = new OrderedStackVec3(argSize, argContainerSize), - _mats = new OrderedStackMat22(argSize, argContainerSize), - _aabbs = new OrderedStackAABB(argSize, argContainerSize), - _rots = new OrderedStackRot(argSize, argContainerSize), - _mat33s = new OrderedStackMat33(argSize, argContainerSize), - _dist = new Distance() { - _pcstack = - new MutableStackPolygonContact(this, Settings.CONTACT_STACK_INIT_SIZE); - _ccstack = - new MutableStackCircleContact(this, Settings.CONTACT_STACK_INIT_SIZE); - _cpstack = new MutableStackPolygonAndCircleContact( - this, Settings.CONTACT_STACK_INIT_SIZE); - _ecstack = new MutableStackEdgeAndCircleContact( - this, Settings.CONTACT_STACK_INIT_SIZE); - _epstack = new MutableStackEdgeAndPolygonContact( - this, Settings.CONTACT_STACK_INIT_SIZE); - _chcstack = new MutableStackChainAndCircleContact( - this, Settings.CONTACT_STACK_INIT_SIZE); - _chpstack = new MutableStackChainAndPolygonContact( - this, Settings.CONTACT_STACK_INIT_SIZE); - _collision = new Collision(this); - _toi = new TimeOfImpact(this); - _world = this; - } - - IDynamicStack getPolyContactStack() { - return _pcstack; - } - - IDynamicStack getCircleContactStack() { - return _ccstack; - } - - IDynamicStack getPolyCircleContactStack() { - return _cpstack; - } - - IDynamicStack getEdgeCircleContactStack() { - return _ecstack; - } - - IDynamicStack getEdgePolyContactStack() { - return _epstack; - } - - IDynamicStack getChainCircleContactStack() { - return _chcstack; - } - - IDynamicStack getChainPolyContactStack() { - return _chpstack; - } - - Vector2 popVec2() { - return _vecs.pop(); - } - - List popVec2Some(int argNum) { - return _vecs.popSome(argNum); - } - - void pushVec2(int argNum) { - _vecs.push(argNum); - } - - Vector3 popVec3() { - return _vec3s.pop(); - } - - List popVec3Some(int argNum) { - return _vec3s.popSome(argNum); - } - - void pushVec3(int argNum) { - _vec3s.push(argNum); - } - - Matrix2 popMat22() { - return _mats.pop(); - } - - List popMat22Some(int argNum) { - return _mats.popSome(argNum); - } - - void pushMat22(int argNum) { - _mats.push(argNum); - } - - Matrix3 popMat33() { - return _mat33s.pop(); - } - - void pushMat33(int argNum) { - _mat33s.push(argNum); - } - - AABB popAABB() { - return _aabbs.pop(); - } - - List popAABBSome(int argNum) { - return _aabbs.popSome(argNum); - } - - void pushAABB(int argNum) { - _aabbs.push(argNum); - } - - Rot popRot() { - return _rots.pop(); - } - - void pushRot(int num) { - _rots.push(num); - } - - Collision getCollision() { - return _collision; - } - - TimeOfImpact getTimeOfImpact() { - return _toi; - } - - Distance getDistance() { - return _dist; - } - - Float64List getFloatArray(int argLength) { - if (!_afloats.containsKey(argLength)) { - _afloats[argLength] = new Float64List(argLength); - } - - assert(_afloats[argLength].length == - argLength); // : "Array not built with correct length"; - return _afloats[argLength]; - } - - List getIntArray(int argLength) { - if (!_aints.containsKey(argLength)) { - _aints[argLength] = BufferUtils.allocClearIntList(argLength); - } - - assert(_aints[argLength].length == - argLength); // : "Array not built with correct length"; - return _aints[argLength]; - } - - List getVec2Array(int argLength) { - if (!_avecs.containsKey(argLength)) { - List ray = new List(argLength); - for (int i = 0; i < argLength; i++) { - ray[i] = new Vector2.zero(); - } - _avecs[argLength] = ray; - } - - assert(_avecs[argLength].length == - argLength); // : "Array not built with correct length"; - return _avecs[argLength]; - } -} diff --git a/lib/src/pooling/normal/mutable_stack.dart b/lib/src/pooling/normal/mutable_stack.dart deleted file mode 100644 index 02cd7e6..0000000 --- a/lib/src/pooling/normal/mutable_stack.dart +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -abstract class MutableStack implements IDynamicStack { - List _stack; - int _index; - int _size; - - MutableStack(int argInitSize) { - _index = 0; - _stack = null; - _index = 0; - _size = 0; - extendStack(argInitSize); - } - - void extendStack(int argSize) { - List newStack = newArray(argSize); - if (_stack != null) { - BufferUtils.arraycopy(_stack, 0, newStack, 0, _size); - } - for (int i = 0; i < newStack.length; i++) { - newStack[i] = newInstance(); - } - _stack = newStack; - _size = newStack.length; - } - - E pop() { - if (_index >= _size) { - extendStack(_size * 2); - } - return _stack[_index++]; - } - - void push(E argObject) { - assert(_index > 0); - _stack[--_index] = argObject; - } - - /** Creates a new instance of the object contained by this stack. */ - E newInstance(); - - List newArray(int size) { - return new List(size); - } -} diff --git a/lib/src/pooling/normal/ordered_stack.dart b/lib/src/pooling/normal/ordered_stack.dart deleted file mode 100644 index ec5d84c..0000000 --- a/lib/src/pooling/normal/ordered_stack.dart +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; - -abstract class OrderedStack { - final List _pool; - int _index; - final int _size; - final List _container; - - OrderedStack(int argStackSize, int argContainerSize) - : _pool = new List(argStackSize), - _index = 0, - _size = argStackSize, - _container = new List(argContainerSize) { - // pool = new List(argStackSize); - for (int i = 0; i < argStackSize; i++) { - _pool[i] = newInstance(); - } - } - - E pop() { - assert(_index < - _size); // "End of stack reached, there is probably a leak somewhere"; - return _pool[_index++]; - } - - List popSome(int argNum) { - assert(_index + argNum < - _size); // "End of stack reached, there is probably a leak somewhere"; - assert(argNum <= _container.length); // "Container array is too small"; - BufferUtils.arraycopy(_pool, _index, _container, 0, argNum); - _index += argNum; - return _container; - } - - void push(int argNum) { - _index -= argNum; - assert(_index >= 0); - } - - /** Creates a new instance of the object contained by this stack. */ - E newInstance(); -} diff --git a/lib/src/pooling/stacks/dynamic_int_stack.dart b/lib/src/pooling/stacks/dynamic_int_stack.dart deleted file mode 100644 index 2e7941a..0000000 --- a/lib/src/pooling/stacks/dynamic_int_stack.dart +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - -part of box2d; diff --git a/lib/src/settings.dart b/lib/src/settings.dart index 3678d48..9194471 100644 --- a/lib/src/settings.dart +++ b/lib/src/settings.dart @@ -1,174 +1,104 @@ -/******************************************************************************* - * Copyright (c) 2015, Daniel Murphy, Google - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ - library box2d.settings; import 'dart:math' as Math; const int INTEGER_MAX_VALUE = 0x3FFFFFFF; -/** A "close to zero" float epsilon value for use */ +/// A "close to zero" float epsilon value for use const double EPSILON = 1.1920928955078125E-7; const int CONTACT_STACK_INIT_SIZE = 10; -/** - * The maximum number of contact points between two convex shapes. - */ +/// The maximum number of contact points between two convex shapes. const int maxManifoldPoints = 2; -/** - * The maximum number of vertices on a convex polygon. - */ +/// The maximum number of vertices on a convex polygon. const int maxPolygonVertices = 8; -/** - * This is used to fatten AABBs in the dynamic tree. This allows proxies to move by a small amount - * without triggering a tree adjustment. This is in meters. - */ +/// This is used to fatten AABBs in the dynamic tree. This allows proxies to move by a small amount +/// without triggering a tree adjustment. This is in meters. const double aabbExtension = 0.1; -/** - * This is used to fatten AABBs in the dynamic tree. This is used to predict the future position - * based on the current displacement. This is a dimensionless multiplier. - */ +/// This is used to fatten AABBs in the dynamic tree. This is used to predict the future position +/// based on the current displacement. This is a dimensionless multiplier. const double aabbMultiplier = 2.0; -/** - * A small length used as a collision and constraint tolerance. Usually it is chosen to be - * numerically significant, but visually insignificant. - */ +/// A small length used as a collision and constraint tolerance. Usually it is chosen to be +/// numerically significant, but visually insignificant. const double linearSlop = 0.005; -/** - * A small angle used as a collision and constraint tolerance. Usually it is chosen to be - * numerically significant, but visually insignificant. - */ -const double angularSlop = (2.0 / 180.0 * Math.PI); - -/** - * The radius of the polygon/edge shape skin. This should not be modified. Making this smaller - * means polygons will have and insufficient for continuous collision. Making it larger may create - * artifacts for vertex collision. - */ +/// A small angle used as a collision and constraint tolerance. Usually it is chosen to be +/// numerically significant, but visually insignificant. +const double angularSlop = (2.0 / 180.0 * Math.pi); + +/// The radius of the polygon/edge shape skin. This should not be modified. Making this smaller +/// means polygons will have and insufficient for continuous collision. Making it larger may create +/// artifacts for vertex collision. const double polygonRadius = (2.0 * linearSlop); -/** Maximum number of sub-steps per contact in continuous physics simulation. */ +/// Maximum number of sub-steps per contact in continuous physics simulation. const int maxSubSteps = 8; // Dynamics -/** - * Maximum number of contacts to be handled to solve a TOI island. - */ +/// Maximum number of contacts to be handled to solve a TOI island. const int maxTOIContacts = 32; -/** - * A velocity threshold for elastic collisions. Any collision with a relative linear velocity - * below this threshold will be treated as inelastic. - */ +/// A velocity threshold for elastic collisions. Any collision with a relative linear velocity +/// below this threshold will be treated as inelastic. double velocityThreshold = 1.0; -/** - * The maximum linear position correction used when solving constraints. This helps to prevent - * overshoot. - */ +/// The maximum linear position correction used when solving constraints. This helps to prevent +/// overshoot. const double maxLinearCorrection = 0.2; -/** - * The maximum angular position correction used when solving constraints. This helps to prevent - * overshoot. - */ -const double maxAngularCorrection = (8.0 / 180.0 * Math.PI); +/// The maximum angular position correction used when solving constraints. This helps to prevent +/// overshoot. +const double maxAngularCorrection = (8.0 / 180.0 * Math.pi); -/** - * The maximum linear velocity of a body. This limit is very large and is used to prevent - * numerical problems. You shouldn't need to adjust this. - */ +/// The maximum linear velocity of a body. This limit is very large and is used to prevent +/// numerical problems. You shouldn't need to adjust this. const double maxTranslation = 2.0; const double maxTranslationSquared = (maxTranslation * maxTranslation); -/** - * The maximum angular velocity of a body. This limit is very large and is used to prevent - * numerical problems. You shouldn't need to adjust this. - */ -const double maxRotation = (0.5 * Math.PI); +/// The maximum angular velocity of a body. This limit is very large and is used to prevent +/// numerical problems. You shouldn't need to adjust this. +const double maxRotation = (0.5 * Math.pi); const double maxRotationSquared = (maxRotation * maxRotation); -/** - * This scale factor controls how fast overlap is resolved. Ideally this would be 1 so that - * overlap is removed in one time step. However using values close to 1 often lead to overshoot. - */ +/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so that +/// overlap is removed in one time step. However using values close to 1 often lead to overshoot. const double baumgarte = 0.2; const double toiBaugarte = 0.75; // Sleep -/** - * The time that a body must be still before it will go to sleep. - */ +/// The time that a body must be still before it will go to sleep. const double timeToSleep = 0.5; -/** - * A body cannot sleep if its linear velocity is above this tolerance. - */ +/// A body cannot sleep if its linear velocity is above this tolerance. const double linearSleepTolerance = 0.01; -/** - * A body cannot sleep if its angular velocity is above this tolerance. - */ -const double angularSleepTolerance = (2.0 / 180.0 * Math.PI); +/// A body cannot sleep if its angular velocity is above this tolerance. +const double angularSleepTolerance = (2.0 / 180.0 * Math.pi); // Particle -/** - * A symbolic constant that stands for particle allocation error. - */ +/// A symbolic constant that stands for particle allocation error. const int invalidParticleIndex = (-1); -/** - * The standard distance between particles, divided by the particle radius. - */ +/// The standard distance between particles, divided by the particle radius. const double particleStride = 0.75; -/** - * The minimum particle weight that produces pressure. - */ +/// The minimum particle weight that produces pressure. const double minParticleWeight = 1.0; -/** - * The upper limit for particle weight used in pressure calculation. - */ +/// The upper limit for particle weight used in pressure calculation. const double maxParticleWeight = 5.0; -/** - * The maximum distance between particles in a triad, divided by the particle radius. - */ +/// The maximum distance between particles in a triad, divided by the particle radius. const int maxTriadDistance = 2; const int maxTriadDistanceSquared = (maxTriadDistance * maxTriadDistance); -/** - * The initial size of particle data buffers. - */ +/// The initial size of particle data buffers. const int minParticleBufferCapacity = 256; diff --git a/pubspec.yaml b/pubspec.yaml index 1877604..28cedee 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,17 +1,11 @@ -name: box2d -version: 0.4.0 -authors: -- Kevin Moore -- Srdjan Mitrovic -- Filip Hracek -description: A Dart 2D physics engine -homepage: https://github.com/google/box2d.dart +name: box2d_flame +version: 1.0.0 +description: A Dart 2D physics engine, port from the Java version, works for Web/Flutter +homepage: https://github.com/flame-engine/box2d.dart dependencies: vector_math: '>=2.0.0 <3.0.0' dev_dependencies: - browser: '>=0.10.0 <0.11.0' -transformers: -- $dart2js: - commandLineOptions: - - --trust-type-annotations - - --trust-primitives + build_web_compilers: '>=2.12.0-dev.1 <3.0.0' + build_runner: '>=1.6.2 <2.0.0' +environment: + sdk: ">=2.3.0 <3.0.0"