[
  {
    "path": ".eslintignore",
    "content": "demo/js/Examples.js"
  },
  {
    "path": ".eslintrc",
    "content": "{\n    \"rules\": {\n        \"no-fallthrough\": 2,\n        \"no-console\": 0,\n        \"no-unused-vars\": 0,\n        \"no-redeclare\": 0,\n        \"indent\": [\n            2,\n            4\n        ],\n        \"semi\": [\n            2,\n            \"always\"\n        ]\n    },\n    \"env\": {\n        \"node\": true,\n        \"browser\": true,\n        \"jquery\": true,\n        \"amd\": true\n    },\n    \"globals\": {\n        \"Matter\": false,\n        \"window\": true,\n        \"document\": false,\n        \"Element\": false,\n        \"MatterTools\": false,\n        \"phantom\": false,\n        \"process\": false,\n        \"HTMLElement\": false,\n        \"require\": false,\n        \"$\": false,\n        \"Image\": false,\n        \"navigator\": false,\n        \"setTimeout\": false,\n        \"decomp\": false,\n        \"module\": false,\n        \"Body\": false,\n        \"Composite\": false,\n        \"World\": false,\n        \"Contact\": false,\n        \"Detector\": false,\n        \"Grid\": false,\n        \"Pairs\": false,\n        \"Pair\": false,\n        \"Resolver\": false,\n        \"SAT\": false,\n        \"Constraint\": false,\n        \"MouseConstraint\": false,\n        \"Common\": false,\n        \"Engine\": false,\n        \"Mouse\": false,\n        \"Sleeping\": false,\n        \"Bodies\": false,\n        \"Composites\": false,\n        \"Axes\": false,\n        \"Bounds\": false,\n        \"Vector\": false,\n        \"Vertices\": false,\n        \"Render\": false,\n        \"Events\": false,\n        \"Query\": false,\n        \"Runner\": false,\n        \"Svg\": false,\n        \"Example\": false,\n        \"__MATTER_VERSION__\": false,\n        \"__MATTER_IS_DEV__\": false,\n        \"jest\": false,\n        \"test\": false,\n        \"expect\": false,\n        \"describe\": false\n    },\n    \"extends\": \"eslint:recommended\"\n}\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node-version: [16.x]\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@v2\n      with:\n        node-version: ${{ matrix.node-version }}\n        cache: 'npm'\n    - run: npm ci\n    - run: npm run lint\n    - run: npm run build\n    - run: npm run build-demo\n    - run: npm run test\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea\n*.map\nnode_modules\nnpm-debug.log\ndocs\nmatter-doc-theme\nbuild/matter-dev.js\nbuild/matter-dev.min.js\nbuild/matter.dev.js\nbuild/matter.dev.min.js\ndemo/js/lib/matter-dev.js\ndemo/js/Examples.min.js\nexamples/build\ntest/browser/diffs\ntest/browser/refs\ntest/node/diffs\ntest/node/refs\n__snapshots__\n__compare__\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "## 0.20.0 (2024-06-23)\n\n* added event passive options to Matter.Mouse, closes #930, closes #976 ([e888f3c](https://github.com/liabru/matter-js/commit/e888f3c)), closes [#930](https://github.com/liabru/matter-js/issues/930) [#976](https://github.com/liabru/matter-js/issues/976)\n* added arrow key navigation of examples in development demo ([45cad77](https://github.com/liabru/matter-js/commit/45cad77))\n* added body removal to Example.remove ([1209e88](https://github.com/liabru/matter-js/commit/1209e88))\n* added Constraint.currentLength, closes #1184 ([812f8af](https://github.com/liabru/matter-js/commit/812f8af)), closes [#1184](https://github.com/liabru/matter-js/issues/1184)\n* added doc and warning for `Bodies.trapezioid` slope parameter range, closes #1075 ([7ea5bc1](https://github.com/liabru/matter-js/commit/7ea5bc1)), closes [#1075](https://github.com/liabru/matter-js/issues/1075)\n* added docs for `body.chamfer` property, closes #1059 ([5ed985d](https://github.com/liabru/matter-js/commit/5ed985d)), closes [#1059](https://github.com/liabru/matter-js/issues/1059)\n* added engine beforeSolve event, closes #1173 ([8dd0e99](https://github.com/liabru/matter-js/commit/8dd0e99)), closes [#1173](https://github.com/liabru/matter-js/issues/1173)\n* added event.timestamp and event.delta to collision events, closes #368 ([2af54d5](https://github.com/liabru/matter-js/commit/2af54d5)), closes [#368](https://github.com/liabru/matter-js/issues/368)\n* added Example.renderResize ([b88c82f](https://github.com/liabru/matter-js/commit/b88c82f))\n* added Example.stress4 ([0f0ac93](https://github.com/liabru/matter-js/commit/0f0ac93))\n* added Example.substep ([205aaa5](https://github.com/liabru/matter-js/commit/205aaa5))\n* added high delta warning to Matter.Engine ([72e6e89](https://github.com/liabru/matter-js/commit/72e6e89))\n* added local pairs functions in Pairs.update ([e9da32c](https://github.com/liabru/matter-js/commit/e9da32c))\n* added new Matter.Runner with default fixed timestep ([3e61951](https://github.com/liabru/matter-js/commit/3e61951))\n* added pixel ratio scaling to render debug stats ([7ec38a1](https://github.com/liabru/matter-js/commit/7ec38a1))\n* added render.options.wireframeStrokeStyle, closes #406 ([401553d](https://github.com/liabru/matter-js/commit/401553d)), closes [#406](https://github.com/liabru/matter-js/issues/406)\n* added Render.setSize, closes #955, closes #595 ([fc05839](https://github.com/liabru/matter-js/commit/fc05839)), closes [#955](https://github.com/liabru/matter-js/issues/955) [#595](https://github.com/liabru/matter-js/issues/595)\n* added repeats and updates options to test tools ([6142991](https://github.com/liabru/matter-js/commit/6142991))\n* added updates per frame to Matter.Render debug ([a5b5767](https://github.com/liabru/matter-js/commit/a5b5767))\n* changed Composte.removeComposite and Composte.removeBody to reset body.sleepCounter ([6d10c3d](https://github.com/liabru/matter-js/commit/6d10c3d))\n* changed Pair.id format to use shorter ids ([5b6f30b](https://github.com/liabru/matter-js/commit/5b6f30b))\n* fixed collision events for sleeping pairs, closes #1077 ([51f49ce](https://github.com/liabru/matter-js/commit/51f49ce)), closes [#1077](https://github.com/liabru/matter-js/issues/1077)\n* fixed missing `mouse.sourceEvents.mousewheel`, closes #1146 ([272049a](https://github.com/liabru/matter-js/commit/272049a)), closes [#1146](https://github.com/liabru/matter-js/issues/1146)\n* fixed Body.setStatic when applied multiple times, closes #641 ([9655785](https://github.com/liabru/matter-js/commit/9655785)), closes [#641](https://github.com/liabru/matter-js/issues/641)\n* fixed compare tool layer order in demo testbed ([a3e801a](https://github.com/liabru/matter-js/commit/a3e801a)) ([0cc4d96](https://github.com/liabru/matter-js/commit/0cc4d96))\n* fixed Runner.stop docs re. runner.enabled, closes #586, closes #1054 ([2ecc563](https://github.com/liabru/matter-js/commit/2ecc563)), closes [#586](https://github.com/liabru/matter-js/issues/586) [#1054](https://github.com/liabru/matter-js/issues/1054)\n* improved Example.substep comments ([8046341](https://github.com/liabru/matter-js/commit/8046341))\n* improved Matter.Runner ([b8a1563](https://github.com/liabru/matter-js/commit/b8a1563)) ([7206600](https://github.com/liabru/matter-js/commit/7206600))\n* improved Matter.Runner docs ([283cd96](https://github.com/liabru/matter-js/commit/283cd96)) ([dc693e7](https://github.com/liabru/matter-js/commit/dc693e7)) ([6e302a8](https://github.com/liabru/matter-js/commit/6e302a8))\n* improved test comparison report ([962fba5](https://github.com/liabru/matter-js/commit/962fba5)) ([2cc1c1c](https://github.com/liabru/matter-js/commit/2cc1c1c))\n* improved `body.parts` docs ([013698b](https://github.com/liabru/matter-js/commit/013698b)) ([411af06](https://github.com/liabru/matter-js/commit/411af06)), closes #600 ([c1f9584](https://github.com/liabru/matter-js/commit/c1f9584)), closes [#600](https://github.com/liabru/matter-js/issues/600)\n* optimised Collision._findSupports ([653a110](https://github.com/liabru/matter-js/commit/653a110))\n* optimised Collision.collides ([6f8a54b](https://github.com/liabru/matter-js/commit/6f8a54b))\n* optimised contacts and supports memory and gc use ([97d502e](https://github.com/liabru/matter-js/commit/97d502e))\n* optimised pairs and collisions memory and gc use ([f9208df](https://github.com/liabru/matter-js/commit/f9208df))\n* optimised Resolver.solvePosition ([89963f7](https://github.com/liabru/matter-js/commit/89963f7))\n* optimised Resolver.solveVelocity ([182ba90](https://github.com/liabru/matter-js/commit/182ba90))\n* preserve pair.contacts order ([e891d37](https://github.com/liabru/matter-js/commit/e891d37))\n* reduced canvas hit testing in demo when using matter-tools ([da99acb](https://github.com/liabru/matter-js/commit/da99acb))\n* removed redundant runner.isFixed from examples ([aba0e9e](https://github.com/liabru/matter-js/commit/aba0e9e))\n* removed Collision._projectToAxis ([4c56e5b](https://github.com/liabru/matter-js/commit/4c56e5b))\n* removed pair.confirmedActive ([72bc203](https://github.com/liabru/matter-js/commit/72bc203))\n* renamed Composites function xx and yy params, closes #1095 ([6bda7e8](https://github.com/liabru/matter-js/commit/6bda7e8)), closes [#1095](https://github.com/liabru/matter-js/issues/1095)\n* updated development demo render options ([0b131a4](https://github.com/liabru/matter-js/commit/0b131a4))\n* updated benchmark tests ([e668c02](https://github.com/liabru/matter-js/commit/e668c02))\n\n## 0.19.0 (2023-02-16)\n\nSee the release [readme](https://github.com/liabru/matter-js/blob/0.19.0/README.md) for further information.\n\n* added readme note about vue watchers ([035481c](https://github.com/liabru/matter-js/commit/035481c))\n* added readonly body.deltaTime ([0784a5b](https://github.com/liabru/matter-js/commit/0784a5b))\n* added speed setters to Body.set ([3ff6ff4](https://github.com/liabru/matter-js/commit/3ff6ff4))\n* added support for Matter.Runner and Matter.Render in tests ([7d7bad0](https://github.com/liabru/matter-js/commit/7d7bad0))\n* added updateVelocity argument to Body.setPosition, Body.setAngle, Body.translate, Body.rotate ([db8b73f](https://github.com/liabru/matter-js/commit/db8b73f))\n* changed engine collisionStart event to trigger after resolving and after updating body velocities ([70600a8](https://github.com/liabru/matter-js/commit/70600a8))\n* changed examples to be delta independent ([d7e4f58](https://github.com/liabru/matter-js/commit/d7e4f58))\n* deprecated render.controller property ([04d229e](https://github.com/liabru/matter-js/commit/04d229e))\n* derived velocity from position in setters ([b6de9ed](https://github.com/liabru/matter-js/commit/b6de9ed))\n* fixed issues with engine event.delta ([6f5af77](https://github.com/liabru/matter-js/commit/6f5af77))\n* handle null constraint points in Constraint.pointAWorld and Constraint.pointBWorld ([e414464](https://github.com/liabru/matter-js/commit/e414464))\n* improved Body.applyForce docs ([3a8264c](https://github.com/liabru/matter-js/commit/3a8264c))\n* improved delta factors in resolver and constraint stiffness ([9dc6be7](https://github.com/liabru/matter-js/commit/9dc6be7))\n* improved Matter.Body docs for functions and properties including readonly ([85a9eb2](https://github.com/liabru/matter-js/commit/85a9eb2))\n* improved Matter.Engine docs ([50fc8f2](https://github.com/liabru/matter-js/commit/50fc8f2))\n* improved slingshot example constraint ([c6a1a6d](https://github.com/liabru/matter-js/commit/c6a1a6d))\n* improved delta consistency ([87af8a1](https://github.com/liabru/matter-js/commit/87af8a1))\n* improved Example.newtonsCradle ([b2bd492](https://github.com/liabru/matter-js/commit/b2bd492))\n* removed render element warning ([459425b](https://github.com/liabru/matter-js/commit/459425b))\n* removed unused delta params ([a572968](https://github.com/liabru/matter-js/commit/a572968))\n* updated body docs ([6bb2855](https://github.com/liabru/matter-js/commit/6bb2855))\n* updated body velocity properties after resolving ([d52f7e6](https://github.com/liabru/matter-js/commit/d52f7e6))\n* updated Example.manipulation ([5ddac71](https://github.com/liabru/matter-js/commit/5ddac71))\n* updated Example.ragdoll ([ec38638](https://github.com/liabru/matter-js/commit/ec38638))\n* updated Example.staticFriction and Example.timeScale ([11d5e73](https://github.com/liabru/matter-js/commit/11d5e73))\n* updated Matter.Body docs ([db780c3](https://github.com/liabru/matter-js/commit/db780c3))\n* updated timing improvements ([10a2a07](https://github.com/liabru/matter-js/commit/10a2a07))\n* used Body.getVelocity in Matter.Render ([bf90bdd](https://github.com/liabru/matter-js/commit/bf90bdd))\n* used speed getter in Matter.Sleeping and Matter.Render ([6579dfd](https://github.com/liabru/matter-js/commit/6579dfd))\n\n\n\n## 0.18.0 (2021-12-15)\n\n* added test capture sort to improve comparison ([ea3c11b](https://github.com/liabru/matter-js/commit/ea3c11b))\n* added triangles to mixed bodies example ([b116f64](https://github.com/liabru/matter-js/commit/b116f64))\n* added behaviour metric to tests and refactor tests ([8125966](https://github.com/liabru/matter-js/commit/8125966))\n* added benchmark test command ([7f34c45](https://github.com/liabru/matter-js/commit/7f34c45))\n* added broadphase to Matter.Detector ([a6b5e7d](https://github.com/liabru/matter-js/commit/a6b5e7d))\n* added cache checks to Matter.Composite ([32fd285](https://github.com/liabru/matter-js/commit/32fd285))\n* added example for Composite.remove ([bc07f56](https://github.com/liabru/matter-js/commit/bc07f56))\n* added example stress 3 ([d0ee246](https://github.com/liabru/matter-js/commit/d0ee246))\n* added filesize to test comparison report ([b3a8aa3](https://github.com/liabru/matter-js/commit/b3a8aa3))\n* added Matter.Collision ([9037f36](https://github.com/liabru/matter-js/commit/9037f36))\n* added memory comparison to tests ([bedf84c](https://github.com/liabru/matter-js/commit/bedf84c))\n* added note about webpack performance to readme ([80cf76b](https://github.com/liabru/matter-js/commit/80cf76b))\n* added stable sorting to test worker and refactor ([81dd2fb](https://github.com/liabru/matter-js/commit/81dd2fb))\n* added support for build metadata in Plugin.versionParse ([8bfaff0](https://github.com/liabru/matter-js/commit/8bfaff0))\n* changed raycasting example events to enable use in tests ([10afaea](https://github.com/liabru/matter-js/commit/10afaea))\n* changed build config to 'source-map' devtool ([e909b04](https://github.com/liabru/matter-js/commit/e909b04))\n* changed tests to use a production build rather than source ([55feb89](https://github.com/liabru/matter-js/commit/55feb89))\n* deprecated Matter.Grid ([e366d0e](https://github.com/liabru/matter-js/commit/e366d0e))\n* fixed sync issues on demo compare tool ([826ed46](https://github.com/liabru/matter-js/commit/826ed46))\n* improved performance measurement accuracy in tests ([cd289ec](https://github.com/liabru/matter-js/commit/cd289ec))\n* improved test comparison report ([de04c00](https://github.com/liabru/matter-js/commit/de04c00))\n* optimised Matter.Detector ([c7cec16](https://github.com/liabru/matter-js/commit/c7cec16)), ([fd1a70e](https://github.com/liabru/matter-js/commit/fd1a70e)), ([caeb07e](https://github.com/liabru/matter-js/commit/caeb07e)), ([efede6e](https://github.com/liabru/matter-js/commit/efede6e))\n* optimised Matter.Composite ([52e7977](https://github.com/liabru/matter-js/commit/52e7977))\n* optimised Matter.Pair ([d8a6380](https://github.com/liabru/matter-js/commit/d8a6380)), ([48673db](https://github.com/liabru/matter-js/commit/48673db)), ([1073dde](https://github.com/liabru/matter-js/commit/1073dde))\n* optimised Matter.Pairs ([a30707f](https://github.com/liabru/matter-js/commit/a30707f)), ([a882a74](https://github.com/liabru/matter-js/commit/a882a74))\n* optimised Matter.Resolver ([fceb0ca](https://github.com/liabru/matter-js/commit/fceb0ca)), ([49fbfba](https://github.com/liabru/matter-js/commit/49fbfba)), ([0b07a31](https://github.com/liabru/matter-js/commit/0b07a31)), ([f847f4c](https://github.com/liabru/matter-js/commit/f847f4c)), ([3cf65e8](https://github.com/liabru/matter-js/commit/3cf65e8)), ([30b899c](https://github.com/liabru/matter-js/commit/30b899c)), ([e4b35d3](https://github.com/liabru/matter-js/commit/e4b35d3))\n* optimised Matter.SAT ([0d90a17](https://github.com/liabru/matter-js/commit/0d90a17)), ([2096961](https://github.com/liabru/matter-js/commit/2096961)), ([0af144c](https://github.com/liabru/matter-js/commit/0af144c))\n* optimised Matter.Vertices ([c198878](https://github.com/liabru/matter-js/commit/c198878)), ([6883d0d](https://github.com/liabru/matter-js/commit/6883d0d)), ([792ae2e](https://github.com/liabru/matter-js/commit/792ae2e))\n* refactor test worker and prevent test cache ([ca2fe75](https://github.com/liabru/matter-js/commit/ca2fe75)), ([bcc3168](https://github.com/liabru/matter-js/commit/bcc3168))\n* replaced Matter.SAT with Matter.Collision ([b9e7d9d](https://github.com/liabru/matter-js/commit/b9e7d9d))\n* show debug stats in dev demo ([2f14ec5](https://github.com/liabru/matter-js/commit/2f14ec5))\n* updated dev dependencies ([c5028d5](https://github.com/liabru/matter-js/commit/c5028d5))\n* updated examples ([c80ed5c](https://github.com/liabru/matter-js/commit/c80ed5c))\n* updated test scripts ([afa467a](https://github.com/liabru/matter-js/commit/afa467a))\n* use force exit in tests ([8adf810](https://github.com/liabru/matter-js/commit/8adf810))\n* use Matter.Runner in test worker ([2581595](https://github.com/liabru/matter-js/commit/2581595))\n\n\n\n## <small>0.17.1 (2021-04-14)</small>\n\n* deprecate Engine.run alias replaced by Runner.run ([5817046](https://github.com/liabru/matter-js/commit/5817046))\n\n\n\n## 0.17.0 (2021-04-11)\n\n* add Common.setDecomp and Common.getDecomp ([313c150](https://github.com/liabru/matter-js/commit/313c150))\n* add demo build config and refactor demo ([653a647](https://github.com/liabru/matter-js/commit/653a647))\n* add docs for all Matter.Render options ([ec3eecc](https://github.com/liabru/matter-js/commit/ec3eecc))\n* add title to all examples ([f4d72ba](https://github.com/liabru/matter-js/commit/f4d72ba))\n* added Common.deprecated ([ffa3193](https://github.com/liabru/matter-js/commit/ffa3193))\n* added Common.warnOnce ([6957dbf](https://github.com/liabru/matter-js/commit/6957dbf))\n* added Date.now fallback to Common.now, closes #739 ([c06c107](https://github.com/liabru/matter-js/commit/c06c107)), closes [#739](https://github.com/liabru/matter-js/issues/739)\n* added debug stats and performance monitoring to Matter.Render ([119881b](https://github.com/liabru/matter-js/commit/119881b))\n* added doc watch script ([164456b](https://github.com/liabru/matter-js/commit/164456b))\n* added docs for additional engine timing and render properties ([8017bdb](https://github.com/liabru/matter-js/commit/8017bdb))\n* added Example.stats ([9915007](https://github.com/liabru/matter-js/commit/9915007))\n* added lastDelta and lastElapsed to engine.timing ([6dc703f](https://github.com/liabru/matter-js/commit/6dc703f))\n* build demo ([0816454](https://github.com/liabru/matter-js/commit/0816454))\n* change all examples to use Composite.add instead of the alias World.add ([a3f298f](https://github.com/liabru/matter-js/commit/a3f298f))\n* changed engine.broadphase to engine.grid ([b74e400](https://github.com/liabru/matter-js/commit/b74e400))\n* changed Example.views to use render events ([3ac3498](https://github.com/liabru/matter-js/commit/3ac3498))\n* changed world.gravity to engine.gravity ([6abb3b7](https://github.com/liabru/matter-js/commit/6abb3b7))\n* deprecated Composites.car and added to car example ([cd9c5d4](https://github.com/liabru/matter-js/commit/cd9c5d4))\n* deprecated Composites.newtonsCradle and added to newtonsCradle example ([9ad980b](https://github.com/liabru/matter-js/commit/9ad980b))\n* deprecated Composites.softBody and added to softBody and cloth examples ([818f354](https://github.com/liabru/matter-js/commit/818f354))\n* improve Render.debug ([1753bf0](https://github.com/liabru/matter-js/commit/1753bf0))\n* migrate Matter.World to the equivalent Matter.Composite ([5dbec9b](https://github.com/liabru/matter-js/commit/5dbec9b))\n* remove deprecated backwards compatibility engine events from Matter.Runner ([76bf80e](https://github.com/liabru/matter-js/commit/76bf80e))\n* remove deprecated backwards compatibility render integration from Matter.Engine ([1aa8ed0](https://github.com/liabru/matter-js/commit/1aa8ed0))\n* remove deprecated backwards compatibility render integration from Matter.Runner ([6805f85](https://github.com/liabru/matter-js/commit/6805f85))\n* remove deprecated Matter.Metrics ([63a9e98](https://github.com/liabru/matter-js/commit/63a9e98))\n* remove deprecated Matter.RenderPixi ([08a515b](https://github.com/liabru/matter-js/commit/08a515b))\n* remove unused render shadow function ([e49834d](https://github.com/liabru/matter-js/commit/e49834d))\n* run all examples in browser tests ([5734bfd](https://github.com/liabru/matter-js/commit/5734bfd))\n* set render showDebug option on examples stress and stress2 ([f2ef3aa](https://github.com/liabru/matter-js/commit/f2ef3aa))\n* update matter-tools ([f8d366a](https://github.com/liabru/matter-js/commit/f8d366a))\n\n\n\n## <small>0.16.1 (2021-01-31)</small>\n\n* add log capture and reporting in tests ([7bfd3c2](https://github.com/liabru/matter-js/commit/7bfd3c2))\n* add matter-wrap as dev dependency ([ef7c4c6](https://github.com/liabru/matter-js/commit/ef7c4c6))\n* catch missing plugin require in examples ([1ba1255](https://github.com/liabru/matter-js/commit/1ba1255))\n* change example matter-wrap require precedence ([aa1e4e7](https://github.com/liabru/matter-js/commit/aa1e4e7))\n* change perf threshold in test ([7b00354](https://github.com/liabru/matter-js/commit/7b00354))\n* change test worker decomp require ([5e746b0](https://github.com/liabru/matter-js/commit/5e746b0))\n* disable jest cache ([8ee0ebb](https://github.com/liabru/matter-js/commit/8ee0ebb))\n* enable useful dev server features ([839f7d9](https://github.com/liabru/matter-js/commit/839f7d9))\n* fix decomp require and improve warning message ([e87f64a](https://github.com/liabru/matter-js/commit/e87f64a))\n* fix dev server externals ([1f2f9fe](https://github.com/liabru/matter-js/commit/1f2f9fe))\n* fix named require in test ([92080ff](https://github.com/liabru/matter-js/commit/92080ff))\n* improve CI speed ([1af64eb](https://github.com/liabru/matter-js/commit/1af64eb))\n* improve docs for Bodies.fromVertices ([2ade78f](https://github.com/liabru/matter-js/commit/2ade78f))\n* improve stack examples with exact contact ([522f4e8](https://github.com/liabru/matter-js/commit/522f4e8))\n* improve test report log ([b5326f8](https://github.com/liabru/matter-js/commit/b5326f8))\n\n\n\n## 0.16.0 (2021-01-17)\n\n* added removeDuplicatePoints option from poly-decomp 0.3.0 to Bodies.fromVertices ([#639](https://github.com/liabru/matter-js/issues/639), [947cb97](https://github.com/liabru/matter-js/commit/947cb97), [a9694e6](https://github.com/liabru/matter-js/commit/a9694e6))\n* added support for > and >= operators in plugin version ranges ([0792716](https://github.com/liabru/matter-js/commit/0792716))\n* added support for example versioning in tests ([31d0ace](https://github.com/liabru/matter-js/commit/31d0ace))\n* added version targets for examples ([142b7de](https://github.com/liabru/matter-js/commit/142b7de))\n* added warning check on browser tests ([12377cc](https://github.com/liabru/matter-js/commit/12377cc))\n* changed svg and terrain example to use fetch ([5551cd5](https://github.com/liabru/matter-js/commit/5551cd5))\n* changed deprecated comments to avoid confusion ([1e73cab](https://github.com/liabru/matter-js/commit/1e73cab))\n* fixed poly-decomp external require ([882e07c](https://github.com/liabru/matter-js/commit/882e07c))\n* removed bower.json ([f71d4c0](https://github.com/liabru/matter-js/commit/f71d4c0))\n* removed unused dev dependency run-sequence ([be592fd](https://github.com/liabru/matter-js/commit/be592fd))\n* updated dev dependencies ([151eb30](https://github.com/liabru/matter-js/commit/151eb30))\n* updated matter-tools ([5c66458](https://github.com/liabru/matter-js/commit/5c66458))\n* updated matter-tools ([33e8fe8](https://github.com/liabru/matter-js/commit/33e8fe8))\n* updated demo matter-tools ([a694ae5](https://github.com/liabru/matter-js/commit/a694ae5))\n* updated demo pathseg ([9c5325b](https://github.com/liabru/matter-js/commit/9c5325b))\n* updated readme ([3089b41](https://github.com/liabru/matter-js/commit/3089b41))\n\n\n\n## 0.15.0 (2020-12-24)\n\n* add window global, stub require and handle bad values in test tools ([497ac80](https://github.com/liabru/matter-js/commit/497ac80))\n* added Body.setCentre, closes #684, closes #461, closes #679 ([2ec247b](https://github.com/liabru/matter-js/commit/2ec247b)), closes [#684](https://github.com/liabru/matter-js/issues/684) [#461](https://github.com/liabru/matter-js/issues/461) [#679](https://github.com/liabru/matter-js/issues/679)\n* added browser tests ([ceb7cd5](https://github.com/liabru/matter-js/commit/ceb7cd5))\n* Added build comparison tools and tests ([b7c938a](https://github.com/liabru/matter-js/commit/b7c938a))\n* added check for window in Common.now ([9ef9d02](https://github.com/liabru/matter-js/commit/9ef9d02))\n* added comparison output file option to test tools ([45aae25](https://github.com/liabru/matter-js/commit/45aae25))\n* Added config and test files to lint ([21e4ea6](https://github.com/liabru/matter-js/commit/21e4ea6))\n* added Constraint.pointAWorld and Constraint.pointBWorld ([3c32969](https://github.com/liabru/matter-js/commit/3c32969))\n* added examples to dev server bundle and commit built examples ([fe80478](https://github.com/liabru/matter-js/commit/fe80478))\n* added module export to examples ([f9ea799](https://github.com/liabru/matter-js/commit/f9ea799))\n* added overlap metric to test tools ([3fd674d](https://github.com/liabru/matter-js/commit/3fd674d))\n* added release scripts ([341c247](https://github.com/liabru/matter-js/commit/341c247))\n* added tag push to release task ([060283b](https://github.com/liabru/matter-js/commit/060283b))\n* added timing to engine snapshot ([e0cdbb8](https://github.com/liabru/matter-js/commit/e0cdbb8))\n* Added watch content base to dev server ([f471d4e](https://github.com/liabru/matter-js/commit/f471d4e))\n* added webpack build script ([046013e](https://github.com/liabru/matter-js/commit/046013e))\n* changed alpha build configuration ([182c84a](https://github.com/liabru/matter-js/commit/182c84a))\n* changed demo to auto populate examples with sourceLink and init ([5b0d34b](https://github.com/liabru/matter-js/commit/5b0d34b))\n* changed demo to serve without sub-directory ([823bbc0](https://github.com/liabru/matter-js/commit/823bbc0))\n* changed docs build config ([864452d](https://github.com/liabru/matter-js/commit/864452d))\n* changed example tests to use jest ([104d319](https://github.com/liabru/matter-js/commit/104d319))\n* fix decomp import in Bodies.fromVertices ([94e9614](https://github.com/liabru/matter-js/commit/94e9614))\n* fix decomp require ([0af1645](https://github.com/liabru/matter-js/commit/0af1645))\n* fix issues with render pixel ratio, closes #686, closes #687 ([d577477](https://github.com/liabru/matter-js/commit/d577477)), closes [#686](https://github.com/liabru/matter-js/issues/686) [#687](https://github.com/liabru/matter-js/issues/687)\n* fix lint ([5a0079d](https://github.com/liabru/matter-js/commit/5a0079d))\n* fix lint issues ([9ca21c1](https://github.com/liabru/matter-js/commit/9ca21c1))\n* fix path to build in test worker ([fcdb4fa](https://github.com/liabru/matter-js/commit/fcdb4fa))\n* fix preversion script ([c368c14](https://github.com/liabru/matter-js/commit/c368c14))\n* fix terrain example module export ([4a967ec](https://github.com/liabru/matter-js/commit/4a967ec))\n* Fix typo in docs ([c486635](https://github.com/liabru/matter-js/commit/c486635))\n* fixed plugins in compare ([82bb415](https://github.com/liabru/matter-js/commit/82bb415))\n* implemented threaded comparison testing ([285d70d](https://github.com/liabru/matter-js/commit/285d70d))\n* Optimized Body's hidden class ([b3220cf](https://github.com/liabru/matter-js/commit/b3220cf))\n* Optimized Events.trigger method when no event is emitted ([b17cb48](https://github.com/liabru/matter-js/commit/b17cb48))\n* remove gulp ([6a28090](https://github.com/liabru/matter-js/commit/6a28090))\n* remove old demo libs ([13c7eb5](https://github.com/liabru/matter-js/commit/13c7eb5))\n* removed unused gulp release tasks ([e5a7311](https://github.com/liabru/matter-js/commit/e5a7311))\n* removed yuidocjs dev dependency ([ee848d2](https://github.com/liabru/matter-js/commit/ee848d2))\n* Set loose build version on dev server ([1fcf292](https://github.com/liabru/matter-js/commit/1fcf292))\n* update build script ([90abab6](https://github.com/liabru/matter-js/commit/90abab6))\n* update default render theme ([d258411](https://github.com/liabru/matter-js/commit/d258411))\n* update demo and example render styles ([6dd5ec5](https://github.com/liabru/matter-js/commit/6dd5ec5))\n* update dependencies ([e1e058c](https://github.com/liabru/matter-js/commit/e1e058c)) ([5f5b8a1](https://github.com/liabru/matter-js/commit/5f5b8a1))\n* update examples build config and scripts ([69afb11](https://github.com/liabru/matter-js/commit/69afb11))\n* update package lock ([ac3da07](https://github.com/liabru/matter-js/commit/ac3da07))\n* updated build scripts ([6b698ea](https://github.com/liabru/matter-js/commit/6b698ea))\n* updated ci ([288b9cd](https://github.com/liabru/matter-js/commit/288b9cd))\n* updated docs ([50cf171](https://github.com/liabru/matter-js/commit/50cf171))\n* updated readme ([ea5c012](https://github.com/liabru/matter-js/commit/ea5c012)) ([61b1963](https://github.com/liabru/matter-js/commit/61b1963))\n\n\n\n<a name=\"0.14.2\"></a>\n## <small>0.14.2 (2018-06-11)</small>\n\n* added missing polyfill warning to Svg.pathToVertices ([511de5b](https://github.com/liabru/matter-js/commit/511de5b))\n* fix Composite.bounds global issue, closes #627, closes #544 ([f7f77b4](https://github.com/liabru/matter-js/commit/f7f77b4)), closes [#627](https://github.com/liabru/matter-js/issues/627) [#544](https://github.com/liabru/matter-js/issues/544)\n* fix docs for Vector.angle, closes #471 ([db30d79](https://github.com/liabru/matter-js/commit/db30d79)), closes [#471](https://github.com/liabru/matter-js/issues/471)\n* Fixed constraint pointB documentation ([0b5ce1d](https://github.com/liabru/matter-js/commit/0b5ce1d))\n* fixed require for external libraries, closes #629, closes #559, closes #593, closes #365, closes #62 ([0cf97f5](https://github.com/liabru/matter-js/commit/0cf97f5)), closes [#629](https://github.com/liabru/matter-js/issues/629) [#559](https://github.com/liabru/matter-js/issues/559) [#593](https://github.com/liabru/matter-js/issues/593) [#365](https://github.com/liabru/matter-js/issues/365) [#629](https://github.com/liabru/matter-js/issues/629)\n* remove browserify-shim ([e3c176e](https://github.com/liabru/matter-js/commit/e3c176e))\n* updated pathseg library, closes #548, closes #602, closes #424 ([1e5758f](https://github.com/liabru/matter-js/commit/1e5758f)), closes [#548](https://github.com/liabru/matter-js/issues/548) [#602](https://github.com/liabru/matter-js/issues/602) [#424](https://github.com/liabru/matter-js/issues/424)\n\n\n\n<a name=\"0.14.1\"></a>\n## 0.14.1 (2018-01-10)\n\n* fix Common.isElement on node, closes #535 ([ec38eeb](https://github.com/liabru/matter-js/commit/ec38eeb)), closes [#535](https://github.com/liabru/matter-js/issues/535)\n\n\n\n<a name=\"0.14.0\"></a>\n# 0.14.0 (2017-11-30)\n\n* added .eslintignore ([2279e15](https://github.com/liabru/matter-js/commit/2279e15))\n* added examples build task ([6108a31](https://github.com/liabru/matter-js/commit/6108a31))\n* added missing docs for Matter.World aliases ([841bf97](https://github.com/liabru/matter-js/commit/841bf97))\n* added Query.collides, closes #478 ([6593a72](https://github.com/liabru/matter-js/commit/6593a72)), closes [#478](https://github.com/liabru/matter-js/issues/478)\n* change examples to render using a fixed resolution ([0895d81](https://github.com/liabru/matter-js/commit/0895d81))\n* Do not warn on missing render.element if the canvas is already parented (because it was passed in at ([a529ec9](https://github.com/liabru/matter-js/commit/a529ec9))\n* fix `point` argument of Body.scale, closes #428 ([894c1ef](https://github.com/liabru/matter-js/commit/894c1ef)), closes [#428](https://github.com/liabru/matter-js/issues/428)\n* fix Body.scale for compound bodies ([50a89d0](https://github.com/liabru/matter-js/commit/50a89d0))\n* fix centroid for static compound bodies, closes #483 ([ece66e6](https://github.com/liabru/matter-js/commit/ece66e6)), closes [#483](https://github.com/liabru/matter-js/issues/483)\n* fix Common.isElement, closes #501, closes #507, closes #459, closes #468, closes #517 ([18a0845](https://github.com/liabru/matter-js/commit/18a0845)), closes [#501](https://github.com/liabru/matter-js/issues/501) [#507](https://github.com/liabru/matter-js/issues/507) [#459](https://github.com/liabru/matter-js/issues/459) [#468](https://github.com/liabru/matter-js/issues/468) [#517](https://github.com/liabru/matter-js/issues/517)\n* fix inertia change in Body.setMass, closes #378 ([f7d1877](https://github.com/liabru/matter-js/commit/f7d1877)), closes [#378](https://github.com/liabru/matter-js/issues/378)\n* fix Vertices.chamfer radius argument, closes #467 ([3bceef4](https://github.com/liabru/matter-js/commit/3bceef4)), closes [#467](https://github.com/liabru/matter-js/issues/467)\n* improved docs for constraints on compound bodies, closes #442 ([3307760](https://github.com/liabru/matter-js/commit/3307760)), closes [#442](https://github.com/liabru/matter-js/issues/442)\n* moved all private functions to module namespaces ([64be5a5](https://github.com/liabru/matter-js/commit/64be5a5))\n* moved private Matter.Engine functions on to namespace, closes #523 ([9eae36f](https://github.com/liabru/matter-js/commit/9eae36f)), closes [#523](https://github.com/liabru/matter-js/issues/523)\n* remove spelling mistake ([e5c4b47](https://github.com/liabru/matter-js/commit/e5c4b47))\n\n\n\n<a name=\"0.13.0\"></a>\n# 0.13.0 (2017-07-06)\n\n* added Composite.bounds ([79ffcf8](https://github.com/liabru/matter-js/commit/79ffcf8))\n* added constraint damping ([44c4d1f](https://github.com/liabru/matter-js/commit/44c4d1f))\n* added constraint.render.type and constraint.render.anchor ([0952516](https://github.com/liabru/matter-js/commit/0952516))\n* added Example.constraints ([b93c08f](https://github.com/liabru/matter-js/commit/b93c08f))\n* added Example.doublePendulum ([a7aa47d](https://github.com/liabru/matter-js/commit/a7aa47d))\n* added Examples.ragdoll ([48611c5](https://github.com/liabru/matter-js/commit/48611c5))\n* added optional output argument to Vector.rotate ([59d62be](https://github.com/liabru/matter-js/commit/59d62be))\n* added rotation point parameter to Body.rotate, closes #410 ([749ed50](https://github.com/liabru/matter-js/commit/749ed50)), closes [#410](https://github.com/liabru/matter-js/issues/410)\n* added second pass for constraint solving ([f49d053](https://github.com/liabru/matter-js/commit/f49d053))\n* change constraint solve order ([a5bd6b2](https://github.com/liabru/matter-js/commit/a5bd6b2))\n* changed lint rules ([d1fbe95](https://github.com/liabru/matter-js/commit/d1fbe95))\n* fix constraint.angularStiffness ([ab0283b](https://github.com/liabru/matter-js/commit/ab0283b))\n* fix Example.collisionFiltering rendering ([74a7cfc](https://github.com/liabru/matter-js/commit/74a7cfc))\n* fix lint errors ([774d8bc](https://github.com/liabru/matter-js/commit/774d8bc))\n* fix soft body stiffness ([1bae2de](https://github.com/liabru/matter-js/commit/1bae2de))\n* fixed Common.now ([2b76c4c](https://github.com/liabru/matter-js/commit/2b76c4c))\n* fixed constraint torque calculation ([a8d1950](https://github.com/liabru/matter-js/commit/a8d1950))\n* fixed constraint torque calculation ([068fdc0](https://github.com/liabru/matter-js/commit/068fdc0))\n* fixed Examples.compound constraint offset ([e6babf0](https://github.com/liabru/matter-js/commit/e6babf0))\n* fixed various constraints in examples ([ac67ef8](https://github.com/liabru/matter-js/commit/ac67ef8))\n* fixed various problems with constraints ([26a60e4](https://github.com/liabru/matter-js/commit/26a60e4))\n* implemented constraint warming ([daf26af](https://github.com/liabru/matter-js/commit/daf26af))\n* improved Example.car using pin constraint ([130e6b3](https://github.com/liabru/matter-js/commit/130e6b3))\n* improved Example.catapult using pin constraint ([0e15099](https://github.com/liabru/matter-js/commit/0e15099))\n* improved Example.chains using pin constraint ([9d2f0ff](https://github.com/liabru/matter-js/commit/9d2f0ff))\n* improved Examples.bridge ([b277b39](https://github.com/liabru/matter-js/commit/b277b39))\n* improved Examples.bridge ([b6e5973](https://github.com/liabru/matter-js/commit/b6e5973))\n* improved position resolver ([71998a0](https://github.com/liabru/matter-js/commit/71998a0))\n* improved spring and pin rendering ([837c43b](https://github.com/liabru/matter-js/commit/837c43b))\n* refactored Common.isElement ([295cffe](https://github.com/liabru/matter-js/commit/295cffe))\n* removed Common.shadeColor ([d63b0c2](https://github.com/liabru/matter-js/commit/d63b0c2))\n* tweaked Example.doublePendulum ([4894008](https://github.com/liabru/matter-js/commit/4894008))\n* update alpha build ([fe9b05d](https://github.com/liabru/matter-js/commit/fe9b05d))\n* update alpha build ([b874f4d](https://github.com/liabru/matter-js/commit/b874f4d))\n* update alpha build ([08aa3f2](https://github.com/liabru/matter-js/commit/08aa3f2))\n* update readme and remove redundant plugins ([2560a68](https://github.com/liabru/matter-js/commit/2560a68))\n* Update README.md ([4168d3c](https://github.com/liabru/matter-js/commit/4168d3c))\n* updated license and contributing ([d2af721](https://github.com/liabru/matter-js/commit/d2af721))\n* updated readme ([26c1200](https://github.com/liabru/matter-js/commit/26c1200))\n* upgraded matter-tools ([477f2d7](https://github.com/liabru/matter-js/commit/477f2d7))\n* upgraded matter-wrap ([c9294eb](https://github.com/liabru/matter-js/commit/c9294eb))\n\n\n\n<a name=\"0.12.0\"></a>\n# 0.12.0 (2017-02-02)\n\n* add poly-decamp require shim ([c72a9d0](https://github.com/liabru/matter-js/commit/c72a9d0))\n* added body.plugin, composite.plugin, constraint.plugin, engine.plugin properties ([b353393](https://github.com/liabru/matter-js/commit/b353393))\n* added Render.lookAt ([47443b3](https://github.com/liabru/matter-js/commit/47443b3))\n* added Render.startViewTransform and Render.endViewTransform ([c8e5d5c](https://github.com/liabru/matter-js/commit/c8e5d5c))\n* change Matter.MouseConstraint to use engine beforeUpdate event, closes #73 ([ffb128c](https://github.com/liabru/matter-js/commit/ffb128c)), closes [#73](https://github.com/liabru/matter-js/issues/73)\n* changed default render styles ([719ad64](https://github.com/liabru/matter-js/commit/719ad64))\n* changed plugins to use body.plugin ([3fdf343](https://github.com/liabru/matter-js/commit/3fdf343))\n* fix Body.setStatic(body, false), closes #187 ([a815ce4](https://github.com/liabru/matter-js/commit/a815ce4)), closes [#187](https://github.com/liabru/matter-js/issues/187)\n* fix build temporarily ([805ff2a](https://github.com/liabru/matter-js/commit/805ff2a))\n* fix lint ([0ce686d](https://github.com/liabru/matter-js/commit/0ce686d))\n* fix lint ([714b8ae](https://github.com/liabru/matter-js/commit/714b8ae))\n* fix Render.grid ([dd83386](https://github.com/liabru/matter-js/commit/dd83386))\n* fix test npm script ([6285df9](https://github.com/liabru/matter-js/commit/6285df9))\n* fix v8 optimisation issues ([86c4a61](https://github.com/liabru/matter-js/commit/86c4a61))\n* Fixes #220 ([74de894](https://github.com/liabru/matter-js/commit/74de894)), closes [#220](https://github.com/liabru/matter-js/issues/220)\n* improved demo and examples ([1a40f27](https://github.com/liabru/matter-js/commit/1a40f27))\n* improved demo and examples ([ace1a9f](https://github.com/liabru/matter-js/commit/ace1a9f))\n* improved demo and examples ([8cdbb38](https://github.com/liabru/matter-js/commit/8cdbb38))\n* Update to latest poly-decomp.js API ([3d8f88e](https://github.com/liabru/matter-js/commit/3d8f88e))\n* updated alpha build ([6c19f0b](https://github.com/liabru/matter-js/commit/6c19f0b))\n* updated dependencies ([8c140bd](https://github.com/liabru/matter-js/commit/8c140bd))\n* updated matter-tools ([def8d22](https://github.com/liabru/matter-js/commit/def8d22))\n\n\n\n<a name=\"0.11.1\"></a>\n## 0.11.1 (2016-11-09)\n\n\n* added derequire to build ([ded796c](https://github.com/liabru/matter-js/commit/ded796c))\n\n\n\n<a name=\"0.11.0\"></a>\n# 0.11.0 (2016-11-04)\n\n\n* add logo to readme ([d54dec3](https://github.com/liabru/matter-js/commit/d54dec3))\n* added docs for Matter.Plugin with tweaks ([3883981](https://github.com/liabru/matter-js/commit/3883981))\n* added Example.attractors ([758bbe8](https://github.com/liabru/matter-js/commit/758bbe8))\n* added Matter.before, Matter.after, Common.chainPathBefore, Common.chainPathAfter, Common.get, Common ([50ad7ca](https://github.com/liabru/matter-js/commit/50ad7ca))\n* added Matter.Plugin initial implementation ([e84c537](https://github.com/liabru/matter-js/commit/e84c537))\n* added note in docs about vertices order ([ad033f5](https://github.com/liabru/matter-js/commit/ad033f5))\n* added plugin status logging ([51b7b1d](https://github.com/liabru/matter-js/commit/51b7b1d))\n* added plugins matter-attractors, matter-gravity, matter-world-wrap, removed test plugins ([59bfa0b](https://github.com/liabru/matter-js/commit/59bfa0b))\n* change plugins to use best practices ([37d4258](https://github.com/liabru/matter-js/commit/37d4258))\n* change travis node version to latest stable ([ee33686](https://github.com/liabru/matter-js/commit/ee33686))\n* changed naming approach for prerelease versions ([83ae546](https://github.com/liabru/matter-js/commit/83ae546))\n* fix build flags ([29d182c](https://github.com/liabru/matter-js/commit/29d182c))\n* fix build task for travis ([6aa3661](https://github.com/liabru/matter-js/commit/6aa3661))\n* fix gravity reset in demo ([c00df81](https://github.com/liabru/matter-js/commit/c00df81))\n* fix gulp build version replacement ([faf6bec](https://github.com/liabru/matter-js/commit/faf6bec))\n* fix Matter.Mouse when element does not have fixed dimensions, closes #73 ([1340159](https://github.com/liabru/matter-js/commit/1340159)), closes [#73](https://github.com/liabru/matter-js/issues/73)\n* fix release tasks ([549983d](https://github.com/liabru/matter-js/commit/549983d))\n* fix requestAnimationFrame polyfill for Matter.Runner, closes #252 ([7c8f6ce](https://github.com/liabru/matter-js/commit/7c8f6ce)), closes [#252](https://github.com/liabru/matter-js/issues/252)\n* fix tests ([54e7d9c](https://github.com/liabru/matter-js/commit/54e7d9c))\n* fixed Body.create with no options ([0e5a457](https://github.com/liabru/matter-js/commit/0e5a457))\n* fixed issue with Matter.RenderPixi not being cleared when bodies removed, closes #218 ([4972af8](https://github.com/liabru/matter-js/commit/4972af8)), closes [#218](https://github.com/liabru/matter-js/issues/218)\n* fixed various Matter.Plugin issues ([05d0961](https://github.com/liabru/matter-js/commit/05d0961))\n* improve docs ([9856e3c](https://github.com/liabru/matter-js/commit/9856e3c))\n* improved logging ([d4d64ed](https://github.com/liabru/matter-js/commit/d4d64ed))\n* Limit packaging extraneous files ([3accec6](https://github.com/liabru/matter-js/commit/3accec6))\n* Merge branch 'jackismissing-master' ([3452465](https://github.com/liabru/matter-js/commit/3452465))\n* Merge branch 'master' of https://github.com/jackismissing/matter-js into jackismissing-master ([ba19130](https://github.com/liabru/matter-js/commit/ba19130))\n* Merge branch 'plugins' ([60d0839](https://github.com/liabru/matter-js/commit/60d0839))\n* Merge pull request #1 from jackismissing/jackismissing-patch-1 ([46a2bf6](https://github.com/liabru/matter-js/commit/46a2bf6))\n* Merge pull request #244 from MarkHerhold/master ([3449ca5](https://github.com/liabru/matter-js/commit/3449ca5))\n* refactor plugin system ([8da170f](https://github.com/liabru/matter-js/commit/8da170f))\n* refactored plugins ([b4a3453](https://github.com/liabru/matter-js/commit/b4a3453))\n* remove and ignore all test refs ([7a7187a](https://github.com/liabru/matter-js/commit/7a7187a))\n* RenderPixi.js - added missing dependencies ([aec19ae](https://github.com/liabru/matter-js/commit/aec19ae))\n* update Matter.Plugin docs ([6f8b705](https://github.com/liabru/matter-js/commit/6f8b705))\n* updated edge build ([1d05499](https://github.com/liabru/matter-js/commit/1d05499))\n* updated edge build ([0bdaece](https://github.com/liabru/matter-js/commit/0bdaece))\n* updated readme ([a408854](https://github.com/liabru/matter-js/commit/a408854))\n* updated readme ([4da2e25](https://github.com/liabru/matter-js/commit/4da2e25))\n* updated readme ([9ccc028](https://github.com/liabru/matter-js/commit/9ccc028))\n* updated readme ([faf534a](https://github.com/liabru/matter-js/commit/faf534a))\n* updated readme ([5ca9aca](https://github.com/liabru/matter-js/commit/5ca9aca))\n* updated readme ([e3e9080](https://github.com/liabru/matter-js/commit/e3e9080))\n* updated readme ([c4cce9e](https://github.com/liabru/matter-js/commit/c4cce9e))\n* updated readme ([4b5837e](https://github.com/liabru/matter-js/commit/4b5837e))\n* updated readme ([098f224](https://github.com/liabru/matter-js/commit/098f224))\n\n\n\n<a name=\"0.10.0\"></a>\n# 0.10.0 (2016-05-01)\n\n\n* added release:push:docs task ([04cbd1d](https://github.com/liabru/matter-js/commit/04cbd1d))\n* decouple Matter.Render from Matter.Engine ([de823eb](https://github.com/liabru/matter-js/commit/de823eb))\n* decouple Matter.RenderPixi ([72f90b9](https://github.com/liabru/matter-js/commit/72f90b9))\n* deprecated Matter.RenderPixi ([e8c899a](https://github.com/liabru/matter-js/commit/e8c899a))\n* deprecated Matter.RenderPixi ([a6b97cd](https://github.com/liabru/matter-js/commit/a6b97cd))\n* fix tests ([f59e220](https://github.com/liabru/matter-js/commit/f59e220))\n* fix tests ([c26684e](https://github.com/liabru/matter-js/commit/c26684e))\n* Merge branch 'decouple-renderer' ([31067c9](https://github.com/liabru/matter-js/commit/31067c9))\n\n\n\n<a name=\"0.9.3\"></a>\n## 0.9.3 (2016-04-19)\n\n\n* added readonly to docs for type property, closes #235 ([afd7531](https://github.com/liabru/matter-js/commit/afd7531)), closes [#235](https://github.com/liabru/matter-js/issues/235)\n* Engine uses provided world; fixes issue #230 ([158c404](https://github.com/liabru/matter-js/commit/158c404)), closes [#230](https://github.com/liabru/matter-js/issues/230)\n* fix issue with removed bodies causing collisions ([23a773a](https://github.com/liabru/matter-js/commit/23a773a))\n* fix Matter.Engine.create docs to show element param is optional ([e2e7c0b](https://github.com/liabru/matter-js/commit/e2e7c0b))\n* handle missing options in Engine.create ([f36fe2c](https://github.com/liabru/matter-js/commit/f36fe2c))\n* improved release tasks ([e13d2d2](https://github.com/liabru/matter-js/commit/e13d2d2))\n* Merge branch 'master' of github.com:liabru/matter-js ([d373172](https://github.com/liabru/matter-js/commit/d373172))\n* Merge pull request #237 from iamjoshua/master ([b724959](https://github.com/liabru/matter-js/commit/b724959)), closes [#230](https://github.com/liabru/matter-js/issues/230)\n* set release task to default to patch ([9d396fe](https://github.com/liabru/matter-js/commit/9d396fe))\n* updated edge build ([7eb9ac7](https://github.com/liabru/matter-js/commit/7eb9ac7))\n\n\n\n<a name=\"0.9.2\"></a>\n## 0.9.2 (2016-04-07)\n\n\n* Add permeability example and doc entry ([6e7add1](https://github.com/liabru/matter-js/commit/6e7add1))\n* Add permeable objects ([1573359](https://github.com/liabru/matter-js/commit/1573359))\n* Change permeable name to sensors, add isSensor to Pair ([28084b0](https://github.com/liabru/matter-js/commit/28084b0))\n* Document World bounds and Grid bucket size. ([5054c97](https://github.com/liabru/matter-js/commit/5054c97))\n* fix Body.scale for circles, closes #234 ([f428d6b](https://github.com/liabru/matter-js/commit/f428d6b)), closes [#234](https://github.com/liabru/matter-js/issues/234)\n* Fix the out-of-bounds check in grid broadphase ([a20a9fb](https://github.com/liabru/matter-js/commit/a20a9fb))\n* Merge pull request #224 from brollb/223-bounds-ignored-in-renderer ([1944f6a](https://github.com/liabru/matter-js/commit/1944f6a)), closes [#223](https://github.com/liabru/matter-js/issues/223)\n* Merge pull request #231 from Rantanen/patch-1 ([b6f6a03](https://github.com/liabru/matter-js/commit/b6f6a03))\n* Merge pull request #232 from Rantanen/docs ([79fa57e](https://github.com/liabru/matter-js/commit/79fa57e))\n* Merged sensors from Misiur-master ([e1a52d5](https://github.com/liabru/matter-js/commit/e1a52d5))\n* Update README.md ([a5b535d](https://github.com/liabru/matter-js/commit/a5b535d))\n* Update README.md ([a31ab39](https://github.com/liabru/matter-js/commit/a31ab39))\n* Updated `hasBounds` default value. Fixes #223 ([053ea76](https://github.com/liabru/matter-js/commit/053ea76)), closes [#223](https://github.com/liabru/matter-js/issues/223)\n* updated test refs ([93ba111](https://github.com/liabru/matter-js/commit/93ba111))\n\n\n\n<a name=\"0.9.1\"></a>\n## 0.9.1 (2016-02-15)\n\n\n* added default for delta parameter in Engine.update, closes #200 ([490d232](https://github.com/liabru/matter-js/commit/490d232)), closes [#200](https://github.com/liabru/matter-js/issues/200)\n* added docs for body.render.opacity ([adcb610](https://github.com/liabru/matter-js/commit/adcb610))\n* added SVGPathSeg polyfill, closes #196 ([8fcb893](https://github.com/liabru/matter-js/commit/8fcb893)), closes [#196](https://github.com/liabru/matter-js/issues/196)\n* Adding the opacity attribute to be able to draw semi-transarent sprites ([5b755a1](https://github.com/liabru/matter-js/commit/5b755a1))\n* allow passing of pixi objects to Matter.RenderPixi at creation, closes #193 ([dbdabcc](https://github.com/liabru/matter-js/commit/dbdabcc)), closes [#193](https://github.com/liabru/matter-js/issues/193)\n* change main reference in package.json ([633c305](https://github.com/liabru/matter-js/commit/633c305))\n* Changed bounds checking MIN_VALUE to -MAX_VALUE. Fixes #202 ([dd5e260](https://github.com/liabru/matter-js/commit/dd5e260)), closes [#202](https://github.com/liabru/matter-js/issues/202)\n* fix issue with Bodies.circle label option, closes #195 ([e7e8c26](https://github.com/liabru/matter-js/commit/e7e8c26)), closes [#195](https://github.com/liabru/matter-js/issues/195)\n* fix lint issue ([b4e875b](https://github.com/liabru/matter-js/commit/b4e875b))\n* fixed build issue ([bb3d43f](https://github.com/liabru/matter-js/commit/bb3d43f))\n* fixed rendering of angle indicators ([aaffee3](https://github.com/liabru/matter-js/commit/aaffee3))\n* fixed rendering of compound bodies ([99dd6c5](https://github.com/liabru/matter-js/commit/99dd6c5))\n* fixes to body opacity rendering ([8ac06b2](https://github.com/liabru/matter-js/commit/8ac06b2))\n* Merge branch 'master' of https://github.com/ma1069/matter-js into ma1069-master ([c99e6af](https://github.com/liabru/matter-js/commit/c99e6af))\n* Merge pull request #199 from kevinboudot/master ([34fa27a](https://github.com/liabru/matter-js/commit/34fa27a))\n* remove redundant console.log from gulpfile ([b5006e3](https://github.com/liabru/matter-js/commit/b5006e3))\n* Update README.md ([1bfb758](https://github.com/liabru/matter-js/commit/1bfb758))\n* updated edge build ([cc80837](https://github.com/liabru/matter-js/commit/cc80837))\n* updated test refs ([cfdc0b3](https://github.com/liabru/matter-js/commit/cfdc0b3))\n* updated test refs ([4d65dd1](https://github.com/liabru/matter-js/commit/4d65dd1))\n\n\n\n<a name=\"0.9.0\"></a>\n# 0.9.0 (2016-01-16)\n\n### release summary\n\n* improved documentation\n* improved performance\n* improved stability\n* improved accuracy\n* improved friction\n* improved sleeping\n* improved constraints\n* improved examples\n\n* added concave body support\n* added compound body support\n* added collision filters\n* added Matter.Body property setters\n* added Matter.Sleeping events\n* added Matter.Composite events\n* added Matter.Composite transforms\n* added Matter.MouseConstraint events\n* added Matter.Render events\n* added Matter.Runner\n* added support for nodejs\n* added support for high dpi rendering\n* added multiple examples\n* added automated tests\n\n* migrated from grunt to gulp\n* migrated to browserify\n* migrated to pixi.js v3\n\n* fixed multiple issues (see commit log)\n\n\n### commit log\n\n* Add Pixi DisplayObjectContainer to allow view bounds in webGL ([97f0f8d](https://github.com/liabru/matter-js/commit/97f0f8d))\n* added beforeRender and afterRender events to Matter.Render ([aa48322](https://github.com/liabru/matter-js/commit/aa48322))\n* added body sleepStart and sleepEnd events, closes #91 ([bc26469](https://github.com/liabru/matter-js/commit/bc26469)), closes [#91](https://github.com/liabru/matter-js/issues/91)\n* added Body.nextCategory ([d249165](https://github.com/liabru/matter-js/commit/d249165))\n* added Body.set ([235b6c8](https://github.com/liabru/matter-js/commit/235b6c8))\n* added Body.setMass, Body.setDensity, Body.setInertia ([ca978fa](https://github.com/liabru/matter-js/commit/ca978fa))\n* added Body.setPosition, Body.setAngle, Body.setVelocity, Body.setAngularVelocity ([7ed28f7](https://github.com/liabru/matter-js/commit/7ed28f7))\n* added Body.setVertices and Vector.clone ([b6dbb25](https://github.com/liabru/matter-js/commit/b6dbb25))\n* added building and contributing to readme ([9a59e34](https://github.com/liabru/matter-js/commit/9a59e34))\n* added collisionFilter support to MouseConstraint ([cee8d55](https://github.com/liabru/matter-js/commit/cee8d55))\n* added composite events ([2841522](https://github.com/liabru/matter-js/commit/2841522))\n* added composite events example to Demo.events ([296d47e](https://github.com/liabru/matter-js/commit/296d47e))\n* added Composite.translate, Composite.rotate, Composite.scale ([4c4962f](https://github.com/liabru/matter-js/commit/4c4962f))\n* added compound support to Query.ray ([10e5d0f](https://github.com/liabru/matter-js/commit/10e5d0f))\n* added constraint to Demo.compound ([87fbf51](https://github.com/liabru/matter-js/commit/87fbf51))\n* added CONTRIBUTING.md ([7c936d5](https://github.com/liabru/matter-js/commit/7c936d5))\n* added CONTRIBUTING.md ([261c794](https://github.com/liabru/matter-js/commit/261c794))\n* added Demo.compositeManipulation ([4051823](https://github.com/liabru/matter-js/commit/4051823))\n* added Demo.compound ([b7bf5d6](https://github.com/liabru/matter-js/commit/b7bf5d6))\n* added Demo.concave, added Bodies.fromVertices, added Vertices.isConvex, fixed compound properties ([0b8efa5](https://github.com/liabru/matter-js/commit/0b8efa5))\n* added Demo.manipulation ([0a453a2](https://github.com/liabru/matter-js/commit/0a453a2))\n* added Demo.setManualControl ([203252a](https://github.com/liabru/matter-js/commit/203252a))\n* added Demo.slingshot ([3043baa](https://github.com/liabru/matter-js/commit/3043baa))\n* added Demo.staticFriction ([4491dfd](https://github.com/liabru/matter-js/commit/4491dfd))\n* added Demo.svg, Demo.compoundStack, Demo.concave ([17589bc](https://github.com/liabru/matter-js/commit/17589bc))\n* added Demo.terrain ([3132d70](https://github.com/liabru/matter-js/commit/3132d70))\n* added docs ([200fcbe](https://github.com/liabru/matter-js/commit/200fcbe))\n* added docs for engine.timing.isFixed ([e22ceeb](https://github.com/liabru/matter-js/commit/e22ceeb))\n* added drag events to MouseConstraint, closes #45 ([c254c8d](https://github.com/liabru/matter-js/commit/c254c8d)), closes [#45](https://github.com/liabru/matter-js/issues/45)\n* added early out in Constraint.postSolveAll, pass body.velocity when updating bounds ([8210dbe](https://github.com/liabru/matter-js/commit/8210dbe))\n* added internal edge flagging to Bodies.fromVertices ([ca75fde](https://github.com/liabru/matter-js/commit/ca75fde))\n* added Matter.Svg.pathToPoints ([7822ead](https://github.com/liabru/matter-js/commit/7822ead))\n* added Matter.version ([e0a6de0](https://github.com/liabru/matter-js/commit/e0a6de0))\n* added Matter.World extends  Matter.Composite to docs ([b3921fb](https://github.com/liabru/matter-js/commit/b3921fb))\n* added minimum area check to Bodies.fromVertices ([bf11ee5](https://github.com/liabru/matter-js/commit/bf11ee5))\n* added missing dependency to Render.js ([df5f16c](https://github.com/liabru/matter-js/commit/df5f16c))\n* added mouse constraint collision mask example to demo ([440e9d2](https://github.com/liabru/matter-js/commit/440e9d2))\n* added Mouse.create warning for omitted element ([af83e27](https://github.com/liabru/matter-js/commit/af83e27))\n* added MouseConstraint.create warning for omitted element ([b6603ca](https://github.com/liabru/matter-js/commit/b6603ca))\n* added node demo tests ([71c1ae8](https://github.com/liabru/matter-js/commit/71c1ae8))\n* added options to Metrics.create ([1b7e27d](https://github.com/liabru/matter-js/commit/1b7e27d))\n* added Query.point ([98ea7c7](https://github.com/liabru/matter-js/commit/98ea7c7))\n* added release tasks ([5479fbc](https://github.com/liabru/matter-js/commit/5479fbc))\n* added Render.create warning for omitted element ([0583cdb](https://github.com/liabru/matter-js/commit/0583cdb))\n* added render.options.showMousePosition ([e191d44](https://github.com/liabru/matter-js/commit/e191d44))\n* added Render.showInternalEdges, added rendering bounds + axes + positions for compounds, fixed rende ([5ab2bf3](https://github.com/liabru/matter-js/commit/5ab2bf3))\n* added Render.vertexNumbers, Render.bodyConvexHulls ([9c139ed](https://github.com/liabru/matter-js/commit/9c139ed))\n* added Runner.create and Runner.tick ([5c69f2e](https://github.com/liabru/matter-js/commit/5c69f2e))\n* added source link to demo ([1e756d3](https://github.com/liabru/matter-js/commit/1e756d3))\n* added sprite offsets relative to centre of mass, closes #153 ([3de9d00](https://github.com/liabru/matter-js/commit/3de9d00)), closes [#153](https://github.com/liabru/matter-js/issues/153)\n* added startdrag and enddrag events to Demo.events ([7c75614](https://github.com/liabru/matter-js/commit/7c75614))\n* added support for compound bodies in MouseConstraint ([d6829bf](https://github.com/liabru/matter-js/commit/d6829bf))\n* added support for hidpi rendering ([4746eb9](https://github.com/liabru/matter-js/commit/4746eb9))\n* added support for multiple vertices input in Bodies.fromVertices ([e8205f8](https://github.com/liabru/matter-js/commit/e8205f8))\n* added support for sprite scale in RenderPixi, closes #54 ([8dea166](https://github.com/liabru/matter-js/commit/8dea166)), closes [#54](https://github.com/liabru/matter-js/issues/54)\n* added testDemo to grunt test ([08c5648](https://github.com/liabru/matter-js/commit/08c5648))\n* added time scaling to Sleeping ([0ae2d02](https://github.com/liabru/matter-js/commit/0ae2d02))\n* added Vector.create ([b327a40](https://github.com/liabru/matter-js/commit/b327a40))\n* Allow for negative force to bring a body out of sleeping state. ([d585e80](https://github.com/liabru/matter-js/commit/d585e80))\n* appease jshint ([89140ae](https://github.com/liabru/matter-js/commit/89140ae))\n* appease jshint ([18a2627](https://github.com/liabru/matter-js/commit/18a2627))\n* change browser tests to use JSON.stringify ([75af920](https://github.com/liabru/matter-js/commit/75af920))\n* change gravity scale to variable rather than a constant ([a38b227](https://github.com/liabru/matter-js/commit/a38b227))\n* change main to edge build ([9d0e82b](https://github.com/liabru/matter-js/commit/9d0e82b))\n* change travis to only lint rather than full test (until tests are finished and documented) ([ce478cb](https://github.com/liabru/matter-js/commit/ce478cb))\n* change world.bounds to Infinity, remove world bounds check from Engine, closes #67 ([8b5192d](https://github.com/liabru/matter-js/commit/8b5192d)), closes [#67](https://github.com/liabru/matter-js/issues/67)\n* changed Body._initProperties to use Body.setVertices ([2d04389](https://github.com/liabru/matter-js/commit/2d04389))\n* changed bower main to build/matter.js ([7412335](https://github.com/liabru/matter-js/commit/7412335))\n* changed certain Matter.Composite methods to private in docs ([8aa148d](https://github.com/liabru/matter-js/commit/8aa148d))\n* changed Common.log to use console.warn ([c220f41](https://github.com/liabru/matter-js/commit/c220f41))\n* changed default minimum area in Bodies.fromVertices ([998ab33](https://github.com/liabru/matter-js/commit/998ab33))\n* changed demo to use Matter.Runner and Matter.Render events ([a1d4748](https://github.com/liabru/matter-js/commit/a1d4748))\n* changed friction impulse limiting approach ([de4784c](https://github.com/liabru/matter-js/commit/de4784c))\n* changed Grid.create to accept an options object ([eedd1f2](https://github.com/liabru/matter-js/commit/eedd1f2))\n* changed jquery reference (matter-tools) to local copy ([0849773](https://github.com/liabru/matter-js/commit/0849773))\n* changed Math.random to Common.random and use a seeded RNG ([0a46cb2](https://github.com/liabru/matter-js/commit/0a46cb2))\n* changed Mouse.create to return as a plain object ([eaa9767](https://github.com/liabru/matter-js/commit/eaa9767))\n* changed Render.bodyIds to show all parts ([3ed8034](https://github.com/liabru/matter-js/commit/3ed8034))\n* changed Sleeping constants to be public (module level) ([7eadea9](https://github.com/liabru/matter-js/commit/7eadea9))\n* changed vertex number render fillstyle ([bc88406](https://github.com/liabru/matter-js/commit/bc88406))\n* changed Vertices.create and Vertices.fromPath to create and return a new array rather than apply in- ([e3e462e](https://github.com/liabru/matter-js/commit/e3e462e))\n* cleanup ([5888ffc](https://github.com/liabru/matter-js/commit/5888ffc))\n* cleanup Svg.pathToPoints ([8bf3278](https://github.com/liabru/matter-js/commit/8bf3278))\n* cleanup Svg.pathToVertices ([7db3d28](https://github.com/liabru/matter-js/commit/7db3d28))\n* demo tweaks ([d55c700](https://github.com/liabru/matter-js/commit/d55c700))\n* demo tweaks ([22445c7](https://github.com/liabru/matter-js/commit/22445c7))\n* disabled angle indicators on some demos ([74bc8ae](https://github.com/liabru/matter-js/commit/74bc8ae))\n* don't calculate gravity force if there is no actual gravity ([e54802c](https://github.com/liabru/matter-js/commit/e54802c))\n* dont draw offscreen constraints. Set visible flag on offscreen sprites ([e263ecb](https://github.com/liabru/matter-js/commit/e263ecb))\n* Ensure passed canvas abides by render options ([0b51dd6](https://github.com/liabru/matter-js/commit/0b51dd6))\n* expose demo instance externally ([a9122ed](https://github.com/liabru/matter-js/commit/a9122ed))\n* fix angle indicators for compound bodies ([8031090](https://github.com/liabru/matter-js/commit/8031090))\n* fix bug in Composites.stack when skipping bodies ([b34669e](https://github.com/liabru/matter-js/commit/b34669e))\n* fix bug when using timing.isFixed, closes #44 ([0933620](https://github.com/liabru/matter-js/commit/0933620)), closes [#44](https://github.com/liabru/matter-js/issues/44)\n* fix concat dependency ([84a22ba](https://github.com/liabru/matter-js/commit/84a22ba))\n* fix demo for tests ([5e6b22b](https://github.com/liabru/matter-js/commit/5e6b22b))\n* fix Demo.reset to fully reset ids ([500d566](https://github.com/liabru/matter-js/commit/500d566))\n* fix Demo.stress stability ([d0fdd29](https://github.com/liabru/matter-js/commit/d0fdd29))\n* Fix for travis ([05f1c46](https://github.com/liabru/matter-js/commit/05f1c46))\n* fix grunt for travis ([d405910](https://github.com/liabru/matter-js/commit/d405910))\n* fix grunt for travis ([f55d806](https://github.com/liabru/matter-js/commit/f55d806))\n* fix gulp issues ([4173e70](https://github.com/liabru/matter-js/commit/4173e70))\n* fix gulp issues ([3bd556d](https://github.com/liabru/matter-js/commit/3bd556d))\n* fix handling of engine.render ([c46e915](https://github.com/liabru/matter-js/commit/c46e915))\n* fix issue in Render.inspector on Chrome ([86fcfcd](https://github.com/liabru/matter-js/commit/86fcfcd))\n* fix issue of undefined body.parts in constructor ([9d3755a](https://github.com/liabru/matter-js/commit/9d3755a))\n* fix issue when Bodies.trapezoid slope === 1, closes #138 ([449774c](https://github.com/liabru/matter-js/commit/449774c)), closes [#138](https://github.com/liabru/matter-js/issues/138)\n* fix issue with mouse when changing renderers, closes #96 ([796faeb](https://github.com/liabru/matter-js/commit/796faeb)), closes [#96](https://github.com/liabru/matter-js/issues/96)\n* fix issue with Render.debug when no timing passed, closes #171 and #176 ([087fab2](https://github.com/liabru/matter-js/commit/087fab2)), closes [#171](https://github.com/liabru/matter-js/issues/171) [#176](https://github.com/liabru/matter-js/issues/176)\n* fix jshint ([b0f72ab](https://github.com/liabru/matter-js/commit/b0f72ab))\n* fix lint issue ([9a599f1](https://github.com/liabru/matter-js/commit/9a599f1))\n* fix Matter.Demo for node ([2de1161](https://github.com/liabru/matter-js/commit/2de1161))\n* fix Matter.Demo for node ([06eea3e](https://github.com/liabru/matter-js/commit/06eea3e))\n* fix Matter.Runner for node ([ad55b85](https://github.com/liabru/matter-js/commit/ad55b85))\n* fix mobile demo, remove dev.html, fix debug info rendering ([9d5c27a](https://github.com/liabru/matter-js/commit/9d5c27a))\n* fix orientation event bug in DemoMobile ([f770a7c](https://github.com/liabru/matter-js/commit/f770a7c))\n* fix pair properties for compounds ([b8f3784](https://github.com/liabru/matter-js/commit/b8f3784))\n* fix runner for tests, limit precision of refs ([352bfd6](https://github.com/liabru/matter-js/commit/352bfd6))\n* fix standalone option ([de16529](https://github.com/liabru/matter-js/commit/de16529))\n* fix support for nodejs ([b669ea0](https://github.com/liabru/matter-js/commit/b669ea0))\n* fix tests ([eccf0a7](https://github.com/liabru/matter-js/commit/eccf0a7))\n* fix travis ([3ce6c3a](https://github.com/liabru/matter-js/commit/3ce6c3a))\n* fix travis issue ([131ed5e](https://github.com/liabru/matter-js/commit/131ed5e))\n* fix undefined variables, added jshint checks, closes #102 ([536e55f](https://github.com/liabru/matter-js/commit/536e55f)), closes [#102](https://github.com/liabru/matter-js/issues/102)\n* fixed Body.rotate ([c5212e1](https://github.com/liabru/matter-js/commit/c5212e1))\n* fixed Body.setVertices ([73ded98](https://github.com/liabru/matter-js/commit/73ded98))\n* fixed bug in constraints for compounds ([13fcb4b](https://github.com/liabru/matter-js/commit/13fcb4b))\n* fixed bug in Demo.reset that was creating multiple MouseConstraint ([8204d97](https://github.com/liabru/matter-js/commit/8204d97))\n* fixed build tasks ([69ff33f](https://github.com/liabru/matter-js/commit/69ff33f))\n* fixed build tasks, closes #161 ([d1b8705](https://github.com/liabru/matter-js/commit/d1b8705)), closes [#161](https://github.com/liabru/matter-js/issues/161)\n* fixed chaining for some Matter.Vertices methods ([8746185](https://github.com/liabru/matter-js/commit/8746185))\n* fixed collision detection issue, closes #12 ([3e48825](https://github.com/liabru/matter-js/commit/3e48825)), closes [#12](https://github.com/liabru/matter-js/issues/12)\n* fixed collision incident and reference body mapping ([757fffa](https://github.com/liabru/matter-js/commit/757fffa))\n* fixed collision rendering ([bc9a051](https://github.com/liabru/matter-js/commit/bc9a051))\n* fixed Common.now, closes #55 ([8555c0c](https://github.com/liabru/matter-js/commit/8555c0c)), closes [#55](https://github.com/liabru/matter-js/issues/55)\n* fixed compound body stability, improved position resolver ([e01dd22](https://github.com/liabru/matter-js/commit/e01dd22))\n* fixed critical inertia calculation issue, a potential breaking change, so Body._inertiaScale added t ([9a55b0c](https://github.com/liabru/matter-js/commit/9a55b0c))\n* fixed Example.timescale ([19656cd](https://github.com/liabru/matter-js/commit/19656cd))\n* fixed friction in Demo.manipulation ([95ae911](https://github.com/liabru/matter-js/commit/95ae911))\n* fixed gulp shell task args ([c2b0f30](https://github.com/liabru/matter-js/commit/c2b0f30))\n* fixed incorrect bounds issue when passing angle in Body.create ([810bd26](https://github.com/liabru/matter-js/commit/810bd26))\n* fixed issue with Body.applyForce torque, closes #64 ([3f9364c](https://github.com/liabru/matter-js/commit/3f9364c)), closes [#64](https://github.com/liabru/matter-js/issues/64)\n* fixed issue with docs ([3a16f90](https://github.com/liabru/matter-js/commit/3a16f90))\n* fixed issue with MouseConstraint.create, closes #185 ([dff0e30](https://github.com/liabru/matter-js/commit/dff0e30)), closes [#185](https://github.com/liabru/matter-js/issues/185)\n* fixed issues with friction stability ([1db98a3](https://github.com/liabru/matter-js/commit/1db98a3))\n* Fixed missed variable declaration. ([a940d96](https://github.com/liabru/matter-js/commit/a940d96))\n* fixed options pass through on Bodies.fromVertices ([eb29367](https://github.com/liabru/matter-js/commit/eb29367))\n* fixed Query.ray, Number.MIN_VALUE seems to cause SAT.collides to fail ([ccbb98b](https://github.com/liabru/matter-js/commit/ccbb98b))\n* fixed RenderPixi for compound bodies ([6679b9c](https://github.com/liabru/matter-js/commit/6679b9c))\n* fixed SAT overlap calculation for containment case ([685f2bd](https://github.com/liabru/matter-js/commit/685f2bd))\n* fixed scaling on RenderPixi view bounds ([c1964e2](https://github.com/liabru/matter-js/commit/c1964e2))\n* fixed support finding logic ([bc7dfc7](https://github.com/liabru/matter-js/commit/bc7dfc7))\n* fixed Vertices.fromPath when parsing scientific notation ([dae684d](https://github.com/liabru/matter-js/commit/dae684d))\n* fixes for compound bodies ([87f9065](https://github.com/liabru/matter-js/commit/87f9065))\n* formatting merge ([d4cbdbb](https://github.com/liabru/matter-js/commit/d4cbdbb))\n* further work on compound implementation ([d2f79b4](https://github.com/liabru/matter-js/commit/d2f79b4))\n* hide axis indicator on compound bodies ([6a26696](https://github.com/liabru/matter-js/commit/6a26696))\n* ignoring .idea ([066a416](https://github.com/liabru/matter-js/commit/066a416))\n* implemented automated browser tests ([a88b3ba](https://github.com/liabru/matter-js/commit/a88b3ba))\n* implemented compound bodies, added Body.setParts ([f554d6c](https://github.com/liabru/matter-js/commit/f554d6c))\n* implemented static compound bodies ([90adf14](https://github.com/liabru/matter-js/commit/90adf14))\n* implemented temporary vector pool ([7a477f2](https://github.com/liabru/matter-js/commit/7a477f2))\n* improve Composite.car ([5ff2182](https://github.com/liabru/matter-js/commit/5ff2182))\n* improved collision detection for compounds ([84d9f59](https://github.com/liabru/matter-js/commit/84d9f59))\n* improved Demo.manipulation ([e186ccd](https://github.com/liabru/matter-js/commit/e186ccd))\n* improved docs ([2317f02](https://github.com/liabru/matter-js/commit/2317f02))\n* improved docs ([2e6afd4](https://github.com/liabru/matter-js/commit/2e6afd4))\n* improved examples ([6e1f8e9](https://github.com/liabru/matter-js/commit/6e1f8e9))\n* improved friction, added body.frictionStatic ([937c7bf](https://github.com/liabru/matter-js/commit/937c7bf))\n* improved traction for Composites.car ([95eddb0](https://github.com/liabru/matter-js/commit/95eddb0))\n* increased tollerance on internal edge finding ([40905e8](https://github.com/liabru/matter-js/commit/40905e8))\n* initial work on browser tests ([6a88256](https://github.com/liabru/matter-js/commit/6a88256))\n* initial work on compound bodies ([243fce4](https://github.com/liabru/matter-js/commit/243fce4))\n* Make background:'transparent' work like canvas renderer ([f9123f9](https://github.com/liabru/matter-js/commit/f9123f9))\n* Merge branch 'browser-tests' ([a6b82c1](https://github.com/liabru/matter-js/commit/a6b82c1))\n* Merge branch 'collision-filters' of https://github.com/GustavCarlson/matter-js into GustavCarlson-co ([3a32bda](https://github.com/liabru/matter-js/commit/3a32bda))\n* Merge branch 'GustavCarlson-collision-filters' ([a58fe2a](https://github.com/liabru/matter-js/commit/a58fe2a))\n* Merge branch 'master' into runner-improve ([a48d219](https://github.com/liabru/matter-js/commit/a48d219))\n* Merge branch 'master' into topic/addBounds ([a461fc7](https://github.com/liabru/matter-js/commit/a461fc7))\n* Merge branch 'master' of github.com:liabru/matter-js ([4067108](https://github.com/liabru/matter-js/commit/4067108))\n* Merge branch 'master' of https://github.com/rfoligno/matter-js into rfoligno-master ([41b4b7f](https://github.com/liabru/matter-js/commit/41b4b7f))\n* Merge branch 'master' of https://github.com/schahriar/matter-js into schahriar-master ([2510cdf](https://github.com/liabru/matter-js/commit/2510cdf))\n* Merge branch 'no-gravity-optim' of https://github.com/BlackDice/matter-js into BlackDice-no-gravity- ([1b8574a](https://github.com/liabru/matter-js/commit/1b8574a))\n* Merge branch 'node-tests' into browserify ([6e0e7e4](https://github.com/liabru/matter-js/commit/6e0e7e4))\n* Merge branch 'pr/60' ([42dc72d](https://github.com/liabru/matter-js/commit/42dc72d))\n* Merge branch 'pr/95' ([eed9167](https://github.com/liabru/matter-js/commit/eed9167))\n* Merge branch 'runner-improve' into browserify ([9e3438f](https://github.com/liabru/matter-js/commit/9e3438f))\n* Merge pull request #30 from mrspeaker/master ([e95e328](https://github.com/liabru/matter-js/commit/e95e328))\n* Merge pull request #31 from mrspeaker/topic/addBounds ([6652bb4](https://github.com/liabru/matter-js/commit/6652bb4))\n* Merge pull request #51 from tumult/pair_refreshes_from_body_values ([7c1efb6](https://github.com/liabru/matter-js/commit/7c1efb6))\n* Merge remote-tracking branch 'origin/pr/33' ([c6a9414](https://github.com/liabru/matter-js/commit/c6a9414))\n* merge tumult:old_ie_fixes + tweaks ([6e1ab9a](https://github.com/liabru/matter-js/commit/6e1ab9a))\n* migrated from grunt to gulp, jshint to eslint ([19bb655](https://github.com/liabru/matter-js/commit/19bb655))\n* Missing argument whose default is 1. ([61855ab](https://github.com/liabru/matter-js/commit/61855ab))\n* More fine-grained collision filtering in the style of Box2D ([dd4fc65](https://github.com/liabru/matter-js/commit/dd4fc65))\n* move /tests to /test ([ad403ae](https://github.com/liabru/matter-js/commit/ad403ae))\n* move Demo.* to Example.* ([b722012](https://github.com/liabru/matter-js/commit/b722012))\n* move license in build ([9ba8a2a](https://github.com/liabru/matter-js/commit/9ba8a2a))\n* move require statements below module export ([99c3bb3](https://github.com/liabru/matter-js/commit/99c3bb3))\n* moved collision events into Engine.update, changed collisionStart to trigger before collisions resol ([69b1d05](https://github.com/liabru/matter-js/commit/69b1d05))\n* moved Engine.run to Matter.Runner ([6911395](https://github.com/liabru/matter-js/commit/6911395))\n* moved engine.timing properties, tick events and Engine.render into Matter.Runner module ([dcdc43d](https://github.com/liabru/matter-js/commit/dcdc43d))\n* pass width and height options to Pixi webGL renderer ([a9278fc](https://github.com/liabru/matter-js/commit/a9278fc))\n* publish to npm ([a12fbcb](https://github.com/liabru/matter-js/commit/a12fbcb))\n* refactor Bodies.fromVertices ([4a2c6e7](https://github.com/liabru/matter-js/commit/4a2c6e7))\n* refactor Demo.create ([c0b24da](https://github.com/liabru/matter-js/commit/c0b24da))\n* refactor Demo.init ([fb76605](https://github.com/liabru/matter-js/commit/fb76605))\n* remove constraint torque clamp ([6f89250](https://github.com/liabru/matter-js/commit/6f89250))\n* removed Body.resetForcesAll, removed Body.applyGravityAll, removed Body.updateAll ([9aa0945](https://github.com/liabru/matter-js/commit/9aa0945))\n* removed collision.supportCorrected instead using bodyB.position, added render.options.showSeparation ([2b6a8d3](https://github.com/liabru/matter-js/commit/2b6a8d3))\n* removed complexity check in Bodies.fromVertices, enforce clockwise sort ([2d1ef0d](https://github.com/liabru/matter-js/commit/2d1ef0d))\n* removed Detector.bruteForce ([e04de5f](https://github.com/liabru/matter-js/commit/e04de5f))\n* removed engine.broadphase.current, removed engine.broadphase.instance, changed engine.broadphase to  ([6dd0c05](https://github.com/liabru/matter-js/commit/6dd0c05))\n* removed engine.input, removed Engine mouse events, added MouseConstraint mouse events ([fb5d899](https://github.com/liabru/matter-js/commit/fb5d899))\n* removed line width change from Body.setStatic ([04955bb](https://github.com/liabru/matter-js/commit/04955bb))\n* removed Matter.Metrics from release builds (now dev only) ([968bba2](https://github.com/liabru/matter-js/commit/968bba2))\n* removed old build ([a068bec](https://github.com/liabru/matter-js/commit/a068bec))\n* removed redundant property ([14392b4](https://github.com/liabru/matter-js/commit/14392b4))\n* removed Render.clear (redundant) ([0a15d7d](https://github.com/liabru/matter-js/commit/0a15d7d))\n* removed Render.setBackground (now use render.options) ([01bc813](https://github.com/liabru/matter-js/commit/01bc813))\n* removed unused vars from examples ([0bff037](https://github.com/liabru/matter-js/commit/0bff037))\n* removed version number from edge build name ([e6b998e](https://github.com/liabru/matter-js/commit/e6b998e))\n* render normals pointing out of static bodies ([d082b3a](https://github.com/liabru/matter-js/commit/d082b3a))\n* skip presolve when impulse 0 ([296059c](https://github.com/liabru/matter-js/commit/296059c))\n* skip unnecessary loops in Composites.mesh, closes #85 ([0a73a64](https://github.com/liabru/matter-js/commit/0a73a64)), closes [#85](https://github.com/liabru/matter-js/issues/85)\n* Some fixes in pixi.js v3 update ([96735dd](https://github.com/liabru/matter-js/commit/96735dd))\n* Spellchecking ([940976a](https://github.com/liabru/matter-js/commit/940976a))\n* Spellchecking ([c2e0c23](https://github.com/liabru/matter-js/commit/c2e0c23))\n* Spellchecking ([cd5d401](https://github.com/liabru/matter-js/commit/cd5d401))\n* Spellchecking ([611a429](https://github.com/liabru/matter-js/commit/611a429))\n* Spellchecking ([723ddcf](https://github.com/liabru/matter-js/commit/723ddcf))\n* Spellchecking ([65d5d93](https://github.com/liabru/matter-js/commit/65d5d93))\n* Spellchecking ([3127654](https://github.com/liabru/matter-js/commit/3127654))\n* tweak jshint ([71df1b9](https://github.com/liabru/matter-js/commit/71df1b9))\n* tweaks to collision filtering ([5060c76](https://github.com/liabru/matter-js/commit/5060c76))\n* tweaks to Matter.Runner ([ce474da](https://github.com/liabru/matter-js/commit/ce474da))\n* Update JSDoc ([25ab2a3](https://github.com/liabru/matter-js/commit/25ab2a3))\n* Update JSDoc ([18e0642](https://github.com/liabru/matter-js/commit/18e0642))\n* Update JSDoc ([71ef6c2](https://github.com/liabru/matter-js/commit/71ef6c2))\n* Update JSDoc ([10a46b7](https://github.com/liabru/matter-js/commit/10a46b7))\n* Update JSDoc ([5b87f47](https://github.com/liabru/matter-js/commit/5b87f47))\n* Update JSDoc ([d17eb6c](https://github.com/liabru/matter-js/commit/d17eb6c))\n* Update JSDoc ([aa3eabc](https://github.com/liabru/matter-js/commit/aa3eabc))\n* update node version for travis ([e698b6b](https://github.com/liabru/matter-js/commit/e698b6b))\n* updated browser test refs ([1810f93](https://github.com/liabru/matter-js/commit/1810f93))\n* updated browser test refs ([ae32d63](https://github.com/liabru/matter-js/commit/ae32d63))\n* updated browser test refs ([31fb748](https://github.com/liabru/matter-js/commit/31fb748))\n* updated contributing notes ([8b89e87](https://github.com/liabru/matter-js/commit/8b89e87))\n* updated docs for collisionFilter ([9f10f88](https://github.com/liabru/matter-js/commit/9f10f88))\n* updated edge build ([2fa1570](https://github.com/liabru/matter-js/commit/2fa1570))\n* updated edge build ([02ab198](https://github.com/liabru/matter-js/commit/02ab198))\n* updated edge build ([37a86cd](https://github.com/liabru/matter-js/commit/37a86cd))\n* updated edge build ([cd00353](https://github.com/liabru/matter-js/commit/cd00353))\n* updated edge build ([37ccc84](https://github.com/liabru/matter-js/commit/37ccc84))\n* updated edge build ([bf3f986](https://github.com/liabru/matter-js/commit/bf3f986))\n* updated edge build ([16733ad](https://github.com/liabru/matter-js/commit/16733ad))\n* updated edge build ([2f2d416](https://github.com/liabru/matter-js/commit/2f2d416))\n* updated edge build ([5770013](https://github.com/liabru/matter-js/commit/5770013))\n* updated edge build ([43fd2e3](https://github.com/liabru/matter-js/commit/43fd2e3))\n* updated edge build ([fbb7c1a](https://github.com/liabru/matter-js/commit/fbb7c1a))\n* updated edge build ([d6cbd07](https://github.com/liabru/matter-js/commit/d6cbd07))\n* updated edge build ([9561d5d](https://github.com/liabru/matter-js/commit/9561d5d))\n* updated edge build ([a80fbc1](https://github.com/liabru/matter-js/commit/a80fbc1))\n* updated edge build ([5b2b060](https://github.com/liabru/matter-js/commit/5b2b060))\n* updated edge build ([d22b1b4](https://github.com/liabru/matter-js/commit/d22b1b4))\n* updated edge build ([2ab20b0](https://github.com/liabru/matter-js/commit/2ab20b0))\n* updated edge build ([f2635ab](https://github.com/liabru/matter-js/commit/f2635ab))\n* updated matter-tools ([c969767](https://github.com/liabru/matter-js/commit/c969767))\n* updated matter-tools ([4ecad0f](https://github.com/liabru/matter-js/commit/4ecad0f))\n* updated node test refs ([b1e6a45](https://github.com/liabru/matter-js/commit/b1e6a45))\n* Updated pixi.js to v3 ([419d2ad](https://github.com/liabru/matter-js/commit/419d2ad))\n* updated readme ([137580c](https://github.com/liabru/matter-js/commit/137580c))\n* updated readme ([f4f3bf7](https://github.com/liabru/matter-js/commit/f4f3bf7))\n* updated readme ([d2dcc77](https://github.com/liabru/matter-js/commit/d2dcc77))\n* updated readme ([2806fd3](https://github.com/liabru/matter-js/commit/2806fd3))\n* updated readme ([3e5abab](https://github.com/liabru/matter-js/commit/3e5abab))\n* updated readme ([8f2f8ee](https://github.com/liabru/matter-js/commit/8f2f8ee))\n* updated readme ([6cd00b1](https://github.com/liabru/matter-js/commit/6cd00b1))\n* updated test refs ([b79ece2](https://github.com/liabru/matter-js/commit/b79ece2))\n* updated test refs ([1a55259](https://github.com/liabru/matter-js/commit/1a55259))\n* updated test refs ([110aea8](https://github.com/liabru/matter-js/commit/110aea8))\n* updated test refs ([729e2bf](https://github.com/liabru/matter-js/commit/729e2bf))\n* upgraded pixi.js to v3.0.6 ([d03145e](https://github.com/liabru/matter-js/commit/d03145e))\n* use actual canvas size for default render bounds ([c3129b8](https://github.com/liabru/matter-js/commit/c3129b8))\n* use browserify ([00251e5](https://github.com/liabru/matter-js/commit/00251e5))\n* use build folder for demo ([fa47d5c](https://github.com/liabru/matter-js/commit/fa47d5c))\n* use different port for test server, fix test precision limiter ([c1f71b9](https://github.com/liabru/matter-js/commit/c1f71b9))\n* Use own Common.indexOf method for IE 6-8 compatibility ([b91af36](https://github.com/liabru/matter-js/commit/b91af36))\n* When updating pairs use current values from bodies as they may have changed ([f0e7491](https://github.com/liabru/matter-js/commit/f0e7491))\n\n\n\n# Matter.js Changelog\n\n[brm.io/matter-js](http://brm.io/matter-js)\n\n----------\n\n## 0.8.0-alpha - 2014-05-05\n\n#### Release Highlights\n\n- added [Views](http://brm.io/matter-js-demo/#views) demo\n- added [Time Scaling](http://brm.io/matter-js-demo/#timescale) demo\n- added [Rounded Corners (Chamfering)](http://brm.io/matter-js-demo#rounded) demo\n- added [Raycasting](http://brm.io/matter-js-demo/#raycasting) demo\n- added Query module, including raycasting\n- added 3 useful new Composite methods\n- added support for mouse wheel, mouse scaling and offsets\n- added Body.scale for scaling bodies on the fly\n- added Body.timeScale for slowing down bodies per-body\n- added Body.setStatic for correctly setting static\n- added Vertices.chamfer for rounding corners of any set of vertices\n- added integration of chamfer to body factories\n- added engine.timing.isFixed option to disable dynamic timing\n- added render.bounds for translating and scaling views\n- easier use of Engine.update and Engine.render for those using custom game loops\n- fixed issues with time scaling\n- fixed error in calculation of centre of mass\n- removed Matter.Gui in preparation for the [MatterTools](https://github.com/liabru/matter-tools) project launch\n\n#### Added\n\n- added Demo.views\n- added Demo.timescale\n- added Demo.rounded\n- added Demo.raycasting\n- added demo support for hash + '-inspect' to start the [MatterTools](https://github.com/liabru/matter-tools) inspector\n- added Composite.rebase\n- added Composite.move\n- added Composite.get\n- added Matter.Query\n- added Query.ray\n- added Query.region\n- added Bounds.translate\n- added Bounds.shift\n- added Mouse.setScale\n- added Mouse.setPosition\n- added mouse.absolute\n- added mouse.wheelDelta\n- added mouse.offset\n- added Body.setStatic\n- added Body.scale\n- added body.timeScale\n- added Vector.angle\n- added Vertices.chamfer for rounding corners\n- added Engine.render\n- added engine.timing.isFixed option\n- added render.bounds for translating and scaling views\n- added Common.nextId\n- added body.label\n- added constraint.label\n- added composite.label\n\n#### Changed\n\n- changed engine.timing.timestamp to be simulation based rather than wall-clock based\n- changed correction to now be optional in Engine.update (defaults to 1)\n- changed Events.on to return callback\n- changed Events.off to accept callbacks for removal\n- changed vertices in Bounds.create to optional\n- changed engine.timeScale to engine.timing.timeScale\n- moved Matter.Inspector and Matter.Gui to the [MatterTools](https://github.com/liabru/matter-tools) project\n- moved event documentation to end of file for clarity\n- moved respective engine event triggers into Engine.update and Engine.render\n\n#### Removed\n\n- removed body.render.path (redundant)\n- removed Body.nextId\n- removed Constraint.nextId\n- removed Composite.nextId\n- removed Body.updateProperties (now a private method)\n\n#### Fixed\n\n- fixed issues with timing.timeScale\n- fixed constraints now account for timeScale\n- fixed Vertices.centre calculation to get correct centre of mass\n\n## 0.7.0-alpha - 2014-04-01\n\n#### Release Highlights\n\n- added six new demos\n\t- all demos are now mobile friendly\n- added new event system\n\t- engine, mouse and collision events\n- added sprite texture rendering support\n- added WebGL renderer (pixi.js)\n- improved `Composite` (and `World`)\n\t- batch adding\n\t- type agnostic adding\n\t- body removal\n- major performance increases all round\n\t- collision detection caching\n\t- batched rendering\n\t- improved pair management\n\t- memory leaks fixed\n- stability improvements\n\t- bodies rest better due to collision caching\n\t- bodies sleep better\n\t- constraints are much less volatile\n- fixes for a number of issues (see fixes)\n\n#### Added\n\n- added demos \n\t- sprites\n\t- events\n\t- catapult\n\t- cloth\n\t- soft body\n\t- bridge\n- added collision caching and reuse for improved performance\n\t- added metrics for collision reuse\n- added `Events` module ([Issue #8](https://github.com/liabru/matter-js/issues/8))\n\t- engine events\n\t- mouse events\n\t- collision events\n- added composite functions, including\n\t- batch adding (`Composite.add` / `World.add`)\n\t- type agnostic adding (`Composite.add` / `World.add`)\n\t- body removal (`Composite.remove` / `World.remove`)\n- added factory functions\n\t- constraint meshing (`Composites.mesh`)\n\t- soft body factory (`Composites.softBody`)\n- added `RenderPixi`, a pixi.js WebGL renderer\n\t- added `Gui` option to switch renderer\n\t- added `Mouse.setElement`\n- added `render.visible` flag to `Body` and `Constraint` ([Issue #10](https://github.com/liabru/matter-js/issues/10))\n- added `id` to `Constraint` and `Composite`\n- added `type` names to `Body`, `Constraint`, `Composite`\n- added `Common` functions\n\t- `Common.colorToNumber`\n\t- `Common.log`\n\t- `Common.clone`\n- added jsdoc annotations\n- added travis-ci integration\n- added yuidoc build tasks\n- added multiple build modes to `Gruntfile` (dev, release, edge)\n- added repository to `package.json`, so Browserify may be used\n- added `CHANGELOG.md`\n\n#### Changed\n\n- renamed module `Manager` to `Pairs`\n- changed `Composite` to be tree-based\n- changed timestep to be smoothed over 1s for stability\n- changed default `constraintIterations` to 2 for stability\n- changed demo to use the new composite functions\n- changed right click to now remove bodies in the demos\n- changed `Common.now` to use high-resolution timing\n- changed `MouseConstraint` to reference a single constraint rather than a list\n- changed `Constraint` to now use a `render` property\n- changed `Metrics` to only track FPS by default, use the `extended` flag for full metrics\n\n#### Removed\n\n- removed the default in `MouseConstraint`, you must now instantiate one manually\n\n#### Fixed\n\n- fixed a memory leak in `Grid`\n- fixed a memory leak in `Manager`\n- fixed debug text now uses `Metrics` correctly\n- fixed issues regarding passing custom `Render` modules ([Issue #7](https://github.com/liabru/matter-js/issues/7))\n- fixed issue in `Common.extend` with `null` properties\n- fixed issue with sleeping, now ignores inactive pairs\n- fixed issues with `Body.applyForce` ([Issue #7](https://github.com/liabru/matter-js/issues/7))\n\n## 0.5.0-alpha - 2014-02-28\n\n- initial release"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\n## License Agreement\n\nBy providing any kind of contribution to this project, **you must agree and be legally entitled** to provide them for use and distribution as a part of this project **wholly under the same terms as in the original included [license](https://github.com/liabru/matter-js/blob/master/LICENSE)**.\n\n## Contributions\n\nContributions by pull request or issues are welcome. Please ensure they follow the same style and architecture as the rest of the code. Use `npm run lint` and see [Testing](#Testing) below before submitting. Please **do not include** any changes to the files in the `build` directory. \n\nBefore contributing please read the license agreement described at the beginning of this document.\n\n## Building\n\nTo build you must first install [node.js](http://nodejs.org), then run\n\n\tnpm install\n\nwhich will install the required build dependencies, then run\n\n\tnpm start\n\nwhich will run the development server and opens `http://localhost:8000/` in your browser. Any changes you make to the source will automatically rebuild and reload the page.\n\n## Testing\n\nAll contributions should pass when running the commands\n\n- `npm run lint`\n- `npm run test`\n- `npm run test-browser`\n\nThe output of `npm run test` also includes a [comparison report](https://github.com/liabru/matter-js/pull/794), which highlights changes in results, performance and accuracy against the last release build.\n\n## Commands\n\nThe following development commands can be run at the terminal\n\n- **npm start**  \nruns development server and opens demo page\n- **npm run build**  \ncreates a release build\n- **npm run build-demo**  \nbuilds the demo\n- **npm run lint**  \nruns the linter\n- **npm run test**\nruns the tests and compares results\n- **npm run test-browser**  \nruns the browser tests\n- **npm run doc**  \nbuilds the documentation\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) Liam Brummitt and contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "<img alt=\"Matter.js\" src=\"https://brm.io/matter-js/img/matter-js.svg\" width=\"300\">\n\n> *Matter.js* is a JavaScript 2D rigid body physics engine for the web\n\n[brm.io/matter-js](https://brm.io/matter-js/)\n\n[Demos](#demos) ・ [Gallery](#gallery) ・ [Features](#features) ・ [Plugins](#plugins) ・ [Install](#install) ・ [Usage](#usage) ・ [Examples](#examples) ・ [Docs](#documentation) ・ [Wiki](https://github.com/liabru/matter-js/wiki) ・ [References](#references) ・ [License](#license)\n\n### Demos\n\n<table>\n  <tr>\n    <td>\n      <ul>\n        <li><a href=\"https://brm.io/matter-js/demo/#mixed\">Mixed Shapes</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#mixedSolid\">Solid Shapes</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#svg\">Concave SVG Paths</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#terrain\">Concave Terrain</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#concave\">Concave Bodies</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#compound\">Compound Bodies</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#newtonsCradle\">Newton's Cradle</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#wreckingBall\">Wrecking Ball</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#slingshot\">Slingshot Game</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#rounded\">Rounded Corners</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#views\">Views</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#timescale\">Time Scaling</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#manipulation\">Body Manipulation</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#compositeManipulation\">Composite Manipulation</a></li>\n      </ul>\n    </td>\n    <td>\n      <ul>\n        <li><a href=\"https://brm.io/matter-js/demo/#raycasting\">Raycasting</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#sprites\">Sprites</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#pyramid\">Pyramid</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#car\">Car</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#catapult\">Catapult</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#gravity\">Reverse Gravity</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#bridge\">Bridge</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#avalanche\">Avalanche</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#softBody\">Basic Soft Bodies</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#cloth\">Cloth</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#events\">Events</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#collisionFiltering\">Collision Filtering</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#chains\">Chains</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#ballPool\">Ball Pool</a></li>\n      </ul>\n    </td>\n    <td>\n      <ul>\n        <li><a href=\"https://brm.io/matter-js/demo/#stack\">Stack</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#circleStack\">Circle Stack</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#compoundStack\">Compound Stack</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#restitution\">Restitution</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#friction\">Friction</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#airFriction\">Air Friction</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#staticFriction\">Static Friction</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#sleeping\">Sleeping</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#beachBalls\">Beach Balls</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#stress\">Stress 1</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#stress2\">Stress 2</a></li>\n        <li><a href=\"https://brm.io/matter-js/demo/#sensors\">Sensors</a></li>\n      </ul>\n      <br>\n    </td>\n  </tr>\n</table>\n\n### Gallery\n\nSee how others are using matter.js physics\n\n- [Patrick Heng](https://patrickheng.com/) by Patrick Heng\n- [USELESS](https://useless.london/) by Nice and Serious\n- [Secret 7](https://secret-7.com/) by Goodness\n- [New Company](https://www.new.company/) by New Company\n- [Game of The Year](https://gameoftheyear.withgoogle.com/) by Google\n- [Pablo The Flamingo](https://pablotheflamingo.com/) by Nathan Gordon\n- [Les métamorphoses de Mr. Kalia](https://lab212.org/oeuvres/2:art/18/Les-metamorphoses-de-Mr-Kalia) by Lab212\n- [Phaser](https://phaser.io/) by Photon Storm\n- [Sorry I Have No Filter](https://sorryihavenofilter.com/pages/about/) by Jessica Walsh\n- [Fuse](https://fuse.blog/) by Fuse\n- [Glyphfinder](https://www.glyphfinder.com/) by überdosis\n- [Isolation](https://isolation.is/postcards/my-week) by sabato studio\n- [more...](https://github.com/liabru/matter-js/wiki/Gallery)\n\n### Features\n\n- Rigid bodies\n- Compound bodies\n- Composite bodies\n- Concave and convex hulls\n- Physical properties (mass, area, density etc.)\n- Restitution (elastic and inelastic collisions)\n- Collisions (broad-phase, mid-phase and narrow-phase)\n- Stable stacking and resting\n- Conservation of momentum\n- Friction and resistance\n- Events\n- Constraints\n- Gravity\n- Sleeping and static bodies\n- Plugins\n- Rounded corners (chamfering)\n- Views (translate, zoom)\n- Collision queries (raycasting, region tests)\n- Time scaling (slow-mo, speed-up)\n- Canvas renderer (supports vectors and textures)\n- [MatterTools](https://github.com/liabru/matter-tools) for creating, testing and debugging worlds\n- World state serialisation (requires [resurrect.js](https://github.com/skeeto/resurrect-js))\n- Cross-browser and Node.js support (Chrome, Firefox, Safari, IE8+)\n- Mobile-compatible (touch, responsive)\n- An original JavaScript physics implementation (not a port)\n\n### Install\n\nYou can install using package managers [npm](https://www.npmjs.org/package/matter-js) and [Yarn](https://yarnpkg.com/) using:\n\n    npm install matter-js\n\nAlternatively you can download a [stable release](https://github.com/liabru/matter-js/tags) or try the latest experimental [alpha build](https://github.com/liabru/matter-js/tree/master/build) (master) and include the script in your web page:\n\n    <script src=\"matter.js\" type=\"text/javascript\"></script>\n\n### Performance with other tools (e.g. Webpack, Vue etc.)\n\nBundlers and frameworks may reduce real-time performance when using their default configs, especially in development modes.\n\nWhen using [Webpack](https://webpack.js.org/), the default sourcemap config can have a large impact, for a solution see [issue](https://github.com/liabru/matter-js/issues/1001).\n\nWhen using [Vue.js](https://vuejs.org/), watchers can have a large impact, for a solution see [issue](https://github.com/liabru/matter-js/issues/1001#issuecomment-998911435). \n\n### Usage\n\nVisit the [Getting started](https://github.com/liabru/matter-js/wiki/Getting-started) wiki page for a minimal usage example which should work in both browsers and Node.js.  \nAlso see the [Running](https://github.com/liabru/matter-js/wiki/Running) and [Rendering](https://github.com/liabru/matter-js/wiki/Rendering) wiki pages, which show how to use your own game and rendering loops.\n\n### Tutorials\n\nSee the list of [tutorials](https://github.com/liabru/matter-js/wiki/Tutorials).\n\n### Examples\n\nSee the [examples](https://github.com/liabru/matter-js/tree/master/examples) directory which contains the source for all [demos](#demos).  \nThere are even more examples on [codepen](https://codepen.io/collection/Fuagy/).\n\n### Plugins\n\nThe engine can be extended through plugins, see these resources:\n\n- [Using plugins](https://github.com/liabru/matter-js/wiki/Using-plugins)\n- [Creating plugins](https://github.com/liabru/matter-js/wiki/Creating-plugins)\n- [List of plugins](https://github.com/liabru/matter-js/wiki/List-of-plugins)\n- [matter-plugin-boilerplate](https://github.com/liabru/matter-plugin-boilerplate)\n\n### Documentation\n\nSee the [API Documentation](https://brm.io/matter-js/docs/) and the [wiki](https://github.com/liabru/matter-js/wiki)\n\n### Building and Contributing\n\nTo build you must first install [node.js](https://nodejs.org/), then run\n\n\tnpm install\n\nThis will install the required build dependencies, then run\n\n\tnpm run dev\n\nto spawn a development server. For information on contributing see [CONTRIBUTING.md](https://github.com/liabru/matter-js/blob/master/CONTRIBUTING.md).\n\n### Changelog\n\nTo see what's new or changed in the latest version, see the [changelog](https://github.com/liabru/matter-js/blob/master/CHANGELOG.md).\n\n### References\n\nSee the wiki page on [References](https://github.com/liabru/matter-js/wiki/References).\n\n### License\n\nMatter.js is licensed under [The MIT License (MIT)](https://opensource.org/licenses/MIT)  \nCopyright (c) 2014 Liam Brummitt\n\nThis license is also supplied with the release and source code.  \nAs stated in the license, absolutely no warranty is provided.\n"
  },
  {
    "path": "RELEASE.md",
    "content": "## ▲.● matter.js `0.20.0`\n\nRelease notes for `0.20.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.20.0/README.md) for further information.\n\n### Highlights ✺\n\n- added support for high refresh rate displays with fixed timestep in `Matter.Runner`\n- added support for sub-stepping for higher quality simulations in `Matter.Runner`\n- changed to a fixed timestep by default in `Matter.Runner`\n- improved frame pacing and average performance up to ~6% (see [#1238](https://github.com/liabru/matter-js/pull/1238))\n- reduced average memory usage up to ~30% (see [#1238](https://github.com/liabru/matter-js/pull/1238))\n- reduced memory garbage collection\n- bug fixes and improvements see [changelog](https://github.com/liabru/matter-js/blob/0.20.0/CHANGELOG.md)\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.19.0...0.20.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.20.0/CHANGELOG.md) for a detailed list of changes.\n\n### Migration ⌲\n\n`Matter.Runner` related changes [#1254](https://github.com/liabru/matter-js/pull/1254):\n\n- `Matter.Runner` now defaults to a fixed deterministic timestep and support for non-fixed timestep is removed\n- optionally set your performance budgets `runner.maxFrameTime` (see docs)\n- note that `Matter.Runner` can now call zero, one, or multiple engine updates and events per display frame (see docs)\n- if needed set up your polyfill for `window.requestAnimationFrame`\n- see `Matter.Runner` updated docs throughout\n\nPerformance related changes [#1238](https://github.com/liabru/matter-js/pull/1238):\n\n- `Matter.Collision` use `collision.supportCount` instead of `collision.supports.length` for active support count\n- `Matter.Pair` use `pair.contacts` instead of `pair.activeContacts`\n- `Matter.Pair` use `pair.contactCount` instead of `pair.contacts.length` for active contact count\n- `Pair.id` format has changed\n\n### Comparison ⎄\n\nFor more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput sample comparison estimates of 44 examples against previous release matter-js@0.19.0:  \n\nSimilarity     99.80%    Overlap    -1.92%   Filesize   +3.38%  81.58 KB  \n\nairFriction · · avalanche ● · ballPool ● · bridge ● · car ● · catapult ● · \nchains ● · circleStack · · cloth ● · collisionFiltering ● · compositeManipulation ● · \ncompound · · compoundStack ● · concave ● · constraints ● · doublePendulum · · \nevents ● · friction · · gravity ● · gyro ● · manipulation ● ◆ \nmixed ● · newtonsCradle · · pyramid ● · ragdoll ● · raycasting ● · \nremove ● ◆ restitution · · rounded ● · sensors · · sleeping ● ◆ \nslingshot ● · softBody ● · sprites ● · stack · · staticFriction ● · \nstats ● · stress ● · stress2 ● · stress3 ● · stress4 ● · \ntimescale ● · views ● · wreckingBall ● ·   \n\nwhere for the sample  · no change detected  ● extrinsics changed  ◆ intrinsics changed\n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.19.0...0.20.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n\n---\n\n## ▲.● matter.js `0.19.0`\n\nRelease notes for `0.19.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.19.0/README.md) for further information.\n\n### Highlights ✺\n\n- Changed `Body.setAngularVelocity` and `Body.setVelocity` to be timestep independent\n- Improved similarity of results between different timesteps based on `60hz` as a baseline\n- Added timestep independent `Body.setSpeed`, `Body.setAngularSpeed`, `Body.getSpeed`, `Body.getVelocity`, `Body.getAngularVelocity`\n- Added optional `updateVelocity` argument to `Body.setPosition`, `Body.setAngle`, `Body.translate`, `Body.rotate`\n- Added extended documentation for `Body.applyForce`\n- Moved time correction feature from `Engine.update` to be built-in to `Matter.Body`\n- Improved [documentation](https://brm.io/matter-js/docs/) pages\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.18.0...0.19.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.19.0/CHANGELOG.md) for a more detailed list of changes.\n\n### Migration ⌲\n\nSee [PR #777](https://github.com/liabru/matter-js/pull/777#issue-487893963) for related changes and notes useful for migration.\n\n### Comparison ⎄\n\nFor more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput comparison of 43 examples at 60hz against previous release matter-js@0.18.0\n\nBehaviour    100.00%   Similarity  100.00%   Overlap   +0.00%  \nPerformance  -0.80%   Memory      +0.05%   Filesize  +1.67%  78.97 KB  \n\nairFriction · · avalanche · · ballPool · · bridge · · car · · catapult · · \nchains · · circleStack · · cloth · · collisionFiltering · · compositeManipulation · · \ncompound · · compoundStack · · concave · · constraints · · doublePendulum · · \nevents · · friction · · gravity · · gyro · · manipulation · · \nmixed · · newtonsCradle · · pyramid · · ragdoll · · raycasting · · \nremove · · restitution · · rounded · · sensors · · sleeping · ◆\nslingshot · · softBody · · sprites · · stack · · staticFriction · · \nstats · · stress · · stress2 · · stress3 · · timescale · · \nviews · · wreckingBall · ·   \n\nwhere  · no change  ● extrinsics changed  ◆ intrinsics changed\n    \n▶ code -n -d test/__compare__/examples-build.json test/__compare__/examples-dev.json\n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.18.0...0.19.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n\n---\n\n## ▲.● matter.js `0.18.0`\n\nRelease notes for `0.18.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.18.0/README.md) for further information.\n\n### Highlights ✺\n\n- **Up to ~40% performance improvement (on average measured over all examples, in Node on a Mac Air M1)**\n- Replaces `Matter.Grid` with a faster and more efficient broadphase in `Matter.Detector`\n- Reduced memory usage and garbage collection\n- Resolves issues in `Matter.SAT` related to collision reuse\n- Removes performance issues from `Matter.Grid`\n- Improved collision accuracy\n- Improved API and docs for collision modules\n- Improved [documentation](https://brm.io/matter-js/docs/) pages\n- Added note about avoiding Webpack [performance problems](https://github.com/liabru/matter-js/blob/master/README.md#install)\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.17.1...0.18.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.18.0/CHANGELOG.md) for a detailed list of changes.\n\n### Migration ⌲\n\n- Behaviour and similarity is in practice the same (a fractional difference from improved accuracy)\n- API is the same other than:\n  - [Matter.Detector](https://brm.io/matter-js/docs/classes/Detector.html) replaces [Matter.Grid](https://brm.io/matter-js/docs/classes/Grid.html) (which is now deprecated but will remain for a short term)\n  - [render.options.showBroadphase](https://brm.io/matter-js/docs/classes/Render.html#property_options.showBroadphase) is deprecated (no longer implemented)\n  - [Matter.SAT](https://brm.io/matter-js/docs/classes/SAT.html) is renamed [Matter.Collision](https://brm.io/matter-js/docs/classes/Collision.html)\n  - [Matter.SAT.collides](https://brm.io/matter-js/docs/classes/SAT.html#method_collides) is now [Matter.Collision.collides](https://brm.io/matter-js/docs/classes/Collision.html#method_collides) with a slightly different set of arguments\n\n### Comparison ⎄\n\nDifferences in behaviour, quality and performance against the previous release `0.17.1`. For more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput comparison of 43 examples against previous release matter-js@0.17.1  \n\nBehaviour    99.99%   Similarity  99.98%   Overlap   -0.00%  \nPerformance  +40.62%   Memory      -6.18%   Filesize  -0.16%  77.73 KB  \n\nairFriction · · avalanche ● · ballPool · · bridge · · car · · catapult · · \nchains · · circleStack · · cloth · · collisionFiltering · · compositeManipulation ● · \ncompound · · compoundStack · · concave · · constraints ● · doublePendulum · · \nevents · · friction · · gravity · · gyro · · manipulation · ◆ \nmixed · · newtonsCradle · · pyramid · · ragdoll · · raycasting · · \nremove · · restitution · · rounded · · sensors · · sleeping · ◆ \nslingshot · · softBody · · sprites · · stack · · staticFriction · · \nstats · · stress · · stress2 · · stress3 · · timescale · · \nviews · · wreckingBall · ·   \n\nwhere  · no change  ● extrinsics changed  ◆ intrinsics changed\n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.17.1...0.18.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n\n---\n\n## ▲.● matter.js `0.17.0`\n\nRelease notes for `0.17.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.17.0/README.md) for further information.\n\n### Highlights ✺\n\n- Added performance and stats monitoring overlays to `Matter.Render`\n  - See the [stats demo](https://brm.io/matter-js/demo/#stats) or enable [render.options.showPerformance](https://brm.io/matter-js/docs/classes/Render.html#property_options.showPerformance) and [render.options.showStats](https://brm.io/matter-js/docs/classes/Render.html#property_options.showStats) \n  - Stats shown include\n    - render frequency (e.g. `60 fps`)\n    - engine delta time (e.g. `16.66ms`)\n    - engine execution duration (e.g. `5.00ms`)\n    - render execution duration (e.g.` 0.40ms`)\n    - effective play speed (e.g. `1.00x` is real-time)\n    - various other engine internal stats for debugging\n- Improved [documentation](https://brm.io/matter-js/docs/) pages\n- Added [Common.setDecomp](https://brm.io/matter-js/docs/classes/Common.html#method_setDecomp) and [Common.getDecomp](https://brm.io/matter-js/docs/classes/Common.html#method_getDecomp) to fix [bundler issues](https://github.com/liabru/matter-js/issues/981)\n- Added docs for all [Matter.Render options](https://brm.io/matter-js/docs/classes/Render.html#properties)\n- Migrated usage of `Matter.World` over to `Matter.Composite` (more info in [docs](https://brm.io/matter-js/docs/classes/World.html))\n- Migrated, deprecated and removed various old functionality (see the [changelog](https://github.com/liabru/matter-js/blob/0.17.0/CHANGELOG.md) for details)\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.16.1...0.17.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.17.0/CHANGELOG.md) for a detailed list of changes.\n\n### Comparison ⎄\n\nDifferences in behaviour, quality and performance against the previous release `0.16.1`. For more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput comparison of 37 examples against previous release matter-js@0.16.1  \n\nSimilarity  100%  Performance  +0.00%  Overlap  +0.00%  \n\nairFriction · · avalanche · · ballPool · · bridge · · broadphase · · car · · \ncatapult · · chains · · circleStack · · cloth · · collisionFiltering · · \ncompound · · compoundStack · · constraints · · events · · friction · · \ngyro · · manipulation · · mixed · · newtonsCradle · · pyramid · · \nragdoll · · restitution · · rounded · · sensors · · sleeping · · \nslingshot · · softBody · · sprites · · stack · · staticFriction · · \nstats · · stress · · stress2 · · timescale · · views · · \nwreckingBall · ·   \nwhere  · no change  ● extrinsics changed  ◆ intrinsics changed\n    \n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.16.1...0.17.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n\n---\n\n## ▲.● matter.js `0.16.0`\n\nRelease notes for `0.16.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.16.0/README.md) for further information.\n\n### Highlights ✺\n\n- Changed external require method for `poly-decomp` ([882e07c](https://github.com/liabru/matter-js/commit/882e07c))\n- Improved `Bodies.fromVertices` decomposition quality using `removeDuplicatePoints` ([#639](https://github.com/liabru/matter-js/pull/639))\n- Added support for `>x.x.x` and `>=x.x.x` semver ranges in plugins ([0792716](https://github.com/liabru/matter-js/commit/0792716))\n- Changed demo example select background colour for Windows ([matter-tools #5](https://github.com/liabru/matter-tools/pull/5))\n- Updated demo to use latest [matter-tools](https://github.com/liabru/matter-tools) ([#33e8fe8](https://github.com/liabru/matter-js/commit/33e8fe8))\n- Updated SVG and terrain examples to use `fetch` ([5551cd5](https://github.com/liabru/matter-js/commit/5551cd5))\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.15.0...0.16.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.16.0/CHANGELOG.md) for a detailed list of changes.\n\n### Comparison ⎄\n\nDifferences in behaviour, quality and performance against the previous release `0.15.0`. For more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput comparison of 41 examples against matter-js@0.15.0 build on last run  \n\nSimilarity  100%  Performance  +0.00%  Overlap  +0.00%  \n\nairFriction · · avalanche · · ballPool · · bridge · · broadphase · · car · · \ncatapult · · chains · · circleStack · · cloth · · collisionFiltering · · \ncompositeManipulation · · compound · · compoundStack · · concave · · constraints · · \ndoublePendulum · · events · · friction · · gravity · · gyro · · \nmanipulation · · mixed · · newtonsCradle · · pyramid · · ragdoll · · \nraycasting · · restitution · · rounded · · sensors · · sleeping · · \nslingshot · · softBody · · sprites · · stack · · staticFriction · · \nstress · · stress2 · · timescale · · views · · wreckingBall · · \n  \nwhere  · no change  ● extrinsics changed  ◆ intrinsics changed\n    \n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.15.0...0.16.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n\n---\n\n## ▲.● matter.js `0.15.0`\n\nRelease notes for `0.15.0`. See the release [readme](https://github.com/liabru/matter-js/blob/0.15.0/README.md) for further information.\n\n### Highlights ✺\n\n- __Optimised performance up to ~30% boost vs. `0.14.2`__ ([#528](https://github.com/liabru/matter-js/pull/528)) ([#522](https://github.com/liabru/matter-js/pull/522)) ([#553](https://github.com/liabru/matter-js/pull/553))\n- Added `Body.setCentre` ([2ec247b](https://github.com/liabru/matter-js/commit/2ec247b))\n- Added `Constraint.pointAWorld` and `Constraint.pointBWorld` ([3c32969](https://github.com/liabru/matter-js/commit/3c32969))\n- Changed default colour scheme ([d258411](https://github.com/liabru/matter-js/commit/d258411)) ([6dd5ec5](https://github.com/liabru/matter-js/commit/6dd5ec5))\n- Fixed issues with decomp require ([0af1645](https://github.com/liabru/matter-js/commit/0af1645))\n- Fixed issues with render pixel ratio ([d577477](https://github.com/liabru/matter-js/commit/d577477))\n\n### Changes ✲\n\nSee the release [compare page](https://github.com/liabru/matter-js/compare/0.14.2...0.15.0) and the [changelog](https://github.com/liabru/matter-js/blob/0.15.0/CHANGELOG.md) for a detailed list of all changes.\n\n### Comparison ⎄\n\nDifferences in behaviour, quality and performance against the previous release `0.14.2`. For more information see [comparison method](https://github.com/liabru/matter-js/pull/794).\n\n```ocaml\nOutput comparison of 41 examples against matter-js@0.14.2 build on last run  \n\nSimilarity  100%  Performance  +33.6%  Overlap  +0.00%  \n\nairFriction · · avalanche · · ballPool · · bridge · · broadphase · · car · · \ncatapult · · chains · · circleStack · · cloth · · collisionFiltering · · \ncompositeManipulation · · compound · · compoundStack · · concave · · constraints · · \ndoublePendulum · · events · · friction · · gravity · · gyro · · \nmanipulation · · mixed · · newtonsCradle · · pyramid · · ragdoll · · \nraycasting · · restitution · · rounded · · sensors · · sleeping · · \nslingshot · · softBody · · sprites · · stack · · staticFriction · · \nstress · · stress2 · · timescale · · views · · wreckingBall · · \n  \nwhere  · no change  ● extrinsics changed  ◆ intrinsics changed\n    \n```\n\n### Contributors ♥︎\n\nMany thanks to the [contributors](https://github.com/liabru/matter-js/compare/0.14.2...0.15.0) of this release, [past contributors](https://github.com/liabru/matter-js/graphs/contributors) as well those involved in the [community](https://github.com/liabru/matter-js/issues) for your input and support.\n"
  },
  {
    "path": "build/matter.js",
    "content": "/*!\n * matter-js 0.20.0 by @liabru\n * http://brm.io/matter-js/\n * License MIT\n * \n * The MIT License (MIT)\n * \n * Copyright (c) Liam Brummitt and contributors.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"Matter\", [], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Matter\"] = factory();\n\telse\n\t\troot[\"Matter\"] = factory();\n})(this, function() {\nreturn /******/ (function(modules) { // webpackBootstrap\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// define __esModule on exports\n/******/ \t__webpack_require__.r = function(exports) {\n/******/ \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n/******/ \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n/******/ \t\t}\n/******/ \t\tObject.defineProperty(exports, '__esModule', { value: true });\n/******/ \t};\n/******/\n/******/ \t// create a fake namespace object\n/******/ \t// mode & 1: value is a module id, require it\n/******/ \t// mode & 2: merge all properties of value into the ns\n/******/ \t// mode & 4: return value when already ns object\n/******/ \t// mode & 8|1: behave like require\n/******/ \t__webpack_require__.t = function(value, mode) {\n/******/ \t\tif(mode & 1) value = __webpack_require__(value);\n/******/ \t\tif(mode & 8) return value;\n/******/ \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n/******/ \t\tvar ns = Object.create(null);\n/******/ \t\t__webpack_require__.r(ns);\n/******/ \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n/******/ \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n/******/ \t\treturn ns;\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = 20);\n/******/ })\n/************************************************************************/\n/******/ ([\n/* 0 */\n/***/ (function(module, exports) {\n\n/**\n* The `Matter.Common` module contains utility functions that are common to all modules.\n*\n* @class Common\n*/\n\nvar Common = {};\n\nmodule.exports = Common;\n\n(function() {\n\n    Common._baseDelta = 1000 / 60;\n    Common._nextId = 0;\n    Common._seed = 0;\n    Common._nowStartTime = +(new Date());\n    Common._warnedOnce = {};\n    Common._decomp = null;\n    \n    /**\n     * Extends the object in the first argument using the object in the second argument.\n     * @method extend\n     * @param {} obj\n     * @param {boolean} deep\n     * @return {} obj extended\n     */\n    Common.extend = function(obj, deep) {\n        var argsStart,\n            args,\n            deepClone;\n\n        if (typeof deep === 'boolean') {\n            argsStart = 2;\n            deepClone = deep;\n        } else {\n            argsStart = 1;\n            deepClone = true;\n        }\n\n        for (var i = argsStart; i < arguments.length; i++) {\n            var source = arguments[i];\n\n            if (source) {\n                for (var prop in source) {\n                    if (deepClone && source[prop] && source[prop].constructor === Object) {\n                        if (!obj[prop] || obj[prop].constructor === Object) {\n                            obj[prop] = obj[prop] || {};\n                            Common.extend(obj[prop], deepClone, source[prop]);\n                        } else {\n                            obj[prop] = source[prop];\n                        }\n                    } else {\n                        obj[prop] = source[prop];\n                    }\n                }\n            }\n        }\n        \n        return obj;\n    };\n\n    /**\n     * Creates a new clone of the object, if deep is true references will also be cloned.\n     * @method clone\n     * @param {} obj\n     * @param {bool} deep\n     * @return {} obj cloned\n     */\n    Common.clone = function(obj, deep) {\n        return Common.extend({}, deep, obj);\n    };\n\n    /**\n     * Returns the list of keys for the given object.\n     * @method keys\n     * @param {} obj\n     * @return {string[]} keys\n     */\n    Common.keys = function(obj) {\n        if (Object.keys)\n            return Object.keys(obj);\n\n        // avoid hasOwnProperty for performance\n        var keys = [];\n        for (var key in obj)\n            keys.push(key);\n        return keys;\n    };\n\n    /**\n     * Returns the list of values for the given object.\n     * @method values\n     * @param {} obj\n     * @return {array} Array of the objects property values\n     */\n    Common.values = function(obj) {\n        var values = [];\n        \n        if (Object.keys) {\n            var keys = Object.keys(obj);\n            for (var i = 0; i < keys.length; i++) {\n                values.push(obj[keys[i]]);\n            }\n            return values;\n        }\n        \n        // avoid hasOwnProperty for performance\n        for (var key in obj)\n            values.push(obj[key]);\n        return values;\n    };\n\n    /**\n     * Gets a value from `base` relative to the `path` string.\n     * @method get\n     * @param {} obj The base object\n     * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'\n     * @param {number} [begin] Path slice begin\n     * @param {number} [end] Path slice end\n     * @return {} The object at the given path\n     */\n    Common.get = function(obj, path, begin, end) {\n        path = path.split('.').slice(begin, end);\n\n        for (var i = 0; i < path.length; i += 1) {\n            obj = obj[path[i]];\n        }\n\n        return obj;\n    };\n\n    /**\n     * Sets a value on `base` relative to the given `path` string.\n     * @method set\n     * @param {} obj The base object\n     * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'\n     * @param {} val The value to set\n     * @param {number} [begin] Path slice begin\n     * @param {number} [end] Path slice end\n     * @return {} Pass through `val` for chaining\n     */\n    Common.set = function(obj, path, val, begin, end) {\n        var parts = path.split('.').slice(begin, end);\n        Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val;\n        return val;\n    };\n\n    /**\n     * Shuffles the given array in-place.\n     * The function uses a seeded random generator.\n     * @method shuffle\n     * @param {array} array\n     * @return {array} array shuffled randomly\n     */\n    Common.shuffle = function(array) {\n        for (var i = array.length - 1; i > 0; i--) {\n            var j = Math.floor(Common.random() * (i + 1));\n            var temp = array[i];\n            array[i] = array[j];\n            array[j] = temp;\n        }\n        return array;\n    };\n\n    /**\n     * Randomly chooses a value from a list with equal probability.\n     * The function uses a seeded random generator.\n     * @method choose\n     * @param {array} choices\n     * @return {object} A random choice object from the array\n     */\n    Common.choose = function(choices) {\n        return choices[Math.floor(Common.random() * choices.length)];\n    };\n\n    /**\n     * Returns true if the object is a HTMLElement, otherwise false.\n     * @method isElement\n     * @param {object} obj\n     * @return {boolean} True if the object is a HTMLElement, otherwise false\n     */\n    Common.isElement = function(obj) {\n        if (typeof HTMLElement !== 'undefined') {\n            return obj instanceof HTMLElement;\n        }\n\n        return !!(obj && obj.nodeType && obj.nodeName);\n    };\n\n    /**\n     * Returns true if the object is an array.\n     * @method isArray\n     * @param {object} obj\n     * @return {boolean} True if the object is an array, otherwise false\n     */\n    Common.isArray = function(obj) {\n        return Object.prototype.toString.call(obj) === '[object Array]';\n    };\n\n    /**\n     * Returns true if the object is a function.\n     * @method isFunction\n     * @param {object} obj\n     * @return {boolean} True if the object is a function, otherwise false\n     */\n    Common.isFunction = function(obj) {\n        return typeof obj === \"function\";\n    };\n\n    /**\n     * Returns true if the object is a plain object.\n     * @method isPlainObject\n     * @param {object} obj\n     * @return {boolean} True if the object is a plain object, otherwise false\n     */\n    Common.isPlainObject = function(obj) {\n        return typeof obj === 'object' && obj.constructor === Object;\n    };\n\n    /**\n     * Returns true if the object is a string.\n     * @method isString\n     * @param {object} obj\n     * @return {boolean} True if the object is a string, otherwise false\n     */\n    Common.isString = function(obj) {\n        return toString.call(obj) === '[object String]';\n    };\n    \n    /**\n     * Returns the given value clamped between a minimum and maximum value.\n     * @method clamp\n     * @param {number} value\n     * @param {number} min\n     * @param {number} max\n     * @return {number} The value clamped between min and max inclusive\n     */\n    Common.clamp = function(value, min, max) {\n        if (value < min)\n            return min;\n        if (value > max)\n            return max;\n        return value;\n    };\n    \n    /**\n     * Returns the sign of the given value.\n     * @method sign\n     * @param {number} value\n     * @return {number} -1 if negative, +1 if 0 or positive\n     */\n    Common.sign = function(value) {\n        return value < 0 ? -1 : 1;\n    };\n    \n    /**\n     * Returns the current timestamp since the time origin (e.g. from page load).\n     * The result is in milliseconds and will use high-resolution timing if available.\n     * @method now\n     * @return {number} the current timestamp in milliseconds\n     */\n    Common.now = function() {\n        if (typeof window !== 'undefined' && window.performance) {\n            if (window.performance.now) {\n                return window.performance.now();\n            } else if (window.performance.webkitNow) {\n                return window.performance.webkitNow();\n            }\n        }\n\n        if (Date.now) {\n            return Date.now();\n        }\n\n        return (new Date()) - Common._nowStartTime;\n    };\n    \n    /**\n     * Returns a random value between a minimum and a maximum value inclusive.\n     * The function uses a seeded random generator.\n     * @method random\n     * @param {number} min\n     * @param {number} max\n     * @return {number} A random number between min and max inclusive\n     */\n    Common.random = function(min, max) {\n        min = (typeof min !== \"undefined\") ? min : 0;\n        max = (typeof max !== \"undefined\") ? max : 1;\n        return min + _seededRandom() * (max - min);\n    };\n\n    var _seededRandom = function() {\n        // https://en.wikipedia.org/wiki/Linear_congruential_generator\n        Common._seed = (Common._seed * 9301 + 49297) % 233280;\n        return Common._seed / 233280;\n    };\n\n    /**\n     * Converts a CSS hex colour string into an integer.\n     * @method colorToNumber\n     * @param {string} colorString\n     * @return {number} An integer representing the CSS hex string\n     */\n    Common.colorToNumber = function(colorString) {\n        colorString = colorString.replace('#','');\n\n        if (colorString.length == 3) {\n            colorString = colorString.charAt(0) + colorString.charAt(0)\n                        + colorString.charAt(1) + colorString.charAt(1)\n                        + colorString.charAt(2) + colorString.charAt(2);\n        }\n\n        return parseInt(colorString, 16);\n    };\n\n    /**\n     * The console logging level to use, where each level includes all levels above and excludes the levels below.\n     * The default level is 'debug' which shows all console messages.  \n     *\n     * Possible level values are:\n     * - 0 = None\n     * - 1 = Debug\n     * - 2 = Info\n     * - 3 = Warn\n     * - 4 = Error\n     * @static\n     * @property logLevel\n     * @type {Number}\n     * @default 1\n     */\n    Common.logLevel = 1;\n\n    /**\n     * Shows a `console.log` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method log\n     * @param ...objs {} The objects to log.\n     */\n    Common.log = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 3) {\n            console.log.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Shows a `console.info` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method info\n     * @param ...objs {} The objects to log.\n     */\n    Common.info = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 2) {\n            console.info.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Shows a `console.warn` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method warn\n     * @param ...objs {} The objects to log.\n     */\n    Common.warn = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 3) {\n            console.warn.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Uses `Common.warn` to log the given message one time only.\n     * @method warnOnce\n     * @param ...objs {} The objects to log.\n     */\n    Common.warnOnce = function() {\n        var message = Array.prototype.slice.call(arguments).join(' ');\n\n        if (!Common._warnedOnce[message]) {\n            Common.warn(message);\n            Common._warnedOnce[message] = true;\n        }\n    };\n\n    /**\n     * Shows a deprecated console warning when the function on the given object is called.\n     * The target function will be replaced with a new function that first shows the warning\n     * and then calls the original function.\n     * @method deprecated\n     * @param {object} obj The object or module\n     * @param {string} name The property name of the function on obj\n     * @param {string} warning The one-time message to show if the function is called\n     */\n    Common.deprecated = function(obj, prop, warning) {\n        obj[prop] = Common.chain(function() {\n            Common.warnOnce('🔅 deprecated 🔅', warning);\n        }, obj[prop]);\n    };\n\n    /**\n     * Returns the next unique sequential ID.\n     * @method nextId\n     * @return {Number} Unique sequential ID\n     */\n    Common.nextId = function() {\n        return Common._nextId++;\n    };\n\n    /**\n     * A cross browser compatible indexOf implementation.\n     * @method indexOf\n     * @param {array} haystack\n     * @param {object} needle\n     * @return {number} The position of needle in haystack, otherwise -1.\n     */\n    Common.indexOf = function(haystack, needle) {\n        if (haystack.indexOf)\n            return haystack.indexOf(needle);\n\n        for (var i = 0; i < haystack.length; i++) {\n            if (haystack[i] === needle)\n                return i;\n        }\n\n        return -1;\n    };\n\n    /**\n     * A cross browser compatible array map implementation.\n     * @method map\n     * @param {array} list\n     * @param {function} func\n     * @return {array} Values from list transformed by func.\n     */\n    Common.map = function(list, func) {\n        if (list.map) {\n            return list.map(func);\n        }\n\n        var mapped = [];\n\n        for (var i = 0; i < list.length; i += 1) {\n            mapped.push(func(list[i]));\n        }\n\n        return mapped;\n    };\n\n    /**\n     * Takes a directed graph and returns the partially ordered set of vertices in topological order.\n     * Circular dependencies are allowed.\n     * @method topologicalSort\n     * @param {object} graph\n     * @return {array} Partially ordered set of vertices in topological order.\n     */\n    Common.topologicalSort = function(graph) {\n        // https://github.com/mgechev/javascript-algorithms\n        // Copyright (c) Minko Gechev (MIT license)\n        // Modifications: tidy formatting and naming\n        var result = [],\n            visited = [],\n            temp = [];\n\n        for (var node in graph) {\n            if (!visited[node] && !temp[node]) {\n                Common._topologicalSort(node, visited, temp, graph, result);\n            }\n        }\n\n        return result;\n    };\n\n    Common._topologicalSort = function(node, visited, temp, graph, result) {\n        var neighbors = graph[node] || [];\n        temp[node] = true;\n\n        for (var i = 0; i < neighbors.length; i += 1) {\n            var neighbor = neighbors[i];\n\n            if (temp[neighbor]) {\n                // skip circular dependencies\n                continue;\n            }\n\n            if (!visited[neighbor]) {\n                Common._topologicalSort(neighbor, visited, temp, graph, result);\n            }\n        }\n\n        temp[node] = false;\n        visited[node] = true;\n\n        result.push(node);\n    };\n\n    /**\n     * Takes _n_ functions as arguments and returns a new function that calls them in order.\n     * The arguments applied when calling the new function will also be applied to every function passed.\n     * The value of `this` refers to the last value returned in the chain that was not `undefined`.\n     * Therefore if a passed function does not return a value, the previously returned value is maintained.\n     * After all passed functions have been called the new function returns the last returned value (if any).\n     * If any of the passed functions are a chain, then the chain will be flattened.\n     * @method chain\n     * @param ...funcs {function} The functions to chain.\n     * @return {function} A new function that calls the passed functions in order.\n     */\n    Common.chain = function() {\n        var funcs = [];\n\n        for (var i = 0; i < arguments.length; i += 1) {\n            var func = arguments[i];\n\n            if (func._chained) {\n                // flatten already chained functions\n                funcs.push.apply(funcs, func._chained);\n            } else {\n                funcs.push(func);\n            }\n        }\n\n        var chain = function() {\n            // https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358\n            var lastResult,\n                args = new Array(arguments.length);\n\n            for (var i = 0, l = arguments.length; i < l; i++) {\n                args[i] = arguments[i];\n            }\n\n            for (i = 0; i < funcs.length; i += 1) {\n                var result = funcs[i].apply(lastResult, args);\n\n                if (typeof result !== 'undefined') {\n                    lastResult = result;\n                }\n            }\n\n            return lastResult;\n        };\n\n        chain._chained = funcs;\n\n        return chain;\n    };\n\n    /**\n     * Chains a function to excute before the original function on the given `path` relative to `base`.\n     * See also docs for `Common.chain`.\n     * @method chainPathBefore\n     * @param {} base The base object\n     * @param {string} path The path relative to `base`\n     * @param {function} func The function to chain before the original\n     * @return {function} The chained function that replaced the original\n     */\n    Common.chainPathBefore = function(base, path, func) {\n        return Common.set(base, path, Common.chain(\n            func,\n            Common.get(base, path)\n        ));\n    };\n\n    /**\n     * Chains a function to excute after the original function on the given `path` relative to `base`.\n     * See also docs for `Common.chain`.\n     * @method chainPathAfter\n     * @param {} base The base object\n     * @param {string} path The path relative to `base`\n     * @param {function} func The function to chain after the original\n     * @return {function} The chained function that replaced the original\n     */\n    Common.chainPathAfter = function(base, path, func) {\n        return Common.set(base, path, Common.chain(\n            Common.get(base, path),\n            func\n        ));\n    };\n\n    /**\n     * Provide the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module to enable\n     * concave vertex decomposition support when using `Bodies.fromVertices` e.g. `Common.setDecomp(require('poly-decomp'))`.\n     * @method setDecomp\n     * @param {} decomp The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module.\n     */\n    Common.setDecomp = function(decomp) {\n        Common._decomp = decomp;\n    };\n\n    /**\n     * Returns the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module provided through `Common.setDecomp`,\n     * otherwise returns the global `decomp` if set.\n     * @method getDecomp\n     * @return {} The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module if provided.\n     */\n    Common.getDecomp = function() {\n        // get user provided decomp if set\n        var decomp = Common._decomp;\n\n        try {\n            // otherwise from window global\n            if (!decomp && typeof window !== 'undefined') {\n                decomp = window.decomp;\n            }\n    \n            // otherwise from node global\n            if (!decomp && typeof global !== 'undefined') {\n                decomp = global.decomp;\n            }\n        } catch (e) {\n            // decomp not available\n            decomp = null;\n        }\n\n        return decomp;\n    };\n})();\n\n\n/***/ }),\n/* 1 */\n/***/ (function(module, exports) {\n\n/**\n* The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB).\n*\n* @class Bounds\n*/\n\nvar Bounds = {};\n\nmodule.exports = Bounds;\n\n(function() {\n\n    /**\n     * Creates a new axis-aligned bounding box (AABB) for the given vertices.\n     * @method create\n     * @param {vertices} vertices\n     * @return {bounds} A new bounds object\n     */\n    Bounds.create = function(vertices) {\n        var bounds = { \n            min: { x: 0, y: 0 }, \n            max: { x: 0, y: 0 }\n        };\n\n        if (vertices)\n            Bounds.update(bounds, vertices);\n        \n        return bounds;\n    };\n\n    /**\n     * Updates bounds using the given vertices and extends the bounds given a velocity.\n     * @method update\n     * @param {bounds} bounds\n     * @param {vertices} vertices\n     * @param {vector} velocity\n     */\n    Bounds.update = function(bounds, vertices, velocity) {\n        bounds.min.x = Infinity;\n        bounds.max.x = -Infinity;\n        bounds.min.y = Infinity;\n        bounds.max.y = -Infinity;\n\n        for (var i = 0; i < vertices.length; i++) {\n            var vertex = vertices[i];\n            if (vertex.x > bounds.max.x) bounds.max.x = vertex.x;\n            if (vertex.x < bounds.min.x) bounds.min.x = vertex.x;\n            if (vertex.y > bounds.max.y) bounds.max.y = vertex.y;\n            if (vertex.y < bounds.min.y) bounds.min.y = vertex.y;\n        }\n        \n        if (velocity) {\n            if (velocity.x > 0) {\n                bounds.max.x += velocity.x;\n            } else {\n                bounds.min.x += velocity.x;\n            }\n            \n            if (velocity.y > 0) {\n                bounds.max.y += velocity.y;\n            } else {\n                bounds.min.y += velocity.y;\n            }\n        }\n    };\n\n    /**\n     * Returns true if the bounds contains the given point.\n     * @method contains\n     * @param {bounds} bounds\n     * @param {vector} point\n     * @return {boolean} True if the bounds contain the point, otherwise false\n     */\n    Bounds.contains = function(bounds, point) {\n        return point.x >= bounds.min.x && point.x <= bounds.max.x \n               && point.y >= bounds.min.y && point.y <= bounds.max.y;\n    };\n\n    /**\n     * Returns true if the two bounds intersect.\n     * @method overlaps\n     * @param {bounds} boundsA\n     * @param {bounds} boundsB\n     * @return {boolean} True if the bounds overlap, otherwise false\n     */\n    Bounds.overlaps = function(boundsA, boundsB) {\n        return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x\n                && boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y);\n    };\n\n    /**\n     * Translates the bounds by the given vector.\n     * @method translate\n     * @param {bounds} bounds\n     * @param {vector} vector\n     */\n    Bounds.translate = function(bounds, vector) {\n        bounds.min.x += vector.x;\n        bounds.max.x += vector.x;\n        bounds.min.y += vector.y;\n        bounds.max.y += vector.y;\n    };\n\n    /**\n     * Shifts the bounds to the given position.\n     * @method shift\n     * @param {bounds} bounds\n     * @param {vector} position\n     */\n    Bounds.shift = function(bounds, position) {\n        var deltaX = bounds.max.x - bounds.min.x,\n            deltaY = bounds.max.y - bounds.min.y;\n            \n        bounds.min.x = position.x;\n        bounds.max.x = position.x + deltaX;\n        bounds.min.y = position.y;\n        bounds.max.y = position.y + deltaY;\n    };\n    \n})();\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports) {\n\n/**\n* The `Matter.Vector` module contains methods for creating and manipulating vectors.\n* Vectors are the basis of all the geometry related operations in the engine.\n* A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Vector\n*/\n\n// TODO: consider params for reusing vector objects\n\nvar Vector = {};\n\nmodule.exports = Vector;\n\n(function() {\n\n    /**\n     * Creates a new vector.\n     * @method create\n     * @param {number} x\n     * @param {number} y\n     * @return {vector} A new vector\n     */\n    Vector.create = function(x, y) {\n        return { x: x || 0, y: y || 0 };\n    };\n\n    /**\n     * Returns a new vector with `x` and `y` copied from the given `vector`.\n     * @method clone\n     * @param {vector} vector\n     * @return {vector} A new cloned vector\n     */\n    Vector.clone = function(vector) {\n        return { x: vector.x, y: vector.y };\n    };\n\n    /**\n     * Returns the magnitude (length) of a vector.\n     * @method magnitude\n     * @param {vector} vector\n     * @return {number} The magnitude of the vector\n     */\n    Vector.magnitude = function(vector) {\n        return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y));\n    };\n\n    /**\n     * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation).\n     * @method magnitudeSquared\n     * @param {vector} vector\n     * @return {number} The squared magnitude of the vector\n     */\n    Vector.magnitudeSquared = function(vector) {\n        return (vector.x * vector.x) + (vector.y * vector.y);\n    };\n\n    /**\n     * Rotates the vector about (0, 0) by specified angle.\n     * @method rotate\n     * @param {vector} vector\n     * @param {number} angle\n     * @param {vector} [output]\n     * @return {vector} The vector rotated about (0, 0)\n     */\n    Vector.rotate = function(vector, angle, output) {\n        var cos = Math.cos(angle), sin = Math.sin(angle);\n        if (!output) output = {};\n        var x = vector.x * cos - vector.y * sin;\n        output.y = vector.x * sin + vector.y * cos;\n        output.x = x;\n        return output;\n    };\n\n    /**\n     * Rotates the vector about a specified point by specified angle.\n     * @method rotateAbout\n     * @param {vector} vector\n     * @param {number} angle\n     * @param {vector} point\n     * @param {vector} [output]\n     * @return {vector} A new vector rotated about the point\n     */\n    Vector.rotateAbout = function(vector, angle, point, output) {\n        var cos = Math.cos(angle), sin = Math.sin(angle);\n        if (!output) output = {};\n        var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin);\n        output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos);\n        output.x = x;\n        return output;\n    };\n\n    /**\n     * Normalises a vector (such that its magnitude is `1`).\n     * @method normalise\n     * @param {vector} vector\n     * @return {vector} A new vector normalised\n     */\n    Vector.normalise = function(vector) {\n        var magnitude = Vector.magnitude(vector);\n        if (magnitude === 0)\n            return { x: 0, y: 0 };\n        return { x: vector.x / magnitude, y: vector.y / magnitude };\n    };\n\n    /**\n     * Returns the dot-product of two vectors.\n     * @method dot\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The dot product of the two vectors\n     */\n    Vector.dot = function(vectorA, vectorB) {\n        return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y);\n    };\n\n    /**\n     * Returns the cross-product of two vectors.\n     * @method cross\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The cross product of the two vectors\n     */\n    Vector.cross = function(vectorA, vectorB) {\n        return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x);\n    };\n\n    /**\n     * Returns the cross-product of three vectors.\n     * @method cross3\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} vectorC\n     * @return {number} The cross product of the three vectors\n     */\n    Vector.cross3 = function(vectorA, vectorB, vectorC) {\n        return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x);\n    };\n\n    /**\n     * Adds the two vectors.\n     * @method add\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} [output]\n     * @return {vector} A new vector of vectorA and vectorB added\n     */\n    Vector.add = function(vectorA, vectorB, output) {\n        if (!output) output = {};\n        output.x = vectorA.x + vectorB.x;\n        output.y = vectorA.y + vectorB.y;\n        return output;\n    };\n\n    /**\n     * Subtracts the two vectors.\n     * @method sub\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} [output]\n     * @return {vector} A new vector of vectorA and vectorB subtracted\n     */\n    Vector.sub = function(vectorA, vectorB, output) {\n        if (!output) output = {};\n        output.x = vectorA.x - vectorB.x;\n        output.y = vectorA.y - vectorB.y;\n        return output;\n    };\n\n    /**\n     * Multiplies a vector and a scalar.\n     * @method mult\n     * @param {vector} vector\n     * @param {number} scalar\n     * @return {vector} A new vector multiplied by scalar\n     */\n    Vector.mult = function(vector, scalar) {\n        return { x: vector.x * scalar, y: vector.y * scalar };\n    };\n\n    /**\n     * Divides a vector and a scalar.\n     * @method div\n     * @param {vector} vector\n     * @param {number} scalar\n     * @return {vector} A new vector divided by scalar\n     */\n    Vector.div = function(vector, scalar) {\n        return { x: vector.x / scalar, y: vector.y / scalar };\n    };\n\n    /**\n     * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction.\n     * @method perp\n     * @param {vector} vector\n     * @param {bool} [negate=false]\n     * @return {vector} The perpendicular vector\n     */\n    Vector.perp = function(vector, negate) {\n        negate = negate === true ? -1 : 1;\n        return { x: negate * -vector.y, y: negate * vector.x };\n    };\n\n    /**\n     * Negates both components of a vector such that it points in the opposite direction.\n     * @method neg\n     * @param {vector} vector\n     * @return {vector} The negated vector\n     */\n    Vector.neg = function(vector) {\n        return { x: -vector.x, y: -vector.y };\n    };\n\n    /**\n     * Returns the angle between the vector `vectorB - vectorA` and the x-axis in radians.\n     * @method angle\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The angle in radians\n     */\n    Vector.angle = function(vectorA, vectorB) {\n        return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x);\n    };\n\n    /**\n     * Temporary vector pool (not thread-safe).\n     * @property _temp\n     * @type {vector[]}\n     * @private\n     */\n    Vector._temp = [\n        Vector.create(), Vector.create(), \n        Vector.create(), Vector.create(), \n        Vector.create(), Vector.create()\n    ];\n\n})();\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices.\n* A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`.\n* A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Vertices\n*/\n\nvar Vertices = {};\n\nmodule.exports = Vertices;\n\nvar Vector = __webpack_require__(2);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Creates a new set of `Matter.Body` compatible vertices.\n     * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example:\n     *\n     *     [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]\n     *\n     * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects,\n     * but with some additional references required for efficient collision detection routines.\n     *\n     * Vertices must be specified in clockwise order.\n     *\n     * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided.\n     *\n     * @method create\n     * @param {vector[]} points\n     * @param {body} body\n     */\n    Vertices.create = function(points, body) {\n        var vertices = [];\n\n        for (var i = 0; i < points.length; i++) {\n            var point = points[i],\n                vertex = {\n                    x: point.x,\n                    y: point.y,\n                    index: i,\n                    body: body,\n                    isInternal: false\n                };\n\n            vertices.push(vertex);\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), \n     * into a `Matter.Vertices` object for the given `Matter.Body`.\n     * For parsing SVG paths, see `Svg.pathToVertices`.\n     * @method fromPath\n     * @param {string} path\n     * @param {body} body\n     * @return {vertices} vertices\n     */\n    Vertices.fromPath = function(path, body) {\n        var pathPattern = /L?\\s*([-\\d.e]+)[\\s,]*([-\\d.e]+)*/ig,\n            points = [];\n\n        path.replace(pathPattern, function(match, x, y) {\n            points.push({ x: parseFloat(x), y: parseFloat(y) });\n        });\n\n        return Vertices.create(points, body);\n    };\n\n    /**\n     * Returns the centre (centroid) of the set of vertices.\n     * @method centre\n     * @param {vertices} vertices\n     * @return {vector} The centre point\n     */\n    Vertices.centre = function(vertices) {\n        var area = Vertices.area(vertices, true),\n            centre = { x: 0, y: 0 },\n            cross,\n            temp,\n            j;\n\n        for (var i = 0; i < vertices.length; i++) {\n            j = (i + 1) % vertices.length;\n            cross = Vector.cross(vertices[i], vertices[j]);\n            temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross);\n            centre = Vector.add(centre, temp);\n        }\n\n        return Vector.div(centre, 6 * area);\n    };\n\n    /**\n     * Returns the average (mean) of the set of vertices.\n     * @method mean\n     * @param {vertices} vertices\n     * @return {vector} The average point\n     */\n    Vertices.mean = function(vertices) {\n        var average = { x: 0, y: 0 };\n\n        for (var i = 0; i < vertices.length; i++) {\n            average.x += vertices[i].x;\n            average.y += vertices[i].y;\n        }\n\n        return Vector.div(average, vertices.length);\n    };\n\n    /**\n     * Returns the area of the set of vertices.\n     * @method area\n     * @param {vertices} vertices\n     * @param {bool} signed\n     * @return {number} The area\n     */\n    Vertices.area = function(vertices, signed) {\n        var area = 0,\n            j = vertices.length - 1;\n\n        for (var i = 0; i < vertices.length; i++) {\n            area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y);\n            j = i;\n        }\n\n        if (signed)\n            return area / 2;\n\n        return Math.abs(area) / 2;\n    };\n\n    /**\n     * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass.\n     * @method inertia\n     * @param {vertices} vertices\n     * @param {number} mass\n     * @return {number} The polygon's moment of inertia\n     */\n    Vertices.inertia = function(vertices, mass) {\n        var numerator = 0,\n            denominator = 0,\n            v = vertices,\n            cross,\n            j;\n\n        // find the polygon's moment of inertia, using second moment of area\n        // from equations at http://www.physicsforums.com/showthread.php?t=25293\n        for (var n = 0; n < v.length; n++) {\n            j = (n + 1) % v.length;\n            cross = Math.abs(Vector.cross(v[j], v[n]));\n            numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n]));\n            denominator += cross;\n        }\n\n        return (mass / 6) * (numerator / denominator);\n    };\n\n    /**\n     * Translates the set of vertices in-place.\n     * @method translate\n     * @param {vertices} vertices\n     * @param {vector} vector\n     * @param {number} scalar\n     */\n    Vertices.translate = function(vertices, vector, scalar) {\n        scalar = typeof scalar !== 'undefined' ? scalar : 1;\n\n        var verticesLength = vertices.length,\n            translateX = vector.x * scalar,\n            translateY = vector.y * scalar,\n            i;\n        \n        for (i = 0; i < verticesLength; i++) {\n            vertices[i].x += translateX;\n            vertices[i].y += translateY;\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Rotates the set of vertices in-place.\n     * @method rotate\n     * @param {vertices} vertices\n     * @param {number} angle\n     * @param {vector} point\n     */\n    Vertices.rotate = function(vertices, angle, point) {\n        if (angle === 0)\n            return;\n\n        var cos = Math.cos(angle),\n            sin = Math.sin(angle),\n            pointX = point.x,\n            pointY = point.y,\n            verticesLength = vertices.length,\n            vertex,\n            dx,\n            dy,\n            i;\n\n        for (i = 0; i < verticesLength; i++) {\n            vertex = vertices[i];\n            dx = vertex.x - pointX;\n            dy = vertex.y - pointY;\n            vertex.x = pointX + (dx * cos - dy * sin);\n            vertex.y = pointY + (dx * sin + dy * cos);\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Returns `true` if the `point` is inside the set of `vertices`.\n     * @method contains\n     * @param {vertices} vertices\n     * @param {vector} point\n     * @return {boolean} True if the vertices contains point, otherwise false\n     */\n    Vertices.contains = function(vertices, point) {\n        var pointX = point.x,\n            pointY = point.y,\n            verticesLength = vertices.length,\n            vertex = vertices[verticesLength - 1],\n            nextVertex;\n\n        for (var i = 0; i < verticesLength; i++) {\n            nextVertex = vertices[i];\n\n            if ((pointX - vertex.x) * (nextVertex.y - vertex.y) \n                + (pointY - vertex.y) * (vertex.x - nextVertex.x) > 0) {\n                return false;\n            }\n\n            vertex = nextVertex;\n        }\n\n        return true;\n    };\n\n    /**\n     * Scales the vertices from a point (default is centre) in-place.\n     * @method scale\n     * @param {vertices} vertices\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} point\n     */\n    Vertices.scale = function(vertices, scaleX, scaleY, point) {\n        if (scaleX === 1 && scaleY === 1)\n            return vertices;\n\n        point = point || Vertices.centre(vertices);\n\n        var vertex,\n            delta;\n\n        for (var i = 0; i < vertices.length; i++) {\n            vertex = vertices[i];\n            delta = Vector.sub(vertex, point);\n            vertices[i].x = point.x + delta.x * scaleX;\n            vertices[i].y = point.y + delta.y * scaleY;\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices.\n     * The radius parameter is a single number or an array to specify the radius for each vertex.\n     * @method chamfer\n     * @param {vertices} vertices\n     * @param {number[]} radius\n     * @param {number} quality\n     * @param {number} qualityMin\n     * @param {number} qualityMax\n     */\n    Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {\n        if (typeof radius === 'number') {\n            radius = [radius];\n        } else {\n            radius = radius || [8];\n        }\n\n        // quality defaults to -1, which is auto\n        quality = (typeof quality !== 'undefined') ? quality : -1;\n        qualityMin = qualityMin || 2;\n        qualityMax = qualityMax || 14;\n\n        var newVertices = [];\n\n        for (var i = 0; i < vertices.length; i++) {\n            var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1],\n                vertex = vertices[i],\n                nextVertex = vertices[(i + 1) % vertices.length],\n                currentRadius = radius[i < radius.length ? i : radius.length - 1];\n\n            if (currentRadius === 0) {\n                newVertices.push(vertex);\n                continue;\n            }\n\n            var prevNormal = Vector.normalise({ \n                x: vertex.y - prevVertex.y, \n                y: prevVertex.x - vertex.x\n            });\n\n            var nextNormal = Vector.normalise({ \n                x: nextVertex.y - vertex.y, \n                y: vertex.x - nextVertex.x\n            });\n\n            var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)),\n                radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius),\n                midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), 0.5)),\n                scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius));\n\n            var precision = quality;\n\n            if (quality === -1) {\n                // automatically decide precision\n                precision = Math.pow(currentRadius, 0.32) * 1.75;\n            }\n\n            precision = Common.clamp(precision, qualityMin, qualityMax);\n\n            // use an even value for precision, more likely to reduce axes by using symmetry\n            if (precision % 2 === 1)\n                precision += 1;\n\n            var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)),\n                theta = alpha / precision;\n\n            for (var j = 0; j < precision; j++) {\n                newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex));\n            }\n        }\n\n        return newVertices;\n    };\n\n    /**\n     * Sorts the input vertices into clockwise order in place.\n     * @method clockwiseSort\n     * @param {vertices} vertices\n     * @return {vertices} vertices\n     */\n    Vertices.clockwiseSort = function(vertices) {\n        var centre = Vertices.mean(vertices);\n\n        vertices.sort(function(vertexA, vertexB) {\n            return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB);\n        });\n\n        return vertices;\n    };\n\n    /**\n     * Returns true if the vertices form a convex shape (vertices must be in clockwise order).\n     * @method isConvex\n     * @param {vertices} vertices\n     * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable).\n     */\n    Vertices.isConvex = function(vertices) {\n        // http://paulbourke.net/geometry/polygonmesh/\n        // Copyright (c) Paul Bourke (use permitted)\n\n        var flag = 0,\n            n = vertices.length,\n            i,\n            j,\n            k,\n            z;\n\n        if (n < 3)\n            return null;\n\n        for (i = 0; i < n; i++) {\n            j = (i + 1) % n;\n            k = (i + 2) % n;\n            z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y);\n            z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x);\n\n            if (z < 0) {\n                flag |= 1;\n            } else if (z > 0) {\n                flag |= 2;\n            }\n\n            if (flag === 3) {\n                return false;\n            }\n        }\n\n        if (flag !== 0){\n            return true;\n        } else {\n            return null;\n        }\n    };\n\n    /**\n     * Returns the convex hull of the input vertices as a new array of points.\n     * @method hull\n     * @param {vertices} vertices\n     * @return [vertex] vertices\n     */\n    Vertices.hull = function(vertices) {\n        // http://geomalgorithms.com/a10-_hull-1.html\n\n        var upper = [],\n            lower = [], \n            vertex,\n            i;\n\n        // sort vertices on x-axis (y-axis for ties)\n        vertices = vertices.slice(0);\n        vertices.sort(function(vertexA, vertexB) {\n            var dx = vertexA.x - vertexB.x;\n            return dx !== 0 ? dx : vertexA.y - vertexB.y;\n        });\n\n        // build lower hull\n        for (i = 0; i < vertices.length; i += 1) {\n            vertex = vertices[i];\n\n            while (lower.length >= 2 \n                   && Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) {\n                lower.pop();\n            }\n\n            lower.push(vertex);\n        }\n\n        // build upper hull\n        for (i = vertices.length - 1; i >= 0; i -= 1) {\n            vertex = vertices[i];\n\n            while (upper.length >= 2 \n                   && Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) {\n                upper.pop();\n            }\n\n            upper.push(vertex);\n        }\n\n        // concatenation of the lower and upper hulls gives the convex hull\n        // omit last points because they are repeated at the beginning of the other list\n        upper.pop();\n        lower.pop();\n\n        return upper.concat(lower);\n    };\n\n})();\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Body` module contains methods for creating and manipulating rigid bodies.\n* For creating bodies with common configurations such as rectangles, circles and other polygons see the module `Matter.Bodies`.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n\n* @class Body\n*/\n\nvar Body = {};\n\nmodule.exports = Body;\n\nvar Vertices = __webpack_require__(3);\nvar Vector = __webpack_require__(2);\nvar Sleeping = __webpack_require__(7);\nvar Common = __webpack_require__(0);\nvar Bounds = __webpack_require__(1);\nvar Axes = __webpack_require__(11);\n\n(function() {\n\n    Body._timeCorrection = true;\n    Body._inertiaScale = 4;\n    Body._nextCollidingGroupId = 1;\n    Body._nextNonCollidingGroupId = -1;\n    Body._nextCategory = 0x0001;\n    Body._baseDelta = 1000 / 60;\n\n    /**\n     * Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * Vertices must be specified in clockwise order.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     * @return {body} body\n     */\n    Body.create = function(options) {\n        var defaults = {\n            id: Common.nextId(),\n            type: 'body',\n            label: 'Body',\n            parts: [],\n            plugin: {},\n            angle: 0,\n            vertices: Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'),\n            position: { x: 0, y: 0 },\n            force: { x: 0, y: 0 },\n            torque: 0,\n            positionImpulse: { x: 0, y: 0 },\n            constraintImpulse: { x: 0, y: 0, angle: 0 },\n            totalContacts: 0,\n            speed: 0,\n            angularSpeed: 0,\n            velocity: { x: 0, y: 0 },\n            angularVelocity: 0,\n            isSensor: false,\n            isStatic: false,\n            isSleeping: false,\n            motion: 0,\n            sleepThreshold: 60,\n            density: 0.001,\n            restitution: 0,\n            friction: 0.1,\n            frictionStatic: 0.5,\n            frictionAir: 0.01,\n            collisionFilter: {\n                category: 0x0001,\n                mask: 0xFFFFFFFF,\n                group: 0\n            },\n            slop: 0.05,\n            timeScale: 1,\n            render: {\n                visible: true,\n                opacity: 1,\n                strokeStyle: null,\n                fillStyle: null,\n                lineWidth: null,\n                sprite: {\n                    xScale: 1,\n                    yScale: 1,\n                    xOffset: 0,\n                    yOffset: 0\n                }\n            },\n            events: null,\n            bounds: null,\n            chamfer: null,\n            circleRadius: 0,\n            positionPrev: null,\n            anglePrev: 0,\n            parent: null,\n            axes: null,\n            area: 0,\n            mass: 0,\n            inertia: 0,\n            deltaTime: 1000 / 60,\n            _original: null\n        };\n\n        var body = Common.extend(defaults, options);\n\n        _initProperties(body, options);\n\n        return body;\n    };\n\n    /**\n     * Returns the next unique group index for which bodies will collide.\n     * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide.\n     * See `body.collisionFilter` for more information.\n     * @method nextGroup\n     * @param {bool} [isNonColliding=false]\n     * @return {Number} Unique group index\n     */\n    Body.nextGroup = function(isNonColliding) {\n        if (isNonColliding)\n            return Body._nextNonCollidingGroupId--;\n\n        return Body._nextCollidingGroupId++;\n    };\n\n    /**\n     * Returns the next unique category bitfield (starting after the initial default category `0x0001`).\n     * There are 32 available. See `body.collisionFilter` for more information.\n     * @method nextCategory\n     * @return {Number} Unique category bitfield\n     */\n    Body.nextCategory = function() {\n        Body._nextCategory = Body._nextCategory << 1;\n        return Body._nextCategory;\n    };\n\n    /**\n     * Initialises body properties.\n     * @method _initProperties\n     * @private\n     * @param {body} body\n     * @param {} [options]\n     */\n    var _initProperties = function(body, options) {\n        options = options || {};\n\n        // init required properties (order is important)\n        Body.set(body, {\n            bounds: body.bounds || Bounds.create(body.vertices),\n            positionPrev: body.positionPrev || Vector.clone(body.position),\n            anglePrev: body.anglePrev || body.angle,\n            vertices: body.vertices,\n            parts: body.parts || [body],\n            isStatic: body.isStatic,\n            isSleeping: body.isSleeping,\n            parent: body.parent || body\n        });\n\n        Vertices.rotate(body.vertices, body.angle, body.position);\n        Axes.rotate(body.axes, body.angle);\n        Bounds.update(body.bounds, body.vertices, body.velocity);\n\n        // allow options to override the automatically calculated properties\n        Body.set(body, {\n            axes: options.axes || body.axes,\n            area: options.area || body.area,\n            mass: options.mass || body.mass,\n            inertia: options.inertia || body.inertia\n        });\n\n        // render properties\n        var defaultFillStyle = (body.isStatic ? '#14151f' : Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1'])),\n            defaultStrokeStyle = body.isStatic ? '#555' : '#ccc',\n            defaultLineWidth = body.isStatic && body.render.fillStyle === null ? 1 : 0;\n        body.render.fillStyle = body.render.fillStyle || defaultFillStyle;\n        body.render.strokeStyle = body.render.strokeStyle || defaultStrokeStyle;\n        body.render.lineWidth = body.render.lineWidth || defaultLineWidth;\n        body.render.sprite.xOffset += -(body.bounds.min.x - body.position.x) / (body.bounds.max.x - body.bounds.min.x);\n        body.render.sprite.yOffset += -(body.bounds.min.y - body.position.y) / (body.bounds.max.y - body.bounds.min.y);\n    };\n\n    /**\n     * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist.\n     * Prefer to use the actual setter functions in performance critical situations.\n     * @method set\n     * @param {body} body\n     * @param {} settings A property name (or map of properties and values) to set on the body.\n     * @param {} value The value to set if `settings` is a single property name.\n     */\n    Body.set = function(body, settings, value) {\n        var property;\n\n        if (typeof settings === 'string') {\n            property = settings;\n            settings = {};\n            settings[property] = value;\n        }\n\n        for (property in settings) {\n            if (!Object.prototype.hasOwnProperty.call(settings, property))\n                continue;\n\n            value = settings[property];\n            switch (property) {\n\n            case 'isStatic':\n                Body.setStatic(body, value);\n                break;\n            case 'isSleeping':\n                Sleeping.set(body, value);\n                break;\n            case 'mass':\n                Body.setMass(body, value);\n                break;\n            case 'density':\n                Body.setDensity(body, value);\n                break;\n            case 'inertia':\n                Body.setInertia(body, value);\n                break;\n            case 'vertices':\n                Body.setVertices(body, value);\n                break;\n            case 'position':\n                Body.setPosition(body, value);\n                break;\n            case 'angle':\n                Body.setAngle(body, value);\n                break;\n            case 'velocity':\n                Body.setVelocity(body, value);\n                break;\n            case 'angularVelocity':\n                Body.setAngularVelocity(body, value);\n                break;\n            case 'speed':\n                Body.setSpeed(body, value);\n                break;\n            case 'angularSpeed':\n                Body.setAngularSpeed(body, value);\n                break;\n            case 'parts':\n                Body.setParts(body, value);\n                break;\n            case 'centre':\n                Body.setCentre(body, value);\n                break;\n            default:\n                body[property] = value;\n\n            }\n        }\n    };\n\n    /**\n     * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity.\n     * @method setStatic\n     * @param {body} body\n     * @param {bool} isStatic\n     */\n    Body.setStatic = function(body, isStatic) {\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            if (isStatic) {\n                if (!part.isStatic) {\n                    part._original = {\n                        restitution: part.restitution,\n                        friction: part.friction,\n                        mass: part.mass,\n                        inertia: part.inertia,\n                        density: part.density,\n                        inverseMass: part.inverseMass,\n                        inverseInertia: part.inverseInertia\n                    };\n                }\n\n                part.restitution = 0;\n                part.friction = 1;\n                part.mass = part.inertia = part.density = Infinity;\n                part.inverseMass = part.inverseInertia = 0;\n\n                part.positionPrev.x = part.position.x;\n                part.positionPrev.y = part.position.y;\n                part.anglePrev = part.angle;\n                part.angularVelocity = 0;\n                part.speed = 0;\n                part.angularSpeed = 0;\n                part.motion = 0;\n            } else if (part._original) {\n                part.restitution = part._original.restitution;\n                part.friction = part._original.friction;\n                part.mass = part._original.mass;\n                part.inertia = part._original.inertia;\n                part.density = part._original.density;\n                part.inverseMass = part._original.inverseMass;\n                part.inverseInertia = part._original.inverseInertia;\n\n                part._original = null;\n            }\n\n            part.isStatic = isStatic;\n        }\n    };\n\n    /**\n     * Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change.\n     * @method setMass\n     * @param {body} body\n     * @param {number} mass\n     */\n    Body.setMass = function(body, mass) {\n        var moment = body.inertia / (body.mass / 6);\n        body.inertia = moment * (mass / 6);\n        body.inverseInertia = 1 / body.inertia;\n\n        body.mass = mass;\n        body.inverseMass = 1 / body.mass;\n        body.density = body.mass / body.area;\n    };\n\n    /**\n     * Sets the density of the body. Mass and inertia are automatically updated to reflect the change.\n     * @method setDensity\n     * @param {body} body\n     * @param {number} density\n     */\n    Body.setDensity = function(body, density) {\n        Body.setMass(body, density * body.area);\n        body.density = density;\n    };\n\n    /**\n     * Sets the moment of inertia of the body. This is the second moment of area in two dimensions.\n     * Inverse inertia is automatically updated to reflect the change. Mass is not changed.\n     * @method setInertia\n     * @param {body} body\n     * @param {number} inertia\n     */\n    Body.setInertia = function(body, inertia) {\n        body.inertia = inertia;\n        body.inverseInertia = 1 / body.inertia;\n    };\n\n    /**\n     * Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to `body.density`).\n     * Vertices will be automatically transformed to be orientated around their centre of mass as the origin.\n     * They are then automatically translated to world space based on `body.position`.\n     *\n     * The `vertices` argument should be passed as an array of `Matter.Vector` points (or a `Matter.Vertices` array).\n     * Vertices must form a convex hull. Concave vertices must be decomposed into convex parts.\n     * \n     * @method setVertices\n     * @param {body} body\n     * @param {vector[]} vertices\n     */\n    Body.setVertices = function(body, vertices) {\n        // change vertices\n        if (vertices[0].body === body) {\n            body.vertices = vertices;\n        } else {\n            body.vertices = Vertices.create(vertices, body);\n        }\n\n        // update properties\n        body.axes = Axes.fromVertices(body.vertices);\n        body.area = Vertices.area(body.vertices);\n        Body.setMass(body, body.density * body.area);\n\n        // orient vertices around the centre of mass at origin (0, 0)\n        var centre = Vertices.centre(body.vertices);\n        Vertices.translate(body.vertices, centre, -1);\n\n        // update inertia while vertices are at origin (0, 0)\n        Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass));\n\n        // update geometry\n        Vertices.translate(body.vertices, body.position);\n        Bounds.update(body.bounds, body.vertices, body.velocity);\n    };\n\n    /**\n     * Sets the parts of the `body`. \n     * \n     * See `body.parts` for details and requirements on how parts are used.\n     * \n     * See Bodies.fromVertices for a related utility.\n     * \n     * This function updates `body` mass, inertia and centroid based on the parts geometry.  \n     * Sets each `part.parent` to be this `body`.  \n     * \n     * The convex hull is computed and set on this `body` (unless `autoHull` is `false`).  \n     * Automatically ensures that the first part in `body.parts` is the `body`.\n     * @method setParts\n     * @param {body} body\n     * @param {body[]} parts\n     * @param {bool} [autoHull=true]\n     */\n    Body.setParts = function(body, parts, autoHull) {\n        var i;\n\n        // add all the parts, ensuring that the first part is always the parent body\n        parts = parts.slice(0);\n        body.parts.length = 0;\n        body.parts.push(body);\n        body.parent = body;\n\n        for (i = 0; i < parts.length; i++) {\n            var part = parts[i];\n            if (part !== body) {\n                part.parent = body;\n                body.parts.push(part);\n            }\n        }\n\n        if (body.parts.length === 1)\n            return;\n\n        autoHull = typeof autoHull !== 'undefined' ? autoHull : true;\n\n        // find the convex hull of all parts to set on the parent body\n        if (autoHull) {\n            var vertices = [];\n            for (i = 0; i < parts.length; i++) {\n                vertices = vertices.concat(parts[i].vertices);\n            }\n\n            Vertices.clockwiseSort(vertices);\n\n            var hull = Vertices.hull(vertices),\n                hullCentre = Vertices.centre(hull);\n\n            Body.setVertices(body, hull);\n            Vertices.translate(body.vertices, hullCentre);\n        }\n\n        // sum the properties of all compound parts of the parent body\n        var total = Body._totalProperties(body);\n\n        body.area = total.area;\n        body.parent = body;\n        body.position.x = total.centre.x;\n        body.position.y = total.centre.y;\n        body.positionPrev.x = total.centre.x;\n        body.positionPrev.y = total.centre.y;\n\n        Body.setMass(body, total.mass);\n        Body.setInertia(body, total.inertia);\n        Body.setPosition(body, total.centre);\n    };\n\n    /**\n     * Set the centre of mass of the body. \n     * The `centre` is a vector in world-space unless `relative` is set, in which case it is a translation.\n     * The centre of mass is the point the body rotates about and can be used to simulate non-uniform density.\n     * This is equal to moving `body.position` but not the `body.vertices`.\n     * Invalid if the `centre` falls outside the body's convex hull.\n     * @method setCentre\n     * @param {body} body\n     * @param {vector} centre\n     * @param {bool} relative\n     */\n    Body.setCentre = function(body, centre, relative) {\n        if (!relative) {\n            body.positionPrev.x = centre.x - (body.position.x - body.positionPrev.x);\n            body.positionPrev.y = centre.y - (body.position.y - body.positionPrev.y);\n            body.position.x = centre.x;\n            body.position.y = centre.y;\n        } else {\n            body.positionPrev.x += centre.x;\n            body.positionPrev.y += centre.y;\n            body.position.x += centre.x;\n            body.position.y += centre.y;\n        }\n    };\n\n    /**\n     * Sets the position of the body. By default velocity is unchanged.\n     * If `updateVelocity` is `true` then velocity is inferred from the change in position.\n     * @method setPosition\n     * @param {body} body\n     * @param {vector} position\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.setPosition = function(body, position, updateVelocity) {\n        var delta = Vector.sub(position, body.position);\n\n        if (updateVelocity) {\n            body.positionPrev.x = body.position.x;\n            body.positionPrev.y = body.position.y;\n            body.velocity.x = delta.x;\n            body.velocity.y = delta.y;\n            body.speed = Vector.magnitude(delta);\n        } else {\n            body.positionPrev.x += delta.x;\n            body.positionPrev.y += delta.y;\n        }\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n            part.position.x += delta.x;\n            part.position.y += delta.y;\n            Vertices.translate(part.vertices, delta);\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n    };\n\n    /**\n     * Sets the angle of the body. By default angular velocity is unchanged.\n     * If `updateVelocity` is `true` then angular velocity is inferred from the change in angle.\n     * @method setAngle\n     * @param {body} body\n     * @param {number} angle\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.setAngle = function(body, angle, updateVelocity) {\n        var delta = angle - body.angle;\n        \n        if (updateVelocity) {\n            body.anglePrev = body.angle;\n            body.angularVelocity = delta;\n            body.angularSpeed = Math.abs(delta);\n        } else {\n            body.anglePrev += delta;\n        }\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n            part.angle += delta;\n            Vertices.rotate(part.vertices, delta, body.position);\n            Axes.rotate(part.axes, delta);\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n            if (i > 0) {\n                Vector.rotateAbout(part.position, delta, body.position, part.position);\n            }\n        }\n    };\n\n    /**\n     * Sets the current linear velocity of the body.  \n     * Affects body speed.\n     * @method setVelocity\n     * @param {body} body\n     * @param {vector} velocity\n     */\n    Body.setVelocity = function(body, velocity) {\n        var timeScale = body.deltaTime / Body._baseDelta;\n        body.positionPrev.x = body.position.x - velocity.x * timeScale;\n        body.positionPrev.y = body.position.y - velocity.y * timeScale;\n        body.velocity.x = (body.position.x - body.positionPrev.x) / timeScale;\n        body.velocity.y = (body.position.y - body.positionPrev.y) / timeScale;\n        body.speed = Vector.magnitude(body.velocity);\n    };\n\n    /**\n     * Gets the current linear velocity of the body.\n     * @method getVelocity\n     * @param {body} body\n     * @return {vector} velocity\n     */\n    Body.getVelocity = function(body) {\n        var timeScale = Body._baseDelta / body.deltaTime;\n\n        return {\n            x: (body.position.x - body.positionPrev.x) * timeScale,\n            y: (body.position.y - body.positionPrev.y) * timeScale\n        };\n    };\n\n    /**\n     * Gets the current linear speed of the body.  \n     * Equivalent to the magnitude of its velocity.\n     * @method getSpeed\n     * @param {body} body\n     * @return {number} speed\n     */\n    Body.getSpeed = function(body) {\n        return Vector.magnitude(Body.getVelocity(body));\n    };\n\n    /**\n     * Sets the current linear speed of the body.  \n     * Direction is maintained. Affects body velocity.\n     * @method setSpeed\n     * @param {body} body\n     * @param {number} speed\n     */\n    Body.setSpeed = function(body, speed) {\n        Body.setVelocity(body, Vector.mult(Vector.normalise(Body.getVelocity(body)), speed));\n    };\n\n    /**\n     * Sets the current rotational velocity of the body.  \n     * Affects body angular speed.\n     * @method setAngularVelocity\n     * @param {body} body\n     * @param {number} velocity\n     */\n    Body.setAngularVelocity = function(body, velocity) {\n        var timeScale = body.deltaTime / Body._baseDelta;\n        body.anglePrev = body.angle - velocity * timeScale;\n        body.angularVelocity = (body.angle - body.anglePrev) / timeScale;\n        body.angularSpeed = Math.abs(body.angularVelocity);\n    };\n\n    /**\n     * Gets the current rotational velocity of the body.\n     * @method getAngularVelocity\n     * @param {body} body\n     * @return {number} angular velocity\n     */\n    Body.getAngularVelocity = function(body) {\n        return (body.angle - body.anglePrev) * Body._baseDelta / body.deltaTime;\n    };\n\n    /**\n     * Gets the current rotational speed of the body.  \n     * Equivalent to the magnitude of its angular velocity.\n     * @method getAngularSpeed\n     * @param {body} body\n     * @return {number} angular speed\n     */\n    Body.getAngularSpeed = function(body) {\n        return Math.abs(Body.getAngularVelocity(body));\n    };\n\n    /**\n     * Sets the current rotational speed of the body.  \n     * Direction is maintained. Affects body angular velocity.\n     * @method setAngularSpeed\n     * @param {body} body\n     * @param {number} speed\n     */\n    Body.setAngularSpeed = function(body, speed) {\n        Body.setAngularVelocity(body, Common.sign(Body.getAngularVelocity(body)) * speed);\n    };\n\n    /**\n     * Moves a body by a given vector relative to its current position. By default velocity is unchanged.\n     * If `updateVelocity` is `true` then velocity is inferred from the change in position.\n     * @method translate\n     * @param {body} body\n     * @param {vector} translation\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.translate = function(body, translation, updateVelocity) {\n        Body.setPosition(body, Vector.add(body.position, translation), updateVelocity);\n    };\n\n    /**\n     * Rotates a body by a given angle relative to its current angle. By default angular velocity is unchanged.\n     * If `updateVelocity` is `true` then angular velocity is inferred from the change in angle.\n     * @method rotate\n     * @param {body} body\n     * @param {number} rotation\n     * @param {vector} [point]\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.rotate = function(body, rotation, point, updateVelocity) {\n        if (!point) {\n            Body.setAngle(body, body.angle + rotation, updateVelocity);\n        } else {\n            var cos = Math.cos(rotation),\n                sin = Math.sin(rotation),\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + (dx * cos - dy * sin),\n                y: point.y + (dx * sin + dy * cos)\n            }, updateVelocity);\n\n            Body.setAngle(body, body.angle + rotation, updateVelocity);\n        }\n    };\n\n    /**\n     * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre).\n     * @method scale\n     * @param {body} body\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} [point]\n     */\n    Body.scale = function(body, scaleX, scaleY, point) {\n        var totalArea = 0,\n            totalInertia = 0;\n\n        point = point || body.position;\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            // scale vertices\n            Vertices.scale(part.vertices, scaleX, scaleY, point);\n\n            // update properties\n            part.axes = Axes.fromVertices(part.vertices);\n            part.area = Vertices.area(part.vertices);\n            Body.setMass(part, body.density * part.area);\n\n            // update inertia (requires vertices to be at origin)\n            Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y });\n            Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass));\n            Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y });\n\n            if (i > 0) {\n                totalArea += part.area;\n                totalInertia += part.inertia;\n            }\n\n            // scale position\n            part.position.x = point.x + (part.position.x - point.x) * scaleX;\n            part.position.y = point.y + (part.position.y - point.y) * scaleY;\n\n            // update bounds\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n\n        // handle parent body\n        if (body.parts.length > 1) {\n            body.area = totalArea;\n\n            if (!body.isStatic) {\n                Body.setMass(body, body.density * totalArea);\n                Body.setInertia(body, totalInertia);\n            }\n        }\n\n        // handle circles\n        if (body.circleRadius) { \n            if (scaleX === scaleY) {\n                body.circleRadius *= scaleX;\n            } else {\n                // body is no longer a circle\n                body.circleRadius = null;\n            }\n        }\n    };\n\n    /**\n     * Performs an update by integrating the equations of motion on the `body`.\n     * This is applied every update by `Matter.Engine` automatically.\n     * @method update\n     * @param {body} body\n     * @param {number} [deltaTime=16.666]\n     */\n    Body.update = function(body, deltaTime) {\n        deltaTime = (typeof deltaTime !== 'undefined' ? deltaTime : (1000 / 60)) * body.timeScale;\n\n        var deltaTimeSquared = deltaTime * deltaTime,\n            correction = Body._timeCorrection ? deltaTime / (body.deltaTime || deltaTime) : 1;\n\n        // from the previous step\n        var frictionAir = 1 - body.frictionAir * (deltaTime / Common._baseDelta),\n            velocityPrevX = (body.position.x - body.positionPrev.x) * correction,\n            velocityPrevY = (body.position.y - body.positionPrev.y) * correction;\n\n        // update velocity with Verlet integration\n        body.velocity.x = (velocityPrevX * frictionAir) + (body.force.x / body.mass) * deltaTimeSquared;\n        body.velocity.y = (velocityPrevY * frictionAir) + (body.force.y / body.mass) * deltaTimeSquared;\n\n        body.positionPrev.x = body.position.x;\n        body.positionPrev.y = body.position.y;\n        body.position.x += body.velocity.x;\n        body.position.y += body.velocity.y;\n        body.deltaTime = deltaTime;\n\n        // update angular velocity with Verlet integration\n        body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared;\n        body.anglePrev = body.angle;\n        body.angle += body.angularVelocity;\n\n        // transform the body geometry\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            Vertices.translate(part.vertices, body.velocity);\n            \n            if (i > 0) {\n                part.position.x += body.velocity.x;\n                part.position.y += body.velocity.y;\n            }\n\n            if (body.angularVelocity !== 0) {\n                Vertices.rotate(part.vertices, body.angularVelocity, body.position);\n                Axes.rotate(part.axes, body.angularVelocity);\n                if (i > 0) {\n                    Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position);\n                }\n            }\n\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n    };\n\n    /**\n     * Updates properties `body.velocity`, `body.speed`, `body.angularVelocity` and `body.angularSpeed` which are normalised in relation to `Body._baseDelta`.\n     * @method updateVelocities\n     * @param {body} body\n     */\n    Body.updateVelocities = function(body) {\n        var timeScale = Body._baseDelta / body.deltaTime,\n            bodyVelocity = body.velocity;\n\n        bodyVelocity.x = (body.position.x - body.positionPrev.x) * timeScale;\n        bodyVelocity.y = (body.position.y - body.positionPrev.y) * timeScale;\n        body.speed = Math.sqrt((bodyVelocity.x * bodyVelocity.x) + (bodyVelocity.y * bodyVelocity.y));\n\n        body.angularVelocity = (body.angle - body.anglePrev) * timeScale;\n        body.angularSpeed = Math.abs(body.angularVelocity);\n    };\n\n    /**\n     * Applies the `force` to the `body` from the force origin `position` in world-space, over a single timestep, including applying any resulting angular torque.\n     * \n     * Forces are useful for effects like gravity, wind or rocket thrust, but can be difficult in practice when precise control is needed. In these cases see `Body.setVelocity` and `Body.setPosition` as an alternative.\n     * \n     * The force from this function is only applied once for the duration of a single timestep, in other words the duration depends directly on the current engine update `delta` and the rate of calls to this function.\n     * \n     * Therefore to account for time, you should apply the force constantly over as many engine updates as equivalent to the intended duration.\n     * \n     * If all or part of the force duration is some fraction of a timestep, first multiply the force by `duration / timestep`.\n     * \n     * The force origin `position` in world-space must also be specified. Passing `body.position` will result in zero angular effect as the force origin would be at the centre of mass.\n     * \n     * The `body` will take time to accelerate under a force, the resulting effect depends on duration of the force, the body mass and other forces on the body including friction combined.\n     * @method applyForce\n     * @param {body} body\n     * @param {vector} position The force origin in world-space. Pass `body.position` to avoid angular torque.\n     * @param {vector} force\n     */\n    Body.applyForce = function(body, position, force) {\n        var offset = { x: position.x - body.position.x, y: position.y - body.position.y };\n        body.force.x += force.x;\n        body.force.y += force.y;\n        body.torque += offset.x * force.y - offset.y * force.x;\n    };\n\n    /**\n     * Returns the sums of the properties of all compound parts of the parent body.\n     * @method _totalProperties\n     * @private\n     * @param {body} body\n     * @return {}\n     */\n    Body._totalProperties = function(body) {\n        // from equations at:\n        // https://ecourses.ou.edu/cgi-bin/ebook.cgi?doc=&topic=st&chap_sec=07.2&page=theory\n        // http://output.to/sideway/default.asp?qno=121100087\n\n        var properties = {\n            mass: 0,\n            area: 0,\n            inertia: 0,\n            centre: { x: 0, y: 0 }\n        };\n\n        // sum the properties of all compound parts of the parent body\n        for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) {\n            var part = body.parts[i],\n                mass = part.mass !== Infinity ? part.mass : 1;\n\n            properties.mass += mass;\n            properties.area += part.area;\n            properties.inertia += part.inertia;\n            properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass));\n        }\n\n        properties.centre = Vector.div(properties.centre, properties.mass);\n\n        return properties;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when a body starts sleeping (where `this` is the body).\n    *\n    * @event sleepStart\n    * @this {body} The body that has started sleeping\n    * @param {} event An event object\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a body ends sleeping (where `this` is the body).\n    *\n    * @event sleepEnd\n    * @this {body} The body that has ended sleeping\n    * @param {} event An event object\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * _Read only_. Set by `Body.create`.\n     * \n     * A `String` denoting the type of object.\n     *\n     * @readOnly\n     * @property type\n     * @type string\n     * @default \"body\"\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage bodies.\n     *\n     * @property label\n     * @type string\n     * @default \"Body\"\n     */\n\n    /**\n     * _Read only_. Use `Body.setParts` to set. \n     * \n     * See `Bodies.fromVertices` for a related utility.\n     * \n     * An array of bodies (the 'parts') that make up this body (the 'parent'). The first body in this array must always be a self-reference to this `body`.  \n     * \n     * The parts are fixed together and therefore perform as a single unified rigid body.\n     * \n     * Parts in relation to each other are allowed to overlap, as well as form gaps or holes, so can be used to create complex concave bodies unlike when using a single part. \n     * \n     * Use properties and functions on the parent `body` rather than on parts.\n     *   \n     * Outside of their geometry, most properties on parts are not considered or updated.  \n     * As such 'per-part' material properties among others are not currently considered.\n     * \n     * Parts should be created specifically for their parent body.  \n     * Parts should not be shared or reused between bodies, only one parent is supported.  \n     * Parts should not have their own parts, they are not handled recursively.  \n     * Parts should not be added to the world directly or any other composite.  \n     * Parts own vertices must be convex and in clockwise order.   \n     * \n     * A body with more than one part is sometimes referred to as a 'compound' body. \n     * \n     * Use `Body.setParts` when setting parts to ensure correct updates of all properties.  \n     *\n     * @readOnly\n     * @property parts\n     * @type body[]\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * _Read only_. Updated by `Body.setParts`.\n     * \n     * A reference to the body that this is a part of. See `body.parts`.\n     * This is a self reference if the body is not a part of another body.\n     *\n     * @readOnly\n     * @property parent\n     * @type body\n     */\n\n    /**\n     * A `Number` specifying the angle of the body, in radians.\n     *\n     * @property angle\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setVertices` or `Body.setParts` to set. See also `Bodies.fromVertices`.\n     * \n     * An array of `Vector` objects that specify the convex hull of the rigid body.\n     * These should be provided about the origin `(0, 0)`. E.g.\n     *\n     * `[{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]`\n     * \n     * Vertices must always be convex, in clockwise order and must not contain any duplicate points.\n     * \n     * Concave vertices should be decomposed into convex `parts`, see `Bodies.fromVertices` and `Body.setParts`.\n     *\n     * When set the vertices are translated such that `body.position` is at the centre of mass.\n     * Many other body properties are automatically calculated from these vertices when set including `density`, `area` and `inertia`.\n     * \n     * The module `Matter.Vertices` contains useful methods for working with vertices.\n     *\n     * @readOnly\n     * @property vertices\n     * @type vector[]\n     */\n\n    /**\n     * _Read only_. Use `Body.setPosition` to set. \n     * \n     * A `Vector` that specifies the current world-space position of the body.\n     * \n     * @readOnly\n     * @property position\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that accumulates the total force applied to the body for a single update.\n     * Force is zeroed after every `Engine.update`, so constant forces should be applied for every update they are needed. See also `Body.applyForce`.\n     * \n     * @property force\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Number` that accumulates the total torque (turning force) applied to the body for a single update. See also `Body.applyForce`.\n     * Torque is zeroed after every `Engine.update`, so constant torques should be applied for every update they are needed.\n     *\n     * Torques result in angular acceleration on every update, which depends on body inertia and the engine update delta.\n     * \n     * @property torque\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setSpeed` to set. \n     * \n     * See `Body.getSpeed` for details.\n     * \n     * Equivalent to the magnitude of `body.velocity` (always positive).\n     * \n     * @readOnly\n     * @property speed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setVelocity` to set. \n     * \n     * See `Body.getVelocity` for details.\n     * \n     * Equivalent to the magnitude of `body.angularVelocity` (always positive).\n     * \n     * @readOnly\n     * @property velocity\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * _Read only_. Use `Body.setAngularSpeed` to set. \n     * \n     * See `Body.getAngularSpeed` for details.\n     * \n     * \n     * @readOnly\n     * @property angularSpeed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setAngularVelocity` to set. \n     * \n     * See `Body.getAngularVelocity` for details.\n     * \n     *\n     * @readOnly\n     * @property angularVelocity\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setStatic` to set. \n     * \n     * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.\n     *\n     * @readOnly\n     * @property isStatic\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.\n     *\n     * @property isSensor\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * _Read only_. Use `Sleeping.set` to set. \n     * \n     * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.\n     *\n     * @readOnly\n     * @property isSleeping\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * _Read only_. Calculated during engine update only when sleeping is enabled.\n     * \n     * A `Number` that loosely measures the amount of movement a body currently has.\n     *\n     * Derived from `body.speed^2 + body.angularSpeed^2`. See `Sleeping.update`.\n     * \n     * @readOnly\n     * @property motion\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that defines the length of time during which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine).\n     * \n     * @property sleepThreshold\n     * @type number\n     * @default 60\n     */\n\n    /**\n     * _Read only_. Use `Body.setDensity` to set. \n     * \n     * A `Number` that defines the density of the body (mass per unit area).\n     * \n     * Mass will also be updated when set.\n     *\n     * @readOnly\n     * @property density\n     * @type number\n     * @default 0.001\n     */\n\n    /**\n     * _Read only_. Use `Body.setMass` to set. \n     * \n     * A `Number` that defines the mass of the body.\n     * \n     * Density will also be updated when set.\n     * \n     * @readOnly\n     * @property mass\n     * @type number\n     */\n\n    /**\n     * _Read only_. Use `Body.setMass` to set. \n     * \n     * A `Number` that defines the inverse mass of the body (`1 / mass`).\n     *\n     * @readOnly\n     * @property inverseMass\n     * @type number\n     */\n\n    /**\n     * _Read only_. Automatically calculated when vertices, mass or density are set or set through `Body.setInertia`.\n     * \n     * A `Number` that defines the moment of inertia of the body. This is the second moment of area in two dimensions.\n     * \n     * Can be manually set to `Infinity` to prevent rotation of the body. See `Body.setInertia`.\n     * \n     * @readOnly\n     * @property inertia\n     * @type number\n     */\n\n    /**\n     * _Read only_. Automatically calculated when vertices, mass or density are set or calculated by `Body.setInertia`.\n     * \n     * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`).\n     * \n     * @readOnly\n     * @property inverseInertia\n     * @type number\n     */\n\n    /**\n     * A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`.\n     * A value of `0` means collisions may be perfectly inelastic and no bouncing may occur. \n     * A value of `0.8` means the body may bounce back with approximately 80% of its kinetic energy.\n     * Note that collision response is based on _pairs_ of bodies, and that `restitution` values are _combined_ with the following formula:\n     *\n     * `Math.max(bodyA.restitution, bodyB.restitution)`\n     *\n     * @property restitution\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that defines the friction of the body. The value is always positive and is in the range `(0, 1)`.\n     * A value of `0` means that the body may slide indefinitely.\n     * A value of `1` means the body may come to a stop almost instantly after a force is applied.\n     *\n     * The effects of the value may be non-linear. \n     * High values may be unstable depending on the body.\n     * The engine uses a Coulomb friction model including static and kinetic friction.\n     * Note that collision response is based on _pairs_ of bodies, and that `friction` values are _combined_ with the following formula:\n     *\n     * `Math.min(bodyA.friction, bodyB.friction)`\n     *\n     * @property friction\n     * @type number\n     * @default 0.1\n     */\n\n    /**\n     * A `Number` that defines the static friction of the body (in the Coulomb friction model). \n     * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used.\n     * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary.\n     * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction.\n     *\n     * @property frictionStatic\n     * @type number\n     * @default 0.5\n     */\n\n    /**\n     * A `Number` that defines the air friction of the body (air resistance). \n     * A value of `0` means the body will never slow as it moves through space.\n     * The higher the value, the faster a body slows when moving through space.\n     * The effects of the value are non-linear. \n     *\n     * @property frictionAir\n     * @type number\n     * @default 0.01\n     */\n\n    /**\n     * An `Object` that specifies the collision filtering properties of this body.\n     *\n     * Collisions between two bodies will obey the following rules:\n     * - If the two bodies have the same non-zero value of `collisionFilter.group`,\n     *   they will always collide if the value is positive, and they will never collide\n     *   if the value is negative.\n     * - If the two bodies have different values of `collisionFilter.group` or if one\n     *   (or both) of the bodies has a value of 0, then the category/mask rules apply as follows:\n     *\n     * Each body belongs to a collision category, given by `collisionFilter.category`. This\n     * value is used as a bit field and the category should have only one bit set, meaning that\n     * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32\n     * different collision categories available.\n     *\n     * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies\n     * the categories it collides with (the value is the bitwise AND value of all these categories).\n     *\n     * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's\n     * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0`\n     * are both true.\n     *\n     * @property collisionFilter\n     * @type object\n     */\n\n    /**\n     * An Integer `Number`, that specifies the collision group this body belongs to.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.group\n     * @type object\n     * @default 0\n     */\n\n    /**\n     * A bit field that specifies the collision category this body belongs to.\n     * The category value should have only one bit set, for example `0x0001`.\n     * This means there are up to 32 unique collision categories available.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.category\n     * @type object\n     * @default 1\n     */\n\n    /**\n     * A bit mask that specifies the collision categories this body may collide with.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.mask\n     * @type object\n     * @default -1\n     */\n\n    /**\n     * A `Number` that specifies a thin boundary around the body where it is allowed to slightly sink into other bodies.\n     * \n     * This is required for proper collision response, including friction and restitution effects.\n     * \n     * The default should generally suffice in most cases. You may need to decrease this value for very small bodies that are nearing the default value in scale.\n     *\n     * @property slop\n     * @type number\n     * @default 0.05\n     */\n\n    /**\n     * A `Number` that specifies per-body time scaling.\n     *\n     * @property timeScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * _Read only_. Updated during engine update.\n     * \n     * A `Number` that records the last delta time value used to update this body.\n     * Used to calculate speed and velocity.\n     *\n     * @readOnly\n     * @property deltaTime\n     * @type number\n     * @default 1000 / 60\n     */\n\n    /**\n     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.\n     *\n     * @property render\n     * @type object\n     */\n\n    /**\n     * A flag that indicates if the body should be rendered.\n     *\n     * @property render.visible\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * Sets the opacity to use when rendering.\n     *\n     * @property render.opacity\n     * @type number\n     * @default 1\n    */\n\n    /**\n     * An `Object` that defines the sprite properties to use when rendering, if any.\n     *\n     * @property render.sprite\n     * @type object\n     */\n\n    /**\n     * An `String` that defines the path to the image to use as the sprite texture, if any.\n     *\n     * @property render.sprite.texture\n     * @type string\n     */\n     \n    /**\n     * A `Number` that defines the scaling in the x-axis for the sprite, if any.\n     *\n     * @property render.sprite.xScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that defines the scaling in the y-axis for the sprite, if any.\n     *\n     * @property render.sprite.yScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n      * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width).\n      *\n      * @property render.sprite.xOffset\n      * @type number\n      * @default 0\n      */\n\n    /**\n      * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height).\n      *\n      * @property render.sprite.yOffset\n      * @type number\n      * @default 0\n      */\n\n    /**\n     * A `Number` that defines the line width to use when rendering the body outline (if a sprite is not defined).\n     * A value of `0` means no outline will be rendered.\n     *\n     * @property render.lineWidth\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `String` that defines the fill style to use when rendering the body (if a sprite is not defined).\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.fillStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * A `String` that defines the stroke style to use when rendering the body outline (if a sprite is not defined).\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.strokeStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * _Read only_. Calculated automatically when vertices are set.\n     * \n     * An array of unique axis vectors (edge normals) used for collision detection.\n     * These are automatically calculated when vertices are set.\n     * They are constantly updated by `Body.update` during the simulation.\n     *\n     * @readOnly\n     * @property axes\n     * @type vector[]\n     */\n     \n    /**\n     * _Read only_. Calculated automatically when vertices are set.\n     * \n     * A `Number` that measures the area of the body's convex hull.\n     * \n     * @readOnly\n     * @property area\n     * @type string\n     * @default \n     */\n\n    /**\n     * A `Bounds` object that defines the AABB region for the body.\n     * It is automatically calculated when vertices are set and constantly updated by `Body.update` during simulation.\n     * \n     * @property bounds\n     * @type bounds\n     */\n\n    /**\n     * Temporarily may hold parameters to be passed to `Vertices.chamfer` where supported by external functions.\n     * \n     * See `Vertices.chamfer` for possible parameters this object may hold.\n     * \n     * Currently only functions inside `Matter.Bodies` provide a utility using this property as a vertices pre-processing option.\n     * \n     * Alternatively consider using `Vertices.chamfer` directly on vertices before passing them to a body creation function.\n     * \n     * @property chamfer\n     * @type object|null|undefined\n     */\n\n})();\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Events` module contains methods to fire and listen to events on other objects.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Events\n*/\n\nvar Events = {};\n\nmodule.exports = Events;\n\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Subscribes a callback function to the given object's `eventName`.\n     * @method on\n     * @param {} object\n     * @param {string} eventNames\n     * @param {function} callback\n     */\n    Events.on = function(object, eventNames, callback) {\n        var names = eventNames.split(' '),\n            name;\n\n        for (var i = 0; i < names.length; i++) {\n            name = names[i];\n            object.events = object.events || {};\n            object.events[name] = object.events[name] || [];\n            object.events[name].push(callback);\n        }\n\n        return callback;\n    };\n\n    /**\n     * Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events.\n     * @method off\n     * @param {} object\n     * @param {string} eventNames\n     * @param {function} callback\n     */\n    Events.off = function(object, eventNames, callback) {\n        if (!eventNames) {\n            object.events = {};\n            return;\n        }\n\n        // handle Events.off(object, callback)\n        if (typeof eventNames === 'function') {\n            callback = eventNames;\n            eventNames = Common.keys(object.events).join(' ');\n        }\n\n        var names = eventNames.split(' ');\n\n        for (var i = 0; i < names.length; i++) {\n            var callbacks = object.events[names[i]],\n                newCallbacks = [];\n\n            if (callback && callbacks) {\n                for (var j = 0; j < callbacks.length; j++) {\n                    if (callbacks[j] !== callback)\n                        newCallbacks.push(callbacks[j]);\n                }\n            }\n\n            object.events[names[i]] = newCallbacks;\n        }\n    };\n\n    /**\n     * Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any.\n     * @method trigger\n     * @param {} object\n     * @param {string} eventNames\n     * @param {} event\n     */\n    Events.trigger = function(object, eventNames, event) {\n        var names,\n            name,\n            callbacks,\n            eventClone;\n\n        var events = object.events;\n        \n        if (events && Common.keys(events).length > 0) {\n            if (!event)\n                event = {};\n\n            names = eventNames.split(' ');\n\n            for (var i = 0; i < names.length; i++) {\n                name = names[i];\n                callbacks = events[name];\n\n                if (callbacks) {\n                    eventClone = Common.clone(event, false);\n                    eventClone.name = name;\n                    eventClone.source = object;\n\n                    for (var j = 0; j < callbacks.length; j++) {\n                        callbacks[j].apply(object, [eventClone]);\n                    }\n                }\n            }\n        }\n    };\n\n})();\n\n\n/***/ }),\n/* 6 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* A composite is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite` objects.\n*\n* They are a container that can represent complex objects made of multiple parts, even if they are not physically connected.\n* A composite could contain anything from a single body all the way up to a whole world.\n* \n* When making any changes to composites, use the included functions rather than changing their properties directly.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Composite\n*/\n\nvar Composite = {};\n\nmodule.exports = Composite;\n\nvar Events = __webpack_require__(5);\nvar Common = __webpack_require__(0);\nvar Bounds = __webpack_require__(1);\nvar Body = __webpack_require__(4);\n\n(function() {\n\n    /**\n     * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properites section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} [options]\n     * @return {composite} A new composite\n     */\n    Composite.create = function(options) {\n        return Common.extend({ \n            id: Common.nextId(),\n            type: 'composite',\n            parent: null,\n            isModified: false,\n            bodies: [], \n            constraints: [], \n            composites: [],\n            label: 'Composite',\n            plugin: {},\n            cache: {\n                allBodies: null,\n                allConstraints: null,\n                allComposites: null\n            }\n        }, options);\n    };\n\n    /**\n     * Sets the composite's `isModified` flag. \n     * If `updateParents` is true, all parents will be set (default: false).\n     * If `updateChildren` is true, all children will be set (default: false).\n     * @private\n     * @method setModified\n     * @param {composite} composite\n     * @param {boolean} isModified\n     * @param {boolean} [updateParents=false]\n     * @param {boolean} [updateChildren=false]\n     */\n    Composite.setModified = function(composite, isModified, updateParents, updateChildren) {\n        composite.isModified = isModified;\n\n        if (isModified && composite.cache) {\n            composite.cache.allBodies = null;\n            composite.cache.allConstraints = null;\n            composite.cache.allComposites = null;\n        }\n\n        if (updateParents && composite.parent) {\n            Composite.setModified(composite.parent, isModified, updateParents, updateChildren);\n        }\n\n        if (updateChildren) {\n            for (var i = 0; i < composite.composites.length; i++) {\n                var childComposite = composite.composites[i];\n                Composite.setModified(childComposite, isModified, updateParents, updateChildren);\n            }\n        }\n    };\n\n    /**\n     * Generic single or multi-add function. Adds a single or an array of body(s), constraint(s) or composite(s) to the given composite.\n     * Triggers `beforeAdd` and `afterAdd` events on the `composite`.\n     * @method add\n     * @param {composite} composite\n     * @param {object|array} object A single or an array of body(s), constraint(s) or composite(s)\n     * @return {composite} The original composite with the objects added\n     */\n    Composite.add = function(composite, object) {\n        var objects = [].concat(object);\n\n        Events.trigger(composite, 'beforeAdd', { object: object });\n\n        for (var i = 0; i < objects.length; i++) {\n            var obj = objects[i];\n\n            switch (obj.type) {\n\n            case 'body':\n                // skip adding compound parts\n                if (obj.parent !== obj) {\n                    Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)');\n                    break;\n                }\n\n                Composite.addBody(composite, obj);\n                break;\n            case 'constraint':\n                Composite.addConstraint(composite, obj);\n                break;\n            case 'composite':\n                Composite.addComposite(composite, obj);\n                break;\n            case 'mouseConstraint':\n                Composite.addConstraint(composite, obj.constraint);\n                break;\n\n            }\n        }\n\n        Events.trigger(composite, 'afterAdd', { object: object });\n\n        return composite;\n    };\n\n    /**\n     * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite.\n     * Optionally searching its children recursively.\n     * Triggers `beforeRemove` and `afterRemove` events on the `composite`.\n     * @method remove\n     * @param {composite} composite\n     * @param {object|array} object\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the objects removed\n     */\n    Composite.remove = function(composite, object, deep) {\n        var objects = [].concat(object);\n\n        Events.trigger(composite, 'beforeRemove', { object: object });\n\n        for (var i = 0; i < objects.length; i++) {\n            var obj = objects[i];\n\n            switch (obj.type) {\n\n            case 'body':\n                Composite.removeBody(composite, obj, deep);\n                break;\n            case 'constraint':\n                Composite.removeConstraint(composite, obj, deep);\n                break;\n            case 'composite':\n                Composite.removeComposite(composite, obj, deep);\n                break;\n            case 'mouseConstraint':\n                Composite.removeConstraint(composite, obj.constraint);\n                break;\n\n            }\n        }\n\n        Events.trigger(composite, 'afterRemove', { object: object });\n\n        return composite;\n    };\n\n    /**\n     * Adds a composite to the given composite.\n     * @private\n     * @method addComposite\n     * @param {composite} compositeA\n     * @param {composite} compositeB\n     * @return {composite} The original compositeA with the objects from compositeB added\n     */\n    Composite.addComposite = function(compositeA, compositeB) {\n        compositeA.composites.push(compositeB);\n        compositeB.parent = compositeA;\n        Composite.setModified(compositeA, true, true, false);\n        return compositeA;\n    };\n\n    /**\n     * Removes a composite from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeComposite\n     * @param {composite} compositeA\n     * @param {composite} compositeB\n     * @param {boolean} [deep=false]\n     * @return {composite} The original compositeA with the composite removed\n     */\n    Composite.removeComposite = function(compositeA, compositeB, deep) {\n        var position = Common.indexOf(compositeA.composites, compositeB);\n\n        if (position !== -1) {\n            var bodies = Composite.allBodies(compositeB);\n\n            Composite.removeCompositeAt(compositeA, position);\n\n            for (var i = 0; i < bodies.length; i++) {\n                bodies[i].sleepCounter = 0;\n            }\n        }\n\n        if (deep) {\n            for (var i = 0; i < compositeA.composites.length; i++){\n                Composite.removeComposite(compositeA.composites[i], compositeB, true);\n            }\n        }\n\n        return compositeA;\n    };\n\n    /**\n     * Removes a composite from the given composite.\n     * @private\n     * @method removeCompositeAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the composite removed\n     */\n    Composite.removeCompositeAt = function(composite, position) {\n        composite.composites.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Adds a body to the given composite.\n     * @private\n     * @method addBody\n     * @param {composite} composite\n     * @param {body} body\n     * @return {composite} The original composite with the body added\n     */\n    Composite.addBody = function(composite, body) {\n        composite.bodies.push(body);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeBody\n     * @param {composite} composite\n     * @param {body} body\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the body removed\n     */\n    Composite.removeBody = function(composite, body, deep) {\n        var position = Common.indexOf(composite.bodies, body);\n\n        if (position !== -1) {\n            Composite.removeBodyAt(composite, position);\n            body.sleepCounter = 0;\n        }\n\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.removeBody(composite.composites[i], body, true);\n            }\n        }\n\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite.\n     * @private\n     * @method removeBodyAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the body removed\n     */\n    Composite.removeBodyAt = function(composite, position) {\n        composite.bodies.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Adds a constraint to the given composite.\n     * @private\n     * @method addConstraint\n     * @param {composite} composite\n     * @param {constraint} constraint\n     * @return {composite} The original composite with the constraint added\n     */\n    Composite.addConstraint = function(composite, constraint) {\n        composite.constraints.push(constraint);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes a constraint from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeConstraint\n     * @param {composite} composite\n     * @param {constraint} constraint\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the constraint removed\n     */\n    Composite.removeConstraint = function(composite, constraint, deep) {\n        var position = Common.indexOf(composite.constraints, constraint);\n        \n        if (position !== -1) {\n            Composite.removeConstraintAt(composite, position);\n        }\n\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.removeConstraint(composite.composites[i], constraint, true);\n            }\n        }\n\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite.\n     * @private\n     * @method removeConstraintAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the constraint removed\n     */\n    Composite.removeConstraintAt = function(composite, position) {\n        composite.constraints.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes all bodies, constraints and composites from the given composite.\n     * Optionally clearing its children recursively.\n     * @method clear\n     * @param {composite} composite\n     * @param {boolean} keepStatic\n     * @param {boolean} [deep=false]\n     */\n    Composite.clear = function(composite, keepStatic, deep) {\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.clear(composite.composites[i], keepStatic, true);\n            }\n        }\n        \n        if (keepStatic) {\n            composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; });\n        } else {\n            composite.bodies.length = 0;\n        }\n\n        composite.constraints.length = 0;\n        composite.composites.length = 0;\n\n        Composite.setModified(composite, true, true, false);\n\n        return composite;\n    };\n\n    /**\n     * Returns all bodies in the given composite, including all bodies in its children, recursively.\n     * @method allBodies\n     * @param {composite} composite\n     * @return {body[]} All the bodies\n     */\n    Composite.allBodies = function(composite) {\n        if (composite.cache && composite.cache.allBodies) {\n            return composite.cache.allBodies;\n        }\n\n        var bodies = [].concat(composite.bodies);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            bodies = bodies.concat(Composite.allBodies(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allBodies = bodies;\n        }\n\n        return bodies;\n    };\n\n    /**\n     * Returns all constraints in the given composite, including all constraints in its children, recursively.\n     * @method allConstraints\n     * @param {composite} composite\n     * @return {constraint[]} All the constraints\n     */\n    Composite.allConstraints = function(composite) {\n        if (composite.cache && composite.cache.allConstraints) {\n            return composite.cache.allConstraints;\n        }\n\n        var constraints = [].concat(composite.constraints);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            constraints = constraints.concat(Composite.allConstraints(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allConstraints = constraints;\n        }\n\n        return constraints;\n    };\n\n    /**\n     * Returns all composites in the given composite, including all composites in its children, recursively.\n     * @method allComposites\n     * @param {composite} composite\n     * @return {composite[]} All the composites\n     */\n    Composite.allComposites = function(composite) {\n        if (composite.cache && composite.cache.allComposites) {\n            return composite.cache.allComposites;\n        }\n\n        var composites = [].concat(composite.composites);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            composites = composites.concat(Composite.allComposites(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allComposites = composites;\n        }\n\n        return composites;\n    };\n\n    /**\n     * Searches the composite recursively for an object matching the type and id supplied, null if not found.\n     * @method get\n     * @param {composite} composite\n     * @param {number} id\n     * @param {string} type\n     * @return {object} The requested object, if found\n     */\n    Composite.get = function(composite, id, type) {\n        var objects,\n            object;\n\n        switch (type) {\n        case 'body':\n            objects = Composite.allBodies(composite);\n            break;\n        case 'constraint':\n            objects = Composite.allConstraints(composite);\n            break;\n        case 'composite':\n            objects = Composite.allComposites(composite).concat(composite);\n            break;\n        }\n\n        if (!objects)\n            return null;\n\n        object = objects.filter(function(object) { \n            return object.id.toString() === id.toString(); \n        });\n\n        return object.length === 0 ? null : object[0];\n    };\n\n    /**\n     * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add).\n     * @method move\n     * @param {compositeA} compositeA\n     * @param {object[]} objects\n     * @param {compositeB} compositeB\n     * @return {composite} Returns compositeA\n     */\n    Composite.move = function(compositeA, objects, compositeB) {\n        Composite.remove(compositeA, objects);\n        Composite.add(compositeB, objects);\n        return compositeA;\n    };\n\n    /**\n     * Assigns new ids for all objects in the composite, recursively.\n     * @method rebase\n     * @param {composite} composite\n     * @return {composite} Returns composite\n     */\n    Composite.rebase = function(composite) {\n        var objects = Composite.allBodies(composite)\n            .concat(Composite.allConstraints(composite))\n            .concat(Composite.allComposites(composite));\n\n        for (var i = 0; i < objects.length; i++) {\n            objects[i].id = Common.nextId();\n        }\n\n        return composite;\n    };\n\n    /**\n     * Translates all children in the composite by a given vector relative to their current positions, \n     * without imparting any velocity.\n     * @method translate\n     * @param {composite} composite\n     * @param {vector} translation\n     * @param {bool} [recursive=true]\n     */\n    Composite.translate = function(composite, translation, recursive) {\n        var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            Body.translate(bodies[i], translation);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity.\n     * @method rotate\n     * @param {composite} composite\n     * @param {number} rotation\n     * @param {vector} point\n     * @param {bool} [recursive=true]\n     */\n    Composite.rotate = function(composite, rotation, point, recursive) {\n        var cos = Math.cos(rotation),\n            sin = Math.sin(rotation),\n            bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + (dx * cos - dy * sin),\n                y: point.y + (dx * sin + dy * cos)\n            });\n\n            Body.rotate(body, rotation);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point.\n     * @method scale\n     * @param {composite} composite\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} point\n     * @param {bool} [recursive=true]\n     */\n    Composite.scale = function(composite, scaleX, scaleY, point, recursive) {\n        var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + dx * scaleX,\n                y: point.y + dy * scaleY\n            });\n\n            Body.scale(body, scaleX, scaleY);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Returns the union of the bounds of all of the composite's bodies.\n     * @method bounds\n     * @param {composite} composite The composite.\n     * @returns {bounds} The composite bounds.\n     */\n    Composite.bounds = function(composite) {\n        var bodies = Composite.allBodies(composite),\n            vertices = [];\n\n        for (var i = 0; i < bodies.length; i += 1) {\n            var body = bodies[i];\n            vertices.push(body.bounds.min, body.bounds.max);\n        }\n\n        return Bounds.create(vertices);\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when a call to `Composite.add` is made, before objects have been added.\n    *\n    * @event beforeAdd\n    * @param {} event An event object\n    * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.add` is made, after objects have been added.\n    *\n    * @event afterAdd\n    * @param {} event An event object\n    * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.remove` is made, before objects have been removed.\n    *\n    * @event beforeRemove\n    * @param {} event An event object\n    * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.remove` is made, after objects have been removed.\n    *\n    * @event afterRemove\n    * @param {} event An event object\n    * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"composite\"\n     * @readOnly\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage composites.\n     *\n     * @property label\n     * @type string\n     * @default \"Composite\"\n     */\n\n    /**\n     * A flag that specifies whether the composite has been modified during the current step.\n     * This is automatically managed when bodies, constraints or composites are added or removed.\n     *\n     * @property isModified\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods.\n     *\n     * @property parent\n     * @type composite\n     * @default null\n     */\n\n    /**\n     * An array of `Body` that are _direct_ children of this composite.\n     * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method.\n     *\n     * @property bodies\n     * @type body[]\n     * @default []\n     */\n\n    /**\n     * An array of `Constraint` that are _direct_ children of this composite.\n     * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method.\n     *\n     * @property constraints\n     * @type constraint[]\n     * @default []\n     */\n\n    /**\n     * An array of `Composite` that are _direct_ children of this composite.\n     * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method.\n     *\n     * @property composites\n     * @type composite[]\n     * @default []\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * An object used for storing cached results for performance reasons.\n     * This is used internally only and is automatically managed.\n     *\n     * @private\n     * @property cache\n     * @type {}\n     */\n\n})();\n\n\n/***/ }),\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies.\n*\n* @class Sleeping\n*/\n\nvar Sleeping = {};\n\nmodule.exports = Sleeping;\n\nvar Body = __webpack_require__(4);\nvar Events = __webpack_require__(5);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    Sleeping._motionWakeThreshold = 0.18;\n    Sleeping._motionSleepThreshold = 0.08;\n    Sleeping._minBias = 0.9;\n\n    /**\n     * Puts bodies to sleep or wakes them up depending on their motion.\n     * @method update\n     * @param {body[]} bodies\n     * @param {number} delta\n     */\n    Sleeping.update = function(bodies, delta) {\n        var timeScale = delta / Common._baseDelta,\n            motionSleepThreshold = Sleeping._motionSleepThreshold;\n        \n        // update bodies sleeping status\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                speed = Body.getSpeed(body),\n                angularSpeed = Body.getAngularSpeed(body),\n                motion = speed * speed + angularSpeed * angularSpeed;\n\n            // wake up bodies if they have a force applied\n            if (body.force.x !== 0 || body.force.y !== 0) {\n                Sleeping.set(body, false);\n                continue;\n            }\n\n            var minMotion = Math.min(body.motion, motion),\n                maxMotion = Math.max(body.motion, motion);\n        \n            // biased average motion estimation between frames\n            body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion;\n\n            if (body.sleepThreshold > 0 && body.motion < motionSleepThreshold) {\n                body.sleepCounter += 1;\n                \n                if (body.sleepCounter >= body.sleepThreshold / timeScale) {\n                    Sleeping.set(body, true);\n                }\n            } else if (body.sleepCounter > 0) {\n                body.sleepCounter -= 1;\n            }\n        }\n    };\n\n    /**\n     * Given a set of colliding pairs, wakes the sleeping bodies involved.\n     * @method afterCollisions\n     * @param {pair[]} pairs\n     */\n    Sleeping.afterCollisions = function(pairs) {\n        var motionSleepThreshold = Sleeping._motionSleepThreshold;\n\n        // wake up bodies involved in collisions\n        for (var i = 0; i < pairs.length; i++) {\n            var pair = pairs[i];\n            \n            // don't wake inactive pairs\n            if (!pair.isActive)\n                continue;\n\n            var collision = pair.collision,\n                bodyA = collision.bodyA.parent, \n                bodyB = collision.bodyB.parent;\n        \n            // don't wake if at least one body is static\n            if ((bodyA.isSleeping && bodyB.isSleeping) || bodyA.isStatic || bodyB.isStatic)\n                continue;\n        \n            if (bodyA.isSleeping || bodyB.isSleeping) {\n                var sleepingBody = (bodyA.isSleeping && !bodyA.isStatic) ? bodyA : bodyB,\n                    movingBody = sleepingBody === bodyA ? bodyB : bodyA;\n\n                if (!sleepingBody.isStatic && movingBody.motion > motionSleepThreshold) {\n                    Sleeping.set(sleepingBody, false);\n                }\n            }\n        }\n    };\n  \n    /**\n     * Set a body as sleeping or awake.\n     * @method set\n     * @param {body} body\n     * @param {boolean} isSleeping\n     */\n    Sleeping.set = function(body, isSleeping) {\n        var wasSleeping = body.isSleeping;\n\n        if (isSleeping) {\n            body.isSleeping = true;\n            body.sleepCounter = body.sleepThreshold;\n\n            body.positionImpulse.x = 0;\n            body.positionImpulse.y = 0;\n\n            body.positionPrev.x = body.position.x;\n            body.positionPrev.y = body.position.y;\n\n            body.anglePrev = body.angle;\n            body.speed = 0;\n            body.angularSpeed = 0;\n            body.motion = 0;\n\n            if (!wasSleeping) {\n                Events.trigger(body, 'sleepStart');\n            }\n        } else {\n            body.isSleeping = false;\n            body.sleepCounter = 0;\n\n            if (wasSleeping) {\n                Events.trigger(body, 'sleepEnd');\n            }\n        }\n    };\n\n})();\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Collision` module contains methods for detecting collisions between a given pair of bodies.\n*\n* For efficient detection between a list of bodies, see `Matter.Detector` and `Matter.Query`.\n*\n* See `Matter.Engine` for collision events.\n*\n* @class Collision\n*/\n\nvar Collision = {};\n\nmodule.exports = Collision;\n\nvar Vertices = __webpack_require__(3);\nvar Pair = __webpack_require__(9);\n\n(function() {\n    var _supports = [];\n\n    var _overlapAB = {\n        overlap: 0,\n        axis: null\n    };\n\n    var _overlapBA = {\n        overlap: 0,\n        axis: null\n    };\n\n    /**\n     * Creates a new collision record.\n     * @method create\n     * @param {body} bodyA The first body part represented by the collision record\n     * @param {body} bodyB The second body part represented by the collision record\n     * @return {collision} A new collision record\n     */\n    Collision.create = function(bodyA, bodyB) {\n        return { \n            pair: null,\n            collided: false,\n            bodyA: bodyA,\n            bodyB: bodyB,\n            parentA: bodyA.parent,\n            parentB: bodyB.parent,\n            depth: 0,\n            normal: { x: 0, y: 0 },\n            tangent: { x: 0, y: 0 },\n            penetration: { x: 0, y: 0 },\n            supports: [null, null],\n            supportCount: 0\n        };\n    };\n\n    /**\n     * Detect collision between two bodies.\n     * @method collides\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @param {pairs} [pairs] Optionally reuse collision records from existing pairs.\n     * @return {collision|null} A collision record if detected, otherwise null\n     */\n    Collision.collides = function(bodyA, bodyB, pairs) {\n        Collision._overlapAxes(_overlapAB, bodyA.vertices, bodyB.vertices, bodyA.axes);\n\n        if (_overlapAB.overlap <= 0) {\n            return null;\n        }\n\n        Collision._overlapAxes(_overlapBA, bodyB.vertices, bodyA.vertices, bodyB.axes);\n\n        if (_overlapBA.overlap <= 0) {\n            return null;\n        }\n\n        // reuse collision records for gc efficiency\n        var pair = pairs && pairs.table[Pair.id(bodyA, bodyB)],\n            collision;\n\n        if (!pair) {\n            collision = Collision.create(bodyA, bodyB);\n            collision.collided = true;\n            collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB;\n            collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA;\n            collision.parentA = collision.bodyA.parent;\n            collision.parentB = collision.bodyB.parent;\n        } else {\n            collision = pair.collision;\n        }\n\n        bodyA = collision.bodyA;\n        bodyB = collision.bodyB;\n\n        var minOverlap;\n\n        if (_overlapAB.overlap < _overlapBA.overlap) {\n            minOverlap = _overlapAB;\n        } else {\n            minOverlap = _overlapBA;\n        }\n\n        var normal = collision.normal,\n            tangent = collision.tangent,\n            penetration = collision.penetration,\n            supports = collision.supports,\n            depth = minOverlap.overlap,\n            minAxis = minOverlap.axis,\n            normalX = minAxis.x,\n            normalY = minAxis.y,\n            deltaX = bodyB.position.x - bodyA.position.x,\n            deltaY = bodyB.position.y - bodyA.position.y;\n\n        // ensure normal is facing away from bodyA\n        if (normalX * deltaX + normalY * deltaY >= 0) {\n            normalX = -normalX;\n            normalY = -normalY;\n        }\n\n        normal.x = normalX;\n        normal.y = normalY;\n        \n        tangent.x = -normalY;\n        tangent.y = normalX;\n\n        penetration.x = normalX * depth;\n        penetration.y = normalY * depth;\n\n        collision.depth = depth;\n\n        // find support points, there is always either exactly one or two\n        var supportsB = Collision._findSupports(bodyA, bodyB, normal, 1),\n            supportCount = 0;\n\n        // find the supports from bodyB that are inside bodyA\n        if (Vertices.contains(bodyA.vertices, supportsB[0])) {\n            supports[supportCount++] = supportsB[0];\n        }\n\n        if (Vertices.contains(bodyA.vertices, supportsB[1])) {\n            supports[supportCount++] = supportsB[1];\n        }\n\n        // find the supports from bodyA that are inside bodyB\n        if (supportCount < 2) {\n            var supportsA = Collision._findSupports(bodyB, bodyA, normal, -1);\n\n            if (Vertices.contains(bodyB.vertices, supportsA[0])) {\n                supports[supportCount++] = supportsA[0];\n            }\n\n            if (supportCount < 2 && Vertices.contains(bodyB.vertices, supportsA[1])) {\n                supports[supportCount++] = supportsA[1];\n            }\n        }\n\n        // account for the edge case of overlapping but no vertex containment\n        if (supportCount === 0) {\n            supports[supportCount++] = supportsB[0];\n        }\n\n        // update support count\n        collision.supportCount = supportCount;\n\n        return collision;\n    };\n\n    /**\n     * Find the overlap between two sets of vertices.\n     * @method _overlapAxes\n     * @private\n     * @param {object} result\n     * @param {vertices} verticesA\n     * @param {vertices} verticesB\n     * @param {axes} axes\n     */\n    Collision._overlapAxes = function(result, verticesA, verticesB, axes) {\n        var verticesALength = verticesA.length,\n            verticesBLength = verticesB.length,\n            verticesAX = verticesA[0].x,\n            verticesAY = verticesA[0].y,\n            verticesBX = verticesB[0].x,\n            verticesBY = verticesB[0].y,\n            axesLength = axes.length,\n            overlapMin = Number.MAX_VALUE,\n            overlapAxisNumber = 0,\n            overlap,\n            overlapAB,\n            overlapBA,\n            dot,\n            i,\n            j;\n\n        for (i = 0; i < axesLength; i++) {\n            var axis = axes[i],\n                axisX = axis.x,\n                axisY = axis.y,\n                minA = verticesAX * axisX + verticesAY * axisY,\n                minB = verticesBX * axisX + verticesBY * axisY,\n                maxA = minA,\n                maxB = minB;\n            \n            for (j = 1; j < verticesALength; j += 1) {\n                dot = verticesA[j].x * axisX + verticesA[j].y * axisY;\n\n                if (dot > maxA) { \n                    maxA = dot;\n                } else if (dot < minA) { \n                    minA = dot;\n                }\n            }\n\n            for (j = 1; j < verticesBLength; j += 1) {\n                dot = verticesB[j].x * axisX + verticesB[j].y * axisY;\n\n                if (dot > maxB) { \n                    maxB = dot;\n                } else if (dot < minB) { \n                    minB = dot;\n                }\n            }\n\n            overlapAB = maxA - minB;\n            overlapBA = maxB - minA;\n            overlap = overlapAB < overlapBA ? overlapAB : overlapBA;\n\n            if (overlap < overlapMin) {\n                overlapMin = overlap;\n                overlapAxisNumber = i;\n\n                if (overlap <= 0) {\n                    // can not be intersecting\n                    break;\n                }\n            } \n        }\n\n        result.axis = axes[overlapAxisNumber];\n        result.overlap = overlapMin;\n    };\n\n    /**\n     * Finds supporting vertices given two bodies along a given direction using hill-climbing.\n     * @method _findSupports\n     * @private\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @param {vector} normal\n     * @param {number} direction\n     * @return [vector]\n     */\n    Collision._findSupports = function(bodyA, bodyB, normal, direction) {\n        var vertices = bodyB.vertices,\n            verticesLength = vertices.length,\n            bodyAPositionX = bodyA.position.x,\n            bodyAPositionY = bodyA.position.y,\n            normalX = normal.x * direction,\n            normalY = normal.y * direction,\n            vertexA = vertices[0],\n            vertexB = vertexA,\n            nearestDistance = normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y),\n            vertexC,\n            distance,\n            j;\n\n        // find deepest vertex relative to the axis\n        for (j = 1; j < verticesLength; j += 1) {\n            vertexB = vertices[j];\n            distance = normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y);\n\n            // convex hill-climbing\n            if (distance < nearestDistance) {\n                nearestDistance = distance;\n                vertexA = vertexB;\n            }\n        }\n\n        // measure next vertex\n        vertexC = vertices[(verticesLength + vertexA.index - 1) % verticesLength];\n        nearestDistance = normalX * (bodyAPositionX - vertexC.x) + normalY * (bodyAPositionY - vertexC.y);\n\n        // compare with previous vertex\n        vertexB = vertices[(vertexA.index + 1) % verticesLength];\n        if (normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y) < nearestDistance) {\n            _supports[0] = vertexA;\n            _supports[1] = vertexB;\n\n            return _supports;\n        }\n\n        _supports[0] = vertexA;\n        _supports[1] = vertexC;\n\n        return _supports;\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A reference to the pair using this collision record, if there is one.\n     *\n     * @property pair\n     * @type {pair|null}\n     * @default null\n     */\n\n    /**\n     * A flag that indicates if the bodies were colliding when the collision was last updated.\n     * \n     * @property collided\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * The first body part represented by the collision (see also `collision.parentA`).\n     * \n     * @property bodyA\n     * @type body\n     */\n\n    /**\n     * The second body part represented by the collision (see also `collision.parentB`).\n     * \n     * @property bodyB\n     * @type body\n     */\n\n    /**\n     * The first body represented by the collision (i.e. `collision.bodyA.parent`).\n     * \n     * @property parentA\n     * @type body\n     */\n\n    /**\n     * The second body represented by the collision (i.e. `collision.bodyB.parent`).\n     * \n     * @property parentB\n     * @type body\n     */\n\n    /**\n     * A `Number` that represents the minimum separating distance between the bodies along the collision normal.\n     *\n     * @readOnly\n     * @property depth\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A normalised `Vector` that represents the direction between the bodies that provides the minimum separating distance.\n     *\n     * @property normal\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A normalised `Vector` that is the tangent direction to the collision normal.\n     *\n     * @property tangent\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that represents the direction and depth of the collision.\n     *\n     * @property penetration\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * An array of body vertices that represent the support points in the collision.\n     * \n     * _Note:_ Only the first `collision.supportCount` items of `collision.supports` are active.\n     * Therefore use `collision.supportCount` instead of `collision.supports.length` when iterating the active supports.\n     * \n     * These are the deepest vertices (along the collision normal) of each body that are contained by the other body's vertices.\n     *\n     * @property supports\n     * @type vector[]\n     * @default []\n     */\n\n    /**\n     * The number of active supports for this collision found in `collision.supports`.\n     * \n     * _Note:_ Only the first `collision.supportCount` items of `collision.supports` are active.\n     * Therefore use `collision.supportCount` instead of `collision.supports.length` when iterating the active supports.\n     *\n     * @property supportCount\n     * @type number\n     * @default 0\n     */\n\n})();\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Pair` module contains methods for creating and manipulating collision pairs.\n*\n* @class Pair\n*/\n\nvar Pair = {};\n\nmodule.exports = Pair;\n\nvar Contact = __webpack_require__(16);\n\n(function() {\n    \n    /**\n     * Creates a pair.\n     * @method create\n     * @param {collision} collision\n     * @param {number} timestamp\n     * @return {pair} A new pair\n     */\n    Pair.create = function(collision, timestamp) {\n        var bodyA = collision.bodyA,\n            bodyB = collision.bodyB;\n\n        var pair = {\n            id: Pair.id(bodyA, bodyB),\n            bodyA: bodyA,\n            bodyB: bodyB,\n            collision: collision,\n            contacts: [Contact.create(), Contact.create()],\n            contactCount: 0,\n            separation: 0,\n            isActive: true,\n            isSensor: bodyA.isSensor || bodyB.isSensor,\n            timeCreated: timestamp,\n            timeUpdated: timestamp,\n            inverseMass: 0,\n            friction: 0,\n            frictionStatic: 0,\n            restitution: 0,\n            slop: 0\n        };\n\n        Pair.update(pair, collision, timestamp);\n\n        return pair;\n    };\n\n    /**\n     * Updates a pair given a collision.\n     * @method update\n     * @param {pair} pair\n     * @param {collision} collision\n     * @param {number} timestamp\n     */\n    Pair.update = function(pair, collision, timestamp) {\n        var supports = collision.supports,\n            supportCount = collision.supportCount,\n            contacts = pair.contacts,\n            parentA = collision.parentA,\n            parentB = collision.parentB;\n        \n        pair.isActive = true;\n        pair.timeUpdated = timestamp;\n        pair.collision = collision;\n        pair.separation = collision.depth;\n        pair.inverseMass = parentA.inverseMass + parentB.inverseMass;\n        pair.friction = parentA.friction < parentB.friction ? parentA.friction : parentB.friction;\n        pair.frictionStatic = parentA.frictionStatic > parentB.frictionStatic ? parentA.frictionStatic : parentB.frictionStatic;\n        pair.restitution = parentA.restitution > parentB.restitution ? parentA.restitution : parentB.restitution;\n        pair.slop = parentA.slop > parentB.slop ? parentA.slop : parentB.slop;\n\n        pair.contactCount = supportCount;\n        collision.pair = pair;\n\n        var supportA = supports[0],\n            contactA = contacts[0],\n            supportB = supports[1],\n            contactB = contacts[1];\n\n        // match contacts to supports\n        if (contactB.vertex === supportA || contactA.vertex === supportB) {\n            contacts[1] = contactA;\n            contacts[0] = contactA = contactB;\n            contactB = contacts[1];\n        }\n\n        // update contacts\n        contactA.vertex = supportA;\n        contactB.vertex = supportB;\n    };\n    \n    /**\n     * Set a pair as active or inactive.\n     * @method setActive\n     * @param {pair} pair\n     * @param {bool} isActive\n     * @param {number} timestamp\n     */\n    Pair.setActive = function(pair, isActive, timestamp) {\n        if (isActive) {\n            pair.isActive = true;\n            pair.timeUpdated = timestamp;\n        } else {\n            pair.isActive = false;\n            pair.contactCount = 0;\n        }\n    };\n\n    /**\n     * Get the id for the given pair.\n     * @method id\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {string} Unique pairId\n     */\n    Pair.id = function(bodyA, bodyB) {\n        return bodyA.id < bodyB.id ? bodyA.id.toString(36) + ':' + bodyB.id.toString(36) \n            : bodyB.id.toString(36) + ':' + bodyA.id.toString(36);\n    };\n\n})();\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Constraint` module contains methods for creating and manipulating constraints.\n* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).\n* The stiffness of constraints can be modified to create springs or elastic.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Constraint\n*/\n\nvar Constraint = {};\n\nmodule.exports = Constraint;\n\nvar Vertices = __webpack_require__(3);\nvar Vector = __webpack_require__(2);\nvar Sleeping = __webpack_require__(7);\nvar Bounds = __webpack_require__(1);\nvar Axes = __webpack_require__(11);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    Constraint._warming = 0.4;\n    Constraint._torqueDampen = 1;\n    Constraint._minLength = 0.000001;\n\n    /**\n     * Creates a new constraint.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * To simulate a revolute constraint (or pin joint) set `length: 0` and a high `stiffness` value (e.g. `0.7` or above).\n     * If the constraint is unstable, try lowering the `stiffness` value and / or increasing `engine.constraintIterations`.\n     * For compound bodies, constraints must be applied to the parent body (not one of its parts).\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     * @return {constraint} constraint\n     */\n    Constraint.create = function(options) {\n        var constraint = options;\n\n        // if bodies defined but no points, use body centre\n        if (constraint.bodyA && !constraint.pointA)\n            constraint.pointA = { x: 0, y: 0 };\n        if (constraint.bodyB && !constraint.pointB)\n            constraint.pointB = { x: 0, y: 0 };\n\n        // calculate static length using initial world space points\n        var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA,\n            initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB,\n            length = Vector.magnitude(Vector.sub(initialPointA, initialPointB));\n    \n        constraint.length = typeof constraint.length !== 'undefined' ? constraint.length : length;\n\n        // option defaults\n        constraint.id = constraint.id || Common.nextId();\n        constraint.label = constraint.label || 'Constraint';\n        constraint.type = 'constraint';\n        constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : 0.7);\n        constraint.damping = constraint.damping || 0;\n        constraint.angularStiffness = constraint.angularStiffness || 0;\n        constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA;\n        constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB;\n        constraint.plugin = {};\n\n        // render\n        var render = {\n            visible: true,\n            lineWidth: 2,\n            strokeStyle: '#ffffff',\n            type: 'line',\n            anchors: true\n        };\n\n        if (constraint.length === 0 && constraint.stiffness > 0.1) {\n            render.type = 'pin';\n            render.anchors = false;\n        } else if (constraint.stiffness < 0.9) {\n            render.type = 'spring';\n        }\n\n        constraint.render = Common.extend(render, constraint.render);\n\n        return constraint;\n    };\n\n    /**\n     * Prepares for solving by constraint warming.\n     * @private\n     * @method preSolveAll\n     * @param {body[]} bodies\n     */\n    Constraint.preSolveAll = function(bodies) {\n        for (var i = 0; i < bodies.length; i += 1) {\n            var body = bodies[i],\n                impulse = body.constraintImpulse;\n\n            if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {\n                continue;\n            }\n\n            body.position.x += impulse.x;\n            body.position.y += impulse.y;\n            body.angle += impulse.angle;\n        }\n    };\n\n    /**\n     * Solves all constraints in a list of collisions.\n     * @private\n     * @method solveAll\n     * @param {constraint[]} constraints\n     * @param {number} delta\n     */\n    Constraint.solveAll = function(constraints, delta) {\n        var timeScale = Common.clamp(delta / Common._baseDelta, 0, 1);\n\n        // Solve fixed constraints first.\n        for (var i = 0; i < constraints.length; i += 1) {\n            var constraint = constraints[i],\n                fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic),\n                fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);\n\n            if (fixedA || fixedB) {\n                Constraint.solve(constraints[i], timeScale);\n            }\n        }\n\n        // Solve free constraints last.\n        for (i = 0; i < constraints.length; i += 1) {\n            constraint = constraints[i];\n            fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic);\n            fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);\n\n            if (!fixedA && !fixedB) {\n                Constraint.solve(constraints[i], timeScale);\n            }\n        }\n    };\n\n    /**\n     * Solves a distance constraint with Gauss-Siedel method.\n     * @private\n     * @method solve\n     * @param {constraint} constraint\n     * @param {number} timeScale\n     */\n    Constraint.solve = function(constraint, timeScale) {\n        var bodyA = constraint.bodyA,\n            bodyB = constraint.bodyB,\n            pointA = constraint.pointA,\n            pointB = constraint.pointB;\n\n        if (!bodyA && !bodyB)\n            return;\n\n        // update reference angle\n        if (bodyA && !bodyA.isStatic) {\n            Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA);\n            constraint.angleA = bodyA.angle;\n        }\n        \n        // update reference angle\n        if (bodyB && !bodyB.isStatic) {\n            Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB);\n            constraint.angleB = bodyB.angle;\n        }\n\n        var pointAWorld = pointA,\n            pointBWorld = pointB;\n\n        if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA);\n        if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB);\n\n        if (!pointAWorld || !pointBWorld)\n            return;\n\n        var delta = Vector.sub(pointAWorld, pointBWorld),\n            currentLength = Vector.magnitude(delta);\n\n        // prevent singularity\n        if (currentLength < Constraint._minLength) {\n            currentLength = Constraint._minLength;\n        }\n\n        // solve distance constraint with Gauss-Siedel method\n        var difference = (currentLength - constraint.length) / currentLength,\n            isRigid = constraint.stiffness >= 1 || constraint.length === 0,\n            stiffness = isRigid ? constraint.stiffness * timeScale \n                : constraint.stiffness * timeScale * timeScale,\n            damping = constraint.damping * timeScale,\n            force = Vector.mult(delta, difference * stiffness),\n            massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0),\n            inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0),\n            resistanceTotal = massTotal + inertiaTotal,\n            torque,\n            share,\n            normal,\n            normalVelocity,\n            relativeVelocity;\n    \n        if (damping > 0) {\n            var zero = Vector.create();\n            normal = Vector.div(delta, currentLength);\n\n            relativeVelocity = Vector.sub(\n                bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero,\n                bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero\n            );\n\n            normalVelocity = Vector.dot(normal, relativeVelocity);\n        }\n\n        if (bodyA && !bodyA.isStatic) {\n            share = bodyA.inverseMass / massTotal;\n\n            // keep track of applied impulses for post solving\n            bodyA.constraintImpulse.x -= force.x * share;\n            bodyA.constraintImpulse.y -= force.y * share;\n\n            // apply forces\n            bodyA.position.x -= force.x * share;\n            bodyA.position.y -= force.y * share;\n\n            // apply damping\n            if (damping > 0) {\n                bodyA.positionPrev.x -= damping * normal.x * normalVelocity * share;\n                bodyA.positionPrev.y -= damping * normal.y * normalVelocity * share;\n            }\n\n            // apply torque\n            torque = (Vector.cross(pointA, force) / resistanceTotal) * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness);\n            bodyA.constraintImpulse.angle -= torque;\n            bodyA.angle -= torque;\n        }\n\n        if (bodyB && !bodyB.isStatic) {\n            share = bodyB.inverseMass / massTotal;\n\n            // keep track of applied impulses for post solving\n            bodyB.constraintImpulse.x += force.x * share;\n            bodyB.constraintImpulse.y += force.y * share;\n            \n            // apply forces\n            bodyB.position.x += force.x * share;\n            bodyB.position.y += force.y * share;\n\n            // apply damping\n            if (damping > 0) {\n                bodyB.positionPrev.x += damping * normal.x * normalVelocity * share;\n                bodyB.positionPrev.y += damping * normal.y * normalVelocity * share;\n            }\n\n            // apply torque\n            torque = (Vector.cross(pointB, force) / resistanceTotal) * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness);\n            bodyB.constraintImpulse.angle += torque;\n            bodyB.angle += torque;\n        }\n\n    };\n\n    /**\n     * Performs body updates required after solving constraints.\n     * @private\n     * @method postSolveAll\n     * @param {body[]} bodies\n     */\n    Constraint.postSolveAll = function(bodies) {\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                impulse = body.constraintImpulse;\n\n            if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {\n                continue;\n            }\n\n            Sleeping.set(body, false);\n\n            // update geometry and reset\n            for (var j = 0; j < body.parts.length; j++) {\n                var part = body.parts[j];\n                \n                Vertices.translate(part.vertices, impulse);\n\n                if (j > 0) {\n                    part.position.x += impulse.x;\n                    part.position.y += impulse.y;\n                }\n\n                if (impulse.angle !== 0) {\n                    Vertices.rotate(part.vertices, impulse.angle, body.position);\n                    Axes.rotate(part.axes, impulse.angle);\n                    if (j > 0) {\n                        Vector.rotateAbout(part.position, impulse.angle, body.position, part.position);\n                    }\n                }\n\n                Bounds.update(part.bounds, part.vertices, body.velocity);\n            }\n\n            // dampen the cached impulse for warming next step\n            impulse.angle *= Constraint._warming;\n            impulse.x *= Constraint._warming;\n            impulse.y *= Constraint._warming;\n        }\n    };\n\n    /**\n     * Returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`.\n     * @method pointAWorld\n     * @param {constraint} constraint\n     * @returns {vector} the world-space position\n     */\n    Constraint.pointAWorld = function(constraint) {\n        return {\n            x: (constraint.bodyA ? constraint.bodyA.position.x : 0) \n                + (constraint.pointA ? constraint.pointA.x : 0),\n            y: (constraint.bodyA ? constraint.bodyA.position.y : 0) \n                + (constraint.pointA ? constraint.pointA.y : 0)\n        };\n    };\n\n    /**\n     * Returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`.\n     * @method pointBWorld\n     * @param {constraint} constraint\n     * @returns {vector} the world-space position\n     */\n    Constraint.pointBWorld = function(constraint) {\n        return {\n            x: (constraint.bodyB ? constraint.bodyB.position.x : 0) \n                + (constraint.pointB ? constraint.pointB.x : 0),\n            y: (constraint.bodyB ? constraint.bodyB.position.y : 0) \n                + (constraint.pointB ? constraint.pointB.y : 0)\n        };\n    };\n\n    /**\n     * Returns the current length of the constraint. \n     * This is the distance between both of the constraint's end points.\n     * See `constraint.length` for the target rest length.\n     * @method currentLength\n     * @param {constraint} constraint\n     * @returns {number} the current length\n     */\n    Constraint.currentLength = function(constraint) {\n        var pointAX = (constraint.bodyA ? constraint.bodyA.position.x : 0) \n            + (constraint.pointA ? constraint.pointA.x : 0);\n\n        var pointAY = (constraint.bodyA ? constraint.bodyA.position.y : 0) \n            + (constraint.pointA ? constraint.pointA.y : 0);\n\n        var pointBX = (constraint.bodyB ? constraint.bodyB.position.x : 0) \n            + (constraint.pointB ? constraint.pointB.x : 0);\n            \n        var pointBY = (constraint.bodyB ? constraint.bodyB.position.y : 0) \n            + (constraint.pointB ? constraint.pointB.y : 0);\n\n        var deltaX = pointAX - pointBX;\n        var deltaY = pointAY - pointBY;\n\n        return Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"constraint\"\n     * @readOnly\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage bodies.\n     *\n     * @property label\n     * @type string\n     * @default \"Constraint\"\n     */\n\n    /**\n     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.\n     *\n     * @property render\n     * @type object\n     */\n\n    /**\n     * A flag that indicates if the constraint should be rendered.\n     *\n     * @property render.visible\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A `Number` that defines the line width to use when rendering the constraint outline.\n     * A value of `0` means no outline will be rendered.\n     *\n     * @property render.lineWidth\n     * @type number\n     * @default 2\n     */\n\n    /**\n     * A `String` that defines the stroke style to use when rendering the constraint outline.\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.strokeStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * A `String` that defines the constraint rendering type. \n     * The possible values are 'line', 'pin', 'spring'.\n     * An appropriate render type will be automatically chosen unless one is given in options.\n     *\n     * @property render.type\n     * @type string\n     * @default 'line'\n     */\n\n    /**\n     * A `Boolean` that defines if the constraint's anchor points should be rendered.\n     *\n     * @property render.anchors\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * The first possible `Body` that this constraint is attached to.\n     *\n     * @property bodyA\n     * @type body\n     * @default null\n     */\n\n    /**\n     * The second possible `Body` that this constraint is attached to.\n     *\n     * @property bodyB\n     * @type body\n     * @default null\n     */\n\n    /**\n     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.\n     *\n     * @property pointA\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position.\n     *\n     * @property pointB\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`.\n     * A value of `1` means the constraint should be very stiff.\n     * A value of `0.2` means the constraint acts like a soft spring.\n     *\n     * @property stiffness\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that specifies the damping of the constraint, \n     * i.e. the amount of resistance applied to each body based on their velocities to limit the amount of oscillation.\n     * Damping will only be apparent when the constraint also has a very low `stiffness`.\n     * A value of `0.1` means the constraint will apply heavy damping, resulting in little to no oscillation.\n     * A value of `0` means the constraint will apply no damping.\n     *\n     * @property damping\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that specifies the target resting length of the constraint. \n     * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`.\n     *\n     * @property length\n     * @type number\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n})();\n\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Axes` module contains methods for creating and manipulating sets of axes.\n*\n* @class Axes\n*/\n\nvar Axes = {};\n\nmodule.exports = Axes;\n\nvar Vector = __webpack_require__(2);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Creates a new set of axes from the given vertices.\n     * @method fromVertices\n     * @param {vertices} vertices\n     * @return {axes} A new axes from the given vertices\n     */\n    Axes.fromVertices = function(vertices) {\n        var axes = {};\n\n        // find the unique axes, using edge normal gradients\n        for (var i = 0; i < vertices.length; i++) {\n            var j = (i + 1) % vertices.length, \n                normal = Vector.normalise({ \n                    x: vertices[j].y - vertices[i].y, \n                    y: vertices[i].x - vertices[j].x\n                }),\n                gradient = (normal.y === 0) ? Infinity : (normal.x / normal.y);\n            \n            // limit precision\n            gradient = gradient.toFixed(3).toString();\n            axes[gradient] = normal;\n        }\n\n        return Common.values(axes);\n    };\n\n    /**\n     * Rotates a set of axes by the given angle.\n     * @method rotate\n     * @param {axes} axes\n     * @param {number} angle\n     */\n    Axes.rotate = function(axes, angle) {\n        if (angle === 0)\n            return;\n        \n        var cos = Math.cos(angle),\n            sin = Math.sin(angle);\n\n        for (var i = 0; i < axes.length; i++) {\n            var axis = axes[i],\n                xx;\n            xx = axis.x * cos - axis.y * sin;\n            axis.y = axis.x * sin + axis.y * cos;\n            axis.x = xx;\n        }\n    };\n\n})();\n\n\n/***/ }),\n/* 12 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Bodies` module contains factory methods for creating rigid body models \n* with commonly used body configurations (such as rectangles, circles and other polygons).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Bodies\n*/\n\n// TODO: true circle bodies\n\nvar Bodies = {};\n\nmodule.exports = Bodies;\n\nvar Vertices = __webpack_require__(3);\nvar Common = __webpack_require__(0);\nvar Body = __webpack_require__(4);\nvar Bounds = __webpack_require__(1);\nvar Vector = __webpack_require__(2);\n\n(function() {\n\n    /**\n     * Creates a new rigid body model with a rectangle hull. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method rectangle\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {object} [options]\n     * @return {body} A new rectangle body\n     */\n    Bodies.rectangle = function(x, y, width, height, options) {\n        options = options || {};\n\n        var rectangle = { \n            label: 'Rectangle Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, rectangle, options));\n    };\n    \n    /**\n     * Creates a new rigid body model with a trapezoid hull. \n     * The `slope` is parameterised as a fraction of `width` and must be < 1 to form a valid trapezoid. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method trapezoid\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {number} slope Must be a number < 1.\n     * @param {object} [options]\n     * @return {body} A new trapezoid body\n     */\n    Bodies.trapezoid = function(x, y, width, height, slope, options) {\n        options = options || {};\n\n        if (slope >= 1) {\n            Common.warn('Bodies.trapezoid: slope parameter must be < 1.');\n        }\n\n        slope *= 0.5;\n        var roof = (1 - (slope * 2)) * width;\n        \n        var x1 = width * slope,\n            x2 = x1 + roof,\n            x3 = x2 + x1,\n            verticesPath;\n\n        if (slope < 0.5) {\n            verticesPath = 'L 0 0 L ' + x1 + ' ' + (-height) + ' L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';\n        } else {\n            verticesPath = 'L 0 0 L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';\n        }\n\n        var trapezoid = { \n            label: 'Trapezoid Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath(verticesPath)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, trapezoid, options));\n    };\n\n    /**\n     * Creates a new rigid body model with a circle hull. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method circle\n     * @param {number} x\n     * @param {number} y\n     * @param {number} radius\n     * @param {object} [options]\n     * @param {number} [maxSides]\n     * @return {body} A new circle body\n     */\n    Bodies.circle = function(x, y, radius, options, maxSides) {\n        options = options || {};\n\n        var circle = {\n            label: 'Circle Body',\n            circleRadius: radius\n        };\n        \n        // approximate circles with polygons until true circles implemented in SAT\n        maxSides = maxSides || 25;\n        var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius)));\n\n        // optimisation: always use even number of sides (half the number of unique axes)\n        if (sides % 2 === 1)\n            sides += 1;\n\n        return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options));\n    };\n\n    /**\n     * Creates a new rigid body model with a regular polygon hull with the given number of sides. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method polygon\n     * @param {number} x\n     * @param {number} y\n     * @param {number} sides\n     * @param {number} radius\n     * @param {object} [options]\n     * @return {body} A new regular polygon body\n     */\n    Bodies.polygon = function(x, y, sides, radius, options) {\n        options = options || {};\n\n        if (sides < 3)\n            return Bodies.circle(x, y, radius, options);\n\n        var theta = 2 * Math.PI / sides,\n            path = '',\n            offset = theta * 0.5;\n\n        for (var i = 0; i < sides; i += 1) {\n            var angle = offset + (i * theta),\n                xx = Math.cos(angle) * radius,\n                yy = Math.sin(angle) * radius;\n\n            path += 'L ' + xx.toFixed(3) + ' ' + yy.toFixed(3) + ' ';\n        }\n\n        var polygon = { \n            label: 'Polygon Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath(path)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, polygon, options));\n    };\n\n    /**\n     * Utility to create a compound body based on set(s) of vertices.\n     * \n     * _Note:_ To optionally enable automatic concave vertices decomposition the [poly-decomp](https://github.com/schteppe/poly-decomp.js) \n     * package must be first installed and provided see `Common.setDecomp`, otherwise the convex hull of each vertex set will be used.\n     * \n     * The resulting vertices are reorientated about their centre of mass,\n     * and offset such that `body.position` corresponds to this point.\n     * \n     * The resulting offset may be found if needed by subtracting `body.bounds` from the original input bounds.\n     * To later move the centre of mass see `Body.setCentre`.\n     * \n     * Note that automatic conconcave decomposition results are not always optimal. \n     * For best results, simplify the input vertices as much as possible first.\n     * By default this function applies some addtional simplification to help.\n     * \n     * Some outputs may also require further manual processing afterwards to be robust.\n     * In particular some parts may need to be overlapped to avoid collision gaps.\n     * Thin parts and sharp points should be avoided or removed where possible.\n     *\n     * The options parameter object specifies any `Matter.Body` properties you wish to override the defaults.\n     * \n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method fromVertices\n     * @param {number} x\n     * @param {number} y\n     * @param {array} vertexSets One or more arrays of vertex points e.g. `[[{ x: 0, y: 0 }...], ...]`.\n     * @param {object} [options] The body options.\n     * @param {bool} [flagInternal=false] Optionally marks internal edges with `isInternal`.\n     * @param {number} [removeCollinear=0.01] Threshold when simplifying vertices along the same edge.\n     * @param {number} [minimumArea=10] Threshold when removing small parts.\n     * @param {number} [removeDuplicatePoints=0.01] Threshold when simplifying nearby vertices.\n     * @return {body}\n     */\n    Bodies.fromVertices = function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea, removeDuplicatePoints) {\n        var decomp = Common.getDecomp(),\n            canDecomp,\n            body,\n            parts,\n            isConvex,\n            isConcave,\n            vertices,\n            i,\n            j,\n            k,\n            v,\n            z;\n\n        // check decomp is as expected\n        canDecomp = Boolean(decomp && decomp.quickDecomp);\n\n        options = options || {};\n        parts = [];\n\n        flagInternal = typeof flagInternal !== 'undefined' ? flagInternal : false;\n        removeCollinear = typeof removeCollinear !== 'undefined' ? removeCollinear : 0.01;\n        minimumArea = typeof minimumArea !== 'undefined' ? minimumArea : 10;\n        removeDuplicatePoints = typeof removeDuplicatePoints !== 'undefined' ? removeDuplicatePoints : 0.01;\n\n        // ensure vertexSets is an array of arrays\n        if (!Common.isArray(vertexSets[0])) {\n            vertexSets = [vertexSets];\n        }\n\n        for (v = 0; v < vertexSets.length; v += 1) {\n            vertices = vertexSets[v];\n            isConvex = Vertices.isConvex(vertices);\n            isConcave = !isConvex;\n\n            if (isConcave && !canDecomp) {\n                Common.warnOnce(\n                    'Bodies.fromVertices: Install the \\'poly-decomp\\' library and use Common.setDecomp or provide \\'decomp\\' as a global to decompose concave vertices.'\n                );\n            }\n\n            if (isConvex || !canDecomp) {\n                if (isConvex) {\n                    vertices = Vertices.clockwiseSort(vertices);\n                } else {\n                    // fallback to convex hull when decomposition is not possible\n                    vertices = Vertices.hull(vertices);\n                }\n\n                parts.push({\n                    position: { x: x, y: y },\n                    vertices: vertices\n                });\n            } else {\n                // initialise a decomposition\n                var concave = vertices.map(function(vertex) {\n                    return [vertex.x, vertex.y];\n                });\n\n                // vertices are concave and simple, we can decompose into parts\n                decomp.makeCCW(concave);\n                if (removeCollinear !== false)\n                    decomp.removeCollinearPoints(concave, removeCollinear);\n                if (removeDuplicatePoints !== false && decomp.removeDuplicatePoints)\n                    decomp.removeDuplicatePoints(concave, removeDuplicatePoints);\n\n                // use the quick decomposition algorithm (Bayazit)\n                var decomposed = decomp.quickDecomp(concave);\n\n                // for each decomposed chunk\n                for (i = 0; i < decomposed.length; i++) {\n                    var chunk = decomposed[i];\n\n                    // convert vertices into the correct structure\n                    var chunkVertices = chunk.map(function(vertices) {\n                        return {\n                            x: vertices[0],\n                            y: vertices[1]\n                        };\n                    });\n\n                    // skip small chunks\n                    if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea)\n                        continue;\n\n                    // create a compound part\n                    parts.push({\n                        position: Vertices.centre(chunkVertices),\n                        vertices: chunkVertices\n                    });\n                }\n            }\n        }\n\n        // create body parts\n        for (i = 0; i < parts.length; i++) {\n            parts[i] = Body.create(Common.extend(parts[i], options));\n        }\n\n        // flag internal edges (coincident part edges)\n        if (flagInternal) {\n            var coincident_max_dist = 5;\n\n            for (i = 0; i < parts.length; i++) {\n                var partA = parts[i];\n\n                for (j = i + 1; j < parts.length; j++) {\n                    var partB = parts[j];\n\n                    if (Bounds.overlaps(partA.bounds, partB.bounds)) {\n                        var pav = partA.vertices,\n                            pbv = partB.vertices;\n\n                        // iterate vertices of both parts\n                        for (k = 0; k < partA.vertices.length; k++) {\n                            for (z = 0; z < partB.vertices.length; z++) {\n                                // find distances between the vertices\n                                var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])),\n                                    db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length]));\n\n                                // if both vertices are very close, consider the edge concident (internal)\n                                if (da < coincident_max_dist && db < coincident_max_dist) {\n                                    pav[k].isInternal = true;\n                                    pbv[z].isInternal = true;\n                                }\n                            }\n                        }\n\n                    }\n                }\n            }\n        }\n\n        if (parts.length > 1) {\n            // create the parent body to be returned, that contains generated compound parts\n            body = Body.create(Common.extend({ parts: parts.slice(0) }, options));\n\n            // offset such that body.position is at the centre off mass\n            Body.setPosition(body, { x: x, y: y });\n\n            return body;\n        } else {\n            return parts[0];\n        }\n    };\n\n})();\n\n\n/***/ }),\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Detector` module contains methods for efficiently detecting collisions between a list of bodies using a broadphase algorithm.\n*\n* @class Detector\n*/\n\nvar Detector = {};\n\nmodule.exports = Detector;\n\nvar Common = __webpack_require__(0);\nvar Collision = __webpack_require__(8);\n\n(function() {\n\n    /**\n     * Creates a new collision detector.\n     * @method create\n     * @param {} options\n     * @return {detector} A new collision detector\n     */\n    Detector.create = function(options) {\n        var defaults = {\n            bodies: [],\n            collisions: [],\n            pairs: null\n        };\n\n        return Common.extend(defaults, options);\n    };\n\n    /**\n     * Sets the list of bodies in the detector.\n     * @method setBodies\n     * @param {detector} detector\n     * @param {body[]} bodies\n     */\n    Detector.setBodies = function(detector, bodies) {\n        detector.bodies = bodies.slice(0);\n    };\n\n    /**\n     * Clears the detector including its list of bodies.\n     * @method clear\n     * @param {detector} detector\n     */\n    Detector.clear = function(detector) {\n        detector.bodies = [];\n        detector.collisions = [];\n    };\n\n    /**\n     * Efficiently finds all collisions among all the bodies in `detector.bodies` using a broadphase algorithm.\n     * \n     * _Note:_ The specific ordering of collisions returned is not guaranteed between releases and may change for performance reasons.\n     * If a specific ordering is required then apply a sort to the resulting array.\n     * @method collisions\n     * @param {detector} detector\n     * @return {collision[]} collisions\n     */\n    Detector.collisions = function(detector) {\n        var pairs = detector.pairs,\n            bodies = detector.bodies,\n            bodiesLength = bodies.length,\n            canCollide = Detector.canCollide,\n            collides = Collision.collides,\n            collisions = detector.collisions,\n            collisionIndex = 0,\n            i,\n            j;\n\n        bodies.sort(Detector._compareBoundsX);\n\n        for (i = 0; i < bodiesLength; i++) {\n            var bodyA = bodies[i],\n                boundsA = bodyA.bounds,\n                boundXMax = bodyA.bounds.max.x,\n                boundYMax = bodyA.bounds.max.y,\n                boundYMin = bodyA.bounds.min.y,\n                bodyAStatic = bodyA.isStatic || bodyA.isSleeping,\n                partsALength = bodyA.parts.length,\n                partsASingle = partsALength === 1;\n\n            for (j = i + 1; j < bodiesLength; j++) {\n                var bodyB = bodies[j],\n                    boundsB = bodyB.bounds;\n\n                if (boundsB.min.x > boundXMax) {\n                    break;\n                }\n\n                if (boundYMax < boundsB.min.y || boundYMin > boundsB.max.y) {\n                    continue;\n                }\n\n                if (bodyAStatic && (bodyB.isStatic || bodyB.isSleeping)) {\n                    continue;\n                }\n\n                if (!canCollide(bodyA.collisionFilter, bodyB.collisionFilter)) {\n                    continue;\n                }\n\n                var partsBLength = bodyB.parts.length;\n\n                if (partsASingle && partsBLength === 1) {\n                    var collision = collides(bodyA, bodyB, pairs);\n\n                    if (collision) {\n                        collisions[collisionIndex++] = collision;\n                    }\n                } else {\n                    var partsAStart = partsALength > 1 ? 1 : 0,\n                        partsBStart = partsBLength > 1 ? 1 : 0;\n                    \n                    for (var k = partsAStart; k < partsALength; k++) {\n                        var partA = bodyA.parts[k],\n                            boundsA = partA.bounds;\n\n                        for (var z = partsBStart; z < partsBLength; z++) {\n                            var partB = bodyB.parts[z],\n                                boundsB = partB.bounds;\n\n                            if (boundsA.min.x > boundsB.max.x || boundsA.max.x < boundsB.min.x\n                                || boundsA.max.y < boundsB.min.y || boundsA.min.y > boundsB.max.y) {\n                                continue;\n                            }\n\n                            var collision = collides(partA, partB, pairs);\n\n                            if (collision) {\n                                collisions[collisionIndex++] = collision;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (collisions.length !== collisionIndex) {\n            collisions.length = collisionIndex;\n        }\n\n        return collisions;\n    };\n\n    /**\n     * Returns `true` if both supplied collision filters will allow a collision to occur.\n     * See `body.collisionFilter` for more information.\n     * @method canCollide\n     * @param {} filterA\n     * @param {} filterB\n     * @return {bool} `true` if collision can occur\n     */\n    Detector.canCollide = function(filterA, filterB) {\n        if (filterA.group === filterB.group && filterA.group !== 0)\n            return filterA.group > 0;\n\n        return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0;\n    };\n\n    /**\n     * The comparison function used in the broadphase algorithm.\n     * Returns the signed delta of the bodies bounds on the x-axis.\n     * @private\n     * @method _sortCompare\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {number} The signed delta used for sorting\n     */\n    Detector._compareBoundsX = function(bodyA, bodyB) {\n        return bodyA.bounds.min.x - bodyB.bounds.min.x;\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * The array of `Matter.Body` between which the detector finds collisions.\n     * \n     * _Note:_ The order of bodies in this array _is not fixed_ and will be continually managed by the detector.\n     * @property bodies\n     * @type body[]\n     * @default []\n     */\n\n    /**\n     * The array of `Matter.Collision` found in the last call to `Detector.collisions` on this detector.\n     * @property collisions\n     * @type collision[]\n     * @default []\n     */\n\n    /**\n     * Optional. A `Matter.Pairs` object from which previous collision objects may be reused. Intended for internal `Matter.Engine` usage.\n     * @property pairs\n     * @type {pairs|null}\n     * @default null\n     */\n\n})();\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Mouse` module contains methods for creating and manipulating mouse inputs.\n*\n* @class Mouse\n*/\n\nvar Mouse = {};\n\nmodule.exports = Mouse;\n\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Creates a mouse input.\n     * @method create\n     * @param {HTMLElement} element\n     * @return {mouse} A new mouse\n     */\n    Mouse.create = function(element) {\n        var mouse = {};\n\n        if (!element) {\n            Common.log('Mouse.create: element was undefined, defaulting to document.body', 'warn');\n        }\n        \n        mouse.element = element || document.body;\n        mouse.absolute = { x: 0, y: 0 };\n        mouse.position = { x: 0, y: 0 };\n        mouse.mousedownPosition = { x: 0, y: 0 };\n        mouse.mouseupPosition = { x: 0, y: 0 };\n        mouse.offset = { x: 0, y: 0 };\n        mouse.scale = { x: 1, y: 1 };\n        mouse.wheelDelta = 0;\n        mouse.button = -1;\n        mouse.pixelRatio = parseInt(mouse.element.getAttribute('data-pixel-ratio'), 10) || 1;\n\n        mouse.sourceEvents = {\n            mousemove: null,\n            mousedown: null,\n            mouseup: null,\n            mousewheel: null\n        };\n        \n        mouse.mousemove = function(event) { \n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                mouse.button = 0;\n                event.preventDefault();\n            }\n\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.sourceEvents.mousemove = event;\n        };\n        \n        mouse.mousedown = function(event) {\n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                mouse.button = 0;\n                event.preventDefault();\n            } else {\n                mouse.button = event.button;\n            }\n\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.mousedownPosition.x = mouse.position.x;\n            mouse.mousedownPosition.y = mouse.position.y;\n            mouse.sourceEvents.mousedown = event;\n        };\n        \n        mouse.mouseup = function(event) {\n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                event.preventDefault();\n            }\n            \n            mouse.button = -1;\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.mouseupPosition.x = mouse.position.x;\n            mouse.mouseupPosition.y = mouse.position.y;\n            mouse.sourceEvents.mouseup = event;\n        };\n\n        mouse.mousewheel = function(event) {\n            mouse.wheelDelta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail));\n            event.preventDefault();\n            mouse.sourceEvents.mousewheel = event;\n        };\n\n        Mouse.setElement(mouse, mouse.element);\n\n        return mouse;\n    };\n\n    /**\n     * Sets the element the mouse is bound to (and relative to).\n     * @method setElement\n     * @param {mouse} mouse\n     * @param {HTMLElement} element\n     */\n    Mouse.setElement = function(mouse, element) {\n        mouse.element = element;\n\n        element.addEventListener('mousemove', mouse.mousemove, { passive: true });\n        element.addEventListener('mousedown', mouse.mousedown, { passive: true });\n        element.addEventListener('mouseup', mouse.mouseup, { passive: true });\n        \n        element.addEventListener('wheel', mouse.mousewheel, { passive: false });\n        \n        element.addEventListener('touchmove', mouse.mousemove, { passive: false });\n        element.addEventListener('touchstart', mouse.mousedown, { passive: false });\n        element.addEventListener('touchend', mouse.mouseup, { passive: false });\n    };\n\n    /**\n     * Clears all captured source events.\n     * @method clearSourceEvents\n     * @param {mouse} mouse\n     */\n    Mouse.clearSourceEvents = function(mouse) {\n        mouse.sourceEvents.mousemove = null;\n        mouse.sourceEvents.mousedown = null;\n        mouse.sourceEvents.mouseup = null;\n        mouse.sourceEvents.mousewheel = null;\n        mouse.wheelDelta = 0;\n    };\n\n    /**\n     * Sets the mouse position offset.\n     * @method setOffset\n     * @param {mouse} mouse\n     * @param {vector} offset\n     */\n    Mouse.setOffset = function(mouse, offset) {\n        mouse.offset.x = offset.x;\n        mouse.offset.y = offset.y;\n        mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n        mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n    };\n\n    /**\n     * Sets the mouse position scale.\n     * @method setScale\n     * @param {mouse} mouse\n     * @param {vector} scale\n     */\n    Mouse.setScale = function(mouse, scale) {\n        mouse.scale.x = scale.x;\n        mouse.scale.y = scale.y;\n        mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n        mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n    };\n    \n    /**\n     * Gets the mouse position relative to an element given a screen pixel ratio.\n     * @method _getRelativeMousePosition\n     * @private\n     * @param {} event\n     * @param {} element\n     * @param {number} pixelRatio\n     * @return {}\n     */\n    Mouse._getRelativeMousePosition = function(event, element, pixelRatio) {\n        var elementBounds = element.getBoundingClientRect(),\n            rootNode = (document.documentElement || document.body.parentNode || document.body),\n            scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : rootNode.scrollLeft,\n            scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : rootNode.scrollTop,\n            touches = event.changedTouches,\n            x, y;\n        \n        if (touches) {\n            x = touches[0].pageX - elementBounds.left - scrollX;\n            y = touches[0].pageY - elementBounds.top - scrollY;\n        } else {\n            x = event.pageX - elementBounds.left - scrollX;\n            y = event.pageY - elementBounds.top - scrollY;\n        }\n\n        return { \n            x: x / (element.clientWidth / (element.width || element.clientWidth) * pixelRatio),\n            y: y / (element.clientHeight / (element.height || element.clientHeight) * pixelRatio)\n        };\n    };\n\n})();\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Plugin` module contains functions for registering and installing plugins on modules.\n*\n* @class Plugin\n*/\n\nvar Plugin = {};\n\nmodule.exports = Plugin;\n\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    Plugin._registry = {};\n\n    /**\n     * Registers a plugin object so it can be resolved later by name.\n     * @method register\n     * @param plugin {} The plugin to register.\n     * @return {object} The plugin.\n     */\n    Plugin.register = function(plugin) {\n        if (!Plugin.isPlugin(plugin)) {\n            Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.');\n        }\n\n        if (plugin.name in Plugin._registry) {\n            var registered = Plugin._registry[plugin.name],\n                pluginVersion = Plugin.versionParse(plugin.version).number,\n                registeredVersion = Plugin.versionParse(registered.version).number;\n\n            if (pluginVersion > registeredVersion) {\n                Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin));\n                Plugin._registry[plugin.name] = plugin;\n            } else if (pluginVersion < registeredVersion) {\n                Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin));\n            } else if (plugin !== registered) {\n                Common.warn('Plugin.register:', Plugin.toString(plugin), 'is already registered to different plugin object');\n            }\n        } else {\n            Plugin._registry[plugin.name] = plugin;\n        }\n\n        return plugin;\n    };\n\n    /**\n     * Resolves a dependency to a plugin object from the registry if it exists. \n     * The `dependency` may contain a version, but only the name matters when resolving.\n     * @method resolve\n     * @param dependency {string} The dependency.\n     * @return {object} The plugin if resolved, otherwise `undefined`.\n     */\n    Plugin.resolve = function(dependency) {\n        return Plugin._registry[Plugin.dependencyParse(dependency).name];\n    };\n\n    /**\n     * Returns a pretty printed plugin name and version.\n     * @method toString\n     * @param plugin {} The plugin.\n     * @return {string} Pretty printed plugin name and version.\n     */\n    Plugin.toString = function(plugin) {\n        return typeof plugin === 'string' ? plugin : (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0');\n    };\n\n    /**\n     * Returns `true` if the object meets the minimum standard to be considered a plugin.\n     * This means it must define the following properties:\n     * - `name`\n     * - `version`\n     * - `install`\n     * @method isPlugin\n     * @param obj {} The obj to test.\n     * @return {boolean} `true` if the object can be considered a plugin otherwise `false`.\n     */\n    Plugin.isPlugin = function(obj) {\n        return obj && obj.name && obj.version && obj.install;\n    };\n\n    /**\n     * Returns `true` if a plugin with the given `name` been installed on `module`.\n     * @method isUsed\n     * @param module {} The module.\n     * @param name {string} The plugin name.\n     * @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`.\n     */\n    Plugin.isUsed = function(module, name) {\n        return module.used.indexOf(name) > -1;\n    };\n\n    /**\n     * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`.\n     * If `plugin.for` is not specified then it is assumed to be applicable.\n     * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`.\n     * @method isFor\n     * @param plugin {} The plugin.\n     * @param module {} The module.\n     * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`.\n     */\n    Plugin.isFor = function(plugin, module) {\n        var parsed = plugin.for && Plugin.dependencyParse(plugin.for);\n        return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range));\n    };\n\n    /**\n     * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`.\n     * For installing plugins on `Matter` see the convenience function `Matter.use`.\n     * Plugins may be specified either by their name or a reference to the plugin object.\n     * Plugins themselves may specify further dependencies, but each plugin is installed only once.\n     * Order is important, a topological sort is performed to find the best resulting order of installation.\n     * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases.\n     * This function logs the resulting status of each dependency in the console, along with any warnings.\n     * - A green tick ✅ indicates a dependency was resolved and installed.\n     * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies.\n     * - A red cross ❌ indicates a dependency could not be resolved.\n     * Avoid calling this function multiple times on the same module unless you intend to manually control installation order.\n     * @method use\n     * @param module {} The module install plugins on.\n     * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`).\n     */\n    Plugin.use = function(module, plugins) {\n        module.uses = (module.uses || []).concat(plugins || []);\n\n        if (module.uses.length === 0) {\n            Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.');\n            return;\n        }\n\n        var dependencies = Plugin.dependencies(module),\n            sortedDependencies = Common.topologicalSort(dependencies),\n            status = [];\n\n        for (var i = 0; i < sortedDependencies.length; i += 1) {\n            if (sortedDependencies[i] === module.name) {\n                continue;\n            }\n\n            var plugin = Plugin.resolve(sortedDependencies[i]);\n\n            if (!plugin) {\n                status.push('❌ ' + sortedDependencies[i]);\n                continue;\n            }\n\n            if (Plugin.isUsed(module, plugin.name)) {\n                continue;\n            }\n\n            if (!Plugin.isFor(plugin, module)) {\n                Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.');\n                plugin._warned = true;\n            }\n\n            if (plugin.install) {\n                plugin.install(module);\n            } else {\n                Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.');\n                plugin._warned = true;\n            }\n\n            if (plugin._warned) {\n                status.push('🔶 ' + Plugin.toString(plugin));\n                delete plugin._warned;\n            } else {\n                status.push('✅ ' + Plugin.toString(plugin));\n            }\n\n            module.used.push(plugin.name);\n        }\n\n        if (status.length > 0) {\n            Common.info(status.join('  '));\n        }\n    };\n\n    /**\n     * Recursively finds all of a module's dependencies and returns a flat dependency graph.\n     * @method dependencies\n     * @param module {} The module.\n     * @return {object} A dependency graph.\n     */\n    Plugin.dependencies = function(module, tracked) {\n        var parsedBase = Plugin.dependencyParse(module),\n            name = parsedBase.name;\n\n        tracked = tracked || {};\n\n        if (name in tracked) {\n            return;\n        }\n\n        module = Plugin.resolve(module) || module;\n\n        tracked[name] = Common.map(module.uses || [], function(dependency) {\n            if (Plugin.isPlugin(dependency)) {\n                Plugin.register(dependency);\n            }\n\n            var parsed = Plugin.dependencyParse(dependency),\n                resolved = Plugin.resolve(dependency);\n\n            if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) {\n                Common.warn(\n                    'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy',\n                    Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.'\n                );\n\n                resolved._warned = true;\n                module._warned = true;\n            } else if (!resolved) {\n                Common.warn(\n                    'Plugin.dependencies:', Plugin.toString(dependency), 'used by',\n                    Plugin.toString(parsedBase), 'could not be resolved.'\n                );\n\n                module._warned = true;\n            }\n\n            return parsed.name;\n        });\n\n        for (var i = 0; i < tracked[name].length; i += 1) {\n            Plugin.dependencies(tracked[name][i], tracked);\n        }\n\n        return tracked;\n    };\n\n    /**\n     * Parses a dependency string into its components.\n     * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`.\n     * See documentation for `Plugin.versionParse` for a description of the format.\n     * This function can also handle dependencies that are already resolved (e.g. a module object).\n     * @method dependencyParse\n     * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`.\n     * @return {object} The dependency parsed into its components.\n     */\n    Plugin.dependencyParse = function(dependency) {\n        if (Common.isString(dependency)) {\n            var pattern = /^[\\w-]+(@(\\*|[\\^~]?\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z-+]+)?))?$/;\n\n            if (!pattern.test(dependency)) {\n                Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.');\n            }\n\n            return {\n                name: dependency.split('@')[0],\n                range: dependency.split('@')[1] || '*'\n            };\n        }\n\n        return {\n            name: dependency.name,\n            range: dependency.range || dependency.version\n        };\n    };\n\n    /**\n     * Parses a version string into its components.  \n     * Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).\n     * Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.\n     * Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).\n     * Only the following range types are supported:\n     * - Tilde ranges e.g. `~1.2.3`\n     * - Caret ranges e.g. `^1.2.3`\n     * - Greater than ranges e.g. `>1.2.3`\n     * - Greater than or equal ranges e.g. `>=1.2.3`\n     * - Exact version e.g. `1.2.3`\n     * - Any version `*`\n     * @method versionParse\n     * @param range {string} The version string.\n     * @return {object} The version range parsed into its components.\n     */\n    Plugin.versionParse = function(range) {\n        var pattern = /^(\\*)|(\\^|~|>=|>)?\\s*((\\d+)\\.(\\d+)\\.(\\d+))(-[0-9A-Za-z-+]+)?$/;\n\n        if (!pattern.test(range)) {\n            Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.');\n        }\n\n        var parts = pattern.exec(range);\n        var major = Number(parts[4]);\n        var minor = Number(parts[5]);\n        var patch = Number(parts[6]);\n\n        return {\n            isRange: Boolean(parts[1] || parts[2]),\n            version: parts[3],\n            range: range,\n            operator: parts[1] || parts[2] || '',\n            major: major,\n            minor: minor,\n            patch: patch,\n            parts: [major, minor, patch],\n            prerelease: parts[7],\n            number: major * 1e8 + minor * 1e4 + patch\n        };\n    };\n\n    /**\n     * Returns `true` if `version` satisfies the given `range`.\n     * See documentation for `Plugin.versionParse` for a description of the format.\n     * If a version or range is not specified, then any version (`*`) is assumed to satisfy.\n     * @method versionSatisfies\n     * @param version {string} The version string.\n     * @param range {string} The range string.\n     * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`.\n     */\n    Plugin.versionSatisfies = function(version, range) {\n        range = range || '*';\n\n        var r = Plugin.versionParse(range),\n            v = Plugin.versionParse(version);\n\n        if (r.isRange) {\n            if (r.operator === '*' || version === '*') {\n                return true;\n            }\n\n            if (r.operator === '>') {\n                return v.number > r.number;\n            }\n\n            if (r.operator === '>=') {\n                return v.number >= r.number;\n            }\n\n            if (r.operator === '~') {\n                return v.major === r.major && v.minor === r.minor && v.patch >= r.patch;\n            }\n\n            if (r.operator === '^') {\n                if (r.major > 0) {\n                    return v.major === r.major && v.number >= r.number;\n                }\n\n                if (r.minor > 0) {\n                    return v.minor === r.minor && v.patch >= r.patch;\n                }\n\n                return v.patch === r.patch;\n            }\n        }\n\n        return version === range || version === '*';\n    };\n\n})();\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports) {\n\n/**\n* The `Matter.Contact` module contains methods for creating and manipulating collision contacts.\n*\n* @class Contact\n*/\n\nvar Contact = {};\n\nmodule.exports = Contact;\n\n(function() {\n\n    /**\n     * Creates a new contact.\n     * @method create\n     * @param {vertex} [vertex]\n     * @return {contact} A new contact\n     */\n    Contact.create = function(vertex) {\n        return {\n            vertex: vertex,\n            normalImpulse: 0,\n            tangentImpulse: 0\n        };\n    };\n\n})();\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Engine` module contains methods for creating and manipulating engines.\n* An engine is a controller that manages updating the simulation of the world.\n* See `Matter.Runner` for an optional game loop utility.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Engine\n*/\n\nvar Engine = {};\n\nmodule.exports = Engine;\n\nvar Sleeping = __webpack_require__(7);\nvar Resolver = __webpack_require__(18);\nvar Detector = __webpack_require__(13);\nvar Pairs = __webpack_require__(19);\nvar Events = __webpack_require__(5);\nvar Composite = __webpack_require__(6);\nvar Constraint = __webpack_require__(10);\nvar Common = __webpack_require__(0);\nvar Body = __webpack_require__(4);\n\n(function() {\n\n    Engine._deltaMax = 1000 / 60;\n\n    /**\n     * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {object} [options]\n     * @return {engine} engine\n     */\n    Engine.create = function(options) {\n        options = options || {};\n\n        var defaults = {\n            positionIterations: 6,\n            velocityIterations: 4,\n            constraintIterations: 2,\n            enableSleeping: false,\n            events: [],\n            plugin: {},\n            gravity: {\n                x: 0,\n                y: 1,\n                scale: 0.001\n            },\n            timing: {\n                timestamp: 0,\n                timeScale: 1,\n                lastDelta: 0,\n                lastElapsed: 0,\n                lastUpdatesPerFrame: 0\n            }\n        };\n\n        var engine = Common.extend(defaults, options);\n\n        engine.world = options.world || Composite.create({ label: 'World' });\n        engine.pairs = options.pairs || Pairs.create();\n        engine.detector = options.detector || Detector.create();\n        engine.detector.pairs = engine.pairs;\n\n        // for temporary back compatibility only\n        engine.grid = { buckets: [] };\n        engine.world.gravity = engine.gravity;\n        engine.broadphase = engine.grid;\n        engine.metrics = {};\n        \n        return engine;\n    };\n\n    /**\n     * Moves the simulation forward in time by `delta` milliseconds.\n     * Triggers `beforeUpdate`, `beforeSolve` and `afterUpdate` events.\n     * Triggers `collisionStart`, `collisionActive` and `collisionEnd` events.\n     * @method update\n     * @param {engine} engine\n     * @param {number} [delta=16.666]\n     */\n    Engine.update = function(engine, delta) {\n        var startTime = Common.now();\n\n        var world = engine.world,\n            detector = engine.detector,\n            pairs = engine.pairs,\n            timing = engine.timing,\n            timestamp = timing.timestamp,\n            i;\n\n        // warn if high delta\n        if (delta > Engine._deltaMax) {\n            Common.warnOnce(\n                'Matter.Engine.update: delta argument is recommended to be less than or equal to', Engine._deltaMax.toFixed(3), 'ms.'\n            );\n        }\n\n        delta = typeof delta !== 'undefined' ? delta : Common._baseDelta;\n        delta *= timing.timeScale;\n\n        // increment timestamp\n        timing.timestamp += delta;\n        timing.lastDelta = delta;\n\n        // create an event object\n        var event = {\n            timestamp: timing.timestamp,\n            delta: delta\n        };\n\n        Events.trigger(engine, 'beforeUpdate', event);\n\n        // get all bodies and all constraints in the world\n        var allBodies = Composite.allBodies(world),\n            allConstraints = Composite.allConstraints(world);\n\n        // if the world has changed\n        if (world.isModified) {\n            // update the detector bodies\n            Detector.setBodies(detector, allBodies);\n\n            // reset all composite modified flags\n            Composite.setModified(world, false, false, true);\n        }\n\n        // update sleeping if enabled\n        if (engine.enableSleeping)\n            Sleeping.update(allBodies, delta);\n\n        // apply gravity to all bodies\n        Engine._bodiesApplyGravity(allBodies, engine.gravity);\n\n        // update all body position and rotation by integration\n        if (delta > 0) {\n            Engine._bodiesUpdate(allBodies, delta);\n        }\n\n        Events.trigger(engine, 'beforeSolve', event);\n\n        // update all constraints (first pass)\n        Constraint.preSolveAll(allBodies);\n        for (i = 0; i < engine.constraintIterations; i++) {\n            Constraint.solveAll(allConstraints, delta);\n        }\n        Constraint.postSolveAll(allBodies);\n\n        // find all collisions\n        var collisions = Detector.collisions(detector);\n\n        // update collision pairs\n        Pairs.update(pairs, collisions, timestamp);\n\n        // wake up bodies involved in collisions\n        if (engine.enableSleeping)\n            Sleeping.afterCollisions(pairs.list);\n\n        // trigger collision events\n        if (pairs.collisionStart.length > 0) {\n            Events.trigger(engine, 'collisionStart', { \n                pairs: pairs.collisionStart,\n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        // iteratively resolve position between collisions\n        var positionDamping = Common.clamp(20 / engine.positionIterations, 0, 1);\n        \n        Resolver.preSolvePosition(pairs.list);\n        for (i = 0; i < engine.positionIterations; i++) {\n            Resolver.solvePosition(pairs.list, delta, positionDamping);\n        }\n        Resolver.postSolvePosition(allBodies);\n\n        // update all constraints (second pass)\n        Constraint.preSolveAll(allBodies);\n        for (i = 0; i < engine.constraintIterations; i++) {\n            Constraint.solveAll(allConstraints, delta);\n        }\n        Constraint.postSolveAll(allBodies);\n\n        // iteratively resolve velocity between collisions\n        Resolver.preSolveVelocity(pairs.list);\n        for (i = 0; i < engine.velocityIterations; i++) {\n            Resolver.solveVelocity(pairs.list, delta);\n        }\n\n        // update body speed and velocity properties\n        Engine._bodiesUpdateVelocities(allBodies);\n\n        // trigger collision events\n        if (pairs.collisionActive.length > 0) {\n            Events.trigger(engine, 'collisionActive', { \n                pairs: pairs.collisionActive, \n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        if (pairs.collisionEnd.length > 0) {\n            Events.trigger(engine, 'collisionEnd', {\n                pairs: pairs.collisionEnd,\n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        // clear force buffers\n        Engine._bodiesClearForces(allBodies);\n\n        Events.trigger(engine, 'afterUpdate', event);\n\n        // log the time elapsed computing this update\n        engine.timing.lastElapsed = Common.now() - startTime;\n\n        return engine;\n    };\n    \n    /**\n     * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`.\n     * @method merge\n     * @param {engine} engineA\n     * @param {engine} engineB\n     */\n    Engine.merge = function(engineA, engineB) {\n        Common.extend(engineA, engineB);\n        \n        if (engineB.world) {\n            engineA.world = engineB.world;\n\n            Engine.clear(engineA);\n\n            var bodies = Composite.allBodies(engineA.world);\n\n            for (var i = 0; i < bodies.length; i++) {\n                var body = bodies[i];\n                Sleeping.set(body, false);\n                body.id = Common.nextId();\n            }\n        }\n    };\n\n    /**\n     * Clears the engine pairs and detector.\n     * @method clear\n     * @param {engine} engine\n     */\n    Engine.clear = function(engine) {\n        Pairs.clear(engine.pairs);\n        Detector.clear(engine.detector);\n    };\n\n    /**\n     * Zeroes the `body.force` and `body.torque` force buffers.\n     * @method _bodiesClearForces\n     * @private\n     * @param {body[]} bodies\n     */\n    Engine._bodiesClearForces = function(bodies) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            // reset force buffers\n            body.force.x = 0;\n            body.force.y = 0;\n            body.torque = 0;\n        }\n    };\n\n    /**\n     * Applies gravitational acceleration to all `bodies`.\n     * This models a [uniform gravitational field](https://en.wikipedia.org/wiki/Gravity_of_Earth), similar to near the surface of a planet.\n     * \n     * @method _bodiesApplyGravity\n     * @private\n     * @param {body[]} bodies\n     * @param {vector} gravity\n     */\n    Engine._bodiesApplyGravity = function(bodies, gravity) {\n        var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001,\n            bodiesLength = bodies.length;\n\n        if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) {\n            return;\n        }\n        \n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            if (body.isStatic || body.isSleeping)\n                continue;\n\n            // add the resultant force of gravity\n            body.force.y += body.mass * gravity.y * gravityScale;\n            body.force.x += body.mass * gravity.x * gravityScale;\n        }\n    };\n\n    /**\n     * Applies `Body.update` to all given `bodies`.\n     * @method _bodiesUpdate\n     * @private\n     * @param {body[]} bodies\n     * @param {number} delta The amount of time elapsed between updates\n     */\n    Engine._bodiesUpdate = function(bodies, delta) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            if (body.isStatic || body.isSleeping)\n                continue;\n\n            Body.update(body, delta);\n        }\n    };\n\n    /**\n     * Applies `Body.updateVelocities` to all given `bodies`.\n     * @method _bodiesUpdateVelocities\n     * @private\n     * @param {body[]} bodies\n     */\n    Engine._bodiesUpdateVelocities = function(bodies) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            Body.updateVelocities(bodies[i]);\n        }\n    };\n\n    /**\n     * A deprecated alias for `Runner.run`, use `Matter.Runner.run(engine)` instead and see `Matter.Runner` for more information.\n     * @deprecated use Matter.Runner.run(engine) instead\n     * @method run\n     * @param {engine} engine\n     */\n\n    /**\n    * Fired just before an update\n    *\n    * @event beforeUpdate\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after bodies updated based on their velocity and forces, but before any collision detection, constraints and resolving etc.\n    *\n    * @event beforeSolve\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update and all collision events\n    *\n    * @event afterUpdate\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any)\n    *\n    * @event collisionStart\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any)\n    *\n    * @event collisionActive\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any)\n    *\n    * @event collisionEnd\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` that specifies the number of position iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     *\n     * @property positionIterations\n     * @type number\n     * @default 6\n     */\n\n    /**\n     * An integer `Number` that specifies the number of velocity iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     *\n     * @property velocityIterations\n     * @type number\n     * @default 4\n     */\n\n    /**\n     * An integer `Number` that specifies the number of constraint iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     * The default value of `2` is usually very adequate.\n     *\n     * @property constraintIterations\n     * @type number\n     * @default 2\n     */\n\n    /**\n     * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module.\n     * Sleeping can improve stability and performance, but often at the expense of accuracy.\n     *\n     * @property enableSleeping\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * An `Object` containing properties regarding the timing systems of the engine. \n     *\n     * @property timing\n     * @type object\n     */\n\n    /**\n     * A `Number` that specifies the global scaling factor of time for all bodies.\n     * A value of `0` freezes the simulation.\n     * A value of `0.1` gives a slow-motion effect.\n     * A value of `1.2` gives a speed-up effect.\n     *\n     * @property timing.timeScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. \n     * It is incremented on every `Engine.update` by the given `delta` argument. \n     * \n     * @property timing.timestamp\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that represents the total execution time elapsed during the last `Engine.update` in milliseconds.\n     * It is updated by timing from the start of the last `Engine.update` call until it ends.\n     *\n     * This value will also include the total execution time of all event handlers directly or indirectly triggered by the engine update.\n     * \n     * @property timing.lastElapsed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that represents the `delta` value used in the last engine update.\n     * \n     * @property timing.lastDelta\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Matter.Detector` instance.\n     *\n     * @property detector\n     * @type detector\n     * @default a Matter.Detector instance\n     */\n\n    /**\n     * A `Matter.Grid` instance.\n     *\n     * @deprecated replaced by `engine.detector`\n     * @property grid\n     * @type grid\n     * @default a Matter.Grid instance\n     */\n\n    /**\n     * Replaced by and now alias for `engine.grid`.\n     *\n     * @deprecated replaced by `engine.detector`\n     * @property broadphase\n     * @type grid\n     * @default a Matter.Grid instance\n     */\n\n    /**\n     * The root `Matter.Composite` instance that will contain all bodies, constraints and other composites to be simulated by this engine.\n     *\n     * @property world\n     * @type composite\n     * @default a Matter.Composite instance\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * An optional gravitational acceleration applied to all bodies in `engine.world` on every update.\n     * \n     * This models a [uniform gravitational field](https://en.wikipedia.org/wiki/Gravity_of_Earth), similar to near the surface of a planet. For gravity in other contexts, disable this and apply forces as needed.\n     * \n     * To disable set the `scale` component to `0`.\n     * \n     * This is split into three components for ease of use:  \n     * a normalised direction (`x` and `y`) and magnitude (`scale`).\n     *\n     * @property gravity\n     * @type object\n     */\n\n    /**\n     * The gravitational direction normal `x` component, to be multiplied by `gravity.scale`.\n     * \n     * @property gravity.x\n     * @type object\n     * @default 0\n     */\n\n    /**\n     * The gravitational direction normal `y` component, to be multiplied by `gravity.scale`.\n     *\n     * @property gravity.y\n     * @type object\n     * @default 1\n     */\n\n    /**\n     * The magnitude of the gravitational acceleration.\n     * \n     * @property gravity.scale\n     * @type object\n     * @default 0.001\n     */\n\n})();\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Resolver` module contains methods for resolving collision pairs.\n*\n* @class Resolver\n*/\n\nvar Resolver = {};\n\nmodule.exports = Resolver;\n\nvar Vertices = __webpack_require__(3);\nvar Common = __webpack_require__(0);\nvar Bounds = __webpack_require__(1);\n\n(function() {\n\n    Resolver._restingThresh = 2;\n    Resolver._restingThreshTangent = Math.sqrt(6);\n    Resolver._positionDampen = 0.9;\n    Resolver._positionWarming = 0.8;\n    Resolver._frictionNormalMultiplier = 5;\n    Resolver._frictionMaxStatic = Number.MAX_VALUE;\n\n    /**\n     * Prepare pairs for position solving.\n     * @method preSolvePosition\n     * @param {pair[]} pairs\n     */\n    Resolver.preSolvePosition = function(pairs) {\n        var i,\n            pair,\n            contactCount,\n            pairsLength = pairs.length;\n\n        // find total contacts on each body\n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n            \n            if (!pair.isActive)\n                continue;\n            \n            contactCount = pair.contactCount;\n            pair.collision.parentA.totalContacts += contactCount;\n            pair.collision.parentB.totalContacts += contactCount;\n        }\n    };\n\n    /**\n     * Find a solution for pair positions.\n     * @method solvePosition\n     * @param {pair[]} pairs\n     * @param {number} delta\n     * @param {number} [damping=1]\n     */\n    Resolver.solvePosition = function(pairs, delta, damping) {\n        var i,\n            pair,\n            collision,\n            bodyA,\n            bodyB,\n            normal,\n            contactShare,\n            positionImpulse,\n            positionDampen = Resolver._positionDampen * (damping || 1),\n            slopDampen = Common.clamp(delta / Common._baseDelta, 0, 1),\n            pairsLength = pairs.length;\n\n        // find impulses required to resolve penetration\n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n\n            collision = pair.collision;\n            bodyA = collision.parentA;\n            bodyB = collision.parentB;\n            normal = collision.normal;\n\n            // get current separation between body edges involved in collision\n            pair.separation = \n                collision.depth + normal.x * (bodyB.positionImpulse.x - bodyA.positionImpulse.x)\n                + normal.y * (bodyB.positionImpulse.y - bodyA.positionImpulse.y);\n        }\n        \n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            collision = pair.collision;\n            bodyA = collision.parentA;\n            bodyB = collision.parentB;\n            normal = collision.normal;\n            positionImpulse = pair.separation - pair.slop * slopDampen;\n\n            if (bodyA.isStatic || bodyB.isStatic)\n                positionImpulse *= 2;\n            \n            if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                contactShare = positionDampen / bodyA.totalContacts;\n                bodyA.positionImpulse.x += normal.x * positionImpulse * contactShare;\n                bodyA.positionImpulse.y += normal.y * positionImpulse * contactShare;\n            }\n\n            if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                contactShare = positionDampen / bodyB.totalContacts;\n                bodyB.positionImpulse.x -= normal.x * positionImpulse * contactShare;\n                bodyB.positionImpulse.y -= normal.y * positionImpulse * contactShare;\n            }\n        }\n    };\n\n    /**\n     * Apply position resolution.\n     * @method postSolvePosition\n     * @param {body[]} bodies\n     */\n    Resolver.postSolvePosition = function(bodies) {\n        var positionWarming = Resolver._positionWarming,\n            bodiesLength = bodies.length,\n            verticesTranslate = Vertices.translate,\n            boundsUpdate = Bounds.update;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i],\n                positionImpulse = body.positionImpulse,\n                positionImpulseX = positionImpulse.x,\n                positionImpulseY = positionImpulse.y,\n                velocity = body.velocity;\n\n            // reset contact count\n            body.totalContacts = 0;\n\n            if (positionImpulseX !== 0 || positionImpulseY !== 0) {\n                // update body geometry\n                for (var j = 0; j < body.parts.length; j++) {\n                    var part = body.parts[j];\n                    verticesTranslate(part.vertices, positionImpulse);\n                    boundsUpdate(part.bounds, part.vertices, velocity);\n                    part.position.x += positionImpulseX;\n                    part.position.y += positionImpulseY;\n                }\n\n                // move the body without changing velocity\n                body.positionPrev.x += positionImpulseX;\n                body.positionPrev.y += positionImpulseY;\n\n                if (positionImpulseX * velocity.x + positionImpulseY * velocity.y < 0) {\n                    // reset cached impulse if the body has velocity along it\n                    positionImpulse.x = 0;\n                    positionImpulse.y = 0;\n                } else {\n                    // warm the next iteration\n                    positionImpulse.x *= positionWarming;\n                    positionImpulse.y *= positionWarming;\n                }\n            }\n        }\n    };\n\n    /**\n     * Prepare pairs for velocity solving.\n     * @method preSolveVelocity\n     * @param {pair[]} pairs\n     */\n    Resolver.preSolveVelocity = function(pairs) {\n        var pairsLength = pairs.length,\n            i,\n            j;\n        \n        for (i = 0; i < pairsLength; i++) {\n            var pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            var contacts = pair.contacts,\n                contactCount = pair.contactCount,\n                collision = pair.collision,\n                bodyA = collision.parentA,\n                bodyB = collision.parentB,\n                normal = collision.normal,\n                tangent = collision.tangent;\n    \n            // resolve each contact\n            for (j = 0; j < contactCount; j++) {\n                var contact = contacts[j],\n                    contactVertex = contact.vertex,\n                    normalImpulse = contact.normalImpulse,\n                    tangentImpulse = contact.tangentImpulse;\n    \n                if (normalImpulse !== 0 || tangentImpulse !== 0) {\n                    // total impulse from contact\n                    var impulseX = normal.x * normalImpulse + tangent.x * tangentImpulse,\n                        impulseY = normal.y * normalImpulse + tangent.y * tangentImpulse;\n                    \n                    // apply impulse from contact\n                    if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                        bodyA.positionPrev.x += impulseX * bodyA.inverseMass;\n                        bodyA.positionPrev.y += impulseY * bodyA.inverseMass;\n                        bodyA.anglePrev += bodyA.inverseInertia * (\n                            (contactVertex.x - bodyA.position.x) * impulseY\n                            - (contactVertex.y - bodyA.position.y) * impulseX\n                        );\n                    }\n    \n                    if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                        bodyB.positionPrev.x -= impulseX * bodyB.inverseMass;\n                        bodyB.positionPrev.y -= impulseY * bodyB.inverseMass;\n                        bodyB.anglePrev -= bodyB.inverseInertia * (\n                            (contactVertex.x - bodyB.position.x) * impulseY \n                            - (contactVertex.y - bodyB.position.y) * impulseX\n                        );\n                    }\n                }\n            }\n        }\n    };\n\n    /**\n     * Find a solution for pair velocities.\n     * @method solveVelocity\n     * @param {pair[]} pairs\n     * @param {number} delta\n     */\n    Resolver.solveVelocity = function(pairs, delta) {\n        var timeScale = delta / Common._baseDelta,\n            timeScaleSquared = timeScale * timeScale,\n            timeScaleCubed = timeScaleSquared * timeScale,\n            restingThresh = -Resolver._restingThresh * timeScale,\n            restingThreshTangent = Resolver._restingThreshTangent,\n            frictionNormalMultiplier = Resolver._frictionNormalMultiplier * timeScale,\n            frictionMaxStatic = Resolver._frictionMaxStatic,\n            pairsLength = pairs.length,\n            tangentImpulse,\n            maxFriction,\n            i,\n            j;\n\n        for (i = 0; i < pairsLength; i++) {\n            var pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            var collision = pair.collision,\n                bodyA = collision.parentA,\n                bodyB = collision.parentB,\n                normalX = collision.normal.x,\n                normalY = collision.normal.y,\n                tangentX = collision.tangent.x,\n                tangentY = collision.tangent.y,\n                inverseMassTotal = pair.inverseMass,\n                friction = pair.friction * pair.frictionStatic * frictionNormalMultiplier,\n                contacts = pair.contacts,\n                contactCount = pair.contactCount,\n                contactShare = 1 / contactCount;\n\n            // get body velocities\n            var bodyAVelocityX = bodyA.position.x - bodyA.positionPrev.x,\n                bodyAVelocityY = bodyA.position.y - bodyA.positionPrev.y,\n                bodyAAngularVelocity = bodyA.angle - bodyA.anglePrev,\n                bodyBVelocityX = bodyB.position.x - bodyB.positionPrev.x,\n                bodyBVelocityY = bodyB.position.y - bodyB.positionPrev.y,\n                bodyBAngularVelocity = bodyB.angle - bodyB.anglePrev;\n\n            // resolve each contact\n            for (j = 0; j < contactCount; j++) {\n                var contact = contacts[j],\n                    contactVertex = contact.vertex;\n\n                var offsetAX = contactVertex.x - bodyA.position.x,\n                    offsetAY = contactVertex.y - bodyA.position.y,\n                    offsetBX = contactVertex.x - bodyB.position.x,\n                    offsetBY = contactVertex.y - bodyB.position.y;\n \n                var velocityPointAX = bodyAVelocityX - offsetAY * bodyAAngularVelocity,\n                    velocityPointAY = bodyAVelocityY + offsetAX * bodyAAngularVelocity,\n                    velocityPointBX = bodyBVelocityX - offsetBY * bodyBAngularVelocity,\n                    velocityPointBY = bodyBVelocityY + offsetBX * bodyBAngularVelocity;\n\n                var relativeVelocityX = velocityPointAX - velocityPointBX,\n                    relativeVelocityY = velocityPointAY - velocityPointBY;\n\n                var normalVelocity = normalX * relativeVelocityX + normalY * relativeVelocityY,\n                    tangentVelocity = tangentX * relativeVelocityX + tangentY * relativeVelocityY;\n\n                // coulomb friction\n                var normalOverlap = pair.separation + normalVelocity;\n                var normalForce = Math.min(normalOverlap, 1);\n                normalForce = normalOverlap < 0 ? 0 : normalForce;\n\n                var frictionLimit = normalForce * friction;\n\n                if (tangentVelocity < -frictionLimit || tangentVelocity > frictionLimit) {\n                    maxFriction = (tangentVelocity > 0 ? tangentVelocity : -tangentVelocity);\n                    tangentImpulse = pair.friction * (tangentVelocity > 0 ? 1 : -1) * timeScaleCubed;\n                    \n                    if (tangentImpulse < -maxFriction) {\n                        tangentImpulse = -maxFriction;\n                    } else if (tangentImpulse > maxFriction) {\n                        tangentImpulse = maxFriction;\n                    }\n                } else {\n                    tangentImpulse = tangentVelocity;\n                    maxFriction = frictionMaxStatic;\n                }\n\n                // account for mass, inertia and contact offset\n                var oAcN = offsetAX * normalY - offsetAY * normalX,\n                    oBcN = offsetBX * normalY - offsetBY * normalX,\n                    share = contactShare / (inverseMassTotal + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN);\n\n                // raw impulses\n                var normalImpulse = (1 + pair.restitution) * normalVelocity * share;\n                tangentImpulse *= share;\n\n                // handle high velocity and resting collisions separately\n                if (normalVelocity < restingThresh) {\n                    // high normal velocity so clear cached contact normal impulse\n                    contact.normalImpulse = 0;\n                } else {\n                    // solve resting collision constraints using Erin Catto's method (GDC08)\n                    // impulse constraint tends to 0\n                    var contactNormalImpulse = contact.normalImpulse;\n                    contact.normalImpulse += normalImpulse;\n                    if (contact.normalImpulse > 0) contact.normalImpulse = 0;\n                    normalImpulse = contact.normalImpulse - contactNormalImpulse;\n                }\n\n                // handle high velocity and resting collisions separately\n                if (tangentVelocity < -restingThreshTangent || tangentVelocity > restingThreshTangent) {\n                    // high tangent velocity so clear cached contact tangent impulse\n                    contact.tangentImpulse = 0;\n                } else {\n                    // solve resting collision constraints using Erin Catto's method (GDC08)\n                    // tangent impulse tends to -tangentSpeed or +tangentSpeed\n                    var contactTangentImpulse = contact.tangentImpulse;\n                    contact.tangentImpulse += tangentImpulse;\n                    if (contact.tangentImpulse < -maxFriction) contact.tangentImpulse = -maxFriction;\n                    if (contact.tangentImpulse > maxFriction) contact.tangentImpulse = maxFriction;\n                    tangentImpulse = contact.tangentImpulse - contactTangentImpulse;\n                }\n\n                // total impulse from contact\n                var impulseX = normalX * normalImpulse + tangentX * tangentImpulse,\n                    impulseY = normalY * normalImpulse + tangentY * tangentImpulse;\n                \n                // apply impulse from contact\n                if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                    bodyA.positionPrev.x += impulseX * bodyA.inverseMass;\n                    bodyA.positionPrev.y += impulseY * bodyA.inverseMass;\n                    bodyA.anglePrev += (offsetAX * impulseY - offsetAY * impulseX) * bodyA.inverseInertia;\n                }\n\n                if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                    bodyB.positionPrev.x -= impulseX * bodyB.inverseMass;\n                    bodyB.positionPrev.y -= impulseY * bodyB.inverseMass;\n                    bodyB.anglePrev -= (offsetBX * impulseY - offsetBY * impulseX) * bodyB.inverseInertia;\n                }\n            }\n        }\n    };\n\n})();\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets.\n*\n* @class Pairs\n*/\n\nvar Pairs = {};\n\nmodule.exports = Pairs;\n\nvar Pair = __webpack_require__(9);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Creates a new pairs structure.\n     * @method create\n     * @param {object} options\n     * @return {pairs} A new pairs structure\n     */\n    Pairs.create = function(options) {\n        return Common.extend({ \n            table: {},\n            list: [],\n            collisionStart: [],\n            collisionActive: [],\n            collisionEnd: []\n        }, options);\n    };\n\n    /**\n     * Updates pairs given a list of collisions.\n     * @method update\n     * @param {object} pairs\n     * @param {collision[]} collisions\n     * @param {number} timestamp\n     */\n    Pairs.update = function(pairs, collisions, timestamp) {\n        var pairUpdate = Pair.update,\n            pairCreate = Pair.create,\n            pairSetActive = Pair.setActive,\n            pairsTable = pairs.table,\n            pairsList = pairs.list,\n            pairsListLength = pairsList.length,\n            pairsListIndex = pairsListLength,\n            collisionStart = pairs.collisionStart,\n            collisionEnd = pairs.collisionEnd,\n            collisionActive = pairs.collisionActive,\n            collisionsLength = collisions.length,\n            collisionStartIndex = 0,\n            collisionEndIndex = 0,\n            collisionActiveIndex = 0,\n            collision,\n            pair,\n            i;\n\n        for (i = 0; i < collisionsLength; i++) {\n            collision = collisions[i];\n            pair = collision.pair;\n\n            if (pair) {\n                // pair already exists (but may or may not be active)\n                if (pair.isActive) {\n                    // pair exists and is active\n                    collisionActive[collisionActiveIndex++] = pair;\n                }\n\n                // update the pair\n                pairUpdate(pair, collision, timestamp);\n            } else {\n                // pair did not exist, create a new pair\n                pair = pairCreate(collision, timestamp);\n                pairsTable[pair.id] = pair;\n\n                // add the new pair\n                collisionStart[collisionStartIndex++] = pair;\n                pairsList[pairsListIndex++] = pair;\n            }\n        }\n\n        // find pairs that are no longer active\n        pairsListIndex = 0;\n        pairsListLength = pairsList.length;\n\n        for (i = 0; i < pairsListLength; i++) {\n            pair = pairsList[i];\n            \n            // pair is active if updated this timestep\n            if (pair.timeUpdated >= timestamp) {\n                // keep active pairs\n                pairsList[pairsListIndex++] = pair;\n            } else {\n                pairSetActive(pair, false, timestamp);\n\n                // keep inactive pairs if both bodies may be sleeping\n                if (pair.collision.bodyA.sleepCounter > 0 && pair.collision.bodyB.sleepCounter > 0) {\n                    pairsList[pairsListIndex++] = pair;\n                } else {\n                    // remove inactive pairs if either body awake\n                    collisionEnd[collisionEndIndex++] = pair;\n                    delete pairsTable[pair.id];\n                }\n            }\n        }\n\n        // update array lengths if changed\n        if (pairsList.length !== pairsListIndex) {\n            pairsList.length = pairsListIndex;\n        }\n\n        if (collisionStart.length !== collisionStartIndex) {\n            collisionStart.length = collisionStartIndex;\n        }\n\n        if (collisionEnd.length !== collisionEndIndex) {\n            collisionEnd.length = collisionEndIndex;\n        }\n\n        if (collisionActive.length !== collisionActiveIndex) {\n            collisionActive.length = collisionActiveIndex;\n        }\n    };\n\n    /**\n     * Clears the given pairs structure.\n     * @method clear\n     * @param {pairs} pairs\n     * @return {pairs} pairs\n     */\n    Pairs.clear = function(pairs) {\n        pairs.table = {};\n        pairs.list.length = 0;\n        pairs.collisionStart.length = 0;\n        pairs.collisionActive.length = 0;\n        pairs.collisionEnd.length = 0;\n        return pairs;\n    };\n\n})();\n\n\n/***/ }),\n/* 20 */\n/***/ (function(module, exports, __webpack_require__) {\n\nvar Matter = module.exports = __webpack_require__(21);\r\n\r\nMatter.Axes = __webpack_require__(11);\r\nMatter.Bodies = __webpack_require__(12);\r\nMatter.Body = __webpack_require__(4);\r\nMatter.Bounds = __webpack_require__(1);\r\nMatter.Collision = __webpack_require__(8);\r\nMatter.Common = __webpack_require__(0);\r\nMatter.Composite = __webpack_require__(6);\r\nMatter.Composites = __webpack_require__(22);\r\nMatter.Constraint = __webpack_require__(10);\r\nMatter.Contact = __webpack_require__(16);\r\nMatter.Detector = __webpack_require__(13);\r\nMatter.Engine = __webpack_require__(17);\r\nMatter.Events = __webpack_require__(5);\r\nMatter.Grid = __webpack_require__(23);\r\nMatter.Mouse = __webpack_require__(14);\r\nMatter.MouseConstraint = __webpack_require__(24);\r\nMatter.Pair = __webpack_require__(9);\r\nMatter.Pairs = __webpack_require__(19);\r\nMatter.Plugin = __webpack_require__(15);\r\nMatter.Query = __webpack_require__(25);\r\nMatter.Render = __webpack_require__(26);\r\nMatter.Resolver = __webpack_require__(18);\r\nMatter.Runner = __webpack_require__(27);\r\nMatter.SAT = __webpack_require__(28);\r\nMatter.Sleeping = __webpack_require__(7);\r\nMatter.Svg = __webpack_require__(29);\r\nMatter.Vector = __webpack_require__(2);\r\nMatter.Vertices = __webpack_require__(3);\r\nMatter.World = __webpack_require__(30);\r\n\r\n// temporary back compatibility\r\nMatter.Engine.run = Matter.Runner.run;\r\nMatter.Common.deprecated(Matter.Engine, 'run', 'Engine.run ➤ use Matter.Runner.run(engine) instead');\r\n\n\n/***/ }),\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\r\n* The `Matter` module is the top level namespace. It also includes a function for installing plugins on top of the library.\r\n*\r\n* @class Matter\r\n*/\r\n\r\nvar Matter = {};\r\n\r\nmodule.exports = Matter;\r\n\r\nvar Plugin = __webpack_require__(15);\r\nvar Common = __webpack_require__(0);\r\n\r\n(function() {\r\n\r\n    /**\r\n     * The library name.\r\n     * @property name\r\n     * @readOnly\r\n     * @type {String}\r\n     */\r\n    Matter.name = 'matter-js';\r\n\r\n    /**\r\n     * The library version.\r\n     * @property version\r\n     * @readOnly\r\n     * @type {String}\r\n     */\r\n    Matter.version =  true ? \"0.20.0\" : undefined;\r\n\r\n    /**\r\n     * A list of plugin dependencies to be installed. These are normally set and installed through `Matter.use`.\r\n     * Alternatively you may set `Matter.uses` manually and install them by calling `Plugin.use(Matter)`.\r\n     * @property uses\r\n     * @type {Array}\r\n     */\r\n    Matter.uses = [];\r\n\r\n    /**\r\n     * The plugins that have been installed through `Matter.Plugin.install`. Read only.\r\n     * @property used\r\n     * @readOnly\r\n     * @type {Array}\r\n     */\r\n    Matter.used = [];\r\n\r\n    /**\r\n     * Installs the given plugins on the `Matter` namespace.\r\n     * This is a short-hand for `Plugin.use`, see it for more information.\r\n     * Call this function once at the start of your code, with all of the plugins you wish to install as arguments.\r\n     * Avoid calling this function multiple times unless you intend to manually control installation order.\r\n     * @method use\r\n     * @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument).\r\n     */\r\n    Matter.use = function() {\r\n        Plugin.use(Matter, Array.prototype.slice.call(arguments));\r\n    };\r\n\r\n    /**\r\n     * Chains a function to excute before the original function on the given `path` relative to `Matter`.\r\n     * See also docs for `Common.chain`.\r\n     * @method before\r\n     * @param {string} path The path relative to `Matter`\r\n     * @param {function} func The function to chain before the original\r\n     * @return {function} The chained function that replaced the original\r\n     */\r\n    Matter.before = function(path, func) {\r\n        path = path.replace(/^Matter./, '');\r\n        return Common.chainPathBefore(Matter, path, func);\r\n    };\r\n\r\n    /**\r\n     * Chains a function to excute after the original function on the given `path` relative to `Matter`.\r\n     * See also docs for `Common.chain`.\r\n     * @method after\r\n     * @param {string} path The path relative to `Matter`\r\n     * @param {function} func The function to chain after the original\r\n     * @return {function} The chained function that replaced the original\r\n     */\r\n    Matter.after = function(path, func) {\r\n        path = path.replace(/^Matter./, '');\r\n        return Common.chainPathAfter(Matter, path, func);\r\n    };\r\n\r\n})();\r\n\n\n/***/ }),\n/* 22 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Composites` module contains factory methods for creating composite bodies\n* with commonly used configurations (such as stacks and chains).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Composites\n*/\n\nvar Composites = {};\n\nmodule.exports = Composites;\n\nvar Composite = __webpack_require__(6);\nvar Constraint = __webpack_require__(10);\nvar Common = __webpack_require__(0);\nvar Body = __webpack_require__(4);\nvar Bodies = __webpack_require__(12);\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Create a new composite containing bodies created in the callback in a grid arrangement.\n     * This function uses the body's bounds to prevent overlaps.\n     * @method stack\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {function} callback\n     * @return {composite} A new composite containing objects created in the callback\n     */\n    Composites.stack = function(x, y, columns, rows, columnGap, rowGap, callback) {\n        var stack = Composite.create({ label: 'Stack' }),\n            currentX = x,\n            currentY = y,\n            lastBody,\n            i = 0;\n\n        for (var row = 0; row < rows; row++) {\n            var maxHeight = 0;\n            \n            for (var column = 0; column < columns; column++) {\n                var body = callback(currentX, currentY, column, row, lastBody, i);\n                    \n                if (body) {\n                    var bodyHeight = body.bounds.max.y - body.bounds.min.y,\n                        bodyWidth = body.bounds.max.x - body.bounds.min.x; \n\n                    if (bodyHeight > maxHeight)\n                        maxHeight = bodyHeight;\n                    \n                    Body.translate(body, { x: bodyWidth * 0.5, y: bodyHeight * 0.5 });\n\n                    currentX = body.bounds.max.x + columnGap;\n\n                    Composite.addBody(stack, body);\n                    \n                    lastBody = body;\n                    i += 1;\n                } else {\n                    currentX += columnGap;\n                }\n            }\n            \n            currentY += maxHeight + rowGap;\n            currentX = x;\n        }\n\n        return stack;\n    };\n    \n    /**\n     * Chains all bodies in the given composite together using constraints.\n     * @method chain\n     * @param {composite} composite\n     * @param {number} xOffsetA\n     * @param {number} yOffsetA\n     * @param {number} xOffsetB\n     * @param {number} yOffsetB\n     * @param {object} options\n     * @return {composite} A new composite containing objects chained together with constraints\n     */\n    Composites.chain = function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) {\n        var bodies = composite.bodies;\n        \n        for (var i = 1; i < bodies.length; i++) {\n            var bodyA = bodies[i - 1],\n                bodyB = bodies[i],\n                bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y,\n                bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x, \n                bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y,\n                bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x;\n        \n            var defaults = {\n                bodyA: bodyA,\n                pointA: { x: bodyAWidth * xOffsetA, y: bodyAHeight * yOffsetA },\n                bodyB: bodyB,\n                pointB: { x: bodyBWidth * xOffsetB, y: bodyBHeight * yOffsetB }\n            };\n            \n            var constraint = Common.extend(defaults, options);\n        \n            Composite.addConstraint(composite, Constraint.create(constraint));\n        }\n\n        composite.label += ' Chain';\n        \n        return composite;\n    };\n\n    /**\n     * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces.\n     * @method mesh\n     * @param {composite} composite\n     * @param {number} columns\n     * @param {number} rows\n     * @param {boolean} crossBrace\n     * @param {object} options\n     * @return {composite} The composite containing objects meshed together with constraints\n     */\n    Composites.mesh = function(composite, columns, rows, crossBrace, options) {\n        var bodies = composite.bodies,\n            row,\n            col,\n            bodyA,\n            bodyB,\n            bodyC;\n        \n        for (row = 0; row < rows; row++) {\n            for (col = 1; col < columns; col++) {\n                bodyA = bodies[(col - 1) + (row * columns)];\n                bodyB = bodies[col + (row * columns)];\n                Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options)));\n            }\n\n            if (row > 0) {\n                for (col = 0; col < columns; col++) {\n                    bodyA = bodies[col + ((row - 1) * columns)];\n                    bodyB = bodies[col + (row * columns)];\n                    Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options)));\n\n                    if (crossBrace && col > 0) {\n                        bodyC = bodies[(col - 1) + ((row - 1) * columns)];\n                        Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options)));\n                    }\n\n                    if (crossBrace && col < columns - 1) {\n                        bodyC = bodies[(col + 1) + ((row - 1) * columns)];\n                        Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options)));\n                    }\n                }\n            }\n        }\n\n        composite.label += ' Mesh';\n        \n        return composite;\n    };\n    \n    /**\n     * Create a new composite containing bodies created in the callback in a pyramid arrangement.\n     * This function uses the body's bounds to prevent overlaps.\n     * @method pyramid\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {function} callback\n     * @return {composite} A new composite containing objects created in the callback\n     */\n    Composites.pyramid = function(x, y, columns, rows, columnGap, rowGap, callback) {\n        return Composites.stack(x, y, columns, rows, columnGap, rowGap, function(stackX, stackY, column, row, lastBody, i) {\n            var actualRows = Math.min(rows, Math.ceil(columns / 2)),\n                lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0;\n            \n            if (row > actualRows)\n                return;\n            \n            // reverse row order\n            row = actualRows - row;\n            \n            var start = row,\n                end = columns - 1 - row;\n\n            if (column < start || column > end)\n                return;\n            \n            // retroactively fix the first body's position, since width was unknown\n            if (i === 1) {\n                Body.translate(lastBody, { x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth, y: 0 });\n            }\n\n            var xOffset = lastBody ? column * lastBodyWidth : 0;\n            \n            return callback(x + xOffset + column * columnGap, stackY, column, row, lastBody, i);\n        });\n    };\n\n    /**\n     * This has now moved to the [newtonsCradle example](https://github.com/liabru/matter-js/blob/master/examples/newtonsCradle.js), follow that instead as this function is deprecated here.\n     * @deprecated moved to newtonsCradle example\n     * @method newtonsCradle\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} number\n     * @param {number} size\n     * @param {number} length\n     * @return {composite} A new composite newtonsCradle body\n     */\n    Composites.newtonsCradle = function(x, y, number, size, length) {\n        var newtonsCradle = Composite.create({ label: 'Newtons Cradle' });\n\n        for (var i = 0; i < number; i++) {\n            var separation = 1.9,\n                circle = Bodies.circle(x + i * (size * separation), y + length, size, \n                    { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 0.0001, slop: 1 }),\n                constraint = Constraint.create({ pointA: { x: x + i * (size * separation), y: y }, bodyB: circle });\n\n            Composite.addBody(newtonsCradle, circle);\n            Composite.addConstraint(newtonsCradle, constraint);\n        }\n\n        return newtonsCradle;\n    };\n\n    deprecated(Composites, 'newtonsCradle', 'Composites.newtonsCradle ➤ moved to newtonsCradle example');\n    \n    /**\n     * This has now moved to the [car example](https://github.com/liabru/matter-js/blob/master/examples/car.js), follow that instead as this function is deprecated here.\n     * @deprecated moved to car example\n     * @method car\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} width\n     * @param {number} height\n     * @param {number} wheelSize\n     * @return {composite} A new composite car body\n     */\n    Composites.car = function(x, y, width, height, wheelSize) {\n        var group = Body.nextGroup(true),\n            wheelBase = 20,\n            wheelAOffset = -width * 0.5 + wheelBase,\n            wheelBOffset = width * 0.5 - wheelBase,\n            wheelYOffset = 0;\n    \n        var car = Composite.create({ label: 'Car' }),\n            body = Bodies.rectangle(x, y, width, height, { \n                collisionFilter: {\n                    group: group\n                },\n                chamfer: {\n                    radius: height * 0.5\n                },\n                density: 0.0002\n            });\n    \n        var wheelA = Bodies.circle(x + wheelAOffset, y + wheelYOffset, wheelSize, { \n            collisionFilter: {\n                group: group\n            },\n            friction: 0.8\n        });\n                    \n        var wheelB = Bodies.circle(x + wheelBOffset, y + wheelYOffset, wheelSize, { \n            collisionFilter: {\n                group: group\n            },\n            friction: 0.8\n        });\n                    \n        var axelA = Constraint.create({\n            bodyB: body,\n            pointB: { x: wheelAOffset, y: wheelYOffset },\n            bodyA: wheelA,\n            stiffness: 1,\n            length: 0\n        });\n                        \n        var axelB = Constraint.create({\n            bodyB: body,\n            pointB: { x: wheelBOffset, y: wheelYOffset },\n            bodyA: wheelB,\n            stiffness: 1,\n            length: 0\n        });\n        \n        Composite.addBody(car, body);\n        Composite.addBody(car, wheelA);\n        Composite.addBody(car, wheelB);\n        Composite.addConstraint(car, axelA);\n        Composite.addConstraint(car, axelB);\n\n        return car;\n    };\n\n    deprecated(Composites, 'car', 'Composites.car ➤ moved to car example');\n\n    /**\n     * This has now moved to the [softBody example](https://github.com/liabru/matter-js/blob/master/examples/softBody.js)\n     * and the [cloth example](https://github.com/liabru/matter-js/blob/master/examples/cloth.js), follow those instead as this function is deprecated here.\n     * @deprecated moved to softBody and cloth examples\n     * @method softBody\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {boolean} crossBrace\n     * @param {number} particleRadius\n     * @param {} particleOptions\n     * @param {} constraintOptions\n     * @return {composite} A new composite softBody\n     */\n    Composites.softBody = function(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) {\n        particleOptions = Common.extend({ inertia: Infinity }, particleOptions);\n        constraintOptions = Common.extend({ stiffness: 0.2, render: { type: 'line', anchors: false } }, constraintOptions);\n\n        var softBody = Composites.stack(x, y, columns, rows, columnGap, rowGap, function(stackX, stackY) {\n            return Bodies.circle(stackX, stackY, particleRadius, particleOptions);\n        });\n\n        Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions);\n\n        softBody.label = 'Soft Body';\n\n        return softBody;\n    };\n\n    deprecated(Composites, 'softBody', 'Composites.softBody ➤ moved to softBody and cloth examples');\n})();\n\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* This module has now been replaced by `Matter.Detector`.\n*\n* All usage should be migrated to `Matter.Detector` or another alternative.\n* For back-compatibility purposes this module will remain for a short term and then later removed in a future release.\n*\n* The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures.\n*\n* @class Grid\n* @deprecated\n*/\n\nvar Grid = {};\n\nmodule.exports = Grid;\n\nvar Pair = __webpack_require__(9);\nvar Common = __webpack_require__(0);\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Creates a new grid.\n     * @deprecated replaced by Matter.Detector\n     * @method create\n     * @param {} options\n     * @return {grid} A new grid\n     */\n    Grid.create = function(options) {\n        var defaults = {\n            buckets: {},\n            pairs: {},\n            pairsList: [],\n            bucketWidth: 48,\n            bucketHeight: 48\n        };\n\n        return Common.extend(defaults, options);\n    };\n\n    /**\n     * The width of a single grid bucket.\n     *\n     * @property bucketWidth\n     * @type number\n     * @default 48\n     */\n\n    /**\n     * The height of a single grid bucket.\n     *\n     * @property bucketHeight\n     * @type number\n     * @default 48\n     */\n\n    /**\n     * Updates the grid.\n     * @deprecated replaced by Matter.Detector\n     * @method update\n     * @param {grid} grid\n     * @param {body[]} bodies\n     * @param {engine} engine\n     * @param {boolean} forceUpdate\n     */\n    Grid.update = function(grid, bodies, engine, forceUpdate) {\n        var i, col, row,\n            world = engine.world,\n            buckets = grid.buckets,\n            bucket,\n            bucketId,\n            gridChanged = false;\n\n        for (i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (body.isSleeping && !forceUpdate)\n                continue;\n\n            // temporary back compatibility bounds check\n            if (world.bounds && (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x\n                || body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y))\n                continue;\n\n            var newRegion = Grid._getRegion(grid, body);\n\n            // if the body has changed grid region\n            if (!body.region || newRegion.id !== body.region.id || forceUpdate) {\n\n                if (!body.region || forceUpdate)\n                    body.region = newRegion;\n\n                var union = Grid._regionUnion(newRegion, body.region);\n\n                // update grid buckets affected by region change\n                // iterate over the union of both regions\n                for (col = union.startCol; col <= union.endCol; col++) {\n                    for (row = union.startRow; row <= union.endRow; row++) {\n                        bucketId = Grid._getBucketId(col, row);\n                        bucket = buckets[bucketId];\n\n                        var isInsideNewRegion = (col >= newRegion.startCol && col <= newRegion.endCol\n                                                && row >= newRegion.startRow && row <= newRegion.endRow);\n\n                        var isInsideOldRegion = (col >= body.region.startCol && col <= body.region.endCol\n                                                && row >= body.region.startRow && row <= body.region.endRow);\n\n                        // remove from old region buckets\n                        if (!isInsideNewRegion && isInsideOldRegion) {\n                            if (isInsideOldRegion) {\n                                if (bucket)\n                                    Grid._bucketRemoveBody(grid, bucket, body);\n                            }\n                        }\n\n                        // add to new region buckets\n                        if (body.region === newRegion || (isInsideNewRegion && !isInsideOldRegion) || forceUpdate) {\n                            if (!bucket)\n                                bucket = Grid._createBucket(buckets, bucketId);\n                            Grid._bucketAddBody(grid, bucket, body);\n                        }\n                    }\n                }\n\n                // set the new region\n                body.region = newRegion;\n\n                // flag changes so we can update pairs\n                gridChanged = true;\n            }\n        }\n\n        // update pairs list only if pairs changed (i.e. a body changed region)\n        if (gridChanged)\n            grid.pairsList = Grid._createActivePairsList(grid);\n    };\n\n    deprecated(Grid, 'update', 'Grid.update ➤ replaced by Matter.Detector');\n\n    /**\n     * Clears the grid.\n     * @deprecated replaced by Matter.Detector\n     * @method clear\n     * @param {grid} grid\n     */\n    Grid.clear = function(grid) {\n        grid.buckets = {};\n        grid.pairs = {};\n        grid.pairsList = [];\n    };\n\n    deprecated(Grid, 'clear', 'Grid.clear ➤ replaced by Matter.Detector');\n\n    /**\n     * Finds the union of two regions.\n     * @method _regionUnion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} regionA\n     * @param {} regionB\n     * @return {} region\n     */\n    Grid._regionUnion = function(regionA, regionB) {\n        var startCol = Math.min(regionA.startCol, regionB.startCol),\n            endCol = Math.max(regionA.endCol, regionB.endCol),\n            startRow = Math.min(regionA.startRow, regionB.startRow),\n            endRow = Math.max(regionA.endRow, regionB.endRow);\n\n        return Grid._createRegion(startCol, endCol, startRow, endRow);\n    };\n\n    /**\n     * Gets the region a given body falls in for a given grid.\n     * @method _getRegion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} body\n     * @return {} region\n     */\n    Grid._getRegion = function(grid, body) {\n        var bounds = body.bounds,\n            startCol = Math.floor(bounds.min.x / grid.bucketWidth),\n            endCol = Math.floor(bounds.max.x / grid.bucketWidth),\n            startRow = Math.floor(bounds.min.y / grid.bucketHeight),\n            endRow = Math.floor(bounds.max.y / grid.bucketHeight);\n\n        return Grid._createRegion(startCol, endCol, startRow, endRow);\n    };\n\n    /**\n     * Creates a region.\n     * @method _createRegion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} startCol\n     * @param {} endCol\n     * @param {} startRow\n     * @param {} endRow\n     * @return {} region\n     */\n    Grid._createRegion = function(startCol, endCol, startRow, endRow) {\n        return { \n            id: startCol + ',' + endCol + ',' + startRow + ',' + endRow,\n            startCol: startCol, \n            endCol: endCol, \n            startRow: startRow, \n            endRow: endRow \n        };\n    };\n\n    /**\n     * Gets the bucket id at the given position.\n     * @method _getBucketId\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} column\n     * @param {} row\n     * @return {string} bucket id\n     */\n    Grid._getBucketId = function(column, row) {\n        return 'C' + column + 'R' + row;\n    };\n\n    /**\n     * Creates a bucket.\n     * @method _createBucket\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} buckets\n     * @param {} bucketId\n     * @return {} bucket\n     */\n    Grid._createBucket = function(buckets, bucketId) {\n        var bucket = buckets[bucketId] = [];\n        return bucket;\n    };\n\n    /**\n     * Adds a body to a bucket.\n     * @method _bucketAddBody\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} bucket\n     * @param {} body\n     */\n    Grid._bucketAddBody = function(grid, bucket, body) {\n        var gridPairs = grid.pairs,\n            pairId = Pair.id,\n            bucketLength = bucket.length,\n            i;\n\n        // add new pairs\n        for (i = 0; i < bucketLength; i++) {\n            var bodyB = bucket[i];\n\n            if (body.id === bodyB.id || (body.isStatic && bodyB.isStatic))\n                continue;\n\n            // keep track of the number of buckets the pair exists in\n            // important for Grid.update to work\n            var id = pairId(body, bodyB),\n                pair = gridPairs[id];\n\n            if (pair) {\n                pair[2] += 1;\n            } else {\n                gridPairs[id] = [body, bodyB, 1];\n            }\n        }\n\n        // add to bodies (after pairs, otherwise pairs with self)\n        bucket.push(body);\n    };\n\n    /**\n     * Removes a body from a bucket.\n     * @method _bucketRemoveBody\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} bucket\n     * @param {} body\n     */\n    Grid._bucketRemoveBody = function(grid, bucket, body) {\n        var gridPairs = grid.pairs,\n            pairId = Pair.id,\n            i;\n\n        // remove from bucket\n        bucket.splice(Common.indexOf(bucket, body), 1);\n\n        var bucketLength = bucket.length;\n\n        // update pair counts\n        for (i = 0; i < bucketLength; i++) {\n            // keep track of the number of buckets the pair exists in\n            // important for _createActivePairsList to work\n            var pair = gridPairs[pairId(body, bucket[i])];\n\n            if (pair)\n                pair[2] -= 1;\n        }\n    };\n\n    /**\n     * Generates a list of the active pairs in the grid.\n     * @method _createActivePairsList\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @return [] pairs\n     */\n    Grid._createActivePairsList = function(grid) {\n        var pair,\n            gridPairs = grid.pairs,\n            pairKeys = Common.keys(gridPairs),\n            pairKeysLength = pairKeys.length,\n            pairs = [],\n            k;\n\n        // iterate over grid.pairs\n        for (k = 0; k < pairKeysLength; k++) {\n            pair = gridPairs[pairKeys[k]];\n\n            // if pair exists in at least one bucket\n            // it is a pair that needs further collision testing so push it\n            if (pair[2] > 0) {\n                pairs.push(pair);\n            } else {\n                delete gridPairs[pairKeys[k]];\n            }\n        }\n\n        return pairs;\n    };\n    \n})();\n\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.MouseConstraint` module contains methods for creating mouse constraints.\n* Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class MouseConstraint\n*/\n\nvar MouseConstraint = {};\n\nmodule.exports = MouseConstraint;\n\nvar Vertices = __webpack_require__(3);\nvar Sleeping = __webpack_require__(7);\nvar Mouse = __webpack_require__(14);\nvar Events = __webpack_require__(5);\nvar Detector = __webpack_require__(13);\nvar Constraint = __webpack_require__(10);\nvar Composite = __webpack_require__(6);\nvar Common = __webpack_require__(0);\nvar Bounds = __webpack_require__(1);\n\n(function() {\n\n    /**\n     * Creates a new mouse constraint.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {engine} engine\n     * @param {} options\n     * @return {MouseConstraint} A new MouseConstraint\n     */\n    MouseConstraint.create = function(engine, options) {\n        var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null);\n\n        if (!mouse) {\n            if (engine && engine.render && engine.render.canvas) {\n                mouse = Mouse.create(engine.render.canvas);\n            } else if (options && options.element) {\n                mouse = Mouse.create(options.element);\n            } else {\n                mouse = Mouse.create();\n                Common.warn('MouseConstraint.create: options.mouse was undefined, options.element was undefined, may not function as expected');\n            }\n        }\n\n        var constraint = Constraint.create({ \n            label: 'Mouse Constraint',\n            pointA: mouse.position,\n            pointB: { x: 0, y: 0 },\n            length: 0.01, \n            stiffness: 0.1,\n            angularStiffness: 1,\n            render: {\n                strokeStyle: '#90EE90',\n                lineWidth: 3\n            }\n        });\n\n        var defaults = {\n            type: 'mouseConstraint',\n            mouse: mouse,\n            element: null,\n            body: null,\n            constraint: constraint,\n            collisionFilter: {\n                category: 0x0001,\n                mask: 0xFFFFFFFF,\n                group: 0\n            }\n        };\n\n        var mouseConstraint = Common.extend(defaults, options);\n\n        Events.on(engine, 'beforeUpdate', function() {\n            var allBodies = Composite.allBodies(engine.world);\n            MouseConstraint.update(mouseConstraint, allBodies);\n            MouseConstraint._triggerEvents(mouseConstraint);\n        });\n\n        return mouseConstraint;\n    };\n\n    /**\n     * Updates the given mouse constraint.\n     * @private\n     * @method update\n     * @param {MouseConstraint} mouseConstraint\n     * @param {body[]} bodies\n     */\n    MouseConstraint.update = function(mouseConstraint, bodies) {\n        var mouse = mouseConstraint.mouse,\n            constraint = mouseConstraint.constraint,\n            body = mouseConstraint.body;\n\n        if (mouse.button === 0) {\n            if (!constraint.bodyB) {\n                for (var i = 0; i < bodies.length; i++) {\n                    body = bodies[i];\n                    if (Bounds.contains(body.bounds, mouse.position) \n                            && Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) {\n                        for (var j = body.parts.length > 1 ? 1 : 0; j < body.parts.length; j++) {\n                            var part = body.parts[j];\n                            if (Vertices.contains(part.vertices, mouse.position)) {\n                                constraint.pointA = mouse.position;\n                                constraint.bodyB = mouseConstraint.body = body;\n                                constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y };\n                                constraint.angleB = body.angle;\n\n                                Sleeping.set(body, false);\n                                Events.trigger(mouseConstraint, 'startdrag', { mouse: mouse, body: body });\n\n                                break;\n                            }\n                        }\n                    }\n                }\n            } else {\n                Sleeping.set(constraint.bodyB, false);\n                constraint.pointA = mouse.position;\n            }\n        } else {\n            constraint.bodyB = mouseConstraint.body = null;\n            constraint.pointB = null;\n\n            if (body)\n                Events.trigger(mouseConstraint, 'enddrag', { mouse: mouse, body: body });\n        }\n    };\n\n    /**\n     * Triggers mouse constraint events.\n     * @method _triggerEvents\n     * @private\n     * @param {mouse} mouseConstraint\n     */\n    MouseConstraint._triggerEvents = function(mouseConstraint) {\n        var mouse = mouseConstraint.mouse,\n            mouseEvents = mouse.sourceEvents;\n\n        if (mouseEvents.mousemove)\n            Events.trigger(mouseConstraint, 'mousemove', { mouse: mouse });\n\n        if (mouseEvents.mousedown)\n            Events.trigger(mouseConstraint, 'mousedown', { mouse: mouse });\n\n        if (mouseEvents.mouseup)\n            Events.trigger(mouseConstraint, 'mouseup', { mouse: mouse });\n\n        // reset the mouse state ready for the next step\n        Mouse.clearSourceEvents(mouse);\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when the mouse has moved (or a touch moves) during the last step\n    *\n    * @event mousemove\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the mouse is down (or a touch has started) during the last step\n    *\n    * @event mousedown\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the mouse is up (or a touch has ended) during the last step\n    *\n    * @event mouseup\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the user starts dragging a body\n    *\n    * @event startdrag\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {body} event.body The body being dragged\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the user ends dragging a body\n    *\n    * @event enddrag\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {body} event.body The body that has stopped being dragged\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"constraint\"\n     * @readOnly\n     */\n\n    /**\n     * The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created.\n     *\n     * @property mouse\n     * @type mouse\n     * @default mouse\n     */\n\n    /**\n     * The `Body` that is currently being moved by the user, or `null` if no body.\n     *\n     * @property body\n     * @type body\n     * @default null\n     */\n\n    /**\n     * The `Constraint` object that is used to move the body during interaction.\n     *\n     * @property constraint\n     * @type constraint\n     */\n\n    /**\n     * An `Object` that specifies the collision filter properties.\n     * The collision filter allows the user to define which types of body this mouse constraint can interact with.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter\n     * @type object\n     */\n\n})();\n\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Query` module contains methods for performing collision queries.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Query\n*/\n\nvar Query = {};\n\nmodule.exports = Query;\n\nvar Vector = __webpack_require__(2);\nvar Collision = __webpack_require__(8);\nvar Bounds = __webpack_require__(1);\nvar Bodies = __webpack_require__(12);\nvar Vertices = __webpack_require__(3);\n\n(function() {\n\n    /**\n     * Returns a list of collisions between `body` and `bodies`.\n     * @method collides\n     * @param {body} body\n     * @param {body[]} bodies\n     * @return {collision[]} Collisions\n     */\n    Query.collides = function(body, bodies) {\n        var collisions = [],\n            bodiesLength = bodies.length,\n            bounds = body.bounds,\n            collides = Collision.collides,\n            overlaps = Bounds.overlaps;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var bodyA = bodies[i],\n                partsALength = bodyA.parts.length,\n                partsAStart = partsALength === 1 ? 0 : 1;\n            \n            if (overlaps(bodyA.bounds, bounds)) {\n                for (var j = partsAStart; j < partsALength; j++) {\n                    var part = bodyA.parts[j];\n\n                    if (overlaps(part.bounds, bounds)) {\n                        var collision = collides(part, body);\n\n                        if (collision) {\n                            collisions.push(collision);\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        return collisions;\n    };\n\n    /**\n     * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided.\n     * @method ray\n     * @param {body[]} bodies\n     * @param {vector} startPoint\n     * @param {vector} endPoint\n     * @param {number} [rayWidth]\n     * @return {collision[]} Collisions\n     */\n    Query.ray = function(bodies, startPoint, endPoint, rayWidth) {\n        rayWidth = rayWidth || 1e-100;\n\n        var rayAngle = Vector.angle(startPoint, endPoint),\n            rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)),\n            rayX = (endPoint.x + startPoint.x) * 0.5,\n            rayY = (endPoint.y + startPoint.y) * 0.5,\n            ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, { angle: rayAngle }),\n            collisions = Query.collides(ray, bodies);\n\n        for (var i = 0; i < collisions.length; i += 1) {\n            var collision = collisions[i];\n            collision.body = collision.bodyB = collision.bodyA;            \n        }\n\n        return collisions;\n    };\n\n    /**\n     * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies.\n     * @method region\n     * @param {body[]} bodies\n     * @param {bounds} bounds\n     * @param {bool} [outside=false]\n     * @return {body[]} The bodies matching the query\n     */\n    Query.region = function(bodies, bounds, outside) {\n        var result = [];\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                overlaps = Bounds.overlaps(body.bounds, bounds);\n            if ((overlaps && !outside) || (!overlaps && outside))\n                result.push(body);\n        }\n\n        return result;\n    };\n\n    /**\n     * Returns all bodies whose vertices contain the given point, from the given set of bodies.\n     * @method point\n     * @param {body[]} bodies\n     * @param {vector} point\n     * @return {body[]} The bodies matching the query\n     */\n    Query.point = function(bodies, point) {\n        var result = [];\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n            \n            if (Bounds.contains(body.bounds, point)) {\n                for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) {\n                    var part = body.parts[j];\n\n                    if (Bounds.contains(part.bounds, point)\n                        && Vertices.contains(part.vertices, point)) {\n                        result.push(body);\n                        break;\n                    }\n                }\n            }\n        }\n\n        return result;\n    };\n\n})();\n\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Render` module is a lightweight, optional utility which provides a simple canvas based renderer for visualising instances of `Matter.Engine`.\n* It is intended for development and debugging purposes, but may also be suitable for simple games.\n* It includes a number of drawing options including wireframe, vector with support for sprites and viewports.\n*\n* @class Render\n*/\n\nvar Render = {};\n\nmodule.exports = Render;\n\nvar Body = __webpack_require__(4);\nvar Common = __webpack_require__(0);\nvar Composite = __webpack_require__(6);\nvar Bounds = __webpack_require__(1);\nvar Events = __webpack_require__(5);\nvar Vector = __webpack_require__(2);\nvar Mouse = __webpack_require__(14);\n\n(function() {\n\n    var _requestAnimationFrame,\n        _cancelAnimationFrame;\n\n    if (typeof window !== 'undefined') {\n        _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame\n                                      || window.mozRequestAnimationFrame || window.msRequestAnimationFrame\n                                      || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); };\n\n        _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame\n                                      || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;\n    }\n\n    Render._goodFps = 30;\n    Render._goodDelta = 1000 / 60;\n\n    /**\n     * Creates a new renderer. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {object} [options]\n     * @return {render} A new renderer\n     */\n    Render.create = function(options) {\n        var defaults = {\n            engine: null,\n            element: null,\n            canvas: null,\n            mouse: null,\n            frameRequestId: null,\n            timing: {\n                historySize: 60,\n                delta: 0,\n                deltaHistory: [],\n                lastTime: 0,\n                lastTimestamp: 0,\n                lastElapsed: 0,\n                timestampElapsed: 0,\n                timestampElapsedHistory: [],\n                engineDeltaHistory: [],\n                engineElapsedHistory: [],\n                engineUpdatesHistory: [],\n                elapsedHistory: []\n            },\n            options: {\n                width: 800,\n                height: 600,\n                pixelRatio: 1,\n                background: '#14151f',\n                wireframeBackground: '#14151f',\n                wireframeStrokeStyle: '#bbb',\n                hasBounds: !!options.bounds,\n                enabled: true,\n                wireframes: true,\n                showSleeping: true,\n                showDebug: false,\n                showStats: false,\n                showPerformance: false,\n                showBounds: false,\n                showVelocity: false,\n                showCollisions: false,\n                showSeparations: false,\n                showAxes: false,\n                showPositions: false,\n                showAngleIndicator: false,\n                showIds: false,\n                showVertexNumbers: false,\n                showConvexHulls: false,\n                showInternalEdges: false,\n                showMousePosition: false\n            }\n        };\n\n        var render = Common.extend(defaults, options);\n\n        if (render.canvas) {\n            render.canvas.width = render.options.width || render.canvas.width;\n            render.canvas.height = render.options.height || render.canvas.height;\n        }\n\n        render.mouse = options.mouse;\n        render.engine = options.engine;\n        render.canvas = render.canvas || _createCanvas(render.options.width, render.options.height);\n        render.context = render.canvas.getContext('2d');\n        render.textures = {};\n\n        render.bounds = render.bounds || {\n            min: {\n                x: 0,\n                y: 0\n            },\n            max: {\n                x: render.canvas.width,\n                y: render.canvas.height\n            }\n        };\n\n        // for temporary back compatibility only\n        render.controller = Render;\n        render.options.showBroadphase = false;\n\n        if (render.options.pixelRatio !== 1) {\n            Render.setPixelRatio(render, render.options.pixelRatio);\n        }\n\n        if (Common.isElement(render.element)) {\n            render.element.appendChild(render.canvas);\n        }\n\n        return render;\n    };\n\n    /**\n     * Continuously updates the render canvas on the `requestAnimationFrame` event.\n     * @method run\n     * @param {render} render\n     */\n    Render.run = function(render) {\n        (function loop(time){\n            render.frameRequestId = _requestAnimationFrame(loop);\n            \n            _updateTiming(render, time);\n\n            Render.world(render, time);\n\n            render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n\n            if (render.options.showStats || render.options.showDebug) {\n                Render.stats(render, render.context, time);\n            }\n\n            if (render.options.showPerformance || render.options.showDebug) {\n                Render.performance(render, render.context, time);\n            }\n\n            render.context.setTransform(1, 0, 0, 1, 0, 0);\n        })();\n    };\n\n    /**\n     * Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop.\n     * @method stop\n     * @param {render} render\n     */\n    Render.stop = function(render) {\n        _cancelAnimationFrame(render.frameRequestId);\n    };\n\n    /**\n     * Sets the pixel ratio of the renderer and updates the canvas.\n     * To automatically detect the correct ratio, pass the string `'auto'` for `pixelRatio`.\n     * @method setPixelRatio\n     * @param {render} render\n     * @param {number} pixelRatio\n     */\n    Render.setPixelRatio = function(render, pixelRatio) {\n        var options = render.options,\n            canvas = render.canvas;\n\n        if (pixelRatio === 'auto') {\n            pixelRatio = _getPixelRatio(canvas);\n        }\n\n        options.pixelRatio = pixelRatio;\n        canvas.setAttribute('data-pixel-ratio', pixelRatio);\n        canvas.width = options.width * pixelRatio;\n        canvas.height = options.height * pixelRatio;\n        canvas.style.width = options.width + 'px';\n        canvas.style.height = options.height + 'px';\n    };\n\n    /**\n     * Sets the render `width` and `height`.\n     * \n     * Updates the canvas accounting for `render.options.pixelRatio`.  \n     * \n     * Updates the bottom right render bound `render.bounds.max` relative to the provided `width` and `height`.\n     * The top left render bound `render.bounds.min` isn't changed.\n     * \n     * Follow this call with `Render.lookAt` if you need to change the render bounds.\n     * \n     * See also `Render.setPixelRatio`.\n     * @method setSize\n     * @param {render} render\n     * @param {number} width The width (in CSS pixels)\n     * @param {number} height The height (in CSS pixels)\n     */\n    Render.setSize = function(render, width, height) {\n        render.options.width = width;\n        render.options.height = height;\n        render.bounds.max.x = render.bounds.min.x + width;\n        render.bounds.max.y = render.bounds.min.y + height;\n\n        if (render.options.pixelRatio !== 1) {\n            Render.setPixelRatio(render, render.options.pixelRatio);\n        } else {\n            render.canvas.width = width;\n            render.canvas.height = height;\n        }\n    };\n\n    /**\n     * Positions and sizes the viewport around the given object bounds.\n     * Objects must have at least one of the following properties:\n     * - `object.bounds`\n     * - `object.position`\n     * - `object.min` and `object.max`\n     * - `object.x` and `object.y`\n     * @method lookAt\n     * @param {render} render\n     * @param {object[]} objects\n     * @param {vector} [padding]\n     * @param {bool} [center=true]\n     */\n    Render.lookAt = function(render, objects, padding, center) {\n        center = typeof center !== 'undefined' ? center : true;\n        objects = Common.isArray(objects) ? objects : [objects];\n        padding = padding || {\n            x: 0,\n            y: 0\n        };\n\n        // find bounds of all objects\n        var bounds = {\n            min: { x: Infinity, y: Infinity },\n            max: { x: -Infinity, y: -Infinity }\n        };\n\n        for (var i = 0; i < objects.length; i += 1) {\n            var object = objects[i],\n                min = object.bounds ? object.bounds.min : (object.min || object.position || object),\n                max = object.bounds ? object.bounds.max : (object.max || object.position || object);\n\n            if (min && max) {\n                if (min.x < bounds.min.x)\n                    bounds.min.x = min.x;\n\n                if (max.x > bounds.max.x)\n                    bounds.max.x = max.x;\n\n                if (min.y < bounds.min.y)\n                    bounds.min.y = min.y;\n\n                if (max.y > bounds.max.y)\n                    bounds.max.y = max.y;\n            }\n        }\n\n        // find ratios\n        var width = (bounds.max.x - bounds.min.x) + 2 * padding.x,\n            height = (bounds.max.y - bounds.min.y) + 2 * padding.y,\n            viewHeight = render.canvas.height,\n            viewWidth = render.canvas.width,\n            outerRatio = viewWidth / viewHeight,\n            innerRatio = width / height,\n            scaleX = 1,\n            scaleY = 1;\n\n        // find scale factor\n        if (innerRatio > outerRatio) {\n            scaleY = innerRatio / outerRatio;\n        } else {\n            scaleX = outerRatio / innerRatio;\n        }\n\n        // enable bounds\n        render.options.hasBounds = true;\n\n        // position and size\n        render.bounds.min.x = bounds.min.x;\n        render.bounds.max.x = bounds.min.x + width * scaleX;\n        render.bounds.min.y = bounds.min.y;\n        render.bounds.max.y = bounds.min.y + height * scaleY;\n\n        // center\n        if (center) {\n            render.bounds.min.x += width * 0.5 - (width * scaleX) * 0.5;\n            render.bounds.max.x += width * 0.5 - (width * scaleX) * 0.5;\n            render.bounds.min.y += height * 0.5 - (height * scaleY) * 0.5;\n            render.bounds.max.y += height * 0.5 - (height * scaleY) * 0.5;\n        }\n\n        // padding\n        render.bounds.min.x -= padding.x;\n        render.bounds.max.x -= padding.x;\n        render.bounds.min.y -= padding.y;\n        render.bounds.max.y -= padding.y;\n\n        // update mouse\n        if (render.mouse) {\n            Mouse.setScale(render.mouse, {\n                x: (render.bounds.max.x - render.bounds.min.x) / render.canvas.width,\n                y: (render.bounds.max.y - render.bounds.min.y) / render.canvas.height\n            });\n\n            Mouse.setOffset(render.mouse, render.bounds.min);\n        }\n    };\n\n    /**\n     * Applies viewport transforms based on `render.bounds` to a render context.\n     * @method startViewTransform\n     * @param {render} render\n     */\n    Render.startViewTransform = function(render) {\n        var boundsWidth = render.bounds.max.x - render.bounds.min.x,\n            boundsHeight = render.bounds.max.y - render.bounds.min.y,\n            boundsScaleX = boundsWidth / render.options.width,\n            boundsScaleY = boundsHeight / render.options.height;\n\n        render.context.setTransform(\n            render.options.pixelRatio / boundsScaleX, 0, 0, \n            render.options.pixelRatio / boundsScaleY, 0, 0\n        );\n        \n        render.context.translate(-render.bounds.min.x, -render.bounds.min.y);\n    };\n\n    /**\n     * Resets all transforms on the render context.\n     * @method endViewTransform\n     * @param {render} render\n     */\n    Render.endViewTransform = function(render) {\n        render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n    };\n\n    /**\n     * Renders the given `engine`'s `Matter.World` object.\n     * This is the entry point for all rendering and should be called every time the scene changes.\n     * @method world\n     * @param {render} render\n     */\n    Render.world = function(render, time) {\n        var startTime = Common.now(),\n            engine = render.engine,\n            world = engine.world,\n            canvas = render.canvas,\n            context = render.context,\n            options = render.options,\n            timing = render.timing;\n\n        var allBodies = Composite.allBodies(world),\n            allConstraints = Composite.allConstraints(world),\n            background = options.wireframes ? options.wireframeBackground : options.background,\n            bodies = [],\n            constraints = [],\n            i;\n\n        var event = {\n            timestamp: engine.timing.timestamp\n        };\n\n        Events.trigger(render, 'beforeRender', event);\n\n        // apply background if it has changed\n        if (render.currentBackground !== background)\n            _applyBackground(render, background);\n\n        // clear the canvas with a transparent fill, to allow the canvas background to show\n        context.globalCompositeOperation = 'source-in';\n        context.fillStyle = \"transparent\";\n        context.fillRect(0, 0, canvas.width, canvas.height);\n        context.globalCompositeOperation = 'source-over';\n\n        // handle bounds\n        if (options.hasBounds) {\n            // filter out bodies that are not in view\n            for (i = 0; i < allBodies.length; i++) {\n                var body = allBodies[i];\n                if (Bounds.overlaps(body.bounds, render.bounds))\n                    bodies.push(body);\n            }\n\n            // filter out constraints that are not in view\n            for (i = 0; i < allConstraints.length; i++) {\n                var constraint = allConstraints[i],\n                    bodyA = constraint.bodyA,\n                    bodyB = constraint.bodyB,\n                    pointAWorld = constraint.pointA,\n                    pointBWorld = constraint.pointB;\n\n                if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);\n                if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);\n\n                if (!pointAWorld || !pointBWorld)\n                    continue;\n\n                if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))\n                    constraints.push(constraint);\n            }\n\n            // transform the view\n            Render.startViewTransform(render);\n\n            // update mouse\n            if (render.mouse) {\n                Mouse.setScale(render.mouse, {\n                    x: (render.bounds.max.x - render.bounds.min.x) / render.options.width,\n                    y: (render.bounds.max.y - render.bounds.min.y) / render.options.height\n                });\n\n                Mouse.setOffset(render.mouse, render.bounds.min);\n            }\n        } else {\n            constraints = allConstraints;\n            bodies = allBodies;\n\n            if (render.options.pixelRatio !== 1) {\n                render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n            }\n        }\n\n        if (!options.wireframes || (engine.enableSleeping && options.showSleeping)) {\n            // fully featured rendering of bodies\n            Render.bodies(render, bodies, context);\n        } else {\n            if (options.showConvexHulls)\n                Render.bodyConvexHulls(render, bodies, context);\n\n            // optimised method for wireframes only\n            Render.bodyWireframes(render, bodies, context);\n        }\n\n        if (options.showBounds)\n            Render.bodyBounds(render, bodies, context);\n\n        if (options.showAxes || options.showAngleIndicator)\n            Render.bodyAxes(render, bodies, context);\n\n        if (options.showPositions)\n            Render.bodyPositions(render, bodies, context);\n\n        if (options.showVelocity)\n            Render.bodyVelocity(render, bodies, context);\n\n        if (options.showIds)\n            Render.bodyIds(render, bodies, context);\n\n        if (options.showSeparations)\n            Render.separations(render, engine.pairs.list, context);\n\n        if (options.showCollisions)\n            Render.collisions(render, engine.pairs.list, context);\n\n        if (options.showVertexNumbers)\n            Render.vertexNumbers(render, bodies, context);\n\n        if (options.showMousePosition)\n            Render.mousePosition(render, render.mouse, context);\n\n        Render.constraints(constraints, context);\n\n        if (options.hasBounds) {\n            // revert view transforms\n            Render.endViewTransform(render);\n        }\n\n        Events.trigger(render, 'afterRender', event);\n\n        // log the time elapsed computing this update\n        timing.lastElapsed = Common.now() - startTime;\n    };\n\n    /**\n     * Renders statistics about the engine and world useful for debugging.\n     * @private\n     * @method stats\n     * @param {render} render\n     * @param {RenderingContext} context\n     * @param {Number} time\n     */\n    Render.stats = function(render, context, time) {\n        var engine = render.engine,\n            world = engine.world,\n            bodies = Composite.allBodies(world),\n            parts = 0,\n            width = 55,\n            height = 44,\n            x = 0,\n            y = 0;\n        \n        // count parts\n        for (var i = 0; i < bodies.length; i += 1) {\n            parts += bodies[i].parts.length;\n        }\n\n        // sections\n        var sections = {\n            'Part': parts,\n            'Body': bodies.length,\n            'Cons': Composite.allConstraints(world).length,\n            'Comp': Composite.allComposites(world).length,\n            'Pair': engine.pairs.list.length\n        };\n\n        // background\n        context.fillStyle = '#0e0f19';\n        context.fillRect(x, y, width * 5.5, height);\n\n        context.font = '12px Arial';\n        context.textBaseline = 'top';\n        context.textAlign = 'right';\n\n        // sections\n        for (var key in sections) {\n            var section = sections[key];\n            // label\n            context.fillStyle = '#aaa';\n            context.fillText(key, x + width, y + 8);\n\n            // value\n            context.fillStyle = '#eee';\n            context.fillText(section, x + width, y + 26);\n\n            x += width;\n        }\n    };\n\n    /**\n     * Renders engine and render performance information.\n     * @private\n     * @method performance\n     * @param {render} render\n     * @param {RenderingContext} context\n     */\n    Render.performance = function(render, context) {\n        var engine = render.engine,\n            timing = render.timing,\n            deltaHistory = timing.deltaHistory,\n            elapsedHistory = timing.elapsedHistory,\n            timestampElapsedHistory = timing.timestampElapsedHistory,\n            engineDeltaHistory = timing.engineDeltaHistory,\n            engineUpdatesHistory = timing.engineUpdatesHistory,\n            engineElapsedHistory = timing.engineElapsedHistory,\n            lastEngineUpdatesPerFrame = engine.timing.lastUpdatesPerFrame,\n            lastEngineDelta = engine.timing.lastDelta;\n        \n        var deltaMean = _mean(deltaHistory),\n            elapsedMean = _mean(elapsedHistory),\n            engineDeltaMean = _mean(engineDeltaHistory),\n            engineUpdatesMean = _mean(engineUpdatesHistory),\n            engineElapsedMean = _mean(engineElapsedHistory),\n            timestampElapsedMean = _mean(timestampElapsedHistory),\n            rateMean = (timestampElapsedMean / deltaMean) || 0,\n            neededUpdatesPerFrame = Math.round(deltaMean / lastEngineDelta),\n            fps = (1000 / deltaMean) || 0;\n\n        var graphHeight = 4,\n            gap = 12,\n            width = 60,\n            height = 34,\n            x = 10,\n            y = 69;\n\n        // background\n        context.fillStyle = '#0e0f19';\n        context.fillRect(0, 50, gap * 5 + width * 6 + 22, height);\n\n        // show FPS\n        Render.status(\n            context, x, y, width, graphHeight, deltaHistory.length, \n            Math.round(fps) + ' fps', \n            fps / Render._goodFps,\n            function(i) { return (deltaHistory[i] / deltaMean) - 1; }\n        );\n\n        // show engine delta\n        Render.status(\n            context, x + gap + width, y, width, graphHeight, engineDeltaHistory.length,\n            lastEngineDelta.toFixed(2) + ' dt', \n            Render._goodDelta / lastEngineDelta,\n            function(i) { return (engineDeltaHistory[i] / engineDeltaMean) - 1; }\n        );\n\n        // show engine updates per frame\n        Render.status(\n            context, x + (gap + width) * 2, y, width, graphHeight, engineUpdatesHistory.length,\n            lastEngineUpdatesPerFrame + ' upf', \n            Math.pow(Common.clamp((engineUpdatesMean / neededUpdatesPerFrame) || 1, 0, 1), 4),\n            function(i) { return (engineUpdatesHistory[i] / engineUpdatesMean) - 1; }\n        );\n\n        // show engine update time\n        Render.status(\n            context, x + (gap + width) * 3, y, width, graphHeight, engineElapsedHistory.length,\n            engineElapsedMean.toFixed(2) + ' ut', \n            1 - (lastEngineUpdatesPerFrame * engineElapsedMean / Render._goodFps),\n            function(i) { return (engineElapsedHistory[i] / engineElapsedMean) - 1; }\n        );\n\n        // show render time\n        Render.status(\n            context, x + (gap + width) * 4, y, width, graphHeight, elapsedHistory.length,\n            elapsedMean.toFixed(2) + ' rt', \n            1 - (elapsedMean / Render._goodFps),\n            function(i) { return (elapsedHistory[i] / elapsedMean) - 1; }\n        );\n\n        // show effective speed\n        Render.status(\n            context, x + (gap + width) * 5, y, width, graphHeight, timestampElapsedHistory.length, \n            rateMean.toFixed(2) + ' x', \n            rateMean * rateMean * rateMean,\n            function(i) { return (((timestampElapsedHistory[i] / deltaHistory[i]) / rateMean) || 0) - 1; }\n        );\n    };\n\n    /**\n     * Renders a label, indicator and a chart.\n     * @private\n     * @method status\n     * @param {RenderingContext} context\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {number} count\n     * @param {string} label\n     * @param {string} indicator\n     * @param {function} plotY\n     */\n    Render.status = function(context, x, y, width, height, count, label, indicator, plotY) {\n        // background\n        context.strokeStyle = '#888';\n        context.fillStyle = '#444';\n        context.lineWidth = 1;\n        context.fillRect(x, y + 7, width, 1);\n\n        // chart\n        context.beginPath();\n        context.moveTo(x, y + 7 - height * Common.clamp(0.4 * plotY(0), -2, 2));\n        for (var i = 0; i < width; i += 1) {\n            context.lineTo(x + i, y + 7 - (i < count ? height * Common.clamp(0.4 * plotY(i), -2, 2) : 0));\n        }\n        context.stroke();\n\n        // indicator\n        context.fillStyle = 'hsl(' + Common.clamp(25 + 95 * indicator, 0, 120) + ',100%,60%)';\n        context.fillRect(x, y - 7, 4, 4);\n\n        // label\n        context.font = '12px Arial';\n        context.textBaseline = 'middle';\n        context.textAlign = 'right';\n        context.fillStyle = '#eee';\n        context.fillText(label, x + width, y - 5);\n    };\n\n    /**\n     * Description\n     * @private\n     * @method constraints\n     * @param {constraint[]} constraints\n     * @param {RenderingContext} context\n     */\n    Render.constraints = function(constraints, context) {\n        var c = context;\n\n        for (var i = 0; i < constraints.length; i++) {\n            var constraint = constraints[i];\n\n            if (!constraint.render.visible || !constraint.pointA || !constraint.pointB)\n                continue;\n\n            var bodyA = constraint.bodyA,\n                bodyB = constraint.bodyB,\n                start,\n                end;\n\n            if (bodyA) {\n                start = Vector.add(bodyA.position, constraint.pointA);\n            } else {\n                start = constraint.pointA;\n            }\n\n            if (constraint.render.type === 'pin') {\n                c.beginPath();\n                c.arc(start.x, start.y, 3, 0, 2 * Math.PI);\n                c.closePath();\n            } else {\n                if (bodyB) {\n                    end = Vector.add(bodyB.position, constraint.pointB);\n                } else {\n                    end = constraint.pointB;\n                }\n\n                c.beginPath();\n                c.moveTo(start.x, start.y);\n\n                if (constraint.render.type === 'spring') {\n                    var delta = Vector.sub(end, start),\n                        normal = Vector.perp(Vector.normalise(delta)),\n                        coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)),\n                        offset;\n\n                    for (var j = 1; j < coils; j += 1) {\n                        offset = j % 2 === 0 ? 1 : -1;\n\n                        c.lineTo(\n                            start.x + delta.x * (j / coils) + normal.x * offset * 4,\n                            start.y + delta.y * (j / coils) + normal.y * offset * 4\n                        );\n                    }\n                }\n\n                c.lineTo(end.x, end.y);\n            }\n\n            if (constraint.render.lineWidth) {\n                c.lineWidth = constraint.render.lineWidth;\n                c.strokeStyle = constraint.render.strokeStyle;\n                c.stroke();\n            }\n\n            if (constraint.render.anchors) {\n                c.fillStyle = constraint.render.strokeStyle;\n                c.beginPath();\n                c.arc(start.x, start.y, 3, 0, 2 * Math.PI);\n                c.arc(end.x, end.y, 3, 0, 2 * Math.PI);\n                c.closePath();\n                c.fill();\n            }\n        }\n    };\n\n    /**\n     * Description\n     * @private\n     * @method bodies\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodies = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            showInternalEdges = options.showInternalEdges || !options.wireframes,\n            body,\n            part,\n            i,\n            k;\n\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n\n                if (!part.render.visible)\n                    continue;\n\n                if (options.showSleeping && body.isSleeping) {\n                    c.globalAlpha = 0.5 * part.render.opacity;\n                } else if (part.render.opacity !== 1) {\n                    c.globalAlpha = part.render.opacity;\n                }\n\n                if (part.render.sprite && part.render.sprite.texture && !options.wireframes) {\n                    // part sprite\n                    var sprite = part.render.sprite,\n                        texture = _getTexture(render, sprite.texture);\n\n                    c.translate(part.position.x, part.position.y);\n                    c.rotate(part.angle);\n\n                    c.drawImage(\n                        texture,\n                        texture.width * -sprite.xOffset * sprite.xScale,\n                        texture.height * -sprite.yOffset * sprite.yScale,\n                        texture.width * sprite.xScale,\n                        texture.height * sprite.yScale\n                    );\n\n                    // revert translation, hopefully faster than save / restore\n                    c.rotate(-part.angle);\n                    c.translate(-part.position.x, -part.position.y);\n                } else {\n                    // part polygon\n                    if (part.circleRadius) {\n                        c.beginPath();\n                        c.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI);\n                    } else {\n                        c.beginPath();\n                        c.moveTo(part.vertices[0].x, part.vertices[0].y);\n\n                        for (var j = 1; j < part.vertices.length; j++) {\n                            if (!part.vertices[j - 1].isInternal || showInternalEdges) {\n                                c.lineTo(part.vertices[j].x, part.vertices[j].y);\n                            } else {\n                                c.moveTo(part.vertices[j].x, part.vertices[j].y);\n                            }\n\n                            if (part.vertices[j].isInternal && !showInternalEdges) {\n                                c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);\n                            }\n                        }\n\n                        c.lineTo(part.vertices[0].x, part.vertices[0].y);\n                        c.closePath();\n                    }\n\n                    if (!options.wireframes) {\n                        c.fillStyle = part.render.fillStyle;\n\n                        if (part.render.lineWidth) {\n                            c.lineWidth = part.render.lineWidth;\n                            c.strokeStyle = part.render.strokeStyle;\n                            c.stroke();\n                        }\n\n                        c.fill();\n                    } else {\n                        c.lineWidth = 1;\n                        c.strokeStyle = render.options.wireframeStrokeStyle;\n                        c.stroke();\n                    }\n                }\n\n                c.globalAlpha = 1;\n            }\n        }\n    };\n\n    /**\n     * Optimised method for drawing body wireframes in one pass\n     * @private\n     * @method bodyWireframes\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyWireframes = function(render, bodies, context) {\n        var c = context,\n            showInternalEdges = render.options.showInternalEdges,\n            body,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        // render all bodies\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n\n                c.moveTo(part.vertices[0].x, part.vertices[0].y);\n\n                for (j = 1; j < part.vertices.length; j++) {\n                    if (!part.vertices[j - 1].isInternal || showInternalEdges) {\n                        c.lineTo(part.vertices[j].x, part.vertices[j].y);\n                    } else {\n                        c.moveTo(part.vertices[j].x, part.vertices[j].y);\n                    }\n\n                    if (part.vertices[j].isInternal && !showInternalEdges) {\n                        c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);\n                    }\n                }\n\n                c.lineTo(part.vertices[0].x, part.vertices[0].y);\n            }\n        }\n\n        c.lineWidth = 1;\n        c.strokeStyle = render.options.wireframeStrokeStyle;\n        c.stroke();\n    };\n\n    /**\n     * Optimised method for drawing body convex hull wireframes in one pass\n     * @private\n     * @method bodyConvexHulls\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyConvexHulls = function(render, bodies, context) {\n        var c = context,\n            body,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        // render convex hulls\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible || body.parts.length === 1)\n                continue;\n\n            c.moveTo(body.vertices[0].x, body.vertices[0].y);\n\n            for (j = 1; j < body.vertices.length; j++) {\n                c.lineTo(body.vertices[j].x, body.vertices[j].y);\n            }\n\n            c.lineTo(body.vertices[0].x, body.vertices[0].y);\n        }\n\n        c.lineWidth = 1;\n        c.strokeStyle = 'rgba(255,255,255,0.2)';\n        c.stroke();\n    };\n\n    /**\n     * Renders body vertex numbers.\n     * @private\n     * @method vertexNumbers\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.vertexNumbers = function(render, bodies, context) {\n        var c = context,\n            i,\n            j,\n            k;\n\n        for (i = 0; i < bodies.length; i++) {\n            var parts = bodies[i].parts;\n            for (k = parts.length > 1 ? 1 : 0; k < parts.length; k++) {\n                var part = parts[k];\n                for (j = 0; j < part.vertices.length; j++) {\n                    c.fillStyle = 'rgba(255,255,255,0.2)';\n                    c.fillText(i + '_' + j, part.position.x + (part.vertices[j].x - part.position.x) * 0.8, part.position.y + (part.vertices[j].y - part.position.y) * 0.8);\n                }\n            }\n        }\n    };\n\n    /**\n     * Renders mouse position.\n     * @private\n     * @method mousePosition\n     * @param {render} render\n     * @param {mouse} mouse\n     * @param {RenderingContext} context\n     */\n    Render.mousePosition = function(render, mouse, context) {\n        var c = context;\n        c.fillStyle = 'rgba(255,255,255,0.8)';\n        c.fillText(mouse.position.x + '  ' + mouse.position.y, mouse.position.x + 5, mouse.position.y - 5);\n    };\n\n    /**\n     * Draws body bounds\n     * @private\n     * @method bodyBounds\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyBounds = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options;\n\n        c.beginPath();\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (body.render.visible) {\n                var parts = bodies[i].parts;\n                for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    var part = parts[j];\n                    c.rect(part.bounds.min.x, part.bounds.min.y, part.bounds.max.x - part.bounds.min.x, part.bounds.max.y - part.bounds.min.y);\n                }\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,255,255,0.08)';\n        } else {\n            c.strokeStyle = 'rgba(0,0,0,0.1)';\n        }\n\n        c.lineWidth = 1;\n        c.stroke();\n    };\n\n    /**\n     * Draws body angle indicators and axes\n     * @private\n     * @method bodyAxes\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyAxes = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        for (i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                parts = body.parts;\n\n            if (!body.render.visible)\n                continue;\n\n            if (options.showAxes) {\n                // render all axes\n                for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    part = parts[j];\n                    for (k = 0; k < part.axes.length; k++) {\n                        var axis = part.axes[k];\n                        c.moveTo(part.position.x, part.position.y);\n                        c.lineTo(part.position.x + axis.x * 20, part.position.y + axis.y * 20);\n                    }\n                }\n            } else {\n                for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    part = parts[j];\n                    for (k = 0; k < part.axes.length; k++) {\n                        // render a single axis indicator\n                        c.moveTo(part.position.x, part.position.y);\n                        c.lineTo((part.vertices[0].x + part.vertices[part.vertices.length-1].x) / 2,\n                            (part.vertices[0].y + part.vertices[part.vertices.length-1].y) / 2);\n                    }\n                }\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'indianred';\n            c.lineWidth = 1;\n        } else {\n            c.strokeStyle = 'rgba(255, 255, 255, 0.4)';\n            c.globalCompositeOperation = 'overlay';\n            c.lineWidth = 2;\n        }\n\n        c.stroke();\n        c.globalCompositeOperation = 'source-over';\n    };\n\n    /**\n     * Draws body positions\n     * @private\n     * @method bodyPositions\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyPositions = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            body,\n            part,\n            i,\n            k;\n\n        c.beginPath();\n\n        // render current positions\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n                c.arc(part.position.x, part.position.y, 3, 0, 2 * Math.PI, false);\n                c.closePath();\n            }\n        }\n\n        if (options.wireframes) {\n            c.fillStyle = 'indianred';\n        } else {\n            c.fillStyle = 'rgba(0,0,0,0.5)';\n        }\n        c.fill();\n\n        c.beginPath();\n\n        // render previous positions\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n            if (body.render.visible) {\n                c.arc(body.positionPrev.x, body.positionPrev.y, 2, 0, 2 * Math.PI, false);\n                c.closePath();\n            }\n        }\n\n        c.fillStyle = 'rgba(255,165,0,0.8)';\n        c.fill();\n    };\n\n    /**\n     * Draws body velocity\n     * @private\n     * @method bodyVelocity\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyVelocity = function(render, bodies, context) {\n        var c = context;\n\n        c.beginPath();\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            var velocity = Body.getVelocity(body);\n\n            c.moveTo(body.position.x, body.position.y);\n            c.lineTo(body.position.x + velocity.x, body.position.y + velocity.y);\n        }\n\n        c.lineWidth = 3;\n        c.strokeStyle = 'cornflowerblue';\n        c.stroke();\n    };\n\n    /**\n     * Draws body ids\n     * @private\n     * @method bodyIds\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyIds = function(render, bodies, context) {\n        var c = context,\n            i,\n            j;\n\n        for (i = 0; i < bodies.length; i++) {\n            if (!bodies[i].render.visible)\n                continue;\n\n            var parts = bodies[i].parts;\n            for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                var part = parts[j];\n                c.font = \"12px Arial\";\n                c.fillStyle = 'rgba(255,255,255,0.5)';\n                c.fillText(part.id, part.position.x + 10, part.position.y - 10);\n            }\n        }\n    };\n\n    /**\n     * Description\n     * @private\n     * @method collisions\n     * @param {render} render\n     * @param {pair[]} pairs\n     * @param {RenderingContext} context\n     */\n    Render.collisions = function(render, pairs, context) {\n        var c = context,\n            options = render.options,\n            pair,\n            collision,\n            corrected,\n            bodyA,\n            bodyB,\n            i,\n            j;\n\n        c.beginPath();\n\n        // render collision positions\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n            for (j = 0; j < pair.contactCount; j++) {\n                var contact = pair.contacts[j],\n                    vertex = contact.vertex;\n                c.rect(vertex.x - 1.5, vertex.y - 1.5, 3.5, 3.5);\n            }\n        }\n\n        if (options.wireframes) {\n            c.fillStyle = 'rgba(255,255,255,0.7)';\n        } else {\n            c.fillStyle = 'orange';\n        }\n        c.fill();\n\n        c.beginPath();\n\n        // render collision normals\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n\n            if (pair.contactCount > 0) {\n                var normalPosX = pair.contacts[0].vertex.x,\n                    normalPosY = pair.contacts[0].vertex.y;\n\n                if (pair.contactCount === 2) {\n                    normalPosX = (pair.contacts[0].vertex.x + pair.contacts[1].vertex.x) / 2;\n                    normalPosY = (pair.contacts[0].vertex.y + pair.contacts[1].vertex.y) / 2;\n                }\n\n                if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic === true) {\n                    c.moveTo(normalPosX - collision.normal.x * 8, normalPosY - collision.normal.y * 8);\n                } else {\n                    c.moveTo(normalPosX + collision.normal.x * 8, normalPosY + collision.normal.y * 8);\n                }\n\n                c.lineTo(normalPosX, normalPosY);\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,165,0,0.7)';\n        } else {\n            c.strokeStyle = 'orange';\n        }\n\n        c.lineWidth = 1;\n        c.stroke();\n    };\n\n    /**\n     * Description\n     * @private\n     * @method separations\n     * @param {render} render\n     * @param {pair[]} pairs\n     * @param {RenderingContext} context\n     */\n    Render.separations = function(render, pairs, context) {\n        var c = context,\n            options = render.options,\n            pair,\n            collision,\n            corrected,\n            bodyA,\n            bodyB,\n            i,\n            j;\n\n        c.beginPath();\n\n        // render separations\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n            bodyA = collision.bodyA;\n            bodyB = collision.bodyB;\n\n            var k = 1;\n\n            if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;\n            if (bodyB.isStatic) k = 0;\n\n            c.moveTo(bodyB.position.x, bodyB.position.y);\n            c.lineTo(bodyB.position.x - collision.penetration.x * k, bodyB.position.y - collision.penetration.y * k);\n\n            k = 1;\n\n            if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;\n            if (bodyA.isStatic) k = 0;\n\n            c.moveTo(bodyA.position.x, bodyA.position.y);\n            c.lineTo(bodyA.position.x + collision.penetration.x * k, bodyA.position.y + collision.penetration.y * k);\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,165,0,0.5)';\n        } else {\n            c.strokeStyle = 'orange';\n        }\n        c.stroke();\n    };\n\n    /**\n     * Description\n     * @private\n     * @method inspector\n     * @param {inspector} inspector\n     * @param {RenderingContext} context\n     */\n    Render.inspector = function(inspector, context) {\n        var engine = inspector.engine,\n            selected = inspector.selected,\n            render = inspector.render,\n            options = render.options,\n            bounds;\n\n        if (options.hasBounds) {\n            var boundsWidth = render.bounds.max.x - render.bounds.min.x,\n                boundsHeight = render.bounds.max.y - render.bounds.min.y,\n                boundsScaleX = boundsWidth / render.options.width,\n                boundsScaleY = boundsHeight / render.options.height;\n\n            context.scale(1 / boundsScaleX, 1 / boundsScaleY);\n            context.translate(-render.bounds.min.x, -render.bounds.min.y);\n        }\n\n        for (var i = 0; i < selected.length; i++) {\n            var item = selected[i].data;\n\n            context.translate(0.5, 0.5);\n            context.lineWidth = 1;\n            context.strokeStyle = 'rgba(255,165,0,0.9)';\n            context.setLineDash([1,2]);\n\n            switch (item.type) {\n\n            case 'body':\n\n                // render body selections\n                bounds = item.bounds;\n                context.beginPath();\n                context.rect(Math.floor(bounds.min.x - 3), Math.floor(bounds.min.y - 3),\n                    Math.floor(bounds.max.x - bounds.min.x + 6), Math.floor(bounds.max.y - bounds.min.y + 6));\n                context.closePath();\n                context.stroke();\n\n                break;\n\n            case 'constraint':\n\n                // render constraint selections\n                var point = item.pointA;\n                if (item.bodyA)\n                    point = item.pointB;\n                context.beginPath();\n                context.arc(point.x, point.y, 10, 0, 2 * Math.PI);\n                context.closePath();\n                context.stroke();\n\n                break;\n\n            }\n\n            context.setLineDash([]);\n            context.translate(-0.5, -0.5);\n        }\n\n        // render selection region\n        if (inspector.selectStart !== null) {\n            context.translate(0.5, 0.5);\n            context.lineWidth = 1;\n            context.strokeStyle = 'rgba(255,165,0,0.6)';\n            context.fillStyle = 'rgba(255,165,0,0.1)';\n            bounds = inspector.selectBounds;\n            context.beginPath();\n            context.rect(Math.floor(bounds.min.x), Math.floor(bounds.min.y),\n                Math.floor(bounds.max.x - bounds.min.x), Math.floor(bounds.max.y - bounds.min.y));\n            context.closePath();\n            context.stroke();\n            context.fill();\n            context.translate(-0.5, -0.5);\n        }\n\n        if (options.hasBounds)\n            context.setTransform(1, 0, 0, 1, 0, 0);\n    };\n\n    /**\n     * Updates render timing.\n     * @method _updateTiming\n     * @private\n     * @param {render} render\n     * @param {number} time\n     */\n    var _updateTiming = function(render, time) {\n        var engine = render.engine,\n            timing = render.timing,\n            historySize = timing.historySize,\n            timestamp = engine.timing.timestamp;\n\n        timing.delta = time - timing.lastTime || Render._goodDelta;\n        timing.lastTime = time;\n\n        timing.timestampElapsed = timestamp - timing.lastTimestamp || 0;\n        timing.lastTimestamp = timestamp;\n\n        timing.deltaHistory.unshift(timing.delta);\n        timing.deltaHistory.length = Math.min(timing.deltaHistory.length, historySize);\n\n        timing.engineDeltaHistory.unshift(engine.timing.lastDelta);\n        timing.engineDeltaHistory.length = Math.min(timing.engineDeltaHistory.length, historySize);\n\n        timing.timestampElapsedHistory.unshift(timing.timestampElapsed);\n        timing.timestampElapsedHistory.length = Math.min(timing.timestampElapsedHistory.length, historySize);\n\n        timing.engineUpdatesHistory.unshift(engine.timing.lastUpdatesPerFrame);\n        timing.engineUpdatesHistory.length = Math.min(timing.engineUpdatesHistory.length, historySize);\n\n        timing.engineElapsedHistory.unshift(engine.timing.lastElapsed);\n        timing.engineElapsedHistory.length = Math.min(timing.engineElapsedHistory.length, historySize);\n\n        timing.elapsedHistory.unshift(timing.lastElapsed);\n        timing.elapsedHistory.length = Math.min(timing.elapsedHistory.length, historySize);\n    };\n\n    /**\n     * Returns the mean value of the given numbers.\n     * @method _mean\n     * @private\n     * @param {Number[]} values\n     * @return {Number} the mean of given values\n     */\n    var _mean = function(values) {\n        var result = 0;\n        for (var i = 0; i < values.length; i += 1) {\n            result += values[i];\n        }\n        return (result / values.length) || 0;\n    };\n\n    /**\n     * @method _createCanvas\n     * @private\n     * @param {} width\n     * @param {} height\n     * @return canvas\n     */\n    var _createCanvas = function(width, height) {\n        var canvas = document.createElement('canvas');\n        canvas.width = width;\n        canvas.height = height;\n        canvas.oncontextmenu = function() { return false; };\n        canvas.onselectstart = function() { return false; };\n        return canvas;\n    };\n\n    /**\n     * Gets the pixel ratio of the canvas.\n     * @method _getPixelRatio\n     * @private\n     * @param {HTMLElement} canvas\n     * @return {Number} pixel ratio\n     */\n    var _getPixelRatio = function(canvas) {\n        var context = canvas.getContext('2d'),\n            devicePixelRatio = window.devicePixelRatio || 1,\n            backingStorePixelRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio\n                                      || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio\n                                      || context.backingStorePixelRatio || 1;\n\n        return devicePixelRatio / backingStorePixelRatio;\n    };\n\n    /**\n     * Gets the requested texture (an Image) via its path\n     * @method _getTexture\n     * @private\n     * @param {render} render\n     * @param {string} imagePath\n     * @return {Image} texture\n     */\n    var _getTexture = function(render, imagePath) {\n        var image = render.textures[imagePath];\n\n        if (image)\n            return image;\n\n        image = render.textures[imagePath] = new Image();\n        image.src = imagePath;\n\n        return image;\n    };\n\n    /**\n     * Applies the background to the canvas using CSS.\n     * @method applyBackground\n     * @private\n     * @param {render} render\n     * @param {string} background\n     */\n    var _applyBackground = function(render, background) {\n        var cssBackground = background;\n\n        if (/(jpg|gif|png)$/.test(background))\n            cssBackground = 'url(' + background + ')';\n\n        render.canvas.style.background = cssBackground;\n        render.canvas.style.backgroundSize = \"contain\";\n        render.currentBackground = background;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired before rendering\n    *\n    * @event beforeRender\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired after rendering\n    *\n    * @event afterRender\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A back-reference to the `Matter.Render` module.\n     *\n     * @deprecated\n     * @property controller\n     * @type render\n     */\n\n    /**\n     * A reference to the `Matter.Engine` instance to be used.\n     *\n     * @property engine\n     * @type engine\n     */\n\n    /**\n     * A reference to the element where the canvas is to be inserted (if `render.canvas` has not been specified)\n     *\n     * @property element\n     * @type HTMLElement\n     * @default null\n     */\n\n    /**\n     * The canvas element to render to. If not specified, one will be created if `render.element` has been specified.\n     *\n     * @property canvas\n     * @type HTMLCanvasElement\n     * @default null\n     */\n\n    /**\n     * A `Bounds` object that specifies the drawing view region.\n     * Rendering will be automatically transformed and scaled to fit within the canvas size (`render.options.width` and `render.options.height`).\n     * This allows for creating views that can pan or zoom around the scene.\n     * You must also set `render.options.hasBounds` to `true` to enable bounded rendering.\n     *\n     * @property bounds\n     * @type bounds\n     */\n\n    /**\n     * The 2d rendering context from the `render.canvas` element.\n     *\n     * @property context\n     * @type CanvasRenderingContext2D\n     */\n\n    /**\n     * The sprite texture cache.\n     *\n     * @property textures\n     * @type {}\n     */\n\n    /**\n     * The mouse to render if `render.options.showMousePosition` is enabled.\n     *\n     * @property mouse\n     * @type mouse\n     * @default null\n     */\n\n    /**\n     * The configuration options of the renderer.\n     *\n     * @property options\n     * @type {}\n     */\n\n    /**\n     * The target width in pixels of the `render.canvas` to be created.\n     * See also the `options.pixelRatio` property to change render quality.\n     *\n     * @property options.width\n     * @type number\n     * @default 800\n     */\n\n    /**\n     * The target height in pixels of the `render.canvas` to be created.\n     * See also the `options.pixelRatio` property to change render quality.\n     *\n     * @property options.height\n     * @type number\n     * @default 600\n     */\n\n    /**\n     * The [pixel ratio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) to use when rendering.\n     *\n     * @property options.pixelRatio\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A CSS background color string to use when `render.options.wireframes` is disabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.background\n     * @type string\n     * @default '#14151f'\n     */\n\n    /**\n     * A CSS color string to use for background when `render.options.wireframes` is enabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.wireframeBackground\n     * @type string\n     * @default '#14151f'\n     */\n\n    /**\n     * A CSS color string to use for stroke when `render.options.wireframes` is enabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.wireframeStrokeStyle\n     * @type string\n     * @default '#bbb'\n     */\n\n    /**\n     * A flag that specifies if `render.bounds` should be used when rendering.\n     *\n     * @property options.hasBounds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable all debug information overlays together.  \n     * This includes and has priority over the values of:\n     *\n     * - `render.options.showStats`\n     * - `render.options.showPerformance`\n     *\n     * @property options.showDebug\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the engine stats info overlay.  \n     * From left to right, the values shown are:\n     *\n     * - body parts total\n     * - body total\n     * - constraints total\n     * - composites total\n     * - collision pairs total\n     *\n     * @property options.showStats\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable performance charts.  \n     * From left to right, the values shown are:\n     *\n     * - average render frequency (e.g. 60 fps)\n     * - exact engine delta time used for last update (e.g. 16.66ms)\n     * - average updates per frame (e.g. 1)\n     * - average engine execution duration (e.g. 5.00ms)\n     * - average render execution duration (e.g. 0.40ms)\n     * - average effective play speed (e.g. '1.00x' is 'real-time')\n     *\n     * Each value is recorded over a fixed sample of past frames (60 frames).\n     *\n     * A chart shown below each value indicates the variance from the average over the sample.\n     * The more stable or fixed the value is the flatter the chart will appear.\n     *\n     * @property options.showPerformance\n     * @type boolean\n     * @default false\n     */\n    \n    /**\n     * A flag to enable or disable rendering entirely.\n     *\n     * @property options.enabled\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to toggle wireframe rendering otherwise solid fill rendering is used.\n     *\n     * @property options.wireframes\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A flag to enable or disable sleeping bodies indicators.\n     *\n     * @property options.showSleeping\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A flag to enable or disable the debug information overlay.\n     *\n     * @property options.showDebug\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the collision broadphase debug overlay.\n     *\n     * @deprecated no longer implemented\n     * @property options.showBroadphase\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body bounds debug overlay.\n     *\n     * @property options.showBounds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body velocity debug overlay.\n     *\n     * @property options.showVelocity\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body collisions debug overlay.\n     *\n     * @property options.showCollisions\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the collision resolver separations debug overlay.\n     *\n     * @property options.showSeparations\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body axes debug overlay.\n     *\n     * @property options.showAxes\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body positions debug overlay.\n     *\n     * @property options.showPositions\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body angle debug overlay.\n     *\n     * @property options.showAngleIndicator\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body and part ids debug overlay.\n     *\n     * @property options.showIds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body vertex numbers debug overlay.\n     *\n     * @property options.showVertexNumbers\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body convex hulls debug overlay.\n     *\n     * @property options.showConvexHulls\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body internal edges debug overlay.\n     *\n     * @property options.showInternalEdges\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the mouse position debug overlay.\n     *\n     * @property options.showMousePosition\n     * @type boolean\n     * @default false\n     */\n\n})();\n\n\n/***/ }),\n/* 27 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Runner` module is an optional utility that provides a game loop for running a `Matter.Engine` inside a browser environment.\n* A runner will continuously update a `Matter.Engine` whilst synchronising engine updates with the browser frame rate.\n* This runner favours a smoother user experience over perfect time keeping.\n* This runner is optional and is used for development and debugging but could be useful as a starting point for implementing some games and experiences.\n* Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation as may be needed inside other environments.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Runner\n*/\n\nvar Runner = {};\n\nmodule.exports = Runner;\n\nvar Events = __webpack_require__(5);\nvar Engine = __webpack_require__(17);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    Runner._maxFrameDelta = 1000 / 15;\n    Runner._frameDeltaFallback = 1000 / 60;\n    Runner._timeBufferMargin = 1.5;\n    Runner._elapsedNextEstimate = 1;\n    Runner._smoothingLowerBound = 0.1;\n    Runner._smoothingUpperBound = 0.9;\n\n    /**\n     * Creates a new Runner. \n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     */\n    Runner.create = function(options) {\n        var defaults = {\n            delta: 1000 / 60,\n            frameDelta: null,\n            frameDeltaSmoothing: true,\n            frameDeltaSnapping: true,\n            frameDeltaHistory: [],\n            frameDeltaHistorySize: 100,\n            frameRequestId: null,\n            timeBuffer: 0,\n            timeLastTick: null,\n            maxUpdates: null,\n            maxFrameTime: 1000 / 30,\n            lastUpdatesDeferred: 0,\n            enabled: true\n        };\n\n        var runner = Common.extend(defaults, options);\n\n        // for temporary back compatibility only\n        runner.fps = 0;\n\n        return runner;\n    };\n\n    /**\n     * Runs a `Matter.Engine` whilst synchronising engine updates with the browser frame rate. \n     * See module and properties descriptions for more information on this runner.\n     * Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation.\n     * @method run\n     * @param {runner} runner\n     * @param {engine} [engine]\n     * @return {runner} runner\n     */\n    Runner.run = function(runner, engine) {\n        // initial time buffer for the first frame\n        runner.timeBuffer = Runner._frameDeltaFallback;\n\n        (function onFrame(time){\n            runner.frameRequestId = Runner._onNextFrame(runner, onFrame);\n\n            if (time && runner.enabled) {\n                Runner.tick(runner, engine, time);\n            }\n        })();\n\n        return runner;\n    };\n\n    /**\n     * Performs a single runner tick as used inside `Runner.run`.\n     * See module and properties descriptions for more information on this runner.\n     * Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation.\n     * @method tick\n     * @param {runner} runner\n     * @param {engine} engine\n     * @param {number} time\n     */\n    Runner.tick = function(runner, engine, time) {\n        var tickStartTime = Common.now(),\n            engineDelta = runner.delta,\n            updateCount = 0;\n\n        // find frame delta time since last call\n        var frameDelta = time - runner.timeLastTick;\n\n        // fallback for unusable frame delta values (e.g. 0, NaN, on first frame or long pauses)\n        if (!frameDelta || !runner.timeLastTick || frameDelta > Math.max(Runner._maxFrameDelta, runner.maxFrameTime)) {\n            // reuse last accepted frame delta else fallback\n            frameDelta = runner.frameDelta || Runner._frameDeltaFallback;\n        }\n\n        if (runner.frameDeltaSmoothing) {\n            // record frame delta over a number of frames\n            runner.frameDeltaHistory.push(frameDelta);\n            runner.frameDeltaHistory = runner.frameDeltaHistory.slice(-runner.frameDeltaHistorySize);\n\n            // sort frame delta history\n            var deltaHistorySorted = runner.frameDeltaHistory.slice(0).sort();\n\n            // sample a central window to limit outliers\n            var deltaHistoryWindow = runner.frameDeltaHistory.slice(\n                deltaHistorySorted.length * Runner._smoothingLowerBound, \n                deltaHistorySorted.length * Runner._smoothingUpperBound\n            );\n\n            // take the mean of the central window\n            var frameDeltaSmoothed = _mean(deltaHistoryWindow);\n            frameDelta = frameDeltaSmoothed || frameDelta;\n        }\n\n        if (runner.frameDeltaSnapping) {\n            // snap frame delta to the nearest 1 Hz\n            frameDelta = 1000 / Math.round(1000 / frameDelta);\n        }\n\n        // update runner values for next call\n        runner.frameDelta = frameDelta;\n        runner.timeLastTick = time;\n\n        // accumulate elapsed time\n        runner.timeBuffer += runner.frameDelta;\n\n        // limit time buffer size to a single frame of updates\n        runner.timeBuffer = Common.clamp(\n            runner.timeBuffer, 0, runner.frameDelta + engineDelta * Runner._timeBufferMargin\n        );\n\n        // reset count of over budget updates\n        runner.lastUpdatesDeferred = 0;\n\n        // get max updates per frame\n        var maxUpdates = runner.maxUpdates || Math.ceil(runner.maxFrameTime / engineDelta);\n\n        // create event object\n        var event = {\n            timestamp: engine.timing.timestamp\n        };\n\n        // tick events before update\n        Events.trigger(runner, 'beforeTick', event);\n        Events.trigger(runner, 'tick', event);\n\n        var updateStartTime = Common.now();\n\n        // simulate time elapsed between calls\n        while (engineDelta > 0 && runner.timeBuffer >= engineDelta * Runner._timeBufferMargin) {\n            // update the engine\n            Events.trigger(runner, 'beforeUpdate', event);\n            Engine.update(engine, engineDelta);\n            Events.trigger(runner, 'afterUpdate', event);\n\n            // consume time simulated from buffer\n            runner.timeBuffer -= engineDelta;\n            updateCount += 1;\n\n            // find elapsed time during this tick\n            var elapsedTimeTotal = Common.now() - tickStartTime,\n                elapsedTimeUpdates = Common.now() - updateStartTime,\n                elapsedNextEstimate = elapsedTimeTotal + Runner._elapsedNextEstimate * elapsedTimeUpdates / updateCount;\n\n            // defer updates if over performance budgets for this frame\n            if (updateCount >= maxUpdates || elapsedNextEstimate > runner.maxFrameTime) {\n                runner.lastUpdatesDeferred = Math.round(Math.max(0, (runner.timeBuffer / engineDelta) - Runner._timeBufferMargin));\n                break;\n            }\n        }\n\n        // track timing metrics\n        engine.timing.lastUpdatesPerFrame = updateCount;\n\n        // tick events after update\n        Events.trigger(runner, 'afterTick', event);\n\n        // show useful warnings if needed\n        if (runner.frameDeltaHistory.length >= 100) {\n            if (runner.lastUpdatesDeferred && Math.round(runner.frameDelta / engineDelta) > maxUpdates) {\n                Common.warnOnce('Matter.Runner: runner reached runner.maxUpdates, see docs.');\n            } else if (runner.lastUpdatesDeferred) {\n                Common.warnOnce('Matter.Runner: runner reached runner.maxFrameTime, see docs.');\n            }\n\n            if (typeof runner.isFixed !== 'undefined') {\n                Common.warnOnce('Matter.Runner: runner.isFixed is now redundant, see docs.');\n            }\n\n            if (runner.deltaMin || runner.deltaMax) {\n                Common.warnOnce('Matter.Runner: runner.deltaMin and runner.deltaMax were removed, see docs.');\n            }\n\n            if (runner.fps !== 0) {\n                Common.warnOnce('Matter.Runner: runner.fps was replaced by runner.delta, see docs.');\n            }\n        }\n    };\n\n    /**\n     * Ends execution of `Runner.run` on the given `runner` by canceling the frame loop.\n     * Alternatively to temporarily pause the runner, see `runner.enabled`.\n     * @method stop\n     * @param {runner} runner\n     */\n    Runner.stop = function(runner) {\n        Runner._cancelNextFrame(runner);\n    };\n\n    /**\n     * Schedules the `callback` on this `runner` for the next animation frame.\n     * @private\n     * @method _onNextFrame\n     * @param {runner} runner\n     * @param {function} callback\n     * @return {number} frameRequestId\n     */\n    Runner._onNextFrame = function(runner, callback) {\n        if (typeof window !== 'undefined' && window.requestAnimationFrame) {\n            runner.frameRequestId = window.requestAnimationFrame(callback);\n        } else {\n            throw new Error('Matter.Runner: missing required global window.requestAnimationFrame.');\n        }\n\n        return runner.frameRequestId;\n    };\n\n    /**\n     * Cancels the last callback scheduled by `Runner._onNextFrame` on this `runner`.\n     * @private\n     * @method _cancelNextFrame\n     * @param {runner} runner\n     */\n    Runner._cancelNextFrame = function(runner) {\n        if (typeof window !== 'undefined' && window.cancelAnimationFrame) {\n            window.cancelAnimationFrame(runner.frameRequestId);\n        } else {\n            throw new Error('Matter.Runner: missing required global window.cancelAnimationFrame.');\n        }\n    };\n\n    /**\n     * Returns the mean of the given numbers.\n     * @method _mean\n     * @private\n     * @param {Number[]} values\n     * @return {Number} the mean of given values.\n     */\n    var _mean = function(values) {\n        var result = 0,\n            valuesLength = values.length;\n\n        for (var i = 0; i < valuesLength; i += 1) {\n            result += values[i];\n        }\n\n        return (result / valuesLength) || 0;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired once at the start of the browser frame, before any engine updates.\n    *\n    * @event beforeTick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired once at the start of the browser frame, after `beforeTick`.\n    *\n    * @event tick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired once at the end of the browser frame, after `beforeTick`, `tick` and after any engine updates.\n    *\n    * @event afterTick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired before each and every engine update in this browser frame (if any). \n    * There may be multiple engine update calls per browser frame (or none) depending on framerate and timestep delta.\n    *\n    * @event beforeUpdate\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired after each and every engine update in this browser frame (if any). \n    * There may be multiple engine update calls per browser frame (or none) depending on framerate and timestep delta.\n    *\n    * @event afterUpdate\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * The fixed timestep size used for `Engine.update` calls in milliseconds, known as `delta`.\n     * \n     * This value is recommended to be `1000 / 60` ms or smaller (i.e. equivalent to at least 60hz).\n     * \n     * Smaller `delta` values provide higher quality results at the cost of performance.\n     * \n     * You should usually avoid changing `delta` during running, otherwise quality may be affected. \n     * \n     * For smoother frame pacing choose a `delta` that is an even multiple of each display FPS you target, i.e. `1000 / (n * fps)` as this helps distribute an equal number of updates over each display frame.\n     * \n     * For example with a 60 Hz `delta` i.e. `1000 / 60` the runner will on average perform one update per frame on displays running 60 FPS and one update every two frames on displays running 120 FPS, etc.\n     * \n     * Where as e.g. using a 240 Hz `delta` i.e. `1000 / 240` the runner will on average perform four updates per frame on displays running 60 FPS and two updates per frame on displays running 120 FPS, etc.\n     * \n     * Therefore `Runner.run` will call multiple engine updates (or none) as needed to simulate the time elapsed between browser frames. \n     * \n     * In practice the number of updates in any particular frame may be restricted to respect the runner's performance budgets. These are specified by `runner.maxFrameTime` and `runner.maxUpdates`, see those properties for details.\n     * \n     * @property delta\n     * @type number\n     * @default 1000 / 60\n     */\n\n    /**\n     * A flag that can be toggled to enable or disable tick calls on this runner, therefore pausing engine updates and events while the runner loop remains running.\n     *\n     * @property enabled\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * The accumulated time elapsed that has yet to be simulated in milliseconds.\n     * This value is clamped within certain limits (see `Runner.tick` code).\n     *\n     * @private\n     * @property timeBuffer\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * The measured time elapsed between the last two browser frames measured in milliseconds.\n     * This is useful e.g. to estimate the current browser FPS using `1000 / runner.frameDelta`.\n     *\n     * @readonly\n     * @property frameDelta\n     * @type number\n     */\n\n    /**\n     * Enables averaging to smooth frame rate measurements and therefore stabilise play rate.\n     *\n     * @property frameDeltaSmoothing\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * Rounds measured browser frame delta to the nearest 1 Hz.\n     * This option can help smooth frame rate measurements and simplify handling hardware timing differences e.g. 59.94Hz and 60Hz displays.\n     * For best results you should also round your `runner.delta` equivalent to the nearest 1 Hz.\n     *\n     * @property frameDeltaSnapping\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A performance budget that limits execution time allowed for this runner per browser frame in milliseconds.\n     * \n     * To calculate the effective browser FPS at which this throttle is applied use `1000 / runner.maxFrameTime`.\n     * \n     * This performance budget is intended to help maintain browser interactivity and help improve framerate recovery during temporary high CPU usage.\n     * \n     * This budget only covers the measured time elapsed executing the functions called in the scope of the runner tick, including `Engine.update` and its related user event callbacks.\n     * \n     * You may also reduce this budget to allow for any significant additional processing you perform on the same thread outside the scope of this runner tick, e.g. rendering time.\n     * \n     * See also `runner.maxUpdates`.\n     *\n     * @property maxFrameTime\n     * @type number\n     * @default 1000 / 30\n     */\n\n    /**\n     * An optional limit for maximum engine update count allowed per frame tick in addition to `runner.maxFrameTime`.\n     * \n     * Unless you set a value it is automatically chosen based on `runner.delta` and `runner.maxFrameTime`.\n     * \n     * See also `runner.maxFrameTime`.\n     * \n     * @property maxUpdates\n     * @type number\n     * @default null\n     */\n\n    /**\n     * The timestamp of the last call to `Runner.tick` used to measure `frameDelta`.\n     *\n     * @private\n     * @property timeLastTick\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * The id of the last call to `Runner._onNextFrame`.\n     *\n     * @private\n     * @property frameRequestId\n     * @type number\n     * @default null\n     */\n\n})();\n\n\n/***/ }),\n/* 28 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* This module has now been replaced by `Matter.Collision`.\n*\n* All usage should be migrated to `Matter.Collision`.\n* For back-compatibility purposes this module will remain for a short term and then later removed in a future release.\n*\n* The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem.\n*\n* @class SAT\n* @deprecated\n*/\n\nvar SAT = {};\n\nmodule.exports = SAT;\n\nvar Collision = __webpack_require__(8);\nvar Common = __webpack_require__(0);\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Detect collision between two bodies using the Separating Axis Theorem.\n     * @deprecated replaced by Collision.collides\n     * @method collides\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {collision} collision\n     */\n    SAT.collides = function(bodyA, bodyB) {\n        return Collision.collides(bodyA, bodyB);\n    };\n\n    deprecated(SAT, 'collides', 'SAT.collides ➤ replaced by Collision.collides');\n\n})();\n\n\n/***/ }),\n/* 29 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* The `Matter.Svg` module contains methods for converting SVG images into an array of vector points.\n*\n* To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Svg\n*/\n\nvar Svg = {};\n\nmodule.exports = Svg;\n\nvar Bounds = __webpack_require__(1);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * Converts an SVG path into an array of vector points.\n     * If the input path forms a concave shape, you must decompose the result into convex parts before use.\n     * See `Bodies.fromVertices` which provides support for this.\n     * Note that this function is not guaranteed to support complex paths (such as those with holes).\n     * You must load the `pathseg.js` polyfill on newer browsers.\n     * @method pathToVertices\n     * @param {SVGPathElement} path\n     * @param {Number} [sampleLength=15]\n     * @return {Vector[]} points\n     */\n    Svg.pathToVertices = function(path, sampleLength) {\n        if (typeof window !== 'undefined' && !('SVGPathSeg' in window)) {\n            Common.warn('Svg.pathToVertices: SVGPathSeg not defined, a polyfill is required.');\n        }\n\n        // https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js\n        var i, il, total, point, segment, segments, \n            segmentsQueue, lastSegment, \n            lastPoint, segmentIndex, points = [],\n            lx, ly, length = 0, x = 0, y = 0;\n\n        sampleLength = sampleLength || 15;\n\n        var addPoint = function(px, py, pathSegType) {\n            // all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1)\n            var isRelative = pathSegType % 2 === 1 && pathSegType > 1;\n\n            // when the last point doesn't equal the current point add the current point\n            if (!lastPoint || px != lastPoint.x || py != lastPoint.y) {\n                if (lastPoint && isRelative) {\n                    lx = lastPoint.x;\n                    ly = lastPoint.y;\n                } else {\n                    lx = 0;\n                    ly = 0;\n                }\n\n                var point = {\n                    x: lx + px,\n                    y: ly + py\n                };\n\n                // set last point\n                if (isRelative || !lastPoint) {\n                    lastPoint = point;\n                }\n\n                points.push(point);\n\n                x = lx + px;\n                y = ly + py;\n            }\n        };\n\n        var addSegmentPoint = function(segment) {\n            var segType = segment.pathSegTypeAsLetter.toUpperCase();\n\n            // skip path ends\n            if (segType === 'Z') \n                return;\n\n            // map segment to x and y\n            switch (segType) {\n\n            case 'M':\n            case 'L':\n            case 'T':\n            case 'C':\n            case 'S':\n            case 'Q':\n                x = segment.x;\n                y = segment.y;\n                break;\n            case 'H':\n                x = segment.x;\n                break;\n            case 'V':\n                y = segment.y;\n                break;\n            }\n\n            addPoint(x, y, segment.pathSegType);\n        };\n\n        // ensure path is absolute\n        Svg._svgPathToAbsolute(path);\n\n        // get total length\n        total = path.getTotalLength();\n\n        // queue segments\n        segments = [];\n        for (i = 0; i < path.pathSegList.numberOfItems; i += 1)\n            segments.push(path.pathSegList.getItem(i));\n\n        segmentsQueue = segments.concat();\n\n        // sample through path\n        while (length < total) {\n            // get segment at position\n            segmentIndex = path.getPathSegAtLength(length);\n            segment = segments[segmentIndex];\n\n            // new segment\n            if (segment != lastSegment) {\n                while (segmentsQueue.length && segmentsQueue[0] != segment)\n                    addSegmentPoint(segmentsQueue.shift());\n\n                lastSegment = segment;\n            }\n\n            // add points in between when curving\n            // TODO: adaptive sampling\n            switch (segment.pathSegTypeAsLetter.toUpperCase()) {\n\n            case 'C':\n            case 'T':\n            case 'S':\n            case 'Q':\n            case 'A':\n                point = path.getPointAtLength(length);\n                addPoint(point.x, point.y, 0);\n                break;\n\n            }\n\n            // increment by sample value\n            length += sampleLength;\n        }\n\n        // add remaining segments not passed by sampling\n        for (i = 0, il = segmentsQueue.length; i < il; ++i)\n            addSegmentPoint(segmentsQueue[i]);\n\n        return points;\n    };\n\n    Svg._svgPathToAbsolute = function(path) {\n        // http://phrogz.net/convert-svg-path-to-all-absolute-commands\n        // Copyright (c) Gavin Kistner\n        // http://phrogz.net/js/_ReuseLicense.txt\n        // Modifications: tidy formatting and naming\n        var x0, y0, x1, y1, x2, y2, segs = path.pathSegList,\n            x = 0, y = 0, len = segs.numberOfItems;\n\n        for (var i = 0; i < len; ++i) {\n            var seg = segs.getItem(i),\n                segType = seg.pathSegTypeAsLetter;\n\n            if (/[MLHVCSQTA]/.test(segType)) {\n                if ('x' in seg) x = seg.x;\n                if ('y' in seg) y = seg.y;\n            } else {\n                if ('x1' in seg) x1 = x + seg.x1;\n                if ('x2' in seg) x2 = x + seg.x2;\n                if ('y1' in seg) y1 = y + seg.y1;\n                if ('y2' in seg) y2 = y + seg.y2;\n                if ('x' in seg) x += seg.x;\n                if ('y' in seg) y += seg.y;\n\n                switch (segType) {\n\n                case 'm':\n                    segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i);\n                    break;\n                case 'l':\n                    segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i);\n                    break;\n                case 'h':\n                    segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i);\n                    break;\n                case 'v':\n                    segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i);\n                    break;\n                case 'c':\n                    segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i);\n                    break;\n                case 's':\n                    segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i);\n                    break;\n                case 'q':\n                    segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i);\n                    break;\n                case 't':\n                    segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i);\n                    break;\n                case 'a':\n                    segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i);\n                    break;\n                case 'z':\n                case 'Z':\n                    x = x0;\n                    y = y0;\n                    break;\n\n                }\n            }\n\n            if (segType == 'M' || segType == 'm') {\n                x0 = x;\n                y0 = y;\n            }\n        }\n    };\n\n})();\n\n/***/ }),\n/* 30 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n* This module has now been replaced by `Matter.Composite`.\n*\n* All usage should be migrated to the equivalent functions found on `Matter.Composite`.\n* For example `World.add(world, body)` now becomes `Composite.add(world, body)`.\n*\n* The property `world.gravity` has been moved to `engine.gravity`.\n*\n* For back-compatibility purposes this module will remain as a direct alias to `Matter.Composite` in the short term during migration.\n* Eventually this alias module will be marked as deprecated and then later removed in a future release.\n*\n* @class World\n*/\n\nvar World = {};\n\nmodule.exports = World;\n\nvar Composite = __webpack_require__(6);\nvar Common = __webpack_require__(0);\n\n(function() {\n\n    /**\n     * See above, aliases for back compatibility only\n     */\n    World.create = Composite.create;\n    World.add = Composite.add;\n    World.remove = Composite.remove;\n    World.clear = Composite.clear;\n    World.addComposite = Composite.addComposite;\n    World.addBody = Composite.addBody;\n    World.addConstraint = Composite.addConstraint;\n\n})();\n\n\n/***/ })\n/******/ ]);\n});"
  },
  {
    "path": "demo/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui\">\n    <meta name=\"theme-color\" content=\"#000000\">\n    <meta name=\"msapplication-navbutton-color\" content=\"#000000\">\n    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">\n    <meta name=\"robots\" content=\"noindex\">\n    <title>Matter.js Demo</title>\n\n    <style type=\"text/css\">\n      * {\n        box-sizing: border-box;\n      }\n\n      body {\n        margin: 0;\n        padding: 0;\n      }\n\n      .matter-btn-compare.matter-btn {\n        font-size: 18px;\n        text-align: center;\n        line-height: 32px;\n      }\n\n      .matter-js-compare-build.matter-demo {\n        position: absolute;\n        background: none;\n        top: 0;\n        left: 0;\n        width: 100%;\n        height: 100%;\n        border: 0;\n        pointer-events: none;\n      }\n\n      .matter-js-compare-build.matter-demo .matter-header-outer {\n        display: none;\n      }\n\n      .matter-js.dev.comparing.matter-demo canvas {\n        background: transparent !important;\n        z-index: 20;\n      }\n\n      .matter-js-compare-build.matter-demo canvas {\n        opacity: 0.5;\n        background: transparent !important;\n        z-index: 15 !important;\n      }\n\n      @media only screen and (min-width: 1300px) {\n        /* reduce hit testing when using matter-tools */\n        .matter-demo canvas {\n          position: relative;\n          z-index: 20;\n        }\n\n        .matter-js-compare-build.matter-demo canvas {\n          position: relative;\n          z-index: 15;\n        }\n      }\n    </style>\n  </head>\n  <body>\n    <script src=\"./js/matter-demo.main.cf6d09.min.js\"></script>\n    <script src=\"./js/matter-demo.matter-tools.0f82d2.min.js\"></script>\n    <script src=\"./js/matter-demo.matter-wrap.f14474.min.js\"></script>\n    <script src=\"./js/matter-demo.pathseg.f137cc.min.js\"></script>\n    <script src=\"./js/matter-demo.poly-decomp.6b3373.min.js\"></script>\n    <script src=\"./js/matter-demo.01bd65.min.js\"></script>\n  </body>\n</html>"
  },
  {
    "path": "demo/src/Compare.js",
    "content": "/**\n* A Matter.js version comparison testbed based on MatterTools.\n*\n* Tool to interactively compare engine results of \n* development version against the previous release.\n*\n* USAGE: [host]?compare[=frames]#[example]\n*  e.g. http://localhost:8000/?compare=120#mixed\n*\n* @module Compare\n*/\n\nvar MatterTools = require('matter-tools');\nvar MatterDev = require('MatterDev');\nvar MatterBuild = require('MatterBuild');\n\nvar compare = function(examples, isDev) {\n    // create primary demo for dev build\n    var demo = MatterTools.Demo.create({\n        toolbar: {\n            title: 'matter-js ・ ' + (isDev ? 'dev' : '') + ' ・ comparing to ' + MatterBuild.version,\n            url: 'https://github.com/liabru/matter-js',\n            reset: true,\n            source: true,\n            inspector: false,\n            tools: false,\n            fullscreen: true,\n            exampleSelect: true\n        },\n        // tools disabled to keep sync between instances\n        tools: {\n            inspector: false,\n            gui: false\n        },\n        inline: false,\n        preventZoom: true,\n        resetOnOrientation: true,\n        routing: true,\n        startExample: false,\n        examples: examples\n    });\n\n    // create secondary demo for release build\n    var demoBuild = MatterTools.Demo.create({\n        toolbar: {\n            title: 'matter-js-compare-build',\n            reset: false,\n            source: false,\n            inspector: false,\n            tools: false,\n            fullscreen: false,\n            exampleSelect: false\n        },\n        // tools disabled to keep sync between instances\n        tools: {\n            inspector: false,\n            gui: false\n        },\n        inline: false,\n        preventZoom: true,\n        resetOnOrientation: true,\n        routing: false,\n        startExample: false,\n        examples: examples.map(function(example) { \n            return Matter.Common.extend({}, example); \n        })\n    });\n\n    /**\n     * NOTE: For the actual example code, refer to the source files in `/examples/`.\n     * The code below is tooling for Matter.js maintainers to compare versions of Matter.\n     */\n\n    // build version should not run itself\n    MatterBuild.Runner.run = function() {};\n    MatterBuild.Render.run = function() {};\n\n    // maintain original references to patched methods\n    MatterDev.Runner._tick = MatterDev.Runner.tick;\n    MatterDev.Render._world = MatterDev.Render.world;\n    MatterBuild.Mouse._setElement = MatterBuild.Mouse.setElement;\n\n    // patch MatterTools to control both demo versions simultaneously\n    MatterTools.Demo._setExample = MatterTools.Demo.setExample;\n    MatterTools.Demo.setExample = function(_demo, example) {\n        MatterBuild.Common._nextId = MatterBuild.Common._seed = 0;\n        MatterDev.Common._nextId = MatterDev.Common._seed = 0;\n\n        MatterBuild.Plugin._registry = MatterDev.Plugin._registry;\n        MatterBuild.use.apply(null, MatterDev.used);\n\n        window.Matter = MatterDev;\n        MatterTools.Demo._setExample(\n            demo, demo.examples.find(function(e) { return e.name === example.name; })\n        );\n\n        var maxTicks = parseFloat(window.location.search.split('=')[1]);\n        var ticks = 0;\n\n        MatterDev.Runner.tick = function(runner, engine, time) {\n            if (ticks === -1) {\n                return;\n            }\n\n            if (ticks >= maxTicks) {\n                console.info(\n                    'Demo.Compare: ran ' + ticks + ' ticks, timestamp is now ' \n                        + engine.timing.timestamp.toFixed(2)\n                );\n\n                ticks = -1;\n                    \n                return;\n            }\n\n            ticks += 1;\n\n            var demoBuildInstance = demoBuild.example.instance;\n            runner.delta = demoBuildInstance.runner.delta = 1000 / 60;\n\n            window.Matter = MatterBuild;\n            MatterBuild.Runner.tick(demoBuildInstance.runner, demoBuildInstance.engine, time);\n            window.Matter = MatterDev;\n            return MatterDev.Runner._tick(runner, engine, time);\n        };\n\n        MatterDev.Render.world = function(render) {\n            window.Matter = MatterBuild;\n            MatterBuild.Render.world(demoBuild.example.instance.render);\n            window.Matter = MatterDev;\n            return MatterDev.Render._world(render);\n        };\n\n        MatterBuild.Mouse.setElement = function(mouse) {\n            return MatterBuild.Mouse._setElement(mouse, demo.example.instance.render.canvas);\n        };\n\n        window.Matter = MatterBuild;\n        MatterTools.Demo._setExample(\n            demoBuild, demoBuild.examples.find(function(e) { return e.name === example.name; })\n        );\n            \n        window.Matter = MatterDev;\n    };\n\n    // reset both engine versions simultaneously\n    MatterTools.Demo._reset = MatterTools.Demo.reset;\n    MatterTools.Demo.reset = function(_demo) {\n        MatterBuild.Common._nextId = MatterBuild.Common._seed = 0;\n        MatterDev.Common._nextId = MatterDev.Common._seed = 0;\n\n        window.Matter = MatterBuild;\n        MatterTools.Demo._reset(demoBuild);\n\n        window.Matter = MatterDev;\n        MatterTools.Demo._reset(demo);\n    };\n\n    document.body.appendChild(demo.dom.root);\n    document.body.appendChild(demoBuild.dom.root);\n\n    MatterTools.Demo.start(demo);\n\n    document.title = 'Matter.js Compare' + (isDev ? ' ・ Dev' : '');\n\n    console.info(\n        'Demo.Compare: matter-js@' + MatterDev.version + \n        ' with matter-js@' + MatterBuild.version\n    );\n};\n\nmodule.exports = { compare: compare };\n"
  },
  {
    "path": "demo/src/Demo.js",
    "content": "/**\r\n* A Matter.js demo and development testbed based on MatterTools.\r\n*\r\n* For a simpler, minimal Matter.js example see:\r\n* https://github.com/liabru/matter-js/wiki/Getting-started\r\n*\r\n* The source for examples can be found at `/examples/`.\r\n*\r\n* @module Demo\r\n*/\r\n\r\nvar MatterTools = require('matter-tools');\r\n\r\nvar demo = function(examples, isDev) {\r\n    var demo = MatterTools.Demo.create({\r\n        toolbar: {\r\n            title: 'matter-js' + (isDev ? ' ・ dev' : ''),\r\n            url: 'https://github.com/liabru/matter-js',\r\n            reset: true,\r\n            source: true,\r\n            inspector: true,\r\n            tools: true,\r\n            fullscreen: true,\r\n            exampleSelect: true\r\n        },\r\n        tools: {\r\n            inspector: true,\r\n            gui: true\r\n        },\r\n        inline: false,\r\n        preventZoom: true,\r\n        resetOnOrientation: true,\r\n        routing: true,\r\n        startExample: 'mixed',\r\n        examples: examples\r\n    });\r\n\r\n    window.MatterDemoInstance = demo;\r\n\r\n    document.body.appendChild(demo.dom.root);\r\n    document.title = 'Matter.js Demo' + (isDev ? ' ・ Dev' : '');\r\n\r\n    if (isDev) {\r\n        // add delta control\r\n        Matter.Common.chainPathAfter(MatterTools, 'Gui.create', function() {\r\n            this.datGui.__folders[\"Engine\"]\r\n                .add(demo, \"delta\", 0, 1000 / 55)\r\n                .onChange(function() {\r\n                    var runner = demo.example.instance.runner;\r\n                    runner.delta = demo.delta;\r\n                })\r\n                .step(0.001)\r\n                .listen();\r\n        });\r\n\r\n        Matter.after('Runner.create', function() {\r\n            demo.delta = this.delta;\r\n        });\r\n\r\n        // add compare button\r\n        var buttonSource = demo.dom.buttonSource,\r\n            buttonCompare = buttonSource.cloneNode(true);\r\n\r\n        buttonCompare.textContent = '⎄';\r\n        buttonCompare.title = 'Compare';\r\n        buttonCompare.href = '?compare';\r\n        buttonCompare.target = '';\r\n        buttonCompare.className = 'matter-btn matter-btn-compare';\r\n        buttonCompare.addEventListener('click', function(event) {\r\n            window.location = '?compare#' + demo.example.id;\r\n            event.preventDefault();\r\n        });\r\n\r\n        buttonSource.parentNode.insertBefore(buttonCompare, buttonSource.nextSibling);\r\n\r\n        Matter.before('Render.create', function(renderOptions) {\r\n            // custom render options in development demo\r\n            renderOptions.options.showDebug = true;\r\n            renderOptions.options.pixelRatio = 'auto';\r\n            renderOptions.options.wireframeStrokeStyle = '#aaa';\r\n        });\r\n\r\n        // arrow key navigation of examples\r\n        document.addEventListener('keyup', function(event) {\r\n            var isBackKey = event.key === 'ArrowLeft' || event.key === 'ArrowUp',\r\n                isForwardKey = event.key === 'ArrowRight' || event.key === 'ArrowDown';\r\n\r\n            if (isBackKey || isForwardKey) {\r\n                var direction = isBackKey ? -1 : 1,\r\n                    currentExampleIndex = demo.examples.findIndex(function(example) { \r\n                        return example.id === demo.example.id;\r\n                    }),\r\n                    nextExample = demo.examples[(demo.examples.length + currentExampleIndex + direction) % demo.examples.length];\r\n                \r\n                MatterTools.Demo.setExample(demo, nextExample);\r\n            }\r\n        });\r\n    }\r\n\r\n    MatterTools.Demo.start(demo);\r\n};\r\n\r\nmodule.exports = { demo: demo };\r\n"
  },
  {
    "path": "demo/src/Multi.js",
    "content": "/**\n* A Matter.js multi example testbed based on MatterTools.\n*\n* Tool to interactively test multiple examples at once.\n*\n* USAGE: [host]?multi#[example1,example2,example3...]\n*  e.g. http://localhost:8000/?multi#mixed\n*\n* @module Multi\n*/\n\nvar MatterTools = require('matter-tools');\n\nvar multi = function(examples, isDev) {\n    var demo = MatterTools.Demo.create({\n        toolbar: {\n            title: 'matter-js ・ ' + (isDev ? 'dev' : '') + ' ・ multi',\n            url: 'https://github.com/liabru/matter-js',\n            reset: false,\n            source: false,\n            inspector: false,\n            tools: false,\n            fullscreen: false,\n            exampleSelect: false\n        },\n        tools: {\n            inspector: false,\n            gui: false\n        },\n        inline: false,\n        preventZoom: false,\n        resetOnOrientation: false,\n        routing: false,\n        startExample: false\n    });\n\n    var urlHash = window.location.hash,\n        allExampleIds = examples.map(function(example) { return example.id; }),\n        exampleIds = urlHash ? urlHash.slice(1).split(',') : allExampleIds.slice(0, 4),\n        exampleCount = Math.ceil(Math.sqrt(exampleIds.length));\n\n    var container = document.createElement('div');\n    container.style = 'display: grid; grid-template-columns: repeat(' + exampleCount + ', 1fr); grid-template-rows: repeat(' + exampleCount + ', 1fr); max-width: calc(100vmin * 1.25 - 40px); max-height: 100vmin;';\n\n    demo.dom.root.appendChild(container);\n    document.body.appendChild(demo.dom.root);\n\n    document.title = 'Matter.js Multi' + (isDev ? ' ・ Dev' : '');\n    console.info('Demo.Multi: matter-js@' + Matter.version);\n\n    // always show debug info\n    Matter.before('Render.create', function(renderOptions) {\n        renderOptions.options.showDebug = true;\n    });\n\n    Matter.after('Runner.create', function() {\n        this.isFixed = true;\n    });\n\n    var runExamples = function(exampleIds) {\n        for (var i = 0; i < exampleIds.length; i += 1) {\n            var exampleId = exampleIds[i],\n                example = examples.find(function(example) { return example.id === exampleId; });\n\n            if (!example) {\n                continue;\n            }\n\n            var canvas = example.init().render.canvas;\n            container.appendChild(canvas);\n        }\n    };\n\n    runExamples(exampleIds);\n\n    // arrow key navigation of examples\n    document.addEventListener('keyup', function(event) {\n        var isBackKey = event.key === 'ArrowLeft' || event.key === 'ArrowUp',\n            isForwardKey = event.key === 'ArrowRight' || event.key === 'ArrowDown';\n\n        if (isBackKey || isForwardKey) {\n            var direction = isBackKey ? -1 : 1;\n\n            var currentExampleIndex = allExampleIds.findIndex(function(exampleId) { \n                return exampleId === exampleIds[0];\n            });\n\n            var nextExampleId = (allExampleIds.length + currentExampleIndex + direction * exampleIds.length) % allExampleIds.length,\n                nextExamples = allExampleIds.slice(nextExampleId, (nextExampleId + exampleIds.length) % allExampleIds.length);\n\n            window.location.hash = nextExamples.join(',');\n            window.location.reload();\n        }\n    });\n};\n\nmodule.exports = { multi: multi };\n"
  },
  {
    "path": "demo/src/index.ejs",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,minimal-ui\">\n    <meta name=\"theme-color\" content=\"#000000\">\n    <meta name=\"msapplication-navbutton-color\" content=\"#000000\">\n    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">\n    <meta name=\"robots\" content=\"noindex\">\n    <title>Matter.js Demo</title>\n\n    <style type=\"text/css\">\n      * {\n        box-sizing: border-box;\n      }\n\n      body {\n        margin: 0;\n        padding: 0;\n      }\n\n      .matter-btn-compare.matter-btn {\n        font-size: 18px;\n        text-align: center;\n        line-height: 32px;\n      }\n\n      .matter-js-compare-build.matter-demo {\n        position: absolute;\n        background: none;\n        top: 0;\n        left: 0;\n        width: 100%;\n        height: 100%;\n        border: 0;\n        pointer-events: none;\n      }\n\n      .matter-js-compare-build.matter-demo .matter-header-outer {\n        display: none;\n      }\n\n      .matter-js.dev.comparing.matter-demo canvas {\n        background: transparent !important;\n        z-index: 20;\n      }\n\n      .matter-js-compare-build.matter-demo canvas {\n        opacity: 0.5;\n        background: transparent !important;\n        z-index: 15 !important;\n      }\n\n      @media only screen and (min-width: 1300px) {\n        /* reduce hit testing when using matter-tools */\n        .matter-demo canvas {\n          position: relative;\n          z-index: 20;\n        }\n\n        .matter-js-compare-build.matter-demo canvas {\n          position: relative;\n          z-index: 15;\n        }\n      }\n    </style>\n  </head>\n  <body><% for (var chunk in htmlWebpackPlugin.files.js) { %>\n    <script src=\"<%= htmlWebpackPlugin.files.js[chunk] %>\"></script><% } %>\n  </body>\n</html>"
  },
  {
    "path": "demo/src/index.js",
    "content": "/**\n* Initialise and start the browser demo / compare tool.\n*\n* For a simpler, minimal Matter.js example see:\n* https://github.com/liabru/matter-js/wiki/Getting-started\n*\n* The source for examples can be found at `/examples/`.\n*\n* @module Index\n*/\n\nvar Matter = require('matter-js');\nvar Examples = require('../../examples/index');\nvar compare = require('./Compare').compare;\nvar multi = require('./Multi').multi;\nvar demo = require('./Demo').demo;\n\n// browser globals\nwindow.pathseg = require('pathseg');\nwindow.MatterTools = require('matter-tools');\nwindow.Matter = Matter;\n\n// prepare examples\nvar examples = Matter.Common.keys(Examples).map(function(id){\n    return {\n        id: id,\n        sourceLink: 'https://github.com/liabru/matter-js/blob/master/examples/' + id + '.js',\n        name: Examples[id].title, \n        init: Examples[id]\n    };\n});\n\n// start the requested tool\nvar isCompare = window.location.search.indexOf('compare') >= 0;\nvar isMulti = window.location.search.indexOf('multi') >= 0;\nvar isDev = __MATTER_IS_DEV__;\n\nif (isCompare) {\n    compare(examples, isDev);\n} else if (isMulti) {\n    multi(examples, isDev);\n} else {\n    demo(examples, isDev);\n}\n"
  },
  {
    "path": "examples/airFriction.js",
    "content": "var Example = Example || {};\n\nExample.airFriction = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // falling blocks\n        Bodies.rectangle(200, 100, 60, 60, { frictionAir: 0.001 }),\n        Bodies.rectangle(400, 100, 60, 60, { frictionAir: 0.05 }),\n        Bodies.rectangle(600, 100, 60, 60, { frictionAir: 0.1 }),\n\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.airFriction.title = 'Air Friction';\nExample.airFriction.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.airFriction;\n}\n"
  },
  {
    "path": "examples/avalanche.js",
    "content": "var Example = Example || {};\n\nExample.avalanche = function() {\n    try {\n        if (typeof MatterWrap !== 'undefined') {\n            // either use by name from plugin registry (Browser global)\n            Matter.use('matter-wrap');\n        } else {\n            // or require and use the plugin directly (Node.js, Webpack etc.)\n            Matter.use(require('matter-wrap'));\n        }\n    } catch (e) {\n        // could not require the plugin or install needed\n    }\n    \n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 20, 5, 0, 0, function(x, y) {\n        return Bodies.circle(x, y, Common.random(10, 20), { friction: 0.00001, restitution: 0.5, density: 0.001 });\n    });\n\n    Composite.add(world, stack);\n    \n    Composite.add(world, [\n        Bodies.rectangle(200, 150, 700, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(500, 350, 700, 20, { isStatic: true, angle: -Math.PI * 0.06, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(340, 580, 700, 20, { isStatic: true, angle: Math.PI * 0.04, render: { fillStyle: '#060a19' } })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, Composite.allBodies(world));\n\n    // wrapping using matter-wrap plugin\n    for (var i = 0; i < stack.bodies.length; i += 1) {\n        stack.bodies[i].plugin.wrap = {\n            min: { x: render.bounds.min.x, y: render.bounds.min.y },\n            max: { x: render.bounds.max.x, y: render.bounds.max.y }\n        };\n    }\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.avalanche.title = 'Avalanche';\nExample.avalanche.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.avalanche;\n}\n"
  },
  {
    "path": "examples/ballPool.js",
    "content": "var Example = Example || {};\n\nExample.ballPool = function() {\n    try {\n        if (typeof MatterWrap !== 'undefined') {\n            // either use by name from plugin registry (Browser global)\n            Matter.use('matter-wrap');\n        } else {\n            // or require and use the plugin directly (Node.js, Webpack etc.)\n            Matter.use(require('matter-wrap'));\n        }\n    } catch (e) {\n        // could not require the plugin or install needed\n    }\n    \n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        Bodies.rectangle(400, 600, 1200, 50.5, { isStatic: true, render: { fillStyle: '#060a19' } })\n    ]);\n\n    var stack = Composites.stack(100, 0, 10, 8, 10, 10, function(x, y) {\n        return Bodies.circle(x, y, Common.random(15, 30), { restitution: 0.6, friction: 0.1 });\n    });\n    \n    Composite.add(world, [\n        stack,\n        Bodies.polygon(200, 460, 3, 60),\n        Bodies.polygon(400, 460, 5, 60),\n        Bodies.rectangle(600, 460, 80, 80)\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // wrapping using matter-wrap plugin\n    var allBodies = Composite.allBodies(world);\n\n    for (var i = 0; i < allBodies.length; i += 1) {\n        allBodies[i].plugin.wrap = {\n            min: { x: render.bounds.min.x - 100, y: render.bounds.min.y },\n            max: { x: render.bounds.max.x + 100, y: render.bounds.max.y }\n        };\n    }\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.ballPool.title = 'Ball Pool';\nExample.ballPool.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.ballPool;\n}\n"
  },
  {
    "path": "examples/bridge.js",
    "content": "var Example = Example || {};\n\nExample.bridge = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var group = Body.nextGroup(true);\n\n    var bridge = Composites.stack(160, 290, 15, 1, 0, 0, function(x, y) {\n        return Bodies.rectangle(x - 20, y, 53, 20, { \n            collisionFilter: { group: group },\n            chamfer: 5,\n            density: 0.005,\n            frictionAir: 0.05,\n            render: {\n                fillStyle: '#060a19'\n            }\n        });\n    });\n    \n    Composites.chain(bridge, 0.3, 0, -0.3, 0, { \n        stiffness: 0.99,\n        length: 0.0001,\n        render: {\n            visible: false\n        }\n    });\n    \n    var stack = Composites.stack(250, 50, 6, 3, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 50, 50, Common.random(20, 40));\n    });\n\n    Composite.add(world, [\n        bridge,\n        stack,\n        Bodies.rectangle(30, 490, 220, 380, { \n            isStatic: true, \n            chamfer: { radius: 20 }\n        }),\n        Bodies.rectangle(770, 490, 220, 380, { \n            isStatic: true, \n            chamfer: { radius: 20 }\n        }),\n        Constraint.create({ \n            pointA: { x: 140, y: 300 }, \n            bodyB: bridge.bodies[0], \n            pointB: { x: -25, y: 0 },\n            length: 2,\n            stiffness: 0.9\n        }),\n        Constraint.create({ \n            pointA: { x: 660, y: 300 }, \n            bodyB: bridge.bodies[bridge.bodies.length - 1], \n            pointB: { x: 25, y: 0 },\n            length: 2,\n            stiffness: 0.9\n        })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.1,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.bridge.title = 'Bridge';\nExample.bridge.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.bridge;\n}\n"
  },
  {
    "path": "examples/car.js",
    "content": "var Example = Example || {};\n\nExample.car = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            showCollisions: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // see car function defined later in this file\n    var scale = 0.9;\n    Composite.add(world, Example.car.car(150, 100, 150 * scale, 30 * scale, 30 * scale));\n    \n    scale = 0.8;\n    Composite.add(world, Example.car.car(350, 300, 150 * scale, 30 * scale, 30 * scale));\n    \n    Composite.add(world, [\n        Bodies.rectangle(200, 150, 400, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' }}),\n        Bodies.rectangle(500, 350, 650, 20, { isStatic: true, angle: -Math.PI * 0.06, render: { fillStyle: '#060a19' }}),\n        Bodies.rectangle(300, 560, 600, 20, { isStatic: true, angle: Math.PI * 0.04, render: { fillStyle: '#060a19' }})\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.car.title = 'Car';\nExample.car.for = '>=0.14.2';\n\n/**\n* Creates a composite with simple car setup of bodies and constraints.\n* @method car\n* @param {number} xx\n* @param {number} yy\n* @param {number} width\n* @param {number} height\n* @param {number} wheelSize\n* @return {composite} A new composite car body\n*/\nExample.car.car = function(xx, yy, width, height, wheelSize) {\n    var Body = Matter.Body,\n        Bodies = Matter.Bodies,\n        Composite = Matter.Composite,\n        Constraint = Matter.Constraint;\n\n    var group = Body.nextGroup(true),\n        wheelBase = 20,\n        wheelAOffset = -width * 0.5 + wheelBase,\n        wheelBOffset = width * 0.5 - wheelBase,\n        wheelYOffset = 0;\n\n    var car = Composite.create({ label: 'Car' }),\n        body = Bodies.rectangle(xx, yy, width, height, { \n            collisionFilter: {\n                group: group\n            },\n            chamfer: {\n                radius: height * 0.5\n            },\n            density: 0.0002\n        });\n\n    var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, { \n        collisionFilter: {\n            group: group\n        },\n        friction: 0.8\n    });\n                \n    var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, { \n        collisionFilter: {\n            group: group\n        },\n        friction: 0.8\n    });\n                \n    var axelA = Constraint.create({\n        bodyB: body,\n        pointB: { x: wheelAOffset, y: wheelYOffset },\n        bodyA: wheelA,\n        stiffness: 1,\n        length: 0\n    });\n                    \n    var axelB = Constraint.create({\n        bodyB: body,\n        pointB: { x: wheelBOffset, y: wheelYOffset },\n        bodyA: wheelB,\n        stiffness: 1,\n        length: 0\n    });\n    \n    Composite.addBody(car, body);\n    Composite.addBody(car, wheelA);\n    Composite.addBody(car, wheelB);\n    Composite.addConstraint(car, axelA);\n    Composite.addConstraint(car, axelB);\n\n    return car;\n};\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.car;\n}\n"
  },
  {
    "path": "examples/catapult.js",
    "content": "var Example = Example || {};\n\nExample.catapult = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies,\n        Body = Matter.Body,\n        Vector = Matter.Vector;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            showCollisions: true,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var group = Body.nextGroup(true);\n\n    var stack = Composites.stack(250, 255, 1, 6, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 30, 30);\n    });\n\n    var catapult = Bodies.rectangle(400, 520, 320, 20, { collisionFilter: { group: group } });\n\n    Composite.add(world, [\n        stack,\n        catapult,\n        Bodies.rectangle(400, 600, 800, 50.5, { isStatic: true, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(250, 555, 20, 50, { isStatic: true, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(400, 535, 20, 80, { isStatic: true, collisionFilter: { group: group }, render: { fillStyle: '#060a19' } }),\n        Bodies.circle(560, 100, 50, { density: 0.005 }),\n        Constraint.create({ \n            bodyA: catapult, \n            pointB: Vector.clone(catapult.position),\n            stiffness: 1,\n            length: 0\n        })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.catapult.title = 'Catapult';\nExample.catapult.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.catapult;\n}\n"
  },
  {
    "path": "examples/chains.js",
    "content": "var Example = Example || {};\n\nExample.chains = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            showCollisions: true,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var group = Body.nextGroup(true);\n        \n    var ropeA = Composites.stack(100, 50, 8, 1, 10, 10, function(x, y) {\n        return Bodies.rectangle(x, y, 50, 20, { collisionFilter: { group: group } });\n    });\n    \n    Composites.chain(ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2, render: { type: 'line' } });\n    Composite.add(ropeA, Constraint.create({ \n        bodyB: ropeA.bodies[0],\n        pointB: { x: -25, y: 0 },\n        pointA: { x: ropeA.bodies[0].position.x, y: ropeA.bodies[0].position.y },\n        stiffness: 0.5\n    }));\n    \n    group = Body.nextGroup(true);\n    \n    var ropeB = Composites.stack(350, 50, 10, 1, 10, 10, function(x, y) {\n        return Bodies.circle(x, y, 20, { collisionFilter: { group: group } });\n    });\n    \n    Composites.chain(ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2, render: { type: 'line' } });\n    Composite.add(ropeB, Constraint.create({ \n        bodyB: ropeB.bodies[0],\n        pointB: { x: -20, y: 0 },\n        pointA: { x: ropeB.bodies[0].position.x, y: ropeB.bodies[0].position.y },\n        stiffness: 0.5\n    }));\n    \n    group = Body.nextGroup(true);\n\n    var ropeC = Composites.stack(600, 50, 13, 1, 10, 10, function(x, y) {\n        return Bodies.rectangle(x - 20, y, 50, 20, { collisionFilter: { group: group }, chamfer: 5 });\n    });\n    \n    Composites.chain(ropeC, 0.3, 0, -0.3, 0, { stiffness: 1, length: 0 });\n    Composite.add(ropeC, Constraint.create({ \n        bodyB: ropeC.bodies[0],\n        pointB: { x: -20, y: 0 },\n        pointA: { x: ropeC.bodies[0].position.x, y: ropeC.bodies[0].position.y },\n        stiffness: 0.5\n    }));\n    \n    Composite.add(world, [\n        ropeA,\n        ropeB,\n        ropeC,\n        Bodies.rectangle(400, 600, 1200, 50.5, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 700, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.chains.title = 'Chains';\nExample.chains.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.chains;\n}\n"
  },
  {
    "path": "examples/circleStack.js",
    "content": "var Example = Example || {};\n\nExample.circleStack = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(100, 600 - 21 - 20 * 20, 10, 10, 20, 0, function(x, y) {\n        return Bodies.circle(x, y, 20);\n    });\n    \n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true }),\n        stack\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n    \n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n    \n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.circleStack.title = 'Circle Stack';\nExample.circleStack.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.circleStack;\n}\n"
  },
  {
    "path": "examples/cloth.js",
    "content": "var Example = Example || {};\n\nExample.cloth = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // see cloth function defined later in this file\n    var cloth = Example.cloth.cloth(200, 200, 20, 12, 5, 5, false, 8);\n\n    for (var i = 0; i < 20; i++) {\n        cloth.bodies[i].isStatic = true;\n    }\n\n    Composite.add(world, [\n        cloth,\n        Bodies.circle(300, 500, 80, { isStatic: true, render: { fillStyle: '#060a19' }}),\n        Bodies.rectangle(500, 480, 80, 80, { isStatic: true, render: { fillStyle: '#060a19' }}),\n        Bodies.rectangle(400, 609, 800, 50, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.98,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.cloth.title = 'Cloth';\nExample.cloth.for = '>=0.14.2';\n\n/**\n* Creates a simple cloth like object.\n* @method cloth\n* @param {number} xx\n* @param {number} yy\n* @param {number} columns\n* @param {number} rows\n* @param {number} columnGap\n* @param {number} rowGap\n* @param {boolean} crossBrace\n* @param {number} particleRadius\n* @param {} particleOptions\n* @param {} constraintOptions\n* @return {composite} A new composite cloth\n*/\nExample.cloth.cloth = function(xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) {\n    var Body = Matter.Body,\n        Bodies = Matter.Bodies,\n        Common = Matter.Common,\n        Composites = Matter.Composites;\n\n    var group = Body.nextGroup(true);\n    particleOptions = Common.extend({ inertia: Infinity, friction: 0.00001, collisionFilter: { group: group }, render: { visible: false }}, particleOptions);\n    constraintOptions = Common.extend({ stiffness: 0.06, render: { type: 'line', anchors: false } }, constraintOptions);\n\n    var cloth = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y) {\n        return Bodies.circle(x, y, particleRadius, particleOptions);\n    });\n\n    Composites.mesh(cloth, columns, rows, crossBrace, constraintOptions);\n\n    cloth.label = 'Cloth Body';\n\n    return cloth;\n};\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.cloth;\n}\n"
  },
  {
    "path": "examples/collisionFiltering.js",
    "content": "var Example = Example || {};\n\nExample.collisionFiltering = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            wireframes: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // define our categories (as bit fields, there are up to 32 available)\n    var defaultCategory = 0x0001,\n        redCategory = 0x0002,\n        greenCategory = 0x0004,\n        blueCategory = 0x0008;\n\n    var colorA = '#f55a3c',\n        colorB = '#063e7b',\n        colorC = '#f5d259';\n\n    // add floor\n    Composite.add(world, Bodies.rectangle(400, 600, 900, 50, { \n        isStatic: true,\n        render: {\n            fillStyle: 'transparent',\n            lineWidth: 1\n        } \n    }));\n\n    // create a stack with varying body categories (but these bodies can all collide with each other)\n    Composite.add(world,\n        Composites.stack(275, 100, 5, 9, 10, 10, function(x, y, column, row) {\n            var category = redCategory,\n                color = colorA;\n\n            if (row > 5) {\n                category = blueCategory;\n                color = colorB;\n            } else if (row > 2) {\n                category = greenCategory;\n                color = colorC;\n            }\n\n            return Bodies.circle(x, y, 20, {\n                collisionFilter: {\n                    category: category\n                },\n                render: {\n                    strokeStyle: color,\n                    fillStyle: 'transparent',\n                    lineWidth: 1\n                }\n            });\n        })\n    );\n\n    // this body will only collide with the walls and the green bodies\n    Composite.add(world,\n        Bodies.circle(310, 40, 30, {\n            collisionFilter: {\n                mask: defaultCategory | greenCategory\n            },\n            render: {\n                fillStyle: colorC\n            }\n        })\n    );\n\n    // this body will only collide with the walls and the red bodies\n    Composite.add(world,\n        Bodies.circle(400, 40, 30, {\n            collisionFilter: {\n                mask: defaultCategory | redCategory\n            },\n            render: {\n                fillStyle: colorA\n            }\n        })\n    );\n\n    // this body will only collide with the walls and the blue bodies\n    Composite.add(world,\n        Bodies.circle(480, 40, 30, {\n            collisionFilter: {\n                mask: defaultCategory | blueCategory\n            },\n            render: {\n                fillStyle: colorB\n            }\n        })\n    );\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // red category objects should not be draggable with the mouse\n    mouseConstraint.collisionFilter.mask = defaultCategory | blueCategory | greenCategory;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.collisionFiltering.title = 'Collision Filtering';\nExample.collisionFiltering.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.collisionFiltering;\n}\n"
  },
  {
    "path": "examples/compositeManipulation.js",
    "content": "var Example = Example || {};\n\nExample.compositeManipulation = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Events = Matter.Events,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var stack = Composites.stack(200, 200, 4, 4, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 40, 40);\n    });\n\n    Composite.add(world, stack);\n\n    engine.gravity.y = 0;\n\n    Events.on(engine, 'afterUpdate', function(event) {\n        var time = engine.timing.timestamp,\n            timeScale = (event.delta || (1000 / 60)) / 1000;\n\n        Composite.translate(stack, {\n            x: Math.sin(time * 0.001) * 10 * timeScale,\n            y: 0\n        });\n\n        Composite.rotate(stack, Math.sin(time * 0.001) * 0.75 * timeScale, {\n            x: 300,\n            y: 300\n        });\n\n        var scale = 1 + (Math.sin(time * 0.001) * 0.75 * timeScale);\n\n        Composite.scale(stack, scale, scale, {\n            x: 300,\n            y: 300\n        });\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n    \n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.compositeManipulation.title = 'Composite Manipulation';\nExample.compositeManipulation.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.compositeManipulation;\n}\n"
  },
  {
    "path": "examples/compound.js",
    "content": "var Example = Example || {};\n\nExample.compound = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Constraint = Matter.Constraint,\n        Composite = Matter.Composite,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAxes: true,\n            showConvexHulls: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var size = 200,\n        x = 200,\n        y = 200,\n        partA = Bodies.rectangle(x, y, size, size / 5),\n        partB = Bodies.rectangle(x, y, size / 5, size, { render: partA.render });\n\n    var compoundBodyA = Body.create({\n        parts: [partA, partB]\n    });\n\n    size = 150;\n    x = 400;\n    y = 300;\n\n    var partC = Bodies.circle(x, y, 30),\n        partD = Bodies.circle(x + size, y, 30),\n        partE = Bodies.circle(x + size, y + size, 30),\n        partF = Bodies.circle(x, y + size, 30);\n\n    var compoundBodyB = Body.create({\n        parts: [partC, partD, partE, partF]\n    });\n\n    var constraint = Constraint.create({\n        pointA: { x: 400, y: 100 },\n        bodyB: compoundBodyB,\n        pointB: { x: 0, y: 0 }\n    });\n\n    Composite.add(world, [\n        compoundBodyA, \n        compoundBodyB, \n        constraint,\n        Bodies.rectangle(400, 600, 800, 50.5, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.compound.title = 'Compound Bodies';\nExample.compound.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.compound;\n}\n"
  },
  {
    "path": "examples/compoundStack.js",
    "content": "var Example = Example || {};\n\nExample.compoundStack = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var size = 50;\n\n    var stack = Composites.stack(100, 600 - 17 - size * 6, 12, 6, 0, 0, function(x, y) {\n        var partA = Bodies.rectangle(x, y, size, size / 5),\n            partB = Bodies.rectangle(x, y, size / 5, size, { render: partA.render });\n\n        return Body.create({\n            parts: [partA, partB]\n        });\n    });\n\n    Composite.add(world, [\n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(400, 609, 800, 50, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.compoundStack.title = 'Compound Stack';\nExample.compoundStack.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.compoundStack;\n}\n"
  },
  {
    "path": "examples/concave.js",
    "content": "var Example = Example || {};\n\nExample.concave = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Vertices = Matter.Vertices,\n        Bodies = Matter.Bodies;\n\n    // provide concave decomposition support library\n    Common.setDecomp(require('poly-decomp'));\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var arrow = Vertices.fromPath('40 0 40 20 100 20 100 80 40 80 40 100 0 50'),\n        chevron = Vertices.fromPath('100 0 75 50 100 100 25 100 0 50 25 0'),\n        star = Vertices.fromPath('50 0 63 38 100 38 69 59 82 100 50 75 18 100 31 59 0 38 37 38'),\n        horseShoe = Vertices.fromPath('35 7 19 17 14 38 14 58 25 79 45 85 65 84 65 66 46 67 34 59 30 44 33 29 45 23 66 23 66 7 53 7');\n\n    var stack = Composites.stack(50, 50, 6, 4, 10, 10, function(x, y) {\n        var color = Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1']);\n        return Bodies.fromVertices(x, y, Common.choose([arrow, chevron, star, horseShoe]), {\n            render: {\n                fillStyle: color,\n                strokeStyle: color,\n                lineWidth: 1\n            }\n        }, true);\n    });\n\n    Composite.add(world, stack);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.concave.title = 'Concave';\nExample.concave.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.concave;\n}\n"
  },
  {
    "path": "examples/constraints.js",
    "content": "var Example = Example || {};\n\nExample.constraints = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add stiff global constraint\n    var body = Bodies.polygon(150, 200, 5, 30);\n\n    var constraint = Constraint.create({\n        pointA: { x: 150, y: 100 },\n        bodyB: body,\n        pointB: { x: -10, y: -10 }\n    });\n\n    Composite.add(world, [body, constraint]);\n\n    // add soft global constraint\n    var body = Bodies.polygon(280, 100, 3, 30);\n\n    var constraint = Constraint.create({\n        pointA: { x: 280, y: 120 },\n        bodyB: body,\n        pointB: { x: -10, y: -7 },\n        stiffness: 0.001\n    });\n\n    Composite.add(world, [body, constraint]);\n\n    // add damped soft global constraint\n    var body = Bodies.polygon(400, 100, 4, 30);\n\n    var constraint = Constraint.create({\n        pointA: { x: 400, y: 120 },\n        bodyB: body,\n        pointB: { x: -10, y: -10 },\n        stiffness: 0.001,\n        damping: 0.05\n    });\n\n    Composite.add(world, [body, constraint]);\n\n    // add revolute constraint\n    var body = Bodies.rectangle(600, 200, 200, 20);\n    var ball = Bodies.circle(550, 150, 20);\n\n    var constraint = Constraint.create({\n        pointA: { x: 600, y: 200 },\n        bodyB: body,\n        length: 0\n    });\n\n    Composite.add(world, [body, ball, constraint]);\n\n    // add revolute multi-body constraint\n    var body = Bodies.rectangle(500, 400, 100, 20, { collisionFilter: { group: -1 } });\n    var ball = Bodies.circle(600, 400, 20, { collisionFilter: { group: -1 } });\n\n    var constraint = Constraint.create({\n        bodyA: body,\n        bodyB: ball\n    });\n\n    Composite.add(world, [body, ball, constraint]);\n\n    // add stiff multi-body constraint\n    var bodyA = Bodies.polygon(100, 400, 6, 20);\n    var bodyB = Bodies.polygon(200, 400, 1, 50);\n\n    var constraint = Constraint.create({\n        bodyA: bodyA,\n        pointA: { x: -10, y: -10 },\n        bodyB: bodyB,\n        pointB: { x: -10, y: -10 }\n    });\n\n    Composite.add(world, [bodyA, bodyB, constraint]);\n\n    // add soft global constraint\n    var bodyA = Bodies.polygon(300, 400, 4, 20);\n    var bodyB = Bodies.polygon(400, 400, 3, 30);\n\n    var constraint = Constraint.create({\n        bodyA: bodyA,\n        pointA: { x: -10, y: -10 },\n        bodyB: bodyB,\n        pointB: { x: -10, y: -7 },\n        stiffness: 0.001\n    });\n\n    Composite.add(world, [bodyA, bodyB, constraint]);\n\n    // add damped soft global constraint\n    var bodyA = Bodies.polygon(500, 400, 6, 30);\n    var bodyB = Bodies.polygon(600, 400, 7, 60);\n\n    var constraint = Constraint.create({\n        bodyA: bodyA,\n        pointA: { x: -10, y: -10 },\n        bodyB: bodyB,\n        pointB: { x: -10, y: -10 },\n        stiffness: 0.001,\n        damping: 0.1\n    });\n\n    Composite.add(world, [bodyA, bodyB, constraint]);\n\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                // allow bodies on mouse to rotate\n                angularStiffness: 0,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.constraints.title = 'Constraints';\nExample.constraints.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.constraints;\n}\n"
  },
  {
    "path": "examples/doublePendulum.js",
    "content": "var Example = Example || {};\n\nExample.doublePendulum = function() {\n    var Engine = Matter.Engine,\n        Events = Matter.Events,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies,\n        Vector = Matter.Vector;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            wireframes: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var group = Body.nextGroup(true),\n        length = 200,\n        width = 25;\n        \n    var pendulum = Composites.stack(350, 160, 2, 1, -20, 0, function(x, y) {\n        return Bodies.rectangle(x, y, length, width, { \n            collisionFilter: { group: group },\n            frictionAir: 0,\n            chamfer: 5,\n            render: {\n                fillStyle: 'transparent',\n                lineWidth: 1\n            }\n        });\n    });\n\n    engine.gravity.scale = 0.002;\n    \n    Composites.chain(pendulum, 0.45, 0, -0.45, 0, { \n        stiffness: 0.9, \n        length: 0,\n        angularStiffness: 0.7,\n        render: {\n            strokeStyle: '#4a485b'\n        }\n    });\n    \n    Composite.add(pendulum, Constraint.create({ \n        bodyB: pendulum.bodies[0],\n        pointB: { x: -length * 0.42, y: 0 },\n        pointA: { x: pendulum.bodies[0].position.x - length * 0.42, y: pendulum.bodies[0].position.y },\n        stiffness: 0.9,\n        length: 0,\n        render: {\n            strokeStyle: '#4a485b'\n        }\n    }));\n\n    var lowerArm = pendulum.bodies[1];\n\n    Body.rotate(lowerArm, -Math.PI * 0.3, {\n        x: lowerArm.position.x - 100,\n        y: lowerArm.position.y\n    });\n    \n    Composite.add(world, pendulum);\n\n    var trail = [];\n\n    Events.on(render, 'afterRender', function() {\n        trail.unshift({\n            position: Vector.clone(lowerArm.position),\n            speed: lowerArm.speed\n        });\n\n        Render.startViewTransform(render);\n        render.context.globalAlpha = 0.7;\n\n        for (var i = 0; i < trail.length; i += 1) {\n            var point = trail[i].position,\n                speed = trail[i].speed;\n            \n            var hue = 250 + Math.round((1 - Math.min(1, speed / 10)) * 170);\n            render.context.fillStyle = 'hsl(' + hue + ', 100%, 55%)';\n            render.context.fillRect(point.x, point.y, 2, 2);\n        }\n\n        render.context.globalAlpha = 1;\n        Render.endViewTransform(render);\n\n        if (trail.length > 2000) {\n            trail.pop();\n        }\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 700, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.doublePendulum.title = 'Double Pendulum';\nExample.doublePendulum.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.doublePendulum;\n}\n"
  },
  {
    "path": "examples/events.js",
    "content": "var Example = Example || {};\n\nExample.events = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Events = Matter.Events,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            wireframes: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // an example of using composite events on the world\n    Events.on(world, 'afterAdd', function(event) {\n        // do something with event.object\n    });\n\n    var lastTime = Common.now();\n\n    // an example of using beforeUpdate event on an engine\n    Events.on(engine, 'beforeUpdate', function(event) {\n        var engine = event.source;\n\n        // apply random forces every 5 secs\n        if (Common.now() - lastTime >= 5000) {\n            shakeScene(engine);\n\n            // update last time\n            lastTime = Common.now();\n        }\n    });\n\n    // an example of using collisionStart event on an engine\n    Events.on(engine, 'collisionStart', function(event) {\n        var pairs = event.pairs;\n\n        // change object colours to show those starting a collision\n        for (var i = 0; i < pairs.length; i++) {\n            var pair = pairs[i];\n            pair.bodyA.render.fillStyle = '#333';\n            pair.bodyB.render.fillStyle = '#333';\n        }\n    });\n\n    // an example of using collisionActive event on an engine\n    Events.on(engine, 'collisionActive', function(event) {\n        var pairs = event.pairs;\n\n        // change object colours to show those in an active collision (e.g. resting contact)\n        for (var i = 0; i < pairs.length; i++) {\n            var pair = pairs[i];\n            pair.bodyA.render.fillStyle = '#333';\n            pair.bodyB.render.fillStyle = '#333';\n        }\n    });\n\n    // an example of using collisionEnd event on an engine\n    Events.on(engine, 'collisionEnd', function(event) {\n        var pairs = event.pairs;\n\n        // change object colours to show those ending a collision\n        for (var i = 0; i < pairs.length; i++) {\n            var pair = pairs[i];\n\n            pair.bodyA.render.fillStyle = '#222';\n            pair.bodyB.render.fillStyle = '#222';\n        }\n    });\n\n    var bodyStyle = { fillStyle: '#222' };\n\n    // scene code\n    Composite.add(world, [\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true, render: bodyStyle }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true, render: bodyStyle }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true, render: bodyStyle }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true, render: bodyStyle })\n    ]);\n\n    var stack = Composites.stack(70, 100, 9, 4, 50, 50, function(x, y) {\n        return Bodies.circle(x, y, 15, { restitution: 1, render: bodyStyle });\n    });\n    \n    Composite.add(world, stack);\n\n    var shakeScene = function(engine) {\n        var timeScale = (1000 / 60) / engine.timing.lastDelta;\n        var bodies = Composite.allBodies(engine.world);\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (!body.isStatic && body.position.y >= 500) {\n                // scale force for mass and time applied\n                var forceMagnitude = (0.03 * body.mass) * timeScale;\n\n                // apply the force over a single update\n                Body.applyForce(body, body.position, { \n                    x: (forceMagnitude + Common.random() * forceMagnitude) * Common.choose([1, -1]), \n                    y: -forceMagnitude + Common.random() * -forceMagnitude\n                });\n            }\n        }\n    };\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // an example of using mouse events on a mouse\n    Events.on(mouseConstraint, 'mousedown', function(event) {\n        var mousePosition = event.mouse.position;\n        console.log('mousedown at ' + mousePosition.x + ' ' + mousePosition.y);\n        shakeScene(engine);\n    });\n\n    // an example of using mouse events on a mouse\n    Events.on(mouseConstraint, 'mouseup', function(event) {\n        var mousePosition = event.mouse.position;\n        console.log('mouseup at ' + mousePosition.x + ' ' + mousePosition.y);\n    });\n\n    // an example of using mouse events on a mouse\n    Events.on(mouseConstraint, 'startdrag', function(event) {\n        console.log('startdrag', event);\n    });\n\n    // an example of using mouse events on a mouse\n    Events.on(mouseConstraint, 'enddrag', function(event) {\n        console.log('enddrag', event);\n    });\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.events.title = 'Events';\nExample.events.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.events;\n}\n"
  },
  {
    "path": "examples/friction.js",
    "content": "var Example = Example || {};\n\nExample.friction = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    Composite.add(world, [\n        Bodies.rectangle(300, 180, 700, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(300, 70, 40, 40, { friction: 0.001 })\n    ]);\n\n    Composite.add(world, [\n        Bodies.rectangle(300, 350, 700, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(300, 250, 40, 40, { friction: 0.0005 })\n    ]);\n\n    Composite.add(world, [\n        Bodies.rectangle(300, 520, 700, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' } }),\n        Bodies.rectangle(300, 430, 40, 40, { friction: 0 })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.friction.title = 'Friction';\nExample.friction.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.friction;\n}\n"
  },
  {
    "path": "examples/gravity.js",
    "content": "var Example = Example || {};\n\nExample.gravity = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showVelocity: true,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50.5, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    engine.gravity.y = -1;\n    \n    var stack = Composites.stack(50, 120, 11, 5, 0, 0, function(x, y) {\n        switch (Math.round(Common.random(0, 1))) {\n\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));\n            }\n        case 1:\n            return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));\n\n        }\n    });\n    \n    Composite.add(world, stack);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.gravity.title = 'Reverse Gravity';\nExample.gravity.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.gravity;\n}\n"
  },
  {
    "path": "examples/gyro.js",
    "content": "var Example = Example || {};\n\nExample.gyro = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 10, 5, 0, 0, function(x, y) {\n        var sides = Math.round(Common.random(1, 8));\n\n        // round the edges of some bodies\n        var chamfer = null;\n        if (sides > 2 && Common.random() > 0.7) {\n            chamfer = {\n                radius: 10\n            };\n        }\n\n        switch (Math.round(Common.random(0, 1))) {\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), { chamfer: chamfer });\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), { chamfer: chamfer });\n            }\n        case 1:\n            return Bodies.polygon(x, y, sides, Common.random(25, 50), { chamfer: chamfer });\n        }\n    });\n\n    Composite.add(world, [\n        stack,\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add gyro control\n    if (typeof window !== 'undefined') {\n        var updateGravity = function(event) {\n            var orientation = typeof window.orientation !== 'undefined' ? window.orientation : 0,\n                gravity = engine.gravity;\n\n            if (orientation === 0) {\n                gravity.x = Common.clamp(event.gamma, -90, 90) / 90;\n                gravity.y = Common.clamp(event.beta, -90, 90) / 90;\n            } else if (orientation === 180) {\n                gravity.x = Common.clamp(event.gamma, -90, 90) / 90;\n                gravity.y = Common.clamp(-event.beta, -90, 90) / 90;\n            } else if (orientation === 90) {\n                gravity.x = Common.clamp(event.beta, -90, 90) / 90;\n                gravity.y = Common.clamp(-event.gamma, -90, 90) / 90;\n            } else if (orientation === -90) {\n                gravity.x = Common.clamp(-event.beta, -90, 90) / 90;\n                gravity.y = Common.clamp(event.gamma, -90, 90) / 90;\n            }\n        };\n\n        window.addEventListener('deviceorientation', updateGravity);\n    }\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n            if (typeof window !== 'undefined') {\n                window.removeEventListener('deviceorientation', updateGravity);\n            }\n        }\n    };\n};\n\nExample.gyro.title = 'Gyroscope';\nExample.gyro.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.gyro;\n}\n"
  },
  {
    "path": "examples/index.js",
    "content": "module.exports = {\n    airFriction: require('./airFriction.js'),\n    avalanche: require('./avalanche.js'),\n    ballPool: require('./ballPool.js'),\n    bridge: require('./bridge.js'),\n    car: require('./car.js'),\n    catapult: require('./catapult.js'),\n    chains: require('./chains.js'),\n    circleStack: require('./circleStack.js'),\n    cloth: require('./cloth.js'),\n    collisionFiltering: require('./collisionFiltering.js'),\n    compositeManipulation: require('./compositeManipulation.js'),\n    compound: require('./compound.js'),\n    compoundStack: require('./compoundStack.js'),\n    concave: require('./concave.js'),\n    constraints: require('./constraints.js'),\n    doublePendulum: require('./doublePendulum.js'),\n    events: require('./events.js'),\n    friction: require('./friction.js'),\n    gravity: require('./gravity.js'),\n    gyro: require('./gyro.js'),\n    manipulation: require('./manipulation.js'),\n    mixed: require('./mixed.js'),\n    newtonsCradle: require('./newtonsCradle.js'),\n    ragdoll: require('./ragdoll.js'),\n    pyramid: require('./pyramid.js'),\n    raycasting: require('./raycasting.js'),\n    restitution: require('./restitution.js'),\n    rounded: require('./rounded.js'),\n    remove: require('./remove.js'),\n    renderResize: require('./renderResize.js'),\n    sensors: require('./sensors.js'),\n    sleeping: require('./sleeping.js'),\n    slingshot: require('./slingshot.js'),\n    softBody: require('./softBody.js'),\n    sprites: require('./sprites.js'),\n    stack: require('./stack.js'),\n    staticFriction: require('./staticFriction.js'),\n    stats: require('./stats.js'),\n    stress: require('./stress.js'),\n    stress2: require('./stress2.js'),\n    stress3: require('./stress3.js'),\n    stress4: require('./stress4.js'),\n    substep: require('./substep.js'),\n    svg: require('./svg.js'),\n    terrain: require('./terrain.js'),\n    timescale: require('./timescale.js'),\n    views: require('./views.js'),\n    wreckingBall: require('./wreckingBall.js')\n};"
  },
  {
    "path": "examples/manipulation.js",
    "content": "var Example = Example || {};\n\nExample.manipulation = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Events = Matter.Events,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAxes: true,\n            showCollisions: true,\n            showConvexHulls: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var bodyA = Bodies.rectangle(100, 300, 50, 50, { isStatic: true, render: { fillStyle: '#060a19' } }),\n        bodyB = Bodies.rectangle(200, 200, 50, 50),\n        bodyC = Bodies.rectangle(300, 200, 50, 50),\n        bodyD = Bodies.rectangle(400, 200, 50, 50),\n        bodyE = Bodies.rectangle(550, 200, 50, 50),\n        bodyF = Bodies.rectangle(700, 200, 50, 50),\n        bodyG = Bodies.circle(400, 100, 25, { render: { fillStyle: '#060a19' } });\n\n    // add compound body\n    var partA = Bodies.rectangle(600, 200, 120 * 0.8, 50 * 0.8, { render: { fillStyle: '#060a19' } }),\n        partB = Bodies.rectangle(660, 200, 50 * 0.8, 190 * 0.8, { render: { fillStyle: '#060a19' } }),\n        compound = Body.create({\n            parts: [partA, partB],\n            isStatic: true\n        });\n\n    Body.setPosition(compound, { x: 600, y: 300 });\n\n    Composite.add(world, [bodyA, bodyB, bodyC, bodyD, bodyE, bodyF, bodyG, compound]);\n\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var lastTime = 0,\n        scaleRate = 0.6;\n\n    Events.on(engine, 'beforeUpdate', function(event) {\n        var timeScale = (event.delta || (1000 / 60)) / 1000;\n\n        if (scaleRate > 0) {\n            Body.scale(bodyF, 1 + (scaleRate * timeScale), 1 + (scaleRate * timeScale));\n\n            // modify bodyE vertices\n            bodyE.vertices[0].x -= 0.2 * timeScale;\n            bodyE.vertices[0].y -= 0.2 * timeScale;\n            bodyE.vertices[1].x += 0.2 * timeScale;\n            bodyE.vertices[1].y -= 0.2 * timeScale;\n            Body.setVertices(bodyE, bodyE.vertices);\n        }\n\n        // make bodyA move up and down\n        var py = 300 + 100 * Math.sin(engine.timing.timestamp * 0.002);\n\n        // manual update velocity required for older releases\n        if (Matter.version === '0.18.0') {\n            Body.setVelocity(bodyA, { x: 0, y: py - bodyA.position.y });\n            Body.setVelocity(compound, { x: 0, y: py - compound.position.y });\n            Body.setAngularVelocity(compound, 1 * Math.PI * timeScale);\n        }\n\n        // move body and update velocity\n        Body.setPosition(bodyA, { x: 100, y: py }, true);\n\n        // move compound body move up and down and update velocity\n        Body.setPosition(compound, { x: 600, y: py }, true);\n\n        // rotate compound body and update angular velocity\n        Body.rotate(compound, 1 * Math.PI * timeScale, null, true);\n\n        // after first 0.8 sec (simulation time)\n        if (engine.timing.timestamp >= 800)\n            Body.setStatic(bodyG, true);\n\n        // every 1.5 sec (simulation time)\n        if (engine.timing.timestamp - lastTime >= 1500) {\n            Body.setVelocity(bodyB, { x: 0, y: -10 });\n            Body.setAngle(bodyC, -Math.PI * 0.26);\n            Body.setAngularVelocity(bodyD, 0.2);\n\n            // stop scaling\n            scaleRate = 0;\n            \n            // update last time\n            lastTime = engine.timing.timestamp;\n        }\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.manipulation.title = 'Manipulation';\nExample.manipulation.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.manipulation;\n}\n"
  },
  {
    "path": "examples/mixed.js",
    "content": "var Example = Example || {};\n\nExample.mixed = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 10, 5, 0, 0, function(x, y) {\n        var sides = Math.round(Common.random(1, 8));\n\n        // round the edges of some bodies\n        var chamfer = null;\n        if (sides > 2 && Common.random() > 0.7) {\n            chamfer = {\n                radius: 10\n            };\n        }\n\n        switch (Math.round(Common.random(0, 1))) {\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), { chamfer: chamfer });\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), { chamfer: chamfer });\n            }\n        case 1:\n            return Bodies.polygon(x, y, sides, Common.random(25, 50), { chamfer: chamfer });\n        }\n    });\n\n    Composite.add(world, stack);\n\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.mixed.title = 'Mixed Shapes';\nExample.mixed.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.mixed;\n}\n"
  },
  {
    "path": "examples/newtonsCradle.js",
    "content": "var Example = Example || {};\n\nExample.newtonsCradle = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // see newtonsCradle function defined later in this file\n    var cradle = Example.newtonsCradle.newtonsCradle(280, 100, 5, 30, 200);\n    Composite.add(world, cradle);\n    Body.translate(cradle.bodies[0], { x: -180, y: -100 });\n    \n    cradle = Example.newtonsCradle.newtonsCradle(280, 380, 7, 20, 140);\n    Composite.add(world, cradle);\n    Body.translate(cradle.bodies[0], { x: -140, y: -100 });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 50 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.newtonsCradle.title = 'Newton\\'s Cradle';\nExample.newtonsCradle.for = '>=0.14.2';\n\n/**\n* Creates a composite with a Newton's Cradle setup of bodies and constraints.\n* @method newtonsCradle\n* @param {number} xx\n* @param {number} yy\n* @param {number} number\n* @param {number} size\n* @param {number} length\n* @return {composite} A new composite newtonsCradle body\n*/\nExample.newtonsCradle.newtonsCradle = function(xx, yy, number, size, length) {\n    var Composite = Matter.Composite,\n        Constraint = Matter.Constraint,\n        Bodies = Matter.Bodies;\n\n    var newtonsCradle = Composite.create({ label: 'Newtons Cradle' });\n\n    for (var i = 0; i < number; i++) {\n        var separation = 1.9,\n            circle = Bodies.circle(xx + i * (size * separation), yy + length, size, \n                { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 0, slop: size * 0.02 }),\n            constraint = Constraint.create({ pointA: { x: xx + i * (size * separation), y: yy }, bodyB: circle });\n\n        Composite.addBody(newtonsCradle, circle);\n        Composite.addConstraint(newtonsCradle, constraint);\n    }\n\n    return newtonsCradle;\n};\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.newtonsCradle;\n}\n"
  },
  {
    "path": "examples/pyramid.js",
    "content": "var Example = Example || {};\n\nExample.pyramid = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.pyramid(100, 605 - 25 - 16 * 20, 15, 10, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 40, 40);\n    });\n    \n    Composite.add(world, [\n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(400, 605, 800, 50, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.pyramid.title = 'Pyramid';\nExample.pyramid.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.pyramid;\n}\n"
  },
  {
    "path": "examples/ragdoll.js",
    "content": "var Example = Example || {};\n\nExample.ragdoll = function() {\n    var Engine = Matter.Engine,\n        Events = Matter.Events,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Common = Matter.Common,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // create stairs\n    var stairCount = (render.bounds.max.y - render.bounds.min.y) / 50;\n\n    var stack = Composites.stack(0, 0, stairCount + 2, 1, 0, 0, function(x, y, column) {\n        return Bodies.rectangle(x - 50, y + column * 50, 100, 1000, {\n            isStatic: true,\n            render: {\n                fillStyle: '#060a19',\n                strokeStyle: '#ffffff',\n                lineWidth: 1\n            }\n        });\n    });\n\n    // create obstacles\n    var obstacles = Composites.stack(300, 0, 15, 3, 10, 10, function(x, y, column) {\n        var sides = Math.round(Common.random(1, 8)),\n            options = {\n                render: {\n                    fillStyle: Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1'])\n                }\n            };\n\n        switch (Math.round(Common.random(0, 1))) {\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), options);\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), options);\n            }\n        case 1:\n            return Bodies.polygon(x, y, sides, Common.random(25, 50), options);\n        }\n    });\n\n    var ragdolls = Composite.create();\n\n    for (var i = 0; i < 1; i += 1) {\n        var ragdoll = Example.ragdoll.ragdoll(200, -1000 * i, 1.3);\n\n        Composite.add(ragdolls, ragdoll);\n    }\n\n    Composite.add(world, [stack, obstacles, ragdolls]);\n\n    var timeScaleTarget = 1,\n        lastTime = Common.now();\n\n    Events.on(engine, 'afterUpdate', function(event) {\n        var timeScale = (event.delta || (1000 / 60)) / 1000;\n\n        // tween the timescale for slow-mo\n        if (mouse.button === -1) {\n            engine.timing.timeScale += (timeScaleTarget - engine.timing.timeScale) * 3 * timeScale;\n        } else {\n            engine.timing.timeScale = 1;\n        }\n\n        // every 2 sec (real time)\n        if (Common.now() - lastTime >= 2000) {\n            // flip the timescale\n            if (timeScaleTarget < 1) {\n                timeScaleTarget = 1;\n            } else {\n                timeScaleTarget = 0.05;\n            }\n\n            // update last time\n            lastTime = Common.now();\n        }\n\n        for (var i = 0; i < stack.bodies.length; i += 1) {\n            var body = stack.bodies[i];\n\n            // animate stairs\n            Body.translate(body, {\n                x: -30 * timeScale,\n                y: -30 * timeScale\n            });\n\n            // loop stairs when they go off screen\n            if (body.position.x < -50) {\n                Body.setPosition(body, {\n                    x: 50 * (stack.bodies.length - 1),\n                    y: 25 + render.bounds.max.y + (body.bounds.max.y - body.bounds.min.y) * 0.5\n                });\n                \n                Body.setVelocity(body, {\n                    x: 0,\n                    y: 0\n                });\n            }\n        }\n\n        for (i = 0; i < ragdolls.composites.length; i += 1) {\n            var ragdoll = ragdolls.composites[i],\n                bounds = Composite.bounds(ragdoll);\n\n            // move ragdolls back to the top of the screen\n            if (bounds.min.y > render.bounds.max.y + 100) {\n                Composite.translate(ragdoll, {\n                    x: -bounds.min.x * 0.9,\n                    y: -render.bounds.max.y - 400\n                });\n            }\n        }\n\n        for (i = 0; i < obstacles.bodies.length; i += 1) {\n            var body = obstacles.bodies[i],\n                bounds = body.bounds;\n\n            // move obstacles back to the top of the screen\n            if (bounds.min.y > render.bounds.max.y + 100) {\n                Body.translate(body, {\n                    x: -bounds.min.x,\n                    y: -render.bounds.max.y - 300\n                });\n            }\n        }\n    });\n\n    // add mouse control and make the mouse revolute\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.6,\n                length: 0,\n                angularStiffness: 0,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.ragdoll.ragdoll = function(x, y, scale, options) {\n    scale = typeof scale === 'undefined' ? 1 : scale;\n\n    var Body = Matter.Body,\n        Bodies = Matter.Bodies,\n        Constraint = Matter.Constraint,\n        Composite = Matter.Composite,\n        Common = Matter.Common;\n\n    var headOptions = Common.extend({\n        label: 'head',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: [15 * scale, 15 * scale, 15 * scale, 15 * scale]\n        },\n        render: {\n            fillStyle: '#FFBC42'\n        }\n    }, options);\n\n    var chestOptions = Common.extend({\n        label: 'chest',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: [20 * scale, 20 * scale, 26 * scale, 26 * scale]\n        },\n        render: {\n            fillStyle: '#E0A423'\n        }\n    }, options);\n\n    var leftArmOptions = Common.extend({\n        label: 'left-arm',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: 10 * scale\n        },\n        render: {\n            fillStyle: '#FFBC42'\n        }\n    }, options);\n\n    var leftLowerArmOptions = Common.extend({}, leftArmOptions, {\n        render: {\n            fillStyle: '#E59B12'\n        }\n    });\n\n    var rightArmOptions = Common.extend({\n        label: 'right-arm',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: 10 * scale\n        },\n        render: {\n            fillStyle: '#FFBC42'\n        }\n    }, options);\n\n    var rightLowerArmOptions = Common.extend({}, rightArmOptions, {\n        render: {\n            fillStyle: '#E59B12'\n        }\n    });\n\n    var leftLegOptions = Common.extend({\n        label: 'left-leg',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: 10 * scale\n        },\n        render: {\n            fillStyle: '#FFBC42'\n        }\n    }, options);\n\n    var leftLowerLegOptions = Common.extend({}, leftLegOptions, {\n        render: {\n            fillStyle: '#E59B12'\n        }\n    });\n\n    var rightLegOptions = Common.extend({\n        label: 'right-leg',\n        collisionFilter: {\n            group: Body.nextGroup(true)\n        },\n        chamfer: {\n            radius: 10 * scale\n        },\n        render: {\n            fillStyle: '#FFBC42'\n        }\n    }, options);\n\n    var rightLowerLegOptions = Common.extend({}, rightLegOptions, {\n        render: {\n            fillStyle: '#E59B12'\n        }\n    });\n\n    var head = Bodies.rectangle(x, y - 60 * scale, 34 * scale, 40 * scale, headOptions);\n    var chest = Bodies.rectangle(x, y, 55 * scale, 80 * scale, chestOptions);\n    var rightUpperArm = Bodies.rectangle(x + 39 * scale, y - 15 * scale, 20 * scale, 40 * scale, rightArmOptions);\n    var rightLowerArm = Bodies.rectangle(x + 39 * scale, y + 25 * scale, 20 * scale, 60 * scale, rightLowerArmOptions);\n    var leftUpperArm = Bodies.rectangle(x - 39 * scale, y - 15 * scale, 20 * scale, 40 * scale, leftArmOptions);\n    var leftLowerArm = Bodies.rectangle(x - 39 * scale, y + 25 * scale, 20 * scale, 60 * scale, leftLowerArmOptions);\n    var leftUpperLeg = Bodies.rectangle(x - 20 * scale, y + 57 * scale, 20 * scale, 40 * scale, leftLegOptions);\n    var leftLowerLeg = Bodies.rectangle(x - 20 * scale, y + 97 * scale, 20 * scale, 60 * scale, leftLowerLegOptions);\n    var rightUpperLeg = Bodies.rectangle(x + 20 * scale, y + 57 * scale, 20 * scale, 40 * scale, rightLegOptions);\n    var rightLowerLeg = Bodies.rectangle(x + 20 * scale, y + 97 * scale, 20 * scale, 60 * scale, rightLowerLegOptions);\n\n    var chestToRightUpperArm = Constraint.create({\n        bodyA: chest,\n        pointA: {\n            x: 24 * scale,\n            y: -23 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -8 * scale\n        },\n        bodyB: rightUpperArm,\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var chestToLeftUpperArm = Constraint.create({\n        bodyA: chest,\n        pointA: {\n            x: -24 * scale,\n            y: -23 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -8 * scale\n        },\n        bodyB: leftUpperArm,\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var chestToLeftUpperLeg = Constraint.create({\n        bodyA: chest,\n        pointA: {\n            x: -10 * scale,\n            y: 30 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -10 * scale\n        },\n        bodyB: leftUpperLeg,\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var chestToRightUpperLeg = Constraint.create({\n        bodyA: chest,\n        pointA: {\n            x: 10 * scale,\n            y: 30 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -10 * scale\n        },\n        bodyB: rightUpperLeg,\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var upperToLowerRightArm = Constraint.create({\n        bodyA: rightUpperArm,\n        bodyB: rightLowerArm,\n        pointA: {\n            x: 0,\n            y: 15 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -25 * scale\n        },\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var upperToLowerLeftArm = Constraint.create({\n        bodyA: leftUpperArm,\n        bodyB: leftLowerArm,\n        pointA: {\n            x: 0,\n            y: 15 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -25 * scale\n        },\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var upperToLowerLeftLeg = Constraint.create({\n        bodyA: leftUpperLeg,\n        bodyB: leftLowerLeg,\n        pointA: {\n            x: 0,\n            y: 20 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -20 * scale\n        },\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var upperToLowerRightLeg = Constraint.create({\n        bodyA: rightUpperLeg,\n        bodyB: rightLowerLeg,\n        pointA: {\n            x: 0,\n            y: 20 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -20 * scale\n        },\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var headContraint = Constraint.create({\n        bodyA: head,\n        pointA: {\n            x: 0,\n            y: 25 * scale\n        },\n        pointB: {\n            x: 0,\n            y: -35 * scale\n        },\n        bodyB: chest,\n        stiffness: 0.6,\n        render: {\n            visible: false\n        }\n    });\n\n    var legToLeg = Constraint.create({\n        bodyA: leftLowerLeg,\n        bodyB: rightLowerLeg,\n        stiffness: 0.01,\n        render: {\n            visible: false\n        }\n    });\n\n    var person = Composite.create({\n        bodies: [\n            chest, head, leftLowerArm, leftUpperArm, \n            rightLowerArm, rightUpperArm, leftLowerLeg, \n            rightLowerLeg, leftUpperLeg, rightUpperLeg\n        ],\n        constraints: [\n            upperToLowerLeftArm, upperToLowerRightArm, chestToLeftUpperArm, \n            chestToRightUpperArm, headContraint, upperToLowerLeftLeg, \n            upperToLowerRightLeg, chestToLeftUpperLeg, chestToRightUpperLeg,\n            legToLeg\n        ]\n    });\n\n    return person;\n};\n\nExample.ragdoll.title = 'Ragdoll';\nExample.ragdoll.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.ragdoll;\n}\n"
  },
  {
    "path": "examples/raycasting.js",
    "content": "var Example = Example || {};\n\nExample.raycasting = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        Query = Matter.Query,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Events = Matter.Events,\n        Vertices = Matter.Vertices,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 12, 4, 0, 0, function(x, y) {\n        switch (Math.round(Common.random(0, 1))) {\n\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));\n            }\n        case 1:\n            var sides = Math.round(Common.random(1, 8));\n            sides = (sides === 3) ? 4 : sides;\n            return Bodies.polygon(x, y, sides, Common.random(20, 50));\n        }\n    });\n\n    // for testing raycasting on concave bodies\n    Common.setDecomp(require('poly-decomp'));\n\n    var star = Vertices.fromPath('50 0 63 38 100 38 69 59 82 100 50 75 18 100 31 59 0 38 37 38'),\n        concave = Bodies.fromVertices(200, 200, star);\n    \n    Composite.add(world, [\n        stack, \n        concave,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var collisions = [],\n        startPoint = { x: 400, y: 100 };\n\n    Events.on(engine, 'afterUpdate', function() {\n        var mouse = mouseConstraint.mouse,\n            bodies = Composite.allBodies(engine.world),\n            endPoint = mouse.position || { x: 100, y: 600 };\n\n        collisions = Query.ray(bodies, startPoint, endPoint);\n    });\n\n    Events.on(render, 'afterRender', function() {\n        var mouse = mouseConstraint.mouse,\n            context = render.context,\n            endPoint = mouse.position || { x: 100, y: 600 };\n\n        Render.startViewTransform(render);\n\n        context.beginPath();\n        context.moveTo(startPoint.x, startPoint.y);\n        context.lineTo(endPoint.x, endPoint.y);\n        if (collisions.length > 0) {\n            context.strokeStyle = '#fff';\n        } else {\n            context.strokeStyle = '#555';\n        }\n        context.lineWidth = 0.5;\n        context.stroke();\n\n        for (var i = 0; i < collisions.length; i++) {\n            var collision = collisions[i];\n            context.rect(collision.bodyA.position.x - 4.5, collision.bodyA.position.y - 4.5, 8, 8);\n        }\n\n        context.fillStyle = 'rgba(255,165,0,0.7)';\n        context.fill();\n\n        Render.endViewTransform(render);\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.raycasting.title = 'Raycasting';\nExample.raycasting.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.raycasting;\n}\n"
  },
  {
    "path": "examples/remove.js",
    "content": "var Example = Example || {};\n\nExample.remove = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies,\n        Events = Matter.Events;\n\n    // create engine\n    var engine = Engine.create({\n        enableSleeping: true\n    });\n\n    var world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            showSleeping: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    var createStack = function() {\n        return Composites.stack(20, 20, 10, 5, 0, 0, function(x, y) {\n            var sides = Math.round(Common.random(1, 8));\n\n            // round the edges of some bodies\n            var chamfer = null;\n            if (sides > 2 && Common.random() > 0.7) {\n                chamfer = {\n                    radius: 10\n                };\n            }\n\n            switch (Math.round(Common.random(0, 1))) {\n            case 0:\n                if (Common.random() < 0.8) {\n                    return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), { chamfer: chamfer });\n                } else {\n                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), { chamfer: chamfer });\n                }\n            case 1:\n                return Bodies.polygon(x, y, sides, Common.random(25, 50), { chamfer: chamfer });\n            }\n        });\n    };\n\n    var stack = null,\n        bottomStack = createStack(),\n        lastTimestamp = 0;\n\n    // add and remove bodies and composites every few updates\n    Events.on(engine, 'afterUpdate', function(event) {\n        // limit rate\n        if (event.timestamp - lastTimestamp < 800) {\n            return;\n        }\n\n        lastTimestamp = event.timestamp;\n\n        // remove an old body\n        Composite.remove(bottomStack, bottomStack.bodies[0]);\n\n        // add a new body\n        Composite.add(\n            bottomStack, \n            Bodies.rectangle(Common.random(100, 500), 50, Common.random(25, 50), Common.random(25, 50))\n        );\n\n        // remove last stack\n        if (stack) {\n            Composite.remove(world, stack);\n        }\n\n        // create a new stack\n        stack = createStack();\n\n        // add the new stack\n        Composite.add(world, stack);\n    });\n\n    Composite.add(world, [\n        bottomStack,\n\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.remove.title = 'Composite Remove';\nExample.remove.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.remove;\n}\n"
  },
  {
    "path": "examples/renderResize.js",
    "content": "var Example = Example || {};\n\nExample.renderResize = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            pixelRatio: 2\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 10, 5, 0, 0, function(x, y) {\n        var sides = Math.round(Common.random(1, 8));\n\n        // round the edges of some bodies\n        var chamfer = null;\n        if (sides > 2 && Common.random() > 0.7) {\n            chamfer = {\n                radius: 10\n            };\n        }\n\n        switch (Math.round(Common.random(0, 1))) {\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), { chamfer: chamfer });\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), { chamfer: chamfer });\n            }\n        case 1:\n            return Bodies.polygon(x, y, sides, Common.random(25, 50), { chamfer: chamfer });\n        }\n    });\n\n    Composite.add(world, stack);\n\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // set canvas position to screen top left\n    render.canvas.style.position = 'fixed';\n\n    // resize event handler\n    var handleWindowResize = function() {\n        // get the current window size\n        var width = window.innerWidth,\n            height = window.innerHeight;\n\n        // set the render size to equal window size\n        Render.setSize(render, width, height);\n\n        // update the render bounds to fit the scene\n        Render.lookAt(render, Composite.allBodies(engine.world), {\n            x: 50,\n            y: 50\n        });\n    };\n\n    // add window resize handler\n    window.addEventListener('resize', handleWindowResize);\n\n    // update canvas size to initial window size\n    handleWindowResize();\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.renderResize.title = 'Render Resize';\nExample.renderResize.for = '>=0.20.0';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.renderResize;\n}\n"
  },
  {
    "path": "examples/restitution.js",
    "content": "var Example = Example || {};\n\nExample.restitution = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true,\n            showCollisions: true,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var rest = 0.9, \n        space = 600 / 5;\n    \n    Composite.add(world, [\n        Bodies.rectangle(100 + space * 0, 150, 50, 50, { restitution: rest }),\n        Bodies.rectangle(100 + space * 1, 150, 50, 50, { restitution: rest, angle: -Math.PI * 0.15 }),\n        Bodies.rectangle(100 + space * 2, 150, 50, 50, { restitution: rest, angle: -Math.PI * 0.25 }),\n        Bodies.circle(100 + space * 3, 150, 25, { restitution: rest }),\n        Bodies.rectangle(100 + space * 5, 150, 180, 20, { restitution: rest, angle: -Math.PI * 0.5 }),\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.restitution.title = 'Restitution';\nExample.restitution.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.restitution;\n}\n"
  },
  {
    "path": "examples/rounded.js",
    "content": "var Example = Example || {};\n\nExample.rounded = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAxes: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    Composite.add(world, [\n        Bodies.rectangle(200, 200, 100, 100, { \n            chamfer: { radius: 20 }\n        }),\n\n        Bodies.rectangle(300, 200, 100, 100, { \n            chamfer: { radius: [90, 0, 0, 0] }\n        }),\n\n        Bodies.rectangle(400, 200, 200, 200, { \n            chamfer: { radius: [150, 20, 40, 20] }\n        }),\n\n        Bodies.rectangle(200, 200, 200, 200, { \n            chamfer: { radius: [150, 20, 150, 20] }\n        }),\n\n        Bodies.rectangle(300, 200, 200, 50, { \n            chamfer: { radius: [25, 25, 0, 0] }\n        }),\n\n        Bodies.polygon(200, 100, 8, 80, { \n            chamfer: { radius: 30 }\n        }),\n\n        Bodies.polygon(300, 100, 5, 80, { \n            chamfer: { radius: [10, 40, 20, 40, 10] }\n        }),\n\n        Bodies.polygon(400, 200, 3, 50, { \n            chamfer: { radius: [20, 0, 20] }\n        })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.rounded.title = 'Rounded Corners (Chamfering)';\nExample.rounded.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.rounded;\n}\n"
  },
  {
    "path": "examples/sensors.js",
    "content": "var Example = Example || {};\n\nExample.sensors = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Events = Matter.Events,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            wireframes: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var colorA = '#f55a3c',\n        colorB = '#f5d259';\n\n    var collider = Bodies.rectangle(400, 300, 500, 50, {\n        isSensor: true,\n        isStatic: true,\n        render: {\n            strokeStyle: colorA,\n            fillStyle: 'transparent',\n            lineWidth: 1\n        }\n    });\n\n    Composite.add(world, [\n        collider,\n        Bodies.rectangle(400, 600, 800, 50, { \n            isStatic: true,\n            render: {\n                fillStyle: '#060a19',\n                lineWidth: 0\n            }\n        })\n    ]);\n\n    Composite.add(world,\n        Bodies.circle(400, 40, 30, {\n            render: {\n                strokeStyle: colorB,\n                fillStyle: 'transparent',\n                lineWidth: 1\n            }\n        })\n    );\n\n    Events.on(engine, 'collisionStart', function(event) {\n        var pairs = event.pairs;\n        \n        for (var i = 0, j = pairs.length; i != j; ++i) {\n            var pair = pairs[i];\n\n            if (pair.bodyA === collider) {\n                pair.bodyB.render.strokeStyle = colorA;\n            } else if (pair.bodyB === collider) {\n                pair.bodyA.render.strokeStyle = colorA;\n            }\n        }\n    });\n\n    Events.on(engine, 'collisionEnd', function(event) {\n        var pairs = event.pairs;\n        \n        for (var i = 0, j = pairs.length; i != j; ++i) {\n            var pair = pairs[i];\n\n            if (pair.bodyA === collider) {\n                pair.bodyB.render.strokeStyle = colorB;\n            } else if (pair.bodyB === collider) {\n                pair.bodyA.render.strokeStyle = colorB;\n            }\n        }\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n    \n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.sensors.title = 'Sensors';\nExample.sensors.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.sensors;\n}\n"
  },
  {
    "path": "examples/sleeping.js",
    "content": "var Example = Example || {};\n\nExample.sleeping = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        Events = Matter.Events,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create({\n            enableSleeping: true\n        }),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var stack = Composites.stack(50, 50, 12, 3, 0, 0, function(x, y) {\n        switch (Math.round(Common.random(0, 1))) {\n\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));\n            }\n        case 1:\n            return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));\n\n        }\n    });\n    \n    Composite.add(world, stack);\n\n    /*\n    // sleep events\n    for (var i = 0; i < stack.bodies.length; i++) {\n        Events.on(stack.bodies[i], 'sleepStart sleepEnd', function(event) {\n            var body = this;\n            console.log('body id', body.id, 'sleeping:', body.isSleeping);\n        });\n    }\n    */\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.sleeping.title = 'Sleeping';\nExample.sleeping.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.sleeping;\n}\n"
  },
  {
    "path": "examples/slingshot.js",
    "content": "var Example = Example || {};\n\nExample.slingshot = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Events = Matter.Events,\n        Constraint = Matter.Constraint,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Body = Matter.Body,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var ground = Bodies.rectangle(395, 600, 815, 50, { isStatic: true, render: { fillStyle: '#060a19' } }),\n        rockOptions = { density: 0.004 },\n        rock = Bodies.polygon(170, 450, 8, 20, rockOptions),\n        anchor = { x: 170, y: 450 },\n        elastic = Constraint.create({ \n            pointA: anchor, \n            bodyB: rock, \n            length: 0.01,\n            damping: 0.01,\n            stiffness: 0.05\n        });\n\n    var pyramid = Composites.pyramid(500, 300, 9, 10, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 25, 40);\n    });\n\n    var ground2 = Bodies.rectangle(610, 250, 200, 20, { isStatic: true, render: { fillStyle: '#060a19' } });\n\n    var pyramid2 = Composites.pyramid(550, 0, 5, 10, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 25, 40);\n    });\n\n    Composite.add(engine.world, [ground, pyramid, ground2, pyramid2, rock, elastic]);\n\n    Events.on(engine, 'afterUpdate', function() {\n        if (mouseConstraint.mouse.button === -1 && (rock.position.x > 190 || rock.position.y < 430)) {\n            // Limit maximum speed of current rock.\n            if (Body.getSpeed(rock) > 45) {\n                Body.setSpeed(rock, 45);\n            }\n\n            // Release current rock and add a new one.\n            rock = Bodies.polygon(170, 450, 7, 20, rockOptions);\n            Composite.add(engine.world, rock);\n            elastic.bodyB = rock;\n        }\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.slingshot.title = 'Slingshot';\nExample.slingshot.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.slingshot;\n}\n"
  },
  {
    "path": "examples/softBody.js",
    "content": "var Example = Example || {};\n\nExample.softBody = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var particleOptions = { \n        friction: 0.05,\n        frictionStatic: 0.1,\n        render: { visible: true } \n    };\n\n    Composite.add(world, [\n        // see softBody function defined later in this file\n        Example.softBody.softBody(250, 100, 5, 5, 0, 0, true, 18, particleOptions),\n        Example.softBody.softBody(400, 300, 8, 3, 0, 0, true, 15, particleOptions),\n        Example.softBody.softBody(250, 400, 4, 4, 0, 0, true, 15, particleOptions),\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.9,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.softBody.title = 'Soft Body';\nExample.softBody.for = '>=0.14.2';\n\n/**\n* Creates a simple soft body like object.\n* @method softBody\n* @param {number} xx\n* @param {number} yy\n* @param {number} columns\n* @param {number} rows\n* @param {number} columnGap\n* @param {number} rowGap\n* @param {boolean} crossBrace\n* @param {number} particleRadius\n* @param {} particleOptions\n* @param {} constraintOptions\n* @return {composite} A new composite softBody\n*/\nExample.softBody.softBody = function(xx, yy, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) {\n    var Common = Matter.Common,\n        Composites = Matter.Composites,\n        Bodies = Matter.Bodies;\n\n    particleOptions = Common.extend({ inertia: Infinity }, particleOptions);\n    constraintOptions = Common.extend({ stiffness: 0.2, render: { type: 'line', anchors: false } }, constraintOptions);\n\n    var softBody = Composites.stack(xx, yy, columns, rows, columnGap, rowGap, function(x, y) {\n        return Bodies.circle(x, y, particleRadius, particleOptions);\n    });\n\n    Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions);\n\n    softBody.label = 'Soft Body';\n\n    return softBody;\n};\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.softBody;\n}\n"
  },
  {
    "path": "examples/sprites.js",
    "content": "var Example = Example || {};\n\nExample.sprites = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: false,\n            wireframes: false\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var offset = 10,\n        options = { \n            isStatic: true\n        };\n\n    world.bodies = [];\n\n    // these static walls will not be rendered in this sprites example, see options\n    Composite.add(world, [\n        Bodies.rectangle(400, -offset, 800.5 + 2 * offset, 50.5, options),\n        Bodies.rectangle(400, 600 + offset, 800.5 + 2 * offset, 50.5, options),\n        Bodies.rectangle(800 + offset, 300, 50.5, 600.5 + 2 * offset, options),\n        Bodies.rectangle(-offset, 300, 50.5, 600.5 + 2 * offset, options)\n    ]);\n\n    var stack = Composites.stack(20, 20, 10, 4, 0, 0, function(x, y) {\n        if (Common.random() > 0.35) {\n            return Bodies.rectangle(x, y, 64, 64, {\n                render: {\n                    strokeStyle: '#ffffff',\n                    sprite: {\n                        texture: './img/box.png'\n                    }\n                }\n            });\n        } else {\n            return Bodies.circle(x, y, 46, {\n                density: 0.0005,\n                frictionAir: 0.06,\n                restitution: 0.3,\n                friction: 0.01,\n                render: {\n                    sprite: {\n                        texture: './img/ball.png'\n                    }\n                }\n            });\n        }\n    });\n\n    Composite.add(world, stack);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.sprites.title = 'Sprites';\nExample.sprites.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.sprites;\n}\n"
  },
  {
    "path": "examples/stack.js",
    "content": "var Example = Example || {};\n\nExample.stack = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = Composites.stack(200, 606 - 25.25 - 5 * 40, 10, 5, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 40, 40);\n    });\n    \n    Composite.add(world, [\n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(400, 606, 800, 50.5, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stack.title = 'Stack';\nExample.stack.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stack;\n}\n"
  },
  {
    "path": "examples/staticFriction.js",
    "content": "var Example = Example || {};\n\nExample.staticFriction = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Composites = Matter.Composites,\n        Events = Matter.Events,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showVelocity: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var body = Bodies.rectangle(400, 500, 200, 60, { isStatic: true, chamfer: 10, render: { fillStyle: '#060a19' } }),\n        size = 50;\n\n    var stack = Composites.stack(350, 470 - 6 * size, 1, 6, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, size * 2, size, {\n            slop: 0.5,\n            friction: 1,\n            frictionStatic: Infinity\n        });\n    });\n    \n    Composite.add(world, [\n        body, \n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    Events.on(engine, 'beforeUpdate', function() {\n        if (engine.timing.timestamp < 1500) {\n            return;\n        }\n\n        var px = 400 + 100 * Math.sin((engine.timing.timestamp - 1500) * 0.001);\n\n        // manual update velocity required for older releases\n        if (Matter.version === '0.18.0') {\n            Body.setVelocity(body, { x: px - body.position.x, y: 0 });\n        }\n\n        Body.setPosition(body, { x: px, y: body.position.y }, true);\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.staticFriction.title = 'Static Friction';\nExample.staticFriction.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.staticFriction;\n}\n"
  },
  {
    "path": "examples/stats.js",
    "content": "var Example = Example || {};\n\nExample.stats = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Common = Matter.Common,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        World = Matter.World,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            // show stats and performance monitors\n            showStats: true,\n            showPerformance: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // scene code\n    var stack = Composites.stack(70, 30, 13, 9, 5, 5, function(x, y) {\n        return Bodies.circle(x, y, 10 + Common.random() * 20);\n    });\n    \n    World.add(world, [\n        stack,\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    World.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stats.title = 'Stats & Performance';\nExample.stats.for = '>=0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stats;\n}\n"
  },
  {
    "path": "examples/stress.js",
    "content": "var Example = Example || {};\n\nExample.stress = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showStats: true,\n            showPerformance: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // scene code\n    var stack = Composites.stack(90, 600 - 25 - 15 * 35, 18, 15, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 35, 35);\n    });\n    \n    Composite.add(world, [\n        stack,\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stress.title = 'Stress';\nExample.stress.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stress;\n}\n"
  },
  {
    "path": "examples/stress2.js",
    "content": "var Example = Example || {};\n\nExample.stress2 = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showStats: true,\n            showPerformance: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // scene code\n    var stack = Composites.stack(100, 600 - 25 - 18 * 25, 25, 18, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 25, 25);\n    });\n    \n    Composite.add(world, [\n        stack,\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stress2.title = 'Stress 2';\nExample.stress2.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stress2;\n}\n"
  },
  {
    "path": "examples/stress3.js",
    "content": "var Example = Example || {};\n\nExample.stress3 = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create({\n        positionIterations: 10,\n        velocityIterations: 10\n    });\n\n    var world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showStats: true,\n            showPerformance: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var scale = 0.3;\n    \n    var stack = Composites.stack(40, 40, 38, 18, 0, 0, function(x, y) {\n        var sides = Math.round(Common.random(1, 8));\n\n        switch (Math.round(Common.random(0, 1))) {\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(25, 50) * scale, Common.random(25, 50) * scale);\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120) * scale, Common.random(25, 30) * scale);\n            }\n        case 1:\n            return Bodies.polygon(x, y, sides, Common.random(25, 50) * scale);\n        }\n    });\n\n    Composite.add(world, stack);\n\n    Composite.add(world, [\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stress3.title = 'Stress 3';\nExample.stress3.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stress3;\n}\n"
  },
  {
    "path": "examples/stress4.js",
    "content": "var Example = Example || {};\n\nExample.stress4 = function() {\n    var Engine = Matter.Engine,\n        Events = Matter.Events,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create({\n        positionIterations: 25,\n        velocityIterations: 35\n    });\n\n    var world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showStats: true,\n            showPerformance: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n\n    Runner.run(runner, engine);\n\n    // add bodies\n    var stack = function(scale, columns, rows) {\n        return Composites.stack(40, 40, columns, rows, 0, 0, function(x, y) {\n            var sides = Math.round(Common.random(1, 8));\n\n            switch (Math.round(Common.random(0, 1))) {\n            case 0:\n                if (Common.random() < 0.8) {\n                    return Bodies.rectangle(x, y, Common.random(25, 50) * scale, Common.random(25, 50) * scale);\n                } else {\n                    return Bodies.rectangle(x, y, Common.random(80, 120) * scale, Common.random(25, 30) * scale);\n                }\n            case 1:\n                return Bodies.polygon(x, y, sides, Common.random(25, 50) * scale);\n            }\n        });\n    };\n\n    Composite.add(world, [\n        stack(0.2, 61, 15), \n        stack(0.3, 31, 12),\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true, render: { visible: false } })\n    ]);\n\n    // scene animation\n    engine.timing.timeScale = 0.9;\n    engine.gravity.scale = 0.0007;\n\n    Events.on(engine, 'beforeUpdate', function() {\n        engine.gravity.x = Math.cos(engine.timing.timestamp * 0.0005);\n        engine.gravity.y = Math.sin(engine.timing.timestamp * 0.0005);\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.stress4.title = 'Stress 4';\nExample.stress4.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.stress4;\n}\n"
  },
  {
    "path": "examples/substep.js",
    "content": "var Example = Example || {};\n\nExample.substep = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Events = Matter.Events,\n        Composite = Matter.Composite,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            wireframes: false,\n            showDebug: true,\n            background: '#000',\n            pixelRatio: 2\n        }\n    });\n\n    Render.run(render);\n\n    // create runner with higher precision timestep (requires >= v0.20.0 beta)\n    var runner = Runner.create({\n        // 600Hz delta = 1.666ms = 10upf @ 60fps (i.e. 10x default precision)\n        delta: 1000 / (60 * 10),\n        // 50fps minimum performance target (i.e. budget allows up to ~20ms execution per frame)\n        maxFrameTime: 1000 / 50\n    });\n\n    Runner.run(runner, engine);\n\n    // demo substepping using very thin bodies (than is typically recommended)\n    Composite.add(world, [\n        Bodies.rectangle(250, 250, 300, 1.25, {\n            frictionAir: 0, \n            friction: 0,\n            restitution: 0.9,\n            angle: 0.5,\n            render: {\n                lineWidth: 0.5,\n                fillStyle: '#f55a3c'\n            }\n        }),\n        Bodies.circle(200, 200, 2.25, {\n            frictionAir: 0, \n            friction: 0,\n            restitution: 0.9,\n            angle: 0.5,\n            render: {\n                fillStyle: '#fff'\n            }\n        })\n    ]);\n\n    // add bodies\n    Composite.add(world, [\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true, render: { visible: false } }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true, render: { visible: false } })\n    ]);\n\n    // scene animation\n    Events.on(engine, 'afterUpdate', function(event) {\n        engine.gravity.scale = 0.00035;\n        engine.gravity.x = Math.cos(engine.timing.timestamp * 0.0005);\n        engine.gravity.y = Math.sin(engine.timing.timestamp * 0.0005);\n    });\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.substep.title = 'High Substeps (Low Delta)';\nExample.substep.for = '>=0.20.0';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.substep;\n}"
  },
  {
    "path": "examples/svg.js",
    "content": "var Example = Example || {};\n\nExample.svg = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Vertices = Matter.Vertices,\n        Svg = Matter.Svg,\n        Bodies = Matter.Bodies;\n\n    // provide concave decomposition support library\n    Common.setDecomp(require('poly-decomp'));\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    if (typeof fetch !== 'undefined') {\n        var select = function(root, selector) {\n            return Array.prototype.slice.call(root.querySelectorAll(selector));\n        };\n\n        var loadSvg = function(url) {\n            return fetch(url)\n                .then(function(response) { return response.text(); })\n                .then(function(raw) { return (new window.DOMParser()).parseFromString(raw, 'image/svg+xml'); });\n        };\n\n        ([\n            './svg/iconmonstr-check-mark-8-icon.svg', \n            './svg/iconmonstr-paperclip-2-icon.svg',\n            './svg/iconmonstr-puzzle-icon.svg',\n            './svg/iconmonstr-user-icon.svg'\n        ]).forEach(function(path, i) { \n            loadSvg(path).then(function(root) {\n                var color = Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1']);\n\n                var vertexSets = select(root, 'path')\n                    .map(function(path) { return Vertices.scale(Svg.pathToVertices(path, 30), 0.4, 0.4); });\n\n                Composite.add(world, Bodies.fromVertices(100 + i * 150, 200 + i * 50, vertexSets, {\n                    render: {\n                        fillStyle: color,\n                        strokeStyle: color,\n                        lineWidth: 1\n                    }\n                }, true));\n            });\n        });\n\n        loadSvg('./svg/svg.svg').then(function(root) {\n            var color = Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1']);\n            \n            var vertexSets = select(root, 'path')\n                .map(function(path) { return Svg.pathToVertices(path, 30); });\n\n            Composite.add(world, Bodies.fromVertices(400, 80, vertexSets, {\n                render: {\n                    fillStyle: color,\n                    strokeStyle: color,\n                    lineWidth: 1\n                }\n            }, true));\n        });\n    } else {\n        Common.warn('Fetch is not available. Could not load SVG.');\n    }\n\n    Composite.add(world, [\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.svg.title = 'Concave SVG Paths';\nExample.svg.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.svg;\n}\n"
  },
  {
    "path": "examples/terrain.js",
    "content": "var Example = Example || {};\n\nExample.terrain = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Query = Matter.Query,\n        Svg = Matter.Svg,\n        Bodies = Matter.Bodies;\n\n    // provide concave decomposition support library\n    Common.setDecomp(require('poly-decomp'));\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    if (typeof fetch !== 'undefined') {\n        var select = function(root, selector) {\n            return Array.prototype.slice.call(root.querySelectorAll(selector));\n        };\n\n        var loadSvg = function(url) {\n            return fetch(url)\n                .then(function(response) { return response.text(); })\n                .then(function(raw) { return (new window.DOMParser()).parseFromString(raw, 'image/svg+xml'); });\n        };\n\n        loadSvg('./svg/terrain.svg')\n            .then(function(root) {\n                var paths = select(root, 'path');\n\n                var vertexSets = paths.map(function(path) { return Svg.pathToVertices(path, 30); });\n\n                var terrain = Bodies.fromVertices(400, 350, vertexSets, {\n                    isStatic: true,\n                    render: {\n                        fillStyle: '#060a19',\n                        strokeStyle: '#060a19',\n                        lineWidth: 1\n                    }\n                }, true);\n\n                Composite.add(world, terrain);\n\n                var bodyOptions = {\n                    frictionAir: 0, \n                    friction: 0.0001,\n                    restitution: 0.6\n                };\n                \n                Composite.add(world, Composites.stack(80, 100, 20, 20, 10, 10, function(x, y) {\n                    if (Query.point([terrain], { x: x, y: y }).length === 0) {\n                        return Bodies.polygon(x, y, 5, 12, bodyOptions);\n                    }\n                }));\n            });\n    } else {\n        Common.warn('Fetch is not available. Could not load SVG.');\n    }\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.terrain.title = 'Terrain';\nExample.terrain.for = '>0.16.1';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.terrain;\n}\n"
  },
  {
    "path": "examples/timescale.js",
    "content": "var Example = Example || {};\n\nExample.timescale = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Body = Matter.Body,\n        Events = Matter.Events,\n        Composite = Matter.Composite,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    Composite.add(world, [\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n\n    var explosion = function(engine, delta) {\n        var timeScale = (1000 / 60) / delta;\n        var bodies = Composite.allBodies(engine.world);\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (!body.isStatic && body.position.y >= 500) {\n                // scale force for mass and time applied\n                var forceMagnitude = (0.05 * body.mass) * timeScale;\n\n                // apply the force over a single update\n                Body.applyForce(body, body.position, {\n                    x: (forceMagnitude + Common.random() * forceMagnitude) * Common.choose([1, -1]), \n                    y: -forceMagnitude + Common.random() * -forceMagnitude\n                });\n            }\n        }\n    };\n\n    var timeScaleTarget = 1,\n        lastTime = Common.now();\n\n    Events.on(engine, 'afterUpdate', function(event) {\n        var timeScale = (event.delta || (1000 / 60)) / 1000;\n\n        // tween the timescale for bullet time slow-mo\n        engine.timing.timeScale += (timeScaleTarget - engine.timing.timeScale) * 12 * timeScale;\n\n        // every 2 sec (real time)\n        if (Common.now() - lastTime >= 2000) {\n\n            // flip the timescale\n            if (timeScaleTarget < 1) {\n                timeScaleTarget = 1;\n            } else {\n                timeScaleTarget = 0;\n            }\n\n            // create some random forces\n            explosion(engine, event.delta);\n\n            // update last time\n            lastTime = Common.now();\n        }\n    });\n\n    var bodyOptions = {\n        frictionAir: 0, \n        friction: 0.0001,\n        restitution: 0.8\n    };\n    \n    Composite.add(world, Composites.stack(20, 100, 15, 3, 20, 40, function(x, y) {\n        return Bodies.circle(x, y, Common.random(10, 20), bodyOptions);\n    }));\n\n    Composite.add(world, Composites.stack(50, 50, 8, 3, 0, 0, function(x, y) {\n        switch (Math.round(Common.random(0, 1))) {\n\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50), bodyOptions);\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30), bodyOptions);\n            }\n        case 1:\n            return Bodies.polygon(x, y, Math.round(Common.random(4, 8)), Common.random(20, 50), bodyOptions);\n\n        }\n    }));\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.timescale.title = 'Time Scaling';\nExample.timescale.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.timescale;\n}"
  },
  {
    "path": "examples/views.js",
    "content": "var Example = Example || {};\n\nExample.views = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Events = Matter.Events,\n        Composites = Matter.Composites,\n        Common = Matter.Common,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Vector = Matter.Vector,\n        Bounds = Matter.Bounds,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            hasBounds: true,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // add bodies\n    var stack = Composites.stack(20, 20, 10, 4, 0, 0, function(x, y) {\n        switch (Math.round(Common.random(0, 1))) {\n\n        case 0:\n            if (Common.random() < 0.8) {\n                return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));\n            } else {\n                return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));\n            }\n        case 1:\n            var sides = Math.round(Common.random(1, 8));\n            sides = (sides === 3) ? 4 : sides;\n            return Bodies.polygon(x, y, sides, Common.random(20, 50));\n        }\n    });\n\n    Composite.add(world, [\n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n    \n    // get the centre of the viewport\n    var viewportCentre = {\n        x: render.options.width * 0.5,\n        y: render.options.height * 0.5\n    };\n\n    // create limits for the viewport\n    var extents = {\n        min: { x: -300, y: -300 },\n        max: { x: 1100, y: 900 }\n    };\n\n    // keep track of current bounds scale (view zoom)\n    var boundsScaleTarget = 1,\n        boundsScale = {\n            x: 1,\n            y: 1\n        };\n\n    // use a render event to control our view\n    Events.on(render, 'beforeRender', function() {\n        var world = engine.world,\n            mouse = mouseConstraint.mouse,\n            translate;\n\n        // mouse wheel controls zoom\n        var scaleFactor = mouse.wheelDelta * -0.1;\n        if (scaleFactor !== 0) {\n            if ((scaleFactor < 0 && boundsScale.x >= 0.6) || (scaleFactor > 0 && boundsScale.x <= 1.4)) {\n                boundsScaleTarget += scaleFactor;\n            }\n        }\n\n        // if scale has changed\n        if (Math.abs(boundsScale.x - boundsScaleTarget) > 0.01) {\n            // smoothly tween scale factor\n            scaleFactor = (boundsScaleTarget - boundsScale.x) * 0.2;\n            boundsScale.x += scaleFactor;\n            boundsScale.y += scaleFactor;\n\n            // scale the render bounds\n            render.bounds.max.x = render.bounds.min.x + render.options.width * boundsScale.x;\n            render.bounds.max.y = render.bounds.min.y + render.options.height * boundsScale.y;\n\n            // translate so zoom is from centre of view\n            translate = {\n                x: render.options.width * scaleFactor * -0.5,\n                y: render.options.height * scaleFactor * -0.5\n            };\n\n            Bounds.translate(render.bounds, translate);\n\n            // update mouse\n            Mouse.setScale(mouse, boundsScale);\n            Mouse.setOffset(mouse, render.bounds.min);\n        }\n\n        // get vector from mouse relative to centre of viewport\n        var deltaCentre = Vector.sub(mouse.absolute, viewportCentre),\n            centreDist = Vector.magnitude(deltaCentre);\n\n        // translate the view if mouse has moved over 50px from the centre of viewport\n        if (centreDist > 50) {\n            // create a vector to translate the view, allowing the user to control view speed\n            var direction = Vector.normalise(deltaCentre),\n                speed = Math.min(10, Math.pow(centreDist - 50, 2) * 0.0002);\n\n            translate = Vector.mult(direction, speed);\n\n            // prevent the view moving outside the extents\n            if (render.bounds.min.x + translate.x < extents.min.x)\n                translate.x = extents.min.x - render.bounds.min.x;\n\n            if (render.bounds.max.x + translate.x > extents.max.x)\n                translate.x = extents.max.x - render.bounds.max.x;\n\n            if (render.bounds.min.y + translate.y < extents.min.y)\n                translate.y = extents.min.y - render.bounds.min.y;\n\n            if (render.bounds.max.y + translate.y > extents.max.y)\n                translate.y = extents.max.y - render.bounds.max.y;\n\n            // move the view\n            Bounds.translate(render.bounds, translate);\n\n            // we must update the mouse too\n            Mouse.setOffset(mouse, render.bounds.min);\n        }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.views.title = 'Views';\nExample.views.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.views;\n}\n"
  },
  {
    "path": "examples/wreckingBall.js",
    "content": "var Example = Example || {};\n\nExample.wreckingBall = function() {\n    var Engine = Matter.Engine,\n        Render = Matter.Render,\n        Runner = Matter.Runner,\n        Composites = Matter.Composites,\n        MouseConstraint = Matter.MouseConstraint,\n        Mouse = Matter.Mouse,\n        Composite = Matter.Composite,\n        Constraint = Matter.Constraint,\n        Bodies = Matter.Bodies;\n\n    // create engine\n    var engine = Engine.create(),\n        world = engine.world;\n\n    // create renderer\n    var render = Render.create({\n        element: document.body,\n        engine: engine,\n        options: {\n            width: 800,\n            height: 600,\n            showAngleIndicator: true\n        }\n    });\n\n    Render.run(render);\n\n    // create runner\n    var runner = Runner.create();\n    Runner.run(runner, engine);\n\n    // add bodies\n    var rows = 10,\n        yy = 600 - 25 - 40 * rows;\n    \n    var stack = Composites.stack(400, yy, 5, rows, 0, 0, function(x, y) {\n        return Bodies.rectangle(x, y, 40, 40);\n    });\n    \n    Composite.add(world, [\n        stack,\n        // walls\n        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),\n        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),\n        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),\n        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })\n    ]);\n    \n    var ball = Bodies.circle(100, 400, 50, { density: 0.04, frictionAir: 0.005});\n    \n    Composite.add(world, ball);\n    Composite.add(world, Constraint.create({\n        pointA: { x: 300, y: 100 },\n        bodyB: ball\n    }));\n\n    // add mouse control\n    var mouse = Mouse.create(render.canvas),\n        mouseConstraint = MouseConstraint.create(engine, {\n            mouse: mouse,\n            constraint: {\n                stiffness: 0.2,\n                render: {\n                    visible: false\n                }\n            }\n        });\n\n    Composite.add(world, mouseConstraint);\n\n    // keep the mouse in sync with rendering\n    render.mouse = mouse;\n\n    // fit the render viewport to the scene\n    Render.lookAt(render, {\n        min: { x: 0, y: 0 },\n        max: { x: 800, y: 600 }\n    });\n\n    // context for MatterTools.Demo\n    return {\n        engine: engine,\n        runner: runner,\n        render: render,\n        canvas: render.canvas,\n        stop: function() {\n            Matter.Render.stop(render);\n            Matter.Runner.stop(runner);\n        }\n    };\n};\n\nExample.wreckingBall.title = 'Wrecking Ball';\nExample.wreckingBall.for = '>=0.14.2';\n\nif (typeof module !== 'undefined') {\n    module.exports = Example.wreckingBall;\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"matter-js\",\n  \"version\": \"0.20.0\",\n  \"license\": \"MIT\",\n  \"homepage\": \"http://brm.io/matter-js/\",\n  \"author\": \"Liam Brummitt <liam@brm.io> (http://brm.io/)\",\n  \"description\": \"a 2D rigid body physics engine for the web\",\n  \"main\": \"build/matter.js\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/liabru/matter-js.git\"\n  },\n  \"keywords\": [\n    \"javascript\",\n    \"canvas\",\n    \"html5\",\n    \"physics\",\n    \"physics engine\",\n    \"game engine\",\n    \"rigid body physics\"\n  ],\n  \"devDependencies\": {\n    \"conventional-changelog-cli\": \"^2.1.1\",\n    \"eslint\": \"^6.8.0\",\n    \"html-webpack-plugin\": \"^4.5.1\",\n    \"jest\": \"^29.7.0\",\n    \"jest-worker\": \"^29.7.0\",\n    \"json-stringify-pretty-compact\": \"^2.0.0\",\n    \"matter-tools\": \"^0.14.0\",\n    \"matter-wrap\": \"^0.2.0\",\n    \"mock-require\": \"^3.0.3\",\n    \"pathseg\": \"^1.2.0\",\n    \"poly-decomp\": \"^0.3.0\",\n    \"puppeteer-core\": \"^5.5.0\",\n    \"terser-webpack-plugin\": \"^4.2.3\",\n    \"webpack\": \"^4.46.0\",\n    \"webpack-bundle-analyzer\": \"^4.4.0\",\n    \"webpack-cli\": \"^3.3.11\",\n    \"webpack-dev-server\": \"^3.11.1\"\n  },\n  \"scripts\": {\n    \"start\": \"npm run dev\",\n    \"dev\": \"npm run serve -- --open\",\n    \"serve\": \"webpack-dev-server --no-cache --mode development --config webpack.demo.config.js\",\n    \"watch\": \"nodemon --watch webpack.demo.config.js --exec \\\"npm run serve\\\"\",\n    \"build\": \"webpack --mode=production --no-hot --no-watch & webpack --mode=production --no-hot --no-watch --env.MINIMIZE\",\n    \"build-alpha\": \"webpack --mode=production --no-hot --no-watch --env.KIND=alpha & webpack --mode=production --no-hot --no-watch --env.MINIMIZE --env.KIND=alpha\",\n    \"build-dev\": \"webpack --mode=production --no-hot --no-watch --env.KIND=dev & webpack --mode=production --no-hot --no-watch --env.MINIMIZE --env.KIND=dev\",\n    \"build-demo\": \"rm -rf ./demo/js && webpack --no-hot --no-watch --config webpack.demo.config.js --mode=production && webpack --no-hot --no-watch --config webpack.demo.config.js --mode=production --env.MINIMIZE\",\n    \"lint\": \"eslint 'src/**/*.js' 'demo/src/**/*.js' 'examples/*.js' 'webpack.*.js'\",\n    \"doc\": \"yuidoc --config yuidoc.json --project-version $npm_package_version\",\n    \"doc-watch\": \"nodemon --delay 3 --watch 'matter-doc-theme' --watch src -e 'js,html,css,handlebars' --exec 'npm run doc'\",\n    \"benchmark\": \"npm run test-node -- --examples=stress3,stress4 --benchmark=true --updates=300 --repeats=3\",\n    \"test\": \"npm run test-node\",\n    \"test-node\": \"npm run build-dev && node --expose-gc node_modules/.bin/jest --force-exit --no-cache --runInBand ./test/Examples.spec.js\",\n    \"test-browser\": \"node --expose-gc node_modules/.bin/jest --force-exit --no-cache --runInBand ./test/Browser.spec.js\",\n    \"test-all\": \"npm run test-node && npm run test-browser\",\n    \"test-save\": \"npm run test-node -- --save=true\",\n    \"test-watch\": \"npm run test-node -- --watch\",\n    \"changelog\": \"conventional-changelog -i CHANGELOG.md -s -r\",\n    \"release\": \"npm version --no-git-tag-version\",\n    \"preversion\": \"git checkout master && npm run lint && npm run test-node -- --save=true\",\n    \"version\": \"git checkout -b release/$npm_package_version && npm run build\"\n  },\n  \"files\": [\n    \"src\",\n    \"build/matter.js\",\n    \"build/matter.min.js\",\n    \"README.md\",\n    \"CHANGELOG.md\",\n    \"LICENSE\",\n    \"package.json\"\n  ]\n}\n"
  },
  {
    "path": "src/body/Body.js",
    "content": "/**\n* The `Matter.Body` module contains methods for creating and manipulating rigid bodies.\n* For creating bodies with common configurations such as rectangles, circles and other polygons see the module `Matter.Bodies`.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n\n* @class Body\n*/\n\nvar Body = {};\n\nmodule.exports = Body;\n\nvar Vertices = require('../geometry/Vertices');\nvar Vector = require('../geometry/Vector');\nvar Sleeping = require('../core/Sleeping');\nvar Common = require('../core/Common');\nvar Bounds = require('../geometry/Bounds');\nvar Axes = require('../geometry/Axes');\n\n(function() {\n\n    Body._timeCorrection = true;\n    Body._inertiaScale = 4;\n    Body._nextCollidingGroupId = 1;\n    Body._nextNonCollidingGroupId = -1;\n    Body._nextCategory = 0x0001;\n    Body._baseDelta = 1000 / 60;\n\n    /**\n     * Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * Vertices must be specified in clockwise order.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     * @return {body} body\n     */\n    Body.create = function(options) {\n        var defaults = {\n            id: Common.nextId(),\n            type: 'body',\n            label: 'Body',\n            parts: [],\n            plugin: {},\n            angle: 0,\n            vertices: Vertices.fromPath('L 0 0 L 40 0 L 40 40 L 0 40'),\n            position: { x: 0, y: 0 },\n            force: { x: 0, y: 0 },\n            torque: 0,\n            positionImpulse: { x: 0, y: 0 },\n            constraintImpulse: { x: 0, y: 0, angle: 0 },\n            totalContacts: 0,\n            speed: 0,\n            angularSpeed: 0,\n            velocity: { x: 0, y: 0 },\n            angularVelocity: 0,\n            isSensor: false,\n            isStatic: false,\n            isSleeping: false,\n            motion: 0,\n            sleepThreshold: 60,\n            density: 0.001,\n            restitution: 0,\n            friction: 0.1,\n            frictionStatic: 0.5,\n            frictionAir: 0.01,\n            collisionFilter: {\n                category: 0x0001,\n                mask: 0xFFFFFFFF,\n                group: 0\n            },\n            slop: 0.05,\n            timeScale: 1,\n            render: {\n                visible: true,\n                opacity: 1,\n                strokeStyle: null,\n                fillStyle: null,\n                lineWidth: null,\n                sprite: {\n                    xScale: 1,\n                    yScale: 1,\n                    xOffset: 0,\n                    yOffset: 0\n                }\n            },\n            events: null,\n            bounds: null,\n            chamfer: null,\n            circleRadius: 0,\n            positionPrev: null,\n            anglePrev: 0,\n            parent: null,\n            axes: null,\n            area: 0,\n            mass: 0,\n            inertia: 0,\n            deltaTime: 1000 / 60,\n            _original: null\n        };\n\n        var body = Common.extend(defaults, options);\n\n        _initProperties(body, options);\n\n        return body;\n    };\n\n    /**\n     * Returns the next unique group index for which bodies will collide.\n     * If `isNonColliding` is `true`, returns the next unique group index for which bodies will _not_ collide.\n     * See `body.collisionFilter` for more information.\n     * @method nextGroup\n     * @param {bool} [isNonColliding=false]\n     * @return {Number} Unique group index\n     */\n    Body.nextGroup = function(isNonColliding) {\n        if (isNonColliding)\n            return Body._nextNonCollidingGroupId--;\n\n        return Body._nextCollidingGroupId++;\n    };\n\n    /**\n     * Returns the next unique category bitfield (starting after the initial default category `0x0001`).\n     * There are 32 available. See `body.collisionFilter` for more information.\n     * @method nextCategory\n     * @return {Number} Unique category bitfield\n     */\n    Body.nextCategory = function() {\n        Body._nextCategory = Body._nextCategory << 1;\n        return Body._nextCategory;\n    };\n\n    /**\n     * Initialises body properties.\n     * @method _initProperties\n     * @private\n     * @param {body} body\n     * @param {} [options]\n     */\n    var _initProperties = function(body, options) {\n        options = options || {};\n\n        // init required properties (order is important)\n        Body.set(body, {\n            bounds: body.bounds || Bounds.create(body.vertices),\n            positionPrev: body.positionPrev || Vector.clone(body.position),\n            anglePrev: body.anglePrev || body.angle,\n            vertices: body.vertices,\n            parts: body.parts || [body],\n            isStatic: body.isStatic,\n            isSleeping: body.isSleeping,\n            parent: body.parent || body\n        });\n\n        Vertices.rotate(body.vertices, body.angle, body.position);\n        Axes.rotate(body.axes, body.angle);\n        Bounds.update(body.bounds, body.vertices, body.velocity);\n\n        // allow options to override the automatically calculated properties\n        Body.set(body, {\n            axes: options.axes || body.axes,\n            area: options.area || body.area,\n            mass: options.mass || body.mass,\n            inertia: options.inertia || body.inertia\n        });\n\n        // render properties\n        var defaultFillStyle = (body.isStatic ? '#14151f' : Common.choose(['#f19648', '#f5d259', '#f55a3c', '#063e7b', '#ececd1'])),\n            defaultStrokeStyle = body.isStatic ? '#555' : '#ccc',\n            defaultLineWidth = body.isStatic && body.render.fillStyle === null ? 1 : 0;\n        body.render.fillStyle = body.render.fillStyle || defaultFillStyle;\n        body.render.strokeStyle = body.render.strokeStyle || defaultStrokeStyle;\n        body.render.lineWidth = body.render.lineWidth || defaultLineWidth;\n        body.render.sprite.xOffset += -(body.bounds.min.x - body.position.x) / (body.bounds.max.x - body.bounds.min.x);\n        body.render.sprite.yOffset += -(body.bounds.min.y - body.position.y) / (body.bounds.max.y - body.bounds.min.y);\n    };\n\n    /**\n     * Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist.\n     * Prefer to use the actual setter functions in performance critical situations.\n     * @method set\n     * @param {body} body\n     * @param {} settings A property name (or map of properties and values) to set on the body.\n     * @param {} value The value to set if `settings` is a single property name.\n     */\n    Body.set = function(body, settings, value) {\n        var property;\n\n        if (typeof settings === 'string') {\n            property = settings;\n            settings = {};\n            settings[property] = value;\n        }\n\n        for (property in settings) {\n            if (!Object.prototype.hasOwnProperty.call(settings, property))\n                continue;\n\n            value = settings[property];\n            switch (property) {\n\n            case 'isStatic':\n                Body.setStatic(body, value);\n                break;\n            case 'isSleeping':\n                Sleeping.set(body, value);\n                break;\n            case 'mass':\n                Body.setMass(body, value);\n                break;\n            case 'density':\n                Body.setDensity(body, value);\n                break;\n            case 'inertia':\n                Body.setInertia(body, value);\n                break;\n            case 'vertices':\n                Body.setVertices(body, value);\n                break;\n            case 'position':\n                Body.setPosition(body, value);\n                break;\n            case 'angle':\n                Body.setAngle(body, value);\n                break;\n            case 'velocity':\n                Body.setVelocity(body, value);\n                break;\n            case 'angularVelocity':\n                Body.setAngularVelocity(body, value);\n                break;\n            case 'speed':\n                Body.setSpeed(body, value);\n                break;\n            case 'angularSpeed':\n                Body.setAngularSpeed(body, value);\n                break;\n            case 'parts':\n                Body.setParts(body, value);\n                break;\n            case 'centre':\n                Body.setCentre(body, value);\n                break;\n            default:\n                body[property] = value;\n\n            }\n        }\n    };\n\n    /**\n     * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity.\n     * @method setStatic\n     * @param {body} body\n     * @param {bool} isStatic\n     */\n    Body.setStatic = function(body, isStatic) {\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            if (isStatic) {\n                if (!part.isStatic) {\n                    part._original = {\n                        restitution: part.restitution,\n                        friction: part.friction,\n                        mass: part.mass,\n                        inertia: part.inertia,\n                        density: part.density,\n                        inverseMass: part.inverseMass,\n                        inverseInertia: part.inverseInertia\n                    };\n                }\n\n                part.restitution = 0;\n                part.friction = 1;\n                part.mass = part.inertia = part.density = Infinity;\n                part.inverseMass = part.inverseInertia = 0;\n\n                part.positionPrev.x = part.position.x;\n                part.positionPrev.y = part.position.y;\n                part.anglePrev = part.angle;\n                part.angularVelocity = 0;\n                part.speed = 0;\n                part.angularSpeed = 0;\n                part.motion = 0;\n            } else if (part._original) {\n                part.restitution = part._original.restitution;\n                part.friction = part._original.friction;\n                part.mass = part._original.mass;\n                part.inertia = part._original.inertia;\n                part.density = part._original.density;\n                part.inverseMass = part._original.inverseMass;\n                part.inverseInertia = part._original.inverseInertia;\n\n                part._original = null;\n            }\n\n            part.isStatic = isStatic;\n        }\n    };\n\n    /**\n     * Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change.\n     * @method setMass\n     * @param {body} body\n     * @param {number} mass\n     */\n    Body.setMass = function(body, mass) {\n        var moment = body.inertia / (body.mass / 6);\n        body.inertia = moment * (mass / 6);\n        body.inverseInertia = 1 / body.inertia;\n\n        body.mass = mass;\n        body.inverseMass = 1 / body.mass;\n        body.density = body.mass / body.area;\n    };\n\n    /**\n     * Sets the density of the body. Mass and inertia are automatically updated to reflect the change.\n     * @method setDensity\n     * @param {body} body\n     * @param {number} density\n     */\n    Body.setDensity = function(body, density) {\n        Body.setMass(body, density * body.area);\n        body.density = density;\n    };\n\n    /**\n     * Sets the moment of inertia of the body. This is the second moment of area in two dimensions.\n     * Inverse inertia is automatically updated to reflect the change. Mass is not changed.\n     * @method setInertia\n     * @param {body} body\n     * @param {number} inertia\n     */\n    Body.setInertia = function(body, inertia) {\n        body.inertia = inertia;\n        body.inverseInertia = 1 / body.inertia;\n    };\n\n    /**\n     * Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to `body.density`).\n     * Vertices will be automatically transformed to be orientated around their centre of mass as the origin.\n     * They are then automatically translated to world space based on `body.position`.\n     *\n     * The `vertices` argument should be passed as an array of `Matter.Vector` points (or a `Matter.Vertices` array).\n     * Vertices must form a convex hull. Concave vertices must be decomposed into convex parts.\n     * \n     * @method setVertices\n     * @param {body} body\n     * @param {vector[]} vertices\n     */\n    Body.setVertices = function(body, vertices) {\n        // change vertices\n        if (vertices[0].body === body) {\n            body.vertices = vertices;\n        } else {\n            body.vertices = Vertices.create(vertices, body);\n        }\n\n        // update properties\n        body.axes = Axes.fromVertices(body.vertices);\n        body.area = Vertices.area(body.vertices);\n        Body.setMass(body, body.density * body.area);\n\n        // orient vertices around the centre of mass at origin (0, 0)\n        var centre = Vertices.centre(body.vertices);\n        Vertices.translate(body.vertices, centre, -1);\n\n        // update inertia while vertices are at origin (0, 0)\n        Body.setInertia(body, Body._inertiaScale * Vertices.inertia(body.vertices, body.mass));\n\n        // update geometry\n        Vertices.translate(body.vertices, body.position);\n        Bounds.update(body.bounds, body.vertices, body.velocity);\n    };\n\n    /**\n     * Sets the parts of the `body`. \n     * \n     * See `body.parts` for details and requirements on how parts are used.\n     * \n     * See Bodies.fromVertices for a related utility.\n     * \n     * This function updates `body` mass, inertia and centroid based on the parts geometry.  \n     * Sets each `part.parent` to be this `body`.  \n     * \n     * The convex hull is computed and set on this `body` (unless `autoHull` is `false`).  \n     * Automatically ensures that the first part in `body.parts` is the `body`.\n     * @method setParts\n     * @param {body} body\n     * @param {body[]} parts\n     * @param {bool} [autoHull=true]\n     */\n    Body.setParts = function(body, parts, autoHull) {\n        var i;\n\n        // add all the parts, ensuring that the first part is always the parent body\n        parts = parts.slice(0);\n        body.parts.length = 0;\n        body.parts.push(body);\n        body.parent = body;\n\n        for (i = 0; i < parts.length; i++) {\n            var part = parts[i];\n            if (part !== body) {\n                part.parent = body;\n                body.parts.push(part);\n            }\n        }\n\n        if (body.parts.length === 1)\n            return;\n\n        autoHull = typeof autoHull !== 'undefined' ? autoHull : true;\n\n        // find the convex hull of all parts to set on the parent body\n        if (autoHull) {\n            var vertices = [];\n            for (i = 0; i < parts.length; i++) {\n                vertices = vertices.concat(parts[i].vertices);\n            }\n\n            Vertices.clockwiseSort(vertices);\n\n            var hull = Vertices.hull(vertices),\n                hullCentre = Vertices.centre(hull);\n\n            Body.setVertices(body, hull);\n            Vertices.translate(body.vertices, hullCentre);\n        }\n\n        // sum the properties of all compound parts of the parent body\n        var total = Body._totalProperties(body);\n\n        body.area = total.area;\n        body.parent = body;\n        body.position.x = total.centre.x;\n        body.position.y = total.centre.y;\n        body.positionPrev.x = total.centre.x;\n        body.positionPrev.y = total.centre.y;\n\n        Body.setMass(body, total.mass);\n        Body.setInertia(body, total.inertia);\n        Body.setPosition(body, total.centre);\n    };\n\n    /**\n     * Set the centre of mass of the body. \n     * The `centre` is a vector in world-space unless `relative` is set, in which case it is a translation.\n     * The centre of mass is the point the body rotates about and can be used to simulate non-uniform density.\n     * This is equal to moving `body.position` but not the `body.vertices`.\n     * Invalid if the `centre` falls outside the body's convex hull.\n     * @method setCentre\n     * @param {body} body\n     * @param {vector} centre\n     * @param {bool} relative\n     */\n    Body.setCentre = function(body, centre, relative) {\n        if (!relative) {\n            body.positionPrev.x = centre.x - (body.position.x - body.positionPrev.x);\n            body.positionPrev.y = centre.y - (body.position.y - body.positionPrev.y);\n            body.position.x = centre.x;\n            body.position.y = centre.y;\n        } else {\n            body.positionPrev.x += centre.x;\n            body.positionPrev.y += centre.y;\n            body.position.x += centre.x;\n            body.position.y += centre.y;\n        }\n    };\n\n    /**\n     * Sets the position of the body. By default velocity is unchanged.\n     * If `updateVelocity` is `true` then velocity is inferred from the change in position.\n     * @method setPosition\n     * @param {body} body\n     * @param {vector} position\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.setPosition = function(body, position, updateVelocity) {\n        var delta = Vector.sub(position, body.position);\n\n        if (updateVelocity) {\n            body.positionPrev.x = body.position.x;\n            body.positionPrev.y = body.position.y;\n            body.velocity.x = delta.x;\n            body.velocity.y = delta.y;\n            body.speed = Vector.magnitude(delta);\n        } else {\n            body.positionPrev.x += delta.x;\n            body.positionPrev.y += delta.y;\n        }\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n            part.position.x += delta.x;\n            part.position.y += delta.y;\n            Vertices.translate(part.vertices, delta);\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n    };\n\n    /**\n     * Sets the angle of the body. By default angular velocity is unchanged.\n     * If `updateVelocity` is `true` then angular velocity is inferred from the change in angle.\n     * @method setAngle\n     * @param {body} body\n     * @param {number} angle\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.setAngle = function(body, angle, updateVelocity) {\n        var delta = angle - body.angle;\n        \n        if (updateVelocity) {\n            body.anglePrev = body.angle;\n            body.angularVelocity = delta;\n            body.angularSpeed = Math.abs(delta);\n        } else {\n            body.anglePrev += delta;\n        }\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n            part.angle += delta;\n            Vertices.rotate(part.vertices, delta, body.position);\n            Axes.rotate(part.axes, delta);\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n            if (i > 0) {\n                Vector.rotateAbout(part.position, delta, body.position, part.position);\n            }\n        }\n    };\n\n    /**\n     * Sets the current linear velocity of the body.  \n     * Affects body speed.\n     * @method setVelocity\n     * @param {body} body\n     * @param {vector} velocity\n     */\n    Body.setVelocity = function(body, velocity) {\n        var timeScale = body.deltaTime / Body._baseDelta;\n        body.positionPrev.x = body.position.x - velocity.x * timeScale;\n        body.positionPrev.y = body.position.y - velocity.y * timeScale;\n        body.velocity.x = (body.position.x - body.positionPrev.x) / timeScale;\n        body.velocity.y = (body.position.y - body.positionPrev.y) / timeScale;\n        body.speed = Vector.magnitude(body.velocity);\n    };\n\n    /**\n     * Gets the current linear velocity of the body.\n     * @method getVelocity\n     * @param {body} body\n     * @return {vector} velocity\n     */\n    Body.getVelocity = function(body) {\n        var timeScale = Body._baseDelta / body.deltaTime;\n\n        return {\n            x: (body.position.x - body.positionPrev.x) * timeScale,\n            y: (body.position.y - body.positionPrev.y) * timeScale\n        };\n    };\n\n    /**\n     * Gets the current linear speed of the body.  \n     * Equivalent to the magnitude of its velocity.\n     * @method getSpeed\n     * @param {body} body\n     * @return {number} speed\n     */\n    Body.getSpeed = function(body) {\n        return Vector.magnitude(Body.getVelocity(body));\n    };\n\n    /**\n     * Sets the current linear speed of the body.  \n     * Direction is maintained. Affects body velocity.\n     * @method setSpeed\n     * @param {body} body\n     * @param {number} speed\n     */\n    Body.setSpeed = function(body, speed) {\n        Body.setVelocity(body, Vector.mult(Vector.normalise(Body.getVelocity(body)), speed));\n    };\n\n    /**\n     * Sets the current rotational velocity of the body.  \n     * Affects body angular speed.\n     * @method setAngularVelocity\n     * @param {body} body\n     * @param {number} velocity\n     */\n    Body.setAngularVelocity = function(body, velocity) {\n        var timeScale = body.deltaTime / Body._baseDelta;\n        body.anglePrev = body.angle - velocity * timeScale;\n        body.angularVelocity = (body.angle - body.anglePrev) / timeScale;\n        body.angularSpeed = Math.abs(body.angularVelocity);\n    };\n\n    /**\n     * Gets the current rotational velocity of the body.\n     * @method getAngularVelocity\n     * @param {body} body\n     * @return {number} angular velocity\n     */\n    Body.getAngularVelocity = function(body) {\n        return (body.angle - body.anglePrev) * Body._baseDelta / body.deltaTime;\n    };\n\n    /**\n     * Gets the current rotational speed of the body.  \n     * Equivalent to the magnitude of its angular velocity.\n     * @method getAngularSpeed\n     * @param {body} body\n     * @return {number} angular speed\n     */\n    Body.getAngularSpeed = function(body) {\n        return Math.abs(Body.getAngularVelocity(body));\n    };\n\n    /**\n     * Sets the current rotational speed of the body.  \n     * Direction is maintained. Affects body angular velocity.\n     * @method setAngularSpeed\n     * @param {body} body\n     * @param {number} speed\n     */\n    Body.setAngularSpeed = function(body, speed) {\n        Body.setAngularVelocity(body, Common.sign(Body.getAngularVelocity(body)) * speed);\n    };\n\n    /**\n     * Moves a body by a given vector relative to its current position. By default velocity is unchanged.\n     * If `updateVelocity` is `true` then velocity is inferred from the change in position.\n     * @method translate\n     * @param {body} body\n     * @param {vector} translation\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.translate = function(body, translation, updateVelocity) {\n        Body.setPosition(body, Vector.add(body.position, translation), updateVelocity);\n    };\n\n    /**\n     * Rotates a body by a given angle relative to its current angle. By default angular velocity is unchanged.\n     * If `updateVelocity` is `true` then angular velocity is inferred from the change in angle.\n     * @method rotate\n     * @param {body} body\n     * @param {number} rotation\n     * @param {vector} [point]\n     * @param {boolean} [updateVelocity=false]\n     */\n    Body.rotate = function(body, rotation, point, updateVelocity) {\n        if (!point) {\n            Body.setAngle(body, body.angle + rotation, updateVelocity);\n        } else {\n            var cos = Math.cos(rotation),\n                sin = Math.sin(rotation),\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + (dx * cos - dy * sin),\n                y: point.y + (dx * sin + dy * cos)\n            }, updateVelocity);\n\n            Body.setAngle(body, body.angle + rotation, updateVelocity);\n        }\n    };\n\n    /**\n     * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre).\n     * @method scale\n     * @param {body} body\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} [point]\n     */\n    Body.scale = function(body, scaleX, scaleY, point) {\n        var totalArea = 0,\n            totalInertia = 0;\n\n        point = point || body.position;\n\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            // scale vertices\n            Vertices.scale(part.vertices, scaleX, scaleY, point);\n\n            // update properties\n            part.axes = Axes.fromVertices(part.vertices);\n            part.area = Vertices.area(part.vertices);\n            Body.setMass(part, body.density * part.area);\n\n            // update inertia (requires vertices to be at origin)\n            Vertices.translate(part.vertices, { x: -part.position.x, y: -part.position.y });\n            Body.setInertia(part, Body._inertiaScale * Vertices.inertia(part.vertices, part.mass));\n            Vertices.translate(part.vertices, { x: part.position.x, y: part.position.y });\n\n            if (i > 0) {\n                totalArea += part.area;\n                totalInertia += part.inertia;\n            }\n\n            // scale position\n            part.position.x = point.x + (part.position.x - point.x) * scaleX;\n            part.position.y = point.y + (part.position.y - point.y) * scaleY;\n\n            // update bounds\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n\n        // handle parent body\n        if (body.parts.length > 1) {\n            body.area = totalArea;\n\n            if (!body.isStatic) {\n                Body.setMass(body, body.density * totalArea);\n                Body.setInertia(body, totalInertia);\n            }\n        }\n\n        // handle circles\n        if (body.circleRadius) { \n            if (scaleX === scaleY) {\n                body.circleRadius *= scaleX;\n            } else {\n                // body is no longer a circle\n                body.circleRadius = null;\n            }\n        }\n    };\n\n    /**\n     * Performs an update by integrating the equations of motion on the `body`.\n     * This is applied every update by `Matter.Engine` automatically.\n     * @method update\n     * @param {body} body\n     * @param {number} [deltaTime=16.666]\n     */\n    Body.update = function(body, deltaTime) {\n        deltaTime = (typeof deltaTime !== 'undefined' ? deltaTime : (1000 / 60)) * body.timeScale;\n\n        var deltaTimeSquared = deltaTime * deltaTime,\n            correction = Body._timeCorrection ? deltaTime / (body.deltaTime || deltaTime) : 1;\n\n        // from the previous step\n        var frictionAir = 1 - body.frictionAir * (deltaTime / Common._baseDelta),\n            velocityPrevX = (body.position.x - body.positionPrev.x) * correction,\n            velocityPrevY = (body.position.y - body.positionPrev.y) * correction;\n\n        // update velocity with Verlet integration\n        body.velocity.x = (velocityPrevX * frictionAir) + (body.force.x / body.mass) * deltaTimeSquared;\n        body.velocity.y = (velocityPrevY * frictionAir) + (body.force.y / body.mass) * deltaTimeSquared;\n\n        body.positionPrev.x = body.position.x;\n        body.positionPrev.y = body.position.y;\n        body.position.x += body.velocity.x;\n        body.position.y += body.velocity.y;\n        body.deltaTime = deltaTime;\n\n        // update angular velocity with Verlet integration\n        body.angularVelocity = ((body.angle - body.anglePrev) * frictionAir * correction) + (body.torque / body.inertia) * deltaTimeSquared;\n        body.anglePrev = body.angle;\n        body.angle += body.angularVelocity;\n\n        // transform the body geometry\n        for (var i = 0; i < body.parts.length; i++) {\n            var part = body.parts[i];\n\n            Vertices.translate(part.vertices, body.velocity);\n            \n            if (i > 0) {\n                part.position.x += body.velocity.x;\n                part.position.y += body.velocity.y;\n            }\n\n            if (body.angularVelocity !== 0) {\n                Vertices.rotate(part.vertices, body.angularVelocity, body.position);\n                Axes.rotate(part.axes, body.angularVelocity);\n                if (i > 0) {\n                    Vector.rotateAbout(part.position, body.angularVelocity, body.position, part.position);\n                }\n            }\n\n            Bounds.update(part.bounds, part.vertices, body.velocity);\n        }\n    };\n\n    /**\n     * Updates properties `body.velocity`, `body.speed`, `body.angularVelocity` and `body.angularSpeed` which are normalised in relation to `Body._baseDelta`.\n     * @method updateVelocities\n     * @param {body} body\n     */\n    Body.updateVelocities = function(body) {\n        var timeScale = Body._baseDelta / body.deltaTime,\n            bodyVelocity = body.velocity;\n\n        bodyVelocity.x = (body.position.x - body.positionPrev.x) * timeScale;\n        bodyVelocity.y = (body.position.y - body.positionPrev.y) * timeScale;\n        body.speed = Math.sqrt((bodyVelocity.x * bodyVelocity.x) + (bodyVelocity.y * bodyVelocity.y));\n\n        body.angularVelocity = (body.angle - body.anglePrev) * timeScale;\n        body.angularSpeed = Math.abs(body.angularVelocity);\n    };\n\n    /**\n     * Applies the `force` to the `body` from the force origin `position` in world-space, over a single timestep, including applying any resulting angular torque.\n     * \n     * Forces are useful for effects like gravity, wind or rocket thrust, but can be difficult in practice when precise control is needed. In these cases see `Body.setVelocity` and `Body.setPosition` as an alternative.\n     * \n     * The force from this function is only applied once for the duration of a single timestep, in other words the duration depends directly on the current engine update `delta` and the rate of calls to this function.\n     * \n     * Therefore to account for time, you should apply the force constantly over as many engine updates as equivalent to the intended duration.\n     * \n     * If all or part of the force duration is some fraction of a timestep, first multiply the force by `duration / timestep`.\n     * \n     * The force origin `position` in world-space must also be specified. Passing `body.position` will result in zero angular effect as the force origin would be at the centre of mass.\n     * \n     * The `body` will take time to accelerate under a force, the resulting effect depends on duration of the force, the body mass and other forces on the body including friction combined.\n     * @method applyForce\n     * @param {body} body\n     * @param {vector} position The force origin in world-space. Pass `body.position` to avoid angular torque.\n     * @param {vector} force\n     */\n    Body.applyForce = function(body, position, force) {\n        var offset = { x: position.x - body.position.x, y: position.y - body.position.y };\n        body.force.x += force.x;\n        body.force.y += force.y;\n        body.torque += offset.x * force.y - offset.y * force.x;\n    };\n\n    /**\n     * Returns the sums of the properties of all compound parts of the parent body.\n     * @method _totalProperties\n     * @private\n     * @param {body} body\n     * @return {}\n     */\n    Body._totalProperties = function(body) {\n        // from equations at:\n        // https://ecourses.ou.edu/cgi-bin/ebook.cgi?doc=&topic=st&chap_sec=07.2&page=theory\n        // http://output.to/sideway/default.asp?qno=121100087\n\n        var properties = {\n            mass: 0,\n            area: 0,\n            inertia: 0,\n            centre: { x: 0, y: 0 }\n        };\n\n        // sum the properties of all compound parts of the parent body\n        for (var i = body.parts.length === 1 ? 0 : 1; i < body.parts.length; i++) {\n            var part = body.parts[i],\n                mass = part.mass !== Infinity ? part.mass : 1;\n\n            properties.mass += mass;\n            properties.area += part.area;\n            properties.inertia += part.inertia;\n            properties.centre = Vector.add(properties.centre, Vector.mult(part.position, mass));\n        }\n\n        properties.centre = Vector.div(properties.centre, properties.mass);\n\n        return properties;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when a body starts sleeping (where `this` is the body).\n    *\n    * @event sleepStart\n    * @this {body} The body that has started sleeping\n    * @param {} event An event object\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a body ends sleeping (where `this` is the body).\n    *\n    * @event sleepEnd\n    * @this {body} The body that has ended sleeping\n    * @param {} event An event object\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Body.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * _Read only_. Set by `Body.create`.\n     * \n     * A `String` denoting the type of object.\n     *\n     * @readOnly\n     * @property type\n     * @type string\n     * @default \"body\"\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage bodies.\n     *\n     * @property label\n     * @type string\n     * @default \"Body\"\n     */\n\n    /**\n     * _Read only_. Use `Body.setParts` to set. \n     * \n     * See `Bodies.fromVertices` for a related utility.\n     * \n     * An array of bodies (the 'parts') that make up this body (the 'parent'). The first body in this array must always be a self-reference to this `body`.  \n     * \n     * The parts are fixed together and therefore perform as a single unified rigid body.\n     * \n     * Parts in relation to each other are allowed to overlap, as well as form gaps or holes, so can be used to create complex concave bodies unlike when using a single part. \n     * \n     * Use properties and functions on the parent `body` rather than on parts.\n     *   \n     * Outside of their geometry, most properties on parts are not considered or updated.  \n     * As such 'per-part' material properties among others are not currently considered.\n     * \n     * Parts should be created specifically for their parent body.  \n     * Parts should not be shared or reused between bodies, only one parent is supported.  \n     * Parts should not have their own parts, they are not handled recursively.  \n     * Parts should not be added to the world directly or any other composite.  \n     * Parts own vertices must be convex and in clockwise order.   \n     * \n     * A body with more than one part is sometimes referred to as a 'compound' body. \n     * \n     * Use `Body.setParts` when setting parts to ensure correct updates of all properties.  \n     *\n     * @readOnly\n     * @property parts\n     * @type body[]\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * _Read only_. Updated by `Body.setParts`.\n     * \n     * A reference to the body that this is a part of. See `body.parts`.\n     * This is a self reference if the body is not a part of another body.\n     *\n     * @readOnly\n     * @property parent\n     * @type body\n     */\n\n    /**\n     * A `Number` specifying the angle of the body, in radians.\n     *\n     * @property angle\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setVertices` or `Body.setParts` to set. See also `Bodies.fromVertices`.\n     * \n     * An array of `Vector` objects that specify the convex hull of the rigid body.\n     * These should be provided about the origin `(0, 0)`. E.g.\n     *\n     * `[{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]`\n     * \n     * Vertices must always be convex, in clockwise order and must not contain any duplicate points.\n     * \n     * Concave vertices should be decomposed into convex `parts`, see `Bodies.fromVertices` and `Body.setParts`.\n     *\n     * When set the vertices are translated such that `body.position` is at the centre of mass.\n     * Many other body properties are automatically calculated from these vertices when set including `density`, `area` and `inertia`.\n     * \n     * The module `Matter.Vertices` contains useful methods for working with vertices.\n     *\n     * @readOnly\n     * @property vertices\n     * @type vector[]\n     */\n\n    /**\n     * _Read only_. Use `Body.setPosition` to set. \n     * \n     * A `Vector` that specifies the current world-space position of the body.\n     * \n     * @readOnly\n     * @property position\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that accumulates the total force applied to the body for a single update.\n     * Force is zeroed after every `Engine.update`, so constant forces should be applied for every update they are needed. See also `Body.applyForce`.\n     * \n     * @property force\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Number` that accumulates the total torque (turning force) applied to the body for a single update. See also `Body.applyForce`.\n     * Torque is zeroed after every `Engine.update`, so constant torques should be applied for every update they are needed.\n     *\n     * Torques result in angular acceleration on every update, which depends on body inertia and the engine update delta.\n     * \n     * @property torque\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setSpeed` to set. \n     * \n     * See `Body.getSpeed` for details.\n     * \n     * Equivalent to the magnitude of `body.velocity` (always positive).\n     * \n     * @readOnly\n     * @property speed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setVelocity` to set. \n     * \n     * See `Body.getVelocity` for details.\n     * \n     * Equivalent to the magnitude of `body.angularVelocity` (always positive).\n     * \n     * @readOnly\n     * @property velocity\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * _Read only_. Use `Body.setAngularSpeed` to set. \n     * \n     * See `Body.getAngularSpeed` for details.\n     * \n     * \n     * @readOnly\n     * @property angularSpeed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setAngularVelocity` to set. \n     * \n     * See `Body.getAngularVelocity` for details.\n     * \n     *\n     * @readOnly\n     * @property angularVelocity\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * _Read only_. Use `Body.setStatic` to set. \n     * \n     * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.\n     *\n     * @readOnly\n     * @property isStatic\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.\n     *\n     * @property isSensor\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * _Read only_. Use `Sleeping.set` to set. \n     * \n     * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.\n     *\n     * @readOnly\n     * @property isSleeping\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * _Read only_. Calculated during engine update only when sleeping is enabled.\n     * \n     * A `Number` that loosely measures the amount of movement a body currently has.\n     *\n     * Derived from `body.speed^2 + body.angularSpeed^2`. See `Sleeping.update`.\n     * \n     * @readOnly\n     * @property motion\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that defines the length of time during which this body must have near-zero velocity before it is set as sleeping by the `Matter.Sleeping` module (if sleeping is enabled by the engine).\n     * \n     * @property sleepThreshold\n     * @type number\n     * @default 60\n     */\n\n    /**\n     * _Read only_. Use `Body.setDensity` to set. \n     * \n     * A `Number` that defines the density of the body (mass per unit area).\n     * \n     * Mass will also be updated when set.\n     *\n     * @readOnly\n     * @property density\n     * @type number\n     * @default 0.001\n     */\n\n    /**\n     * _Read only_. Use `Body.setMass` to set. \n     * \n     * A `Number` that defines the mass of the body.\n     * \n     * Density will also be updated when set.\n     * \n     * @readOnly\n     * @property mass\n     * @type number\n     */\n\n    /**\n     * _Read only_. Use `Body.setMass` to set. \n     * \n     * A `Number` that defines the inverse mass of the body (`1 / mass`).\n     *\n     * @readOnly\n     * @property inverseMass\n     * @type number\n     */\n\n    /**\n     * _Read only_. Automatically calculated when vertices, mass or density are set or set through `Body.setInertia`.\n     * \n     * A `Number` that defines the moment of inertia of the body. This is the second moment of area in two dimensions.\n     * \n     * Can be manually set to `Infinity` to prevent rotation of the body. See `Body.setInertia`.\n     * \n     * @readOnly\n     * @property inertia\n     * @type number\n     */\n\n    /**\n     * _Read only_. Automatically calculated when vertices, mass or density are set or calculated by `Body.setInertia`.\n     * \n     * A `Number` that defines the inverse moment of inertia of the body (`1 / inertia`).\n     * \n     * @readOnly\n     * @property inverseInertia\n     * @type number\n     */\n\n    /**\n     * A `Number` that defines the restitution (elasticity) of the body. The value is always positive and is in the range `(0, 1)`.\n     * A value of `0` means collisions may be perfectly inelastic and no bouncing may occur. \n     * A value of `0.8` means the body may bounce back with approximately 80% of its kinetic energy.\n     * Note that collision response is based on _pairs_ of bodies, and that `restitution` values are _combined_ with the following formula:\n     *\n     * `Math.max(bodyA.restitution, bodyB.restitution)`\n     *\n     * @property restitution\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that defines the friction of the body. The value is always positive and is in the range `(0, 1)`.\n     * A value of `0` means that the body may slide indefinitely.\n     * A value of `1` means the body may come to a stop almost instantly after a force is applied.\n     *\n     * The effects of the value may be non-linear. \n     * High values may be unstable depending on the body.\n     * The engine uses a Coulomb friction model including static and kinetic friction.\n     * Note that collision response is based on _pairs_ of bodies, and that `friction` values are _combined_ with the following formula:\n     *\n     * `Math.min(bodyA.friction, bodyB.friction)`\n     *\n     * @property friction\n     * @type number\n     * @default 0.1\n     */\n\n    /**\n     * A `Number` that defines the static friction of the body (in the Coulomb friction model). \n     * A value of `0` means the body will never 'stick' when it is nearly stationary and only dynamic `friction` is used.\n     * The higher the value (e.g. `10`), the more force it will take to initially get the body moving when nearly stationary.\n     * This value is multiplied with the `friction` property to make it easier to change `friction` and maintain an appropriate amount of static friction.\n     *\n     * @property frictionStatic\n     * @type number\n     * @default 0.5\n     */\n\n    /**\n     * A `Number` that defines the air friction of the body (air resistance). \n     * A value of `0` means the body will never slow as it moves through space.\n     * The higher the value, the faster a body slows when moving through space.\n     * The effects of the value are non-linear. \n     *\n     * @property frictionAir\n     * @type number\n     * @default 0.01\n     */\n\n    /**\n     * An `Object` that specifies the collision filtering properties of this body.\n     *\n     * Collisions between two bodies will obey the following rules:\n     * - If the two bodies have the same non-zero value of `collisionFilter.group`,\n     *   they will always collide if the value is positive, and they will never collide\n     *   if the value is negative.\n     * - If the two bodies have different values of `collisionFilter.group` or if one\n     *   (or both) of the bodies has a value of 0, then the category/mask rules apply as follows:\n     *\n     * Each body belongs to a collision category, given by `collisionFilter.category`. This\n     * value is used as a bit field and the category should have only one bit set, meaning that\n     * the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32\n     * different collision categories available.\n     *\n     * Each body also defines a collision bitmask, given by `collisionFilter.mask` which specifies\n     * the categories it collides with (the value is the bitwise AND value of all these categories).\n     *\n     * Using the category/mask rules, two bodies `A` and `B` collide if each includes the other's\n     * category in its mask, i.e. `(categoryA & maskB) !== 0` and `(categoryB & maskA) !== 0`\n     * are both true.\n     *\n     * @property collisionFilter\n     * @type object\n     */\n\n    /**\n     * An Integer `Number`, that specifies the collision group this body belongs to.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.group\n     * @type object\n     * @default 0\n     */\n\n    /**\n     * A bit field that specifies the collision category this body belongs to.\n     * The category value should have only one bit set, for example `0x0001`.\n     * This means there are up to 32 unique collision categories available.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.category\n     * @type object\n     * @default 1\n     */\n\n    /**\n     * A bit mask that specifies the collision categories this body may collide with.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter.mask\n     * @type object\n     * @default -1\n     */\n\n    /**\n     * A `Number` that specifies a thin boundary around the body where it is allowed to slightly sink into other bodies.\n     * \n     * This is required for proper collision response, including friction and restitution effects.\n     * \n     * The default should generally suffice in most cases. You may need to decrease this value for very small bodies that are nearing the default value in scale.\n     *\n     * @property slop\n     * @type number\n     * @default 0.05\n     */\n\n    /**\n     * A `Number` that specifies per-body time scaling.\n     *\n     * @property timeScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * _Read only_. Updated during engine update.\n     * \n     * A `Number` that records the last delta time value used to update this body.\n     * Used to calculate speed and velocity.\n     *\n     * @readOnly\n     * @property deltaTime\n     * @type number\n     * @default 1000 / 60\n     */\n\n    /**\n     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.\n     *\n     * @property render\n     * @type object\n     */\n\n    /**\n     * A flag that indicates if the body should be rendered.\n     *\n     * @property render.visible\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * Sets the opacity to use when rendering.\n     *\n     * @property render.opacity\n     * @type number\n     * @default 1\n    */\n\n    /**\n     * An `Object` that defines the sprite properties to use when rendering, if any.\n     *\n     * @property render.sprite\n     * @type object\n     */\n\n    /**\n     * An `String` that defines the path to the image to use as the sprite texture, if any.\n     *\n     * @property render.sprite.texture\n     * @type string\n     */\n     \n    /**\n     * A `Number` that defines the scaling in the x-axis for the sprite, if any.\n     *\n     * @property render.sprite.xScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that defines the scaling in the y-axis for the sprite, if any.\n     *\n     * @property render.sprite.yScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n      * A `Number` that defines the offset in the x-axis for the sprite (normalised by texture width).\n      *\n      * @property render.sprite.xOffset\n      * @type number\n      * @default 0\n      */\n\n    /**\n      * A `Number` that defines the offset in the y-axis for the sprite (normalised by texture height).\n      *\n      * @property render.sprite.yOffset\n      * @type number\n      * @default 0\n      */\n\n    /**\n     * A `Number` that defines the line width to use when rendering the body outline (if a sprite is not defined).\n     * A value of `0` means no outline will be rendered.\n     *\n     * @property render.lineWidth\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `String` that defines the fill style to use when rendering the body (if a sprite is not defined).\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.fillStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * A `String` that defines the stroke style to use when rendering the body outline (if a sprite is not defined).\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.strokeStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * _Read only_. Calculated automatically when vertices are set.\n     * \n     * An array of unique axis vectors (edge normals) used for collision detection.\n     * These are automatically calculated when vertices are set.\n     * They are constantly updated by `Body.update` during the simulation.\n     *\n     * @readOnly\n     * @property axes\n     * @type vector[]\n     */\n     \n    /**\n     * _Read only_. Calculated automatically when vertices are set.\n     * \n     * A `Number` that measures the area of the body's convex hull.\n     * \n     * @readOnly\n     * @property area\n     * @type string\n     * @default \n     */\n\n    /**\n     * A `Bounds` object that defines the AABB region for the body.\n     * It is automatically calculated when vertices are set and constantly updated by `Body.update` during simulation.\n     * \n     * @property bounds\n     * @type bounds\n     */\n\n    /**\n     * Temporarily may hold parameters to be passed to `Vertices.chamfer` where supported by external functions.\n     * \n     * See `Vertices.chamfer` for possible parameters this object may hold.\n     * \n     * Currently only functions inside `Matter.Bodies` provide a utility using this property as a vertices pre-processing option.\n     * \n     * Alternatively consider using `Vertices.chamfer` directly on vertices before passing them to a body creation function.\n     * \n     * @property chamfer\n     * @type object|null|undefined\n     */\n\n})();\n"
  },
  {
    "path": "src/body/Composite.js",
    "content": "/**\n* A composite is a collection of `Matter.Body`, `Matter.Constraint` and other `Matter.Composite` objects.\n*\n* They are a container that can represent complex objects made of multiple parts, even if they are not physically connected.\n* A composite could contain anything from a single body all the way up to a whole world.\n* \n* When making any changes to composites, use the included functions rather than changing their properties directly.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Composite\n*/\n\nvar Composite = {};\n\nmodule.exports = Composite;\n\nvar Events = require('../core/Events');\nvar Common = require('../core/Common');\nvar Bounds = require('../geometry/Bounds');\nvar Body = require('./Body');\n\n(function() {\n\n    /**\n     * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properites section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} [options]\n     * @return {composite} A new composite\n     */\n    Composite.create = function(options) {\n        return Common.extend({ \n            id: Common.nextId(),\n            type: 'composite',\n            parent: null,\n            isModified: false,\n            bodies: [], \n            constraints: [], \n            composites: [],\n            label: 'Composite',\n            plugin: {},\n            cache: {\n                allBodies: null,\n                allConstraints: null,\n                allComposites: null\n            }\n        }, options);\n    };\n\n    /**\n     * Sets the composite's `isModified` flag. \n     * If `updateParents` is true, all parents will be set (default: false).\n     * If `updateChildren` is true, all children will be set (default: false).\n     * @private\n     * @method setModified\n     * @param {composite} composite\n     * @param {boolean} isModified\n     * @param {boolean} [updateParents=false]\n     * @param {boolean} [updateChildren=false]\n     */\n    Composite.setModified = function(composite, isModified, updateParents, updateChildren) {\n        composite.isModified = isModified;\n\n        if (isModified && composite.cache) {\n            composite.cache.allBodies = null;\n            composite.cache.allConstraints = null;\n            composite.cache.allComposites = null;\n        }\n\n        if (updateParents && composite.parent) {\n            Composite.setModified(composite.parent, isModified, updateParents, updateChildren);\n        }\n\n        if (updateChildren) {\n            for (var i = 0; i < composite.composites.length; i++) {\n                var childComposite = composite.composites[i];\n                Composite.setModified(childComposite, isModified, updateParents, updateChildren);\n            }\n        }\n    };\n\n    /**\n     * Generic single or multi-add function. Adds a single or an array of body(s), constraint(s) or composite(s) to the given composite.\n     * Triggers `beforeAdd` and `afterAdd` events on the `composite`.\n     * @method add\n     * @param {composite} composite\n     * @param {object|array} object A single or an array of body(s), constraint(s) or composite(s)\n     * @return {composite} The original composite with the objects added\n     */\n    Composite.add = function(composite, object) {\n        var objects = [].concat(object);\n\n        Events.trigger(composite, 'beforeAdd', { object: object });\n\n        for (var i = 0; i < objects.length; i++) {\n            var obj = objects[i];\n\n            switch (obj.type) {\n\n            case 'body':\n                // skip adding compound parts\n                if (obj.parent !== obj) {\n                    Common.warn('Composite.add: skipped adding a compound body part (you must add its parent instead)');\n                    break;\n                }\n\n                Composite.addBody(composite, obj);\n                break;\n            case 'constraint':\n                Composite.addConstraint(composite, obj);\n                break;\n            case 'composite':\n                Composite.addComposite(composite, obj);\n                break;\n            case 'mouseConstraint':\n                Composite.addConstraint(composite, obj.constraint);\n                break;\n\n            }\n        }\n\n        Events.trigger(composite, 'afterAdd', { object: object });\n\n        return composite;\n    };\n\n    /**\n     * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite.\n     * Optionally searching its children recursively.\n     * Triggers `beforeRemove` and `afterRemove` events on the `composite`.\n     * @method remove\n     * @param {composite} composite\n     * @param {object|array} object\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the objects removed\n     */\n    Composite.remove = function(composite, object, deep) {\n        var objects = [].concat(object);\n\n        Events.trigger(composite, 'beforeRemove', { object: object });\n\n        for (var i = 0; i < objects.length; i++) {\n            var obj = objects[i];\n\n            switch (obj.type) {\n\n            case 'body':\n                Composite.removeBody(composite, obj, deep);\n                break;\n            case 'constraint':\n                Composite.removeConstraint(composite, obj, deep);\n                break;\n            case 'composite':\n                Composite.removeComposite(composite, obj, deep);\n                break;\n            case 'mouseConstraint':\n                Composite.removeConstraint(composite, obj.constraint);\n                break;\n\n            }\n        }\n\n        Events.trigger(composite, 'afterRemove', { object: object });\n\n        return composite;\n    };\n\n    /**\n     * Adds a composite to the given composite.\n     * @private\n     * @method addComposite\n     * @param {composite} compositeA\n     * @param {composite} compositeB\n     * @return {composite} The original compositeA with the objects from compositeB added\n     */\n    Composite.addComposite = function(compositeA, compositeB) {\n        compositeA.composites.push(compositeB);\n        compositeB.parent = compositeA;\n        Composite.setModified(compositeA, true, true, false);\n        return compositeA;\n    };\n\n    /**\n     * Removes a composite from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeComposite\n     * @param {composite} compositeA\n     * @param {composite} compositeB\n     * @param {boolean} [deep=false]\n     * @return {composite} The original compositeA with the composite removed\n     */\n    Composite.removeComposite = function(compositeA, compositeB, deep) {\n        var position = Common.indexOf(compositeA.composites, compositeB);\n\n        if (position !== -1) {\n            var bodies = Composite.allBodies(compositeB);\n\n            Composite.removeCompositeAt(compositeA, position);\n\n            for (var i = 0; i < bodies.length; i++) {\n                bodies[i].sleepCounter = 0;\n            }\n        }\n\n        if (deep) {\n            for (var i = 0; i < compositeA.composites.length; i++){\n                Composite.removeComposite(compositeA.composites[i], compositeB, true);\n            }\n        }\n\n        return compositeA;\n    };\n\n    /**\n     * Removes a composite from the given composite.\n     * @private\n     * @method removeCompositeAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the composite removed\n     */\n    Composite.removeCompositeAt = function(composite, position) {\n        composite.composites.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Adds a body to the given composite.\n     * @private\n     * @method addBody\n     * @param {composite} composite\n     * @param {body} body\n     * @return {composite} The original composite with the body added\n     */\n    Composite.addBody = function(composite, body) {\n        composite.bodies.push(body);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeBody\n     * @param {composite} composite\n     * @param {body} body\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the body removed\n     */\n    Composite.removeBody = function(composite, body, deep) {\n        var position = Common.indexOf(composite.bodies, body);\n\n        if (position !== -1) {\n            Composite.removeBodyAt(composite, position);\n            body.sleepCounter = 0;\n        }\n\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.removeBody(composite.composites[i], body, true);\n            }\n        }\n\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite.\n     * @private\n     * @method removeBodyAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the body removed\n     */\n    Composite.removeBodyAt = function(composite, position) {\n        composite.bodies.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Adds a constraint to the given composite.\n     * @private\n     * @method addConstraint\n     * @param {composite} composite\n     * @param {constraint} constraint\n     * @return {composite} The original composite with the constraint added\n     */\n    Composite.addConstraint = function(composite, constraint) {\n        composite.constraints.push(constraint);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes a constraint from the given composite, and optionally searching its children recursively.\n     * @private\n     * @method removeConstraint\n     * @param {composite} composite\n     * @param {constraint} constraint\n     * @param {boolean} [deep=false]\n     * @return {composite} The original composite with the constraint removed\n     */\n    Composite.removeConstraint = function(composite, constraint, deep) {\n        var position = Common.indexOf(composite.constraints, constraint);\n        \n        if (position !== -1) {\n            Composite.removeConstraintAt(composite, position);\n        }\n\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.removeConstraint(composite.composites[i], constraint, true);\n            }\n        }\n\n        return composite;\n    };\n\n    /**\n     * Removes a body from the given composite.\n     * @private\n     * @method removeConstraintAt\n     * @param {composite} composite\n     * @param {number} position\n     * @return {composite} The original composite with the constraint removed\n     */\n    Composite.removeConstraintAt = function(composite, position) {\n        composite.constraints.splice(position, 1);\n        Composite.setModified(composite, true, true, false);\n        return composite;\n    };\n\n    /**\n     * Removes all bodies, constraints and composites from the given composite.\n     * Optionally clearing its children recursively.\n     * @method clear\n     * @param {composite} composite\n     * @param {boolean} keepStatic\n     * @param {boolean} [deep=false]\n     */\n    Composite.clear = function(composite, keepStatic, deep) {\n        if (deep) {\n            for (var i = 0; i < composite.composites.length; i++){\n                Composite.clear(composite.composites[i], keepStatic, true);\n            }\n        }\n        \n        if (keepStatic) {\n            composite.bodies = composite.bodies.filter(function(body) { return body.isStatic; });\n        } else {\n            composite.bodies.length = 0;\n        }\n\n        composite.constraints.length = 0;\n        composite.composites.length = 0;\n\n        Composite.setModified(composite, true, true, false);\n\n        return composite;\n    };\n\n    /**\n     * Returns all bodies in the given composite, including all bodies in its children, recursively.\n     * @method allBodies\n     * @param {composite} composite\n     * @return {body[]} All the bodies\n     */\n    Composite.allBodies = function(composite) {\n        if (composite.cache && composite.cache.allBodies) {\n            return composite.cache.allBodies;\n        }\n\n        var bodies = [].concat(composite.bodies);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            bodies = bodies.concat(Composite.allBodies(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allBodies = bodies;\n        }\n\n        return bodies;\n    };\n\n    /**\n     * Returns all constraints in the given composite, including all constraints in its children, recursively.\n     * @method allConstraints\n     * @param {composite} composite\n     * @return {constraint[]} All the constraints\n     */\n    Composite.allConstraints = function(composite) {\n        if (composite.cache && composite.cache.allConstraints) {\n            return composite.cache.allConstraints;\n        }\n\n        var constraints = [].concat(composite.constraints);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            constraints = constraints.concat(Composite.allConstraints(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allConstraints = constraints;\n        }\n\n        return constraints;\n    };\n\n    /**\n     * Returns all composites in the given composite, including all composites in its children, recursively.\n     * @method allComposites\n     * @param {composite} composite\n     * @return {composite[]} All the composites\n     */\n    Composite.allComposites = function(composite) {\n        if (composite.cache && composite.cache.allComposites) {\n            return composite.cache.allComposites;\n        }\n\n        var composites = [].concat(composite.composites);\n\n        for (var i = 0; i < composite.composites.length; i++)\n            composites = composites.concat(Composite.allComposites(composite.composites[i]));\n\n        if (composite.cache) {\n            composite.cache.allComposites = composites;\n        }\n\n        return composites;\n    };\n\n    /**\n     * Searches the composite recursively for an object matching the type and id supplied, null if not found.\n     * @method get\n     * @param {composite} composite\n     * @param {number} id\n     * @param {string} type\n     * @return {object} The requested object, if found\n     */\n    Composite.get = function(composite, id, type) {\n        var objects,\n            object;\n\n        switch (type) {\n        case 'body':\n            objects = Composite.allBodies(composite);\n            break;\n        case 'constraint':\n            objects = Composite.allConstraints(composite);\n            break;\n        case 'composite':\n            objects = Composite.allComposites(composite).concat(composite);\n            break;\n        }\n\n        if (!objects)\n            return null;\n\n        object = objects.filter(function(object) { \n            return object.id.toString() === id.toString(); \n        });\n\n        return object.length === 0 ? null : object[0];\n    };\n\n    /**\n     * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add).\n     * @method move\n     * @param {compositeA} compositeA\n     * @param {object[]} objects\n     * @param {compositeB} compositeB\n     * @return {composite} Returns compositeA\n     */\n    Composite.move = function(compositeA, objects, compositeB) {\n        Composite.remove(compositeA, objects);\n        Composite.add(compositeB, objects);\n        return compositeA;\n    };\n\n    /**\n     * Assigns new ids for all objects in the composite, recursively.\n     * @method rebase\n     * @param {composite} composite\n     * @return {composite} Returns composite\n     */\n    Composite.rebase = function(composite) {\n        var objects = Composite.allBodies(composite)\n            .concat(Composite.allConstraints(composite))\n            .concat(Composite.allComposites(composite));\n\n        for (var i = 0; i < objects.length; i++) {\n            objects[i].id = Common.nextId();\n        }\n\n        return composite;\n    };\n\n    /**\n     * Translates all children in the composite by a given vector relative to their current positions, \n     * without imparting any velocity.\n     * @method translate\n     * @param {composite} composite\n     * @param {vector} translation\n     * @param {bool} [recursive=true]\n     */\n    Composite.translate = function(composite, translation, recursive) {\n        var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            Body.translate(bodies[i], translation);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Rotates all children in the composite by a given angle about the given point, without imparting any angular velocity.\n     * @method rotate\n     * @param {composite} composite\n     * @param {number} rotation\n     * @param {vector} point\n     * @param {bool} [recursive=true]\n     */\n    Composite.rotate = function(composite, rotation, point, recursive) {\n        var cos = Math.cos(rotation),\n            sin = Math.sin(rotation),\n            bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + (dx * cos - dy * sin),\n                y: point.y + (dx * sin + dy * cos)\n            });\n\n            Body.rotate(body, rotation);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Scales all children in the composite, including updating physical properties (mass, area, axes, inertia), from a world-space point.\n     * @method scale\n     * @param {composite} composite\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} point\n     * @param {bool} [recursive=true]\n     */\n    Composite.scale = function(composite, scaleX, scaleY, point, recursive) {\n        var bodies = recursive ? Composite.allBodies(composite) : composite.bodies;\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                dx = body.position.x - point.x,\n                dy = body.position.y - point.y;\n                \n            Body.setPosition(body, {\n                x: point.x + dx * scaleX,\n                y: point.y + dy * scaleY\n            });\n\n            Body.scale(body, scaleX, scaleY);\n        }\n\n        return composite;\n    };\n\n    /**\n     * Returns the union of the bounds of all of the composite's bodies.\n     * @method bounds\n     * @param {composite} composite The composite.\n     * @returns {bounds} The composite bounds.\n     */\n    Composite.bounds = function(composite) {\n        var bodies = Composite.allBodies(composite),\n            vertices = [];\n\n        for (var i = 0; i < bodies.length; i += 1) {\n            var body = bodies[i];\n            vertices.push(body.bounds.min, body.bounds.max);\n        }\n\n        return Bounds.create(vertices);\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when a call to `Composite.add` is made, before objects have been added.\n    *\n    * @event beforeAdd\n    * @param {} event An event object\n    * @param {} event.object The object(s) to be added (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.add` is made, after objects have been added.\n    *\n    * @event afterAdd\n    * @param {} event An event object\n    * @param {} event.object The object(s) that have been added (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.remove` is made, before objects have been removed.\n    *\n    * @event beforeRemove\n    * @param {} event An event object\n    * @param {} event.object The object(s) to be removed (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when a call to `Composite.remove` is made, after objects have been removed.\n    *\n    * @event afterRemove\n    * @param {} event An event object\n    * @param {} event.object The object(s) that have been removed (may be a single body, constraint, composite or a mixed array of these)\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"composite\"\n     * @readOnly\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage composites.\n     *\n     * @property label\n     * @type string\n     * @default \"Composite\"\n     */\n\n    /**\n     * A flag that specifies whether the composite has been modified during the current step.\n     * This is automatically managed when bodies, constraints or composites are added or removed.\n     *\n     * @property isModified\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * The `Composite` that is the parent of this composite. It is automatically managed by the `Matter.Composite` methods.\n     *\n     * @property parent\n     * @type composite\n     * @default null\n     */\n\n    /**\n     * An array of `Body` that are _direct_ children of this composite.\n     * To add or remove bodies you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allBodies` method.\n     *\n     * @property bodies\n     * @type body[]\n     * @default []\n     */\n\n    /**\n     * An array of `Constraint` that are _direct_ children of this composite.\n     * To add or remove constraints you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allConstraints` method.\n     *\n     * @property constraints\n     * @type constraint[]\n     * @default []\n     */\n\n    /**\n     * An array of `Composite` that are _direct_ children of this composite.\n     * To add or remove composites you should use `Composite.add` and `Composite.remove` methods rather than directly modifying this property.\n     * If you wish to recursively find all descendants, you should use the `Composite.allComposites` method.\n     *\n     * @property composites\n     * @type composite[]\n     * @default []\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * An object used for storing cached results for performance reasons.\n     * This is used internally only and is automatically managed.\n     *\n     * @private\n     * @property cache\n     * @type {}\n     */\n\n})();\n"
  },
  {
    "path": "src/body/World.js",
    "content": "/**\n* This module has now been replaced by `Matter.Composite`.\n*\n* All usage should be migrated to the equivalent functions found on `Matter.Composite`.\n* For example `World.add(world, body)` now becomes `Composite.add(world, body)`.\n*\n* The property `world.gravity` has been moved to `engine.gravity`.\n*\n* For back-compatibility purposes this module will remain as a direct alias to `Matter.Composite` in the short term during migration.\n* Eventually this alias module will be marked as deprecated and then later removed in a future release.\n*\n* @class World\n*/\n\nvar World = {};\n\nmodule.exports = World;\n\nvar Composite = require('./Composite');\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * See above, aliases for back compatibility only\n     */\n    World.create = Composite.create;\n    World.add = Composite.add;\n    World.remove = Composite.remove;\n    World.clear = Composite.clear;\n    World.addComposite = Composite.addComposite;\n    World.addBody = Composite.addBody;\n    World.addConstraint = Composite.addConstraint;\n\n})();\n"
  },
  {
    "path": "src/collision/Collision.js",
    "content": "/**\n* The `Matter.Collision` module contains methods for detecting collisions between a given pair of bodies.\n*\n* For efficient detection between a list of bodies, see `Matter.Detector` and `Matter.Query`.\n*\n* See `Matter.Engine` for collision events.\n*\n* @class Collision\n*/\n\nvar Collision = {};\n\nmodule.exports = Collision;\n\nvar Vertices = require('../geometry/Vertices');\nvar Pair = require('./Pair');\n\n(function() {\n    var _supports = [];\n\n    var _overlapAB = {\n        overlap: 0,\n        axis: null\n    };\n\n    var _overlapBA = {\n        overlap: 0,\n        axis: null\n    };\n\n    /**\n     * Creates a new collision record.\n     * @method create\n     * @param {body} bodyA The first body part represented by the collision record\n     * @param {body} bodyB The second body part represented by the collision record\n     * @return {collision} A new collision record\n     */\n    Collision.create = function(bodyA, bodyB) {\n        return { \n            pair: null,\n            collided: false,\n            bodyA: bodyA,\n            bodyB: bodyB,\n            parentA: bodyA.parent,\n            parentB: bodyB.parent,\n            depth: 0,\n            normal: { x: 0, y: 0 },\n            tangent: { x: 0, y: 0 },\n            penetration: { x: 0, y: 0 },\n            supports: [null, null],\n            supportCount: 0\n        };\n    };\n\n    /**\n     * Detect collision between two bodies.\n     * @method collides\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @param {pairs} [pairs] Optionally reuse collision records from existing pairs.\n     * @return {collision|null} A collision record if detected, otherwise null\n     */\n    Collision.collides = function(bodyA, bodyB, pairs) {\n        Collision._overlapAxes(_overlapAB, bodyA.vertices, bodyB.vertices, bodyA.axes);\n\n        if (_overlapAB.overlap <= 0) {\n            return null;\n        }\n\n        Collision._overlapAxes(_overlapBA, bodyB.vertices, bodyA.vertices, bodyB.axes);\n\n        if (_overlapBA.overlap <= 0) {\n            return null;\n        }\n\n        // reuse collision records for gc efficiency\n        var pair = pairs && pairs.table[Pair.id(bodyA, bodyB)],\n            collision;\n\n        if (!pair) {\n            collision = Collision.create(bodyA, bodyB);\n            collision.collided = true;\n            collision.bodyA = bodyA.id < bodyB.id ? bodyA : bodyB;\n            collision.bodyB = bodyA.id < bodyB.id ? bodyB : bodyA;\n            collision.parentA = collision.bodyA.parent;\n            collision.parentB = collision.bodyB.parent;\n        } else {\n            collision = pair.collision;\n        }\n\n        bodyA = collision.bodyA;\n        bodyB = collision.bodyB;\n\n        var minOverlap;\n\n        if (_overlapAB.overlap < _overlapBA.overlap) {\n            minOverlap = _overlapAB;\n        } else {\n            minOverlap = _overlapBA;\n        }\n\n        var normal = collision.normal,\n            tangent = collision.tangent,\n            penetration = collision.penetration,\n            supports = collision.supports,\n            depth = minOverlap.overlap,\n            minAxis = minOverlap.axis,\n            normalX = minAxis.x,\n            normalY = minAxis.y,\n            deltaX = bodyB.position.x - bodyA.position.x,\n            deltaY = bodyB.position.y - bodyA.position.y;\n\n        // ensure normal is facing away from bodyA\n        if (normalX * deltaX + normalY * deltaY >= 0) {\n            normalX = -normalX;\n            normalY = -normalY;\n        }\n\n        normal.x = normalX;\n        normal.y = normalY;\n        \n        tangent.x = -normalY;\n        tangent.y = normalX;\n\n        penetration.x = normalX * depth;\n        penetration.y = normalY * depth;\n\n        collision.depth = depth;\n\n        // find support points, there is always either exactly one or two\n        var supportsB = Collision._findSupports(bodyA, bodyB, normal, 1),\n            supportCount = 0;\n\n        // find the supports from bodyB that are inside bodyA\n        if (Vertices.contains(bodyA.vertices, supportsB[0])) {\n            supports[supportCount++] = supportsB[0];\n        }\n\n        if (Vertices.contains(bodyA.vertices, supportsB[1])) {\n            supports[supportCount++] = supportsB[1];\n        }\n\n        // find the supports from bodyA that are inside bodyB\n        if (supportCount < 2) {\n            var supportsA = Collision._findSupports(bodyB, bodyA, normal, -1);\n\n            if (Vertices.contains(bodyB.vertices, supportsA[0])) {\n                supports[supportCount++] = supportsA[0];\n            }\n\n            if (supportCount < 2 && Vertices.contains(bodyB.vertices, supportsA[1])) {\n                supports[supportCount++] = supportsA[1];\n            }\n        }\n\n        // account for the edge case of overlapping but no vertex containment\n        if (supportCount === 0) {\n            supports[supportCount++] = supportsB[0];\n        }\n\n        // update support count\n        collision.supportCount = supportCount;\n\n        return collision;\n    };\n\n    /**\n     * Find the overlap between two sets of vertices.\n     * @method _overlapAxes\n     * @private\n     * @param {object} result\n     * @param {vertices} verticesA\n     * @param {vertices} verticesB\n     * @param {axes} axes\n     */\n    Collision._overlapAxes = function(result, verticesA, verticesB, axes) {\n        var verticesALength = verticesA.length,\n            verticesBLength = verticesB.length,\n            verticesAX = verticesA[0].x,\n            verticesAY = verticesA[0].y,\n            verticesBX = verticesB[0].x,\n            verticesBY = verticesB[0].y,\n            axesLength = axes.length,\n            overlapMin = Number.MAX_VALUE,\n            overlapAxisNumber = 0,\n            overlap,\n            overlapAB,\n            overlapBA,\n            dot,\n            i,\n            j;\n\n        for (i = 0; i < axesLength; i++) {\n            var axis = axes[i],\n                axisX = axis.x,\n                axisY = axis.y,\n                minA = verticesAX * axisX + verticesAY * axisY,\n                minB = verticesBX * axisX + verticesBY * axisY,\n                maxA = minA,\n                maxB = minB;\n            \n            for (j = 1; j < verticesALength; j += 1) {\n                dot = verticesA[j].x * axisX + verticesA[j].y * axisY;\n\n                if (dot > maxA) { \n                    maxA = dot;\n                } else if (dot < minA) { \n                    minA = dot;\n                }\n            }\n\n            for (j = 1; j < verticesBLength; j += 1) {\n                dot = verticesB[j].x * axisX + verticesB[j].y * axisY;\n\n                if (dot > maxB) { \n                    maxB = dot;\n                } else if (dot < minB) { \n                    minB = dot;\n                }\n            }\n\n            overlapAB = maxA - minB;\n            overlapBA = maxB - minA;\n            overlap = overlapAB < overlapBA ? overlapAB : overlapBA;\n\n            if (overlap < overlapMin) {\n                overlapMin = overlap;\n                overlapAxisNumber = i;\n\n                if (overlap <= 0) {\n                    // can not be intersecting\n                    break;\n                }\n            } \n        }\n\n        result.axis = axes[overlapAxisNumber];\n        result.overlap = overlapMin;\n    };\n\n    /**\n     * Finds supporting vertices given two bodies along a given direction using hill-climbing.\n     * @method _findSupports\n     * @private\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @param {vector} normal\n     * @param {number} direction\n     * @return [vector]\n     */\n    Collision._findSupports = function(bodyA, bodyB, normal, direction) {\n        var vertices = bodyB.vertices,\n            verticesLength = vertices.length,\n            bodyAPositionX = bodyA.position.x,\n            bodyAPositionY = bodyA.position.y,\n            normalX = normal.x * direction,\n            normalY = normal.y * direction,\n            vertexA = vertices[0],\n            vertexB = vertexA,\n            nearestDistance = normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y),\n            vertexC,\n            distance,\n            j;\n\n        // find deepest vertex relative to the axis\n        for (j = 1; j < verticesLength; j += 1) {\n            vertexB = vertices[j];\n            distance = normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y);\n\n            // convex hill-climbing\n            if (distance < nearestDistance) {\n                nearestDistance = distance;\n                vertexA = vertexB;\n            }\n        }\n\n        // measure next vertex\n        vertexC = vertices[(verticesLength + vertexA.index - 1) % verticesLength];\n        nearestDistance = normalX * (bodyAPositionX - vertexC.x) + normalY * (bodyAPositionY - vertexC.y);\n\n        // compare with previous vertex\n        vertexB = vertices[(vertexA.index + 1) % verticesLength];\n        if (normalX * (bodyAPositionX - vertexB.x) + normalY * (bodyAPositionY - vertexB.y) < nearestDistance) {\n            _supports[0] = vertexA;\n            _supports[1] = vertexB;\n\n            return _supports;\n        }\n\n        _supports[0] = vertexA;\n        _supports[1] = vertexC;\n\n        return _supports;\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A reference to the pair using this collision record, if there is one.\n     *\n     * @property pair\n     * @type {pair|null}\n     * @default null\n     */\n\n    /**\n     * A flag that indicates if the bodies were colliding when the collision was last updated.\n     * \n     * @property collided\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * The first body part represented by the collision (see also `collision.parentA`).\n     * \n     * @property bodyA\n     * @type body\n     */\n\n    /**\n     * The second body part represented by the collision (see also `collision.parentB`).\n     * \n     * @property bodyB\n     * @type body\n     */\n\n    /**\n     * The first body represented by the collision (i.e. `collision.bodyA.parent`).\n     * \n     * @property parentA\n     * @type body\n     */\n\n    /**\n     * The second body represented by the collision (i.e. `collision.bodyB.parent`).\n     * \n     * @property parentB\n     * @type body\n     */\n\n    /**\n     * A `Number` that represents the minimum separating distance between the bodies along the collision normal.\n     *\n     * @readOnly\n     * @property depth\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A normalised `Vector` that represents the direction between the bodies that provides the minimum separating distance.\n     *\n     * @property normal\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A normalised `Vector` that is the tangent direction to the collision normal.\n     *\n     * @property tangent\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that represents the direction and depth of the collision.\n     *\n     * @property penetration\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * An array of body vertices that represent the support points in the collision.\n     * \n     * _Note:_ Only the first `collision.supportCount` items of `collision.supports` are active.\n     * Therefore use `collision.supportCount` instead of `collision.supports.length` when iterating the active supports.\n     * \n     * These are the deepest vertices (along the collision normal) of each body that are contained by the other body's vertices.\n     *\n     * @property supports\n     * @type vector[]\n     * @default []\n     */\n\n    /**\n     * The number of active supports for this collision found in `collision.supports`.\n     * \n     * _Note:_ Only the first `collision.supportCount` items of `collision.supports` are active.\n     * Therefore use `collision.supportCount` instead of `collision.supports.length` when iterating the active supports.\n     *\n     * @property supportCount\n     * @type number\n     * @default 0\n     */\n\n})();\n"
  },
  {
    "path": "src/collision/Contact.js",
    "content": "/**\n* The `Matter.Contact` module contains methods for creating and manipulating collision contacts.\n*\n* @class Contact\n*/\n\nvar Contact = {};\n\nmodule.exports = Contact;\n\n(function() {\n\n    /**\n     * Creates a new contact.\n     * @method create\n     * @param {vertex} [vertex]\n     * @return {contact} A new contact\n     */\n    Contact.create = function(vertex) {\n        return {\n            vertex: vertex,\n            normalImpulse: 0,\n            tangentImpulse: 0\n        };\n    };\n\n})();\n"
  },
  {
    "path": "src/collision/Detector.js",
    "content": "/**\n* The `Matter.Detector` module contains methods for efficiently detecting collisions between a list of bodies using a broadphase algorithm.\n*\n* @class Detector\n*/\n\nvar Detector = {};\n\nmodule.exports = Detector;\n\nvar Common = require('../core/Common');\nvar Collision = require('./Collision');\n\n(function() {\n\n    /**\n     * Creates a new collision detector.\n     * @method create\n     * @param {} options\n     * @return {detector} A new collision detector\n     */\n    Detector.create = function(options) {\n        var defaults = {\n            bodies: [],\n            collisions: [],\n            pairs: null\n        };\n\n        return Common.extend(defaults, options);\n    };\n\n    /**\n     * Sets the list of bodies in the detector.\n     * @method setBodies\n     * @param {detector} detector\n     * @param {body[]} bodies\n     */\n    Detector.setBodies = function(detector, bodies) {\n        detector.bodies = bodies.slice(0);\n    };\n\n    /**\n     * Clears the detector including its list of bodies.\n     * @method clear\n     * @param {detector} detector\n     */\n    Detector.clear = function(detector) {\n        detector.bodies = [];\n        detector.collisions = [];\n    };\n\n    /**\n     * Efficiently finds all collisions among all the bodies in `detector.bodies` using a broadphase algorithm.\n     * \n     * _Note:_ The specific ordering of collisions returned is not guaranteed between releases and may change for performance reasons.\n     * If a specific ordering is required then apply a sort to the resulting array.\n     * @method collisions\n     * @param {detector} detector\n     * @return {collision[]} collisions\n     */\n    Detector.collisions = function(detector) {\n        var pairs = detector.pairs,\n            bodies = detector.bodies,\n            bodiesLength = bodies.length,\n            canCollide = Detector.canCollide,\n            collides = Collision.collides,\n            collisions = detector.collisions,\n            collisionIndex = 0,\n            i,\n            j;\n\n        bodies.sort(Detector._compareBoundsX);\n\n        for (i = 0; i < bodiesLength; i++) {\n            var bodyA = bodies[i],\n                boundsA = bodyA.bounds,\n                boundXMax = bodyA.bounds.max.x,\n                boundYMax = bodyA.bounds.max.y,\n                boundYMin = bodyA.bounds.min.y,\n                bodyAStatic = bodyA.isStatic || bodyA.isSleeping,\n                partsALength = bodyA.parts.length,\n                partsASingle = partsALength === 1;\n\n            for (j = i + 1; j < bodiesLength; j++) {\n                var bodyB = bodies[j],\n                    boundsB = bodyB.bounds;\n\n                if (boundsB.min.x > boundXMax) {\n                    break;\n                }\n\n                if (boundYMax < boundsB.min.y || boundYMin > boundsB.max.y) {\n                    continue;\n                }\n\n                if (bodyAStatic && (bodyB.isStatic || bodyB.isSleeping)) {\n                    continue;\n                }\n\n                if (!canCollide(bodyA.collisionFilter, bodyB.collisionFilter)) {\n                    continue;\n                }\n\n                var partsBLength = bodyB.parts.length;\n\n                if (partsASingle && partsBLength === 1) {\n                    var collision = collides(bodyA, bodyB, pairs);\n\n                    if (collision) {\n                        collisions[collisionIndex++] = collision;\n                    }\n                } else {\n                    var partsAStart = partsALength > 1 ? 1 : 0,\n                        partsBStart = partsBLength > 1 ? 1 : 0;\n                    \n                    for (var k = partsAStart; k < partsALength; k++) {\n                        var partA = bodyA.parts[k],\n                            boundsA = partA.bounds;\n\n                        for (var z = partsBStart; z < partsBLength; z++) {\n                            var partB = bodyB.parts[z],\n                                boundsB = partB.bounds;\n\n                            if (boundsA.min.x > boundsB.max.x || boundsA.max.x < boundsB.min.x\n                                || boundsA.max.y < boundsB.min.y || boundsA.min.y > boundsB.max.y) {\n                                continue;\n                            }\n\n                            var collision = collides(partA, partB, pairs);\n\n                            if (collision) {\n                                collisions[collisionIndex++] = collision;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if (collisions.length !== collisionIndex) {\n            collisions.length = collisionIndex;\n        }\n\n        return collisions;\n    };\n\n    /**\n     * Returns `true` if both supplied collision filters will allow a collision to occur.\n     * See `body.collisionFilter` for more information.\n     * @method canCollide\n     * @param {} filterA\n     * @param {} filterB\n     * @return {bool} `true` if collision can occur\n     */\n    Detector.canCollide = function(filterA, filterB) {\n        if (filterA.group === filterB.group && filterA.group !== 0)\n            return filterA.group > 0;\n\n        return (filterA.mask & filterB.category) !== 0 && (filterB.mask & filterA.category) !== 0;\n    };\n\n    /**\n     * The comparison function used in the broadphase algorithm.\n     * Returns the signed delta of the bodies bounds on the x-axis.\n     * @private\n     * @method _sortCompare\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {number} The signed delta used for sorting\n     */\n    Detector._compareBoundsX = function(bodyA, bodyB) {\n        return bodyA.bounds.min.x - bodyB.bounds.min.x;\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * The array of `Matter.Body` between which the detector finds collisions.\n     * \n     * _Note:_ The order of bodies in this array _is not fixed_ and will be continually managed by the detector.\n     * @property bodies\n     * @type body[]\n     * @default []\n     */\n\n    /**\n     * The array of `Matter.Collision` found in the last call to `Detector.collisions` on this detector.\n     * @property collisions\n     * @type collision[]\n     * @default []\n     */\n\n    /**\n     * Optional. A `Matter.Pairs` object from which previous collision objects may be reused. Intended for internal `Matter.Engine` usage.\n     * @property pairs\n     * @type {pairs|null}\n     * @default null\n     */\n\n})();\n"
  },
  {
    "path": "src/collision/Grid.js",
    "content": "/**\n* This module has now been replaced by `Matter.Detector`.\n*\n* All usage should be migrated to `Matter.Detector` or another alternative.\n* For back-compatibility purposes this module will remain for a short term and then later removed in a future release.\n*\n* The `Matter.Grid` module contains methods for creating and manipulating collision broadphase grid structures.\n*\n* @class Grid\n* @deprecated\n*/\n\nvar Grid = {};\n\nmodule.exports = Grid;\n\nvar Pair = require('./Pair');\nvar Common = require('../core/Common');\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Creates a new grid.\n     * @deprecated replaced by Matter.Detector\n     * @method create\n     * @param {} options\n     * @return {grid} A new grid\n     */\n    Grid.create = function(options) {\n        var defaults = {\n            buckets: {},\n            pairs: {},\n            pairsList: [],\n            bucketWidth: 48,\n            bucketHeight: 48\n        };\n\n        return Common.extend(defaults, options);\n    };\n\n    /**\n     * The width of a single grid bucket.\n     *\n     * @property bucketWidth\n     * @type number\n     * @default 48\n     */\n\n    /**\n     * The height of a single grid bucket.\n     *\n     * @property bucketHeight\n     * @type number\n     * @default 48\n     */\n\n    /**\n     * Updates the grid.\n     * @deprecated replaced by Matter.Detector\n     * @method update\n     * @param {grid} grid\n     * @param {body[]} bodies\n     * @param {engine} engine\n     * @param {boolean} forceUpdate\n     */\n    Grid.update = function(grid, bodies, engine, forceUpdate) {\n        var i, col, row,\n            world = engine.world,\n            buckets = grid.buckets,\n            bucket,\n            bucketId,\n            gridChanged = false;\n\n        for (i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (body.isSleeping && !forceUpdate)\n                continue;\n\n            // temporary back compatibility bounds check\n            if (world.bounds && (body.bounds.max.x < world.bounds.min.x || body.bounds.min.x > world.bounds.max.x\n                || body.bounds.max.y < world.bounds.min.y || body.bounds.min.y > world.bounds.max.y))\n                continue;\n\n            var newRegion = Grid._getRegion(grid, body);\n\n            // if the body has changed grid region\n            if (!body.region || newRegion.id !== body.region.id || forceUpdate) {\n\n                if (!body.region || forceUpdate)\n                    body.region = newRegion;\n\n                var union = Grid._regionUnion(newRegion, body.region);\n\n                // update grid buckets affected by region change\n                // iterate over the union of both regions\n                for (col = union.startCol; col <= union.endCol; col++) {\n                    for (row = union.startRow; row <= union.endRow; row++) {\n                        bucketId = Grid._getBucketId(col, row);\n                        bucket = buckets[bucketId];\n\n                        var isInsideNewRegion = (col >= newRegion.startCol && col <= newRegion.endCol\n                                                && row >= newRegion.startRow && row <= newRegion.endRow);\n\n                        var isInsideOldRegion = (col >= body.region.startCol && col <= body.region.endCol\n                                                && row >= body.region.startRow && row <= body.region.endRow);\n\n                        // remove from old region buckets\n                        if (!isInsideNewRegion && isInsideOldRegion) {\n                            if (isInsideOldRegion) {\n                                if (bucket)\n                                    Grid._bucketRemoveBody(grid, bucket, body);\n                            }\n                        }\n\n                        // add to new region buckets\n                        if (body.region === newRegion || (isInsideNewRegion && !isInsideOldRegion) || forceUpdate) {\n                            if (!bucket)\n                                bucket = Grid._createBucket(buckets, bucketId);\n                            Grid._bucketAddBody(grid, bucket, body);\n                        }\n                    }\n                }\n\n                // set the new region\n                body.region = newRegion;\n\n                // flag changes so we can update pairs\n                gridChanged = true;\n            }\n        }\n\n        // update pairs list only if pairs changed (i.e. a body changed region)\n        if (gridChanged)\n            grid.pairsList = Grid._createActivePairsList(grid);\n    };\n\n    deprecated(Grid, 'update', 'Grid.update ➤ replaced by Matter.Detector');\n\n    /**\n     * Clears the grid.\n     * @deprecated replaced by Matter.Detector\n     * @method clear\n     * @param {grid} grid\n     */\n    Grid.clear = function(grid) {\n        grid.buckets = {};\n        grid.pairs = {};\n        grid.pairsList = [];\n    };\n\n    deprecated(Grid, 'clear', 'Grid.clear ➤ replaced by Matter.Detector');\n\n    /**\n     * Finds the union of two regions.\n     * @method _regionUnion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} regionA\n     * @param {} regionB\n     * @return {} region\n     */\n    Grid._regionUnion = function(regionA, regionB) {\n        var startCol = Math.min(regionA.startCol, regionB.startCol),\n            endCol = Math.max(regionA.endCol, regionB.endCol),\n            startRow = Math.min(regionA.startRow, regionB.startRow),\n            endRow = Math.max(regionA.endRow, regionB.endRow);\n\n        return Grid._createRegion(startCol, endCol, startRow, endRow);\n    };\n\n    /**\n     * Gets the region a given body falls in for a given grid.\n     * @method _getRegion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} body\n     * @return {} region\n     */\n    Grid._getRegion = function(grid, body) {\n        var bounds = body.bounds,\n            startCol = Math.floor(bounds.min.x / grid.bucketWidth),\n            endCol = Math.floor(bounds.max.x / grid.bucketWidth),\n            startRow = Math.floor(bounds.min.y / grid.bucketHeight),\n            endRow = Math.floor(bounds.max.y / grid.bucketHeight);\n\n        return Grid._createRegion(startCol, endCol, startRow, endRow);\n    };\n\n    /**\n     * Creates a region.\n     * @method _createRegion\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} startCol\n     * @param {} endCol\n     * @param {} startRow\n     * @param {} endRow\n     * @return {} region\n     */\n    Grid._createRegion = function(startCol, endCol, startRow, endRow) {\n        return { \n            id: startCol + ',' + endCol + ',' + startRow + ',' + endRow,\n            startCol: startCol, \n            endCol: endCol, \n            startRow: startRow, \n            endRow: endRow \n        };\n    };\n\n    /**\n     * Gets the bucket id at the given position.\n     * @method _getBucketId\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} column\n     * @param {} row\n     * @return {string} bucket id\n     */\n    Grid._getBucketId = function(column, row) {\n        return 'C' + column + 'R' + row;\n    };\n\n    /**\n     * Creates a bucket.\n     * @method _createBucket\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} buckets\n     * @param {} bucketId\n     * @return {} bucket\n     */\n    Grid._createBucket = function(buckets, bucketId) {\n        var bucket = buckets[bucketId] = [];\n        return bucket;\n    };\n\n    /**\n     * Adds a body to a bucket.\n     * @method _bucketAddBody\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} bucket\n     * @param {} body\n     */\n    Grid._bucketAddBody = function(grid, bucket, body) {\n        var gridPairs = grid.pairs,\n            pairId = Pair.id,\n            bucketLength = bucket.length,\n            i;\n\n        // add new pairs\n        for (i = 0; i < bucketLength; i++) {\n            var bodyB = bucket[i];\n\n            if (body.id === bodyB.id || (body.isStatic && bodyB.isStatic))\n                continue;\n\n            // keep track of the number of buckets the pair exists in\n            // important for Grid.update to work\n            var id = pairId(body, bodyB),\n                pair = gridPairs[id];\n\n            if (pair) {\n                pair[2] += 1;\n            } else {\n                gridPairs[id] = [body, bodyB, 1];\n            }\n        }\n\n        // add to bodies (after pairs, otherwise pairs with self)\n        bucket.push(body);\n    };\n\n    /**\n     * Removes a body from a bucket.\n     * @method _bucketRemoveBody\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @param {} bucket\n     * @param {} body\n     */\n    Grid._bucketRemoveBody = function(grid, bucket, body) {\n        var gridPairs = grid.pairs,\n            pairId = Pair.id,\n            i;\n\n        // remove from bucket\n        bucket.splice(Common.indexOf(bucket, body), 1);\n\n        var bucketLength = bucket.length;\n\n        // update pair counts\n        for (i = 0; i < bucketLength; i++) {\n            // keep track of the number of buckets the pair exists in\n            // important for _createActivePairsList to work\n            var pair = gridPairs[pairId(body, bucket[i])];\n\n            if (pair)\n                pair[2] -= 1;\n        }\n    };\n\n    /**\n     * Generates a list of the active pairs in the grid.\n     * @method _createActivePairsList\n     * @deprecated replaced by Matter.Detector\n     * @private\n     * @param {} grid\n     * @return [] pairs\n     */\n    Grid._createActivePairsList = function(grid) {\n        var pair,\n            gridPairs = grid.pairs,\n            pairKeys = Common.keys(gridPairs),\n            pairKeysLength = pairKeys.length,\n            pairs = [],\n            k;\n\n        // iterate over grid.pairs\n        for (k = 0; k < pairKeysLength; k++) {\n            pair = gridPairs[pairKeys[k]];\n\n            // if pair exists in at least one bucket\n            // it is a pair that needs further collision testing so push it\n            if (pair[2] > 0) {\n                pairs.push(pair);\n            } else {\n                delete gridPairs[pairKeys[k]];\n            }\n        }\n\n        return pairs;\n    };\n    \n})();\n"
  },
  {
    "path": "src/collision/Pair.js",
    "content": "/**\n* The `Matter.Pair` module contains methods for creating and manipulating collision pairs.\n*\n* @class Pair\n*/\n\nvar Pair = {};\n\nmodule.exports = Pair;\n\nvar Contact = require('./Contact');\n\n(function() {\n    \n    /**\n     * Creates a pair.\n     * @method create\n     * @param {collision} collision\n     * @param {number} timestamp\n     * @return {pair} A new pair\n     */\n    Pair.create = function(collision, timestamp) {\n        var bodyA = collision.bodyA,\n            bodyB = collision.bodyB;\n\n        var pair = {\n            id: Pair.id(bodyA, bodyB),\n            bodyA: bodyA,\n            bodyB: bodyB,\n            collision: collision,\n            contacts: [Contact.create(), Contact.create()],\n            contactCount: 0,\n            separation: 0,\n            isActive: true,\n            isSensor: bodyA.isSensor || bodyB.isSensor,\n            timeCreated: timestamp,\n            timeUpdated: timestamp,\n            inverseMass: 0,\n            friction: 0,\n            frictionStatic: 0,\n            restitution: 0,\n            slop: 0\n        };\n\n        Pair.update(pair, collision, timestamp);\n\n        return pair;\n    };\n\n    /**\n     * Updates a pair given a collision.\n     * @method update\n     * @param {pair} pair\n     * @param {collision} collision\n     * @param {number} timestamp\n     */\n    Pair.update = function(pair, collision, timestamp) {\n        var supports = collision.supports,\n            supportCount = collision.supportCount,\n            contacts = pair.contacts,\n            parentA = collision.parentA,\n            parentB = collision.parentB;\n        \n        pair.isActive = true;\n        pair.timeUpdated = timestamp;\n        pair.collision = collision;\n        pair.separation = collision.depth;\n        pair.inverseMass = parentA.inverseMass + parentB.inverseMass;\n        pair.friction = parentA.friction < parentB.friction ? parentA.friction : parentB.friction;\n        pair.frictionStatic = parentA.frictionStatic > parentB.frictionStatic ? parentA.frictionStatic : parentB.frictionStatic;\n        pair.restitution = parentA.restitution > parentB.restitution ? parentA.restitution : parentB.restitution;\n        pair.slop = parentA.slop > parentB.slop ? parentA.slop : parentB.slop;\n\n        pair.contactCount = supportCount;\n        collision.pair = pair;\n\n        var supportA = supports[0],\n            contactA = contacts[0],\n            supportB = supports[1],\n            contactB = contacts[1];\n\n        // match contacts to supports\n        if (contactB.vertex === supportA || contactA.vertex === supportB) {\n            contacts[1] = contactA;\n            contacts[0] = contactA = contactB;\n            contactB = contacts[1];\n        }\n\n        // update contacts\n        contactA.vertex = supportA;\n        contactB.vertex = supportB;\n    };\n    \n    /**\n     * Set a pair as active or inactive.\n     * @method setActive\n     * @param {pair} pair\n     * @param {bool} isActive\n     * @param {number} timestamp\n     */\n    Pair.setActive = function(pair, isActive, timestamp) {\n        if (isActive) {\n            pair.isActive = true;\n            pair.timeUpdated = timestamp;\n        } else {\n            pair.isActive = false;\n            pair.contactCount = 0;\n        }\n    };\n\n    /**\n     * Get the id for the given pair.\n     * @method id\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {string} Unique pairId\n     */\n    Pair.id = function(bodyA, bodyB) {\n        return bodyA.id < bodyB.id ? bodyA.id.toString(36) + ':' + bodyB.id.toString(36) \n            : bodyB.id.toString(36) + ':' + bodyA.id.toString(36);\n    };\n\n})();\n"
  },
  {
    "path": "src/collision/Pairs.js",
    "content": "/**\n* The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets.\n*\n* @class Pairs\n*/\n\nvar Pairs = {};\n\nmodule.exports = Pairs;\n\nvar Pair = require('./Pair');\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * Creates a new pairs structure.\n     * @method create\n     * @param {object} options\n     * @return {pairs} A new pairs structure\n     */\n    Pairs.create = function(options) {\n        return Common.extend({ \n            table: {},\n            list: [],\n            collisionStart: [],\n            collisionActive: [],\n            collisionEnd: []\n        }, options);\n    };\n\n    /**\n     * Updates pairs given a list of collisions.\n     * @method update\n     * @param {object} pairs\n     * @param {collision[]} collisions\n     * @param {number} timestamp\n     */\n    Pairs.update = function(pairs, collisions, timestamp) {\n        var pairUpdate = Pair.update,\n            pairCreate = Pair.create,\n            pairSetActive = Pair.setActive,\n            pairsTable = pairs.table,\n            pairsList = pairs.list,\n            pairsListLength = pairsList.length,\n            pairsListIndex = pairsListLength,\n            collisionStart = pairs.collisionStart,\n            collisionEnd = pairs.collisionEnd,\n            collisionActive = pairs.collisionActive,\n            collisionsLength = collisions.length,\n            collisionStartIndex = 0,\n            collisionEndIndex = 0,\n            collisionActiveIndex = 0,\n            collision,\n            pair,\n            i;\n\n        for (i = 0; i < collisionsLength; i++) {\n            collision = collisions[i];\n            pair = collision.pair;\n\n            if (pair) {\n                // pair already exists (but may or may not be active)\n                if (pair.isActive) {\n                    // pair exists and is active\n                    collisionActive[collisionActiveIndex++] = pair;\n                }\n\n                // update the pair\n                pairUpdate(pair, collision, timestamp);\n            } else {\n                // pair did not exist, create a new pair\n                pair = pairCreate(collision, timestamp);\n                pairsTable[pair.id] = pair;\n\n                // add the new pair\n                collisionStart[collisionStartIndex++] = pair;\n                pairsList[pairsListIndex++] = pair;\n            }\n        }\n\n        // find pairs that are no longer active\n        pairsListIndex = 0;\n        pairsListLength = pairsList.length;\n\n        for (i = 0; i < pairsListLength; i++) {\n            pair = pairsList[i];\n            \n            // pair is active if updated this timestep\n            if (pair.timeUpdated >= timestamp) {\n                // keep active pairs\n                pairsList[pairsListIndex++] = pair;\n            } else {\n                pairSetActive(pair, false, timestamp);\n\n                // keep inactive pairs if both bodies may be sleeping\n                if (pair.collision.bodyA.sleepCounter > 0 && pair.collision.bodyB.sleepCounter > 0) {\n                    pairsList[pairsListIndex++] = pair;\n                } else {\n                    // remove inactive pairs if either body awake\n                    collisionEnd[collisionEndIndex++] = pair;\n                    delete pairsTable[pair.id];\n                }\n            }\n        }\n\n        // update array lengths if changed\n        if (pairsList.length !== pairsListIndex) {\n            pairsList.length = pairsListIndex;\n        }\n\n        if (collisionStart.length !== collisionStartIndex) {\n            collisionStart.length = collisionStartIndex;\n        }\n\n        if (collisionEnd.length !== collisionEndIndex) {\n            collisionEnd.length = collisionEndIndex;\n        }\n\n        if (collisionActive.length !== collisionActiveIndex) {\n            collisionActive.length = collisionActiveIndex;\n        }\n    };\n\n    /**\n     * Clears the given pairs structure.\n     * @method clear\n     * @param {pairs} pairs\n     * @return {pairs} pairs\n     */\n    Pairs.clear = function(pairs) {\n        pairs.table = {};\n        pairs.list.length = 0;\n        pairs.collisionStart.length = 0;\n        pairs.collisionActive.length = 0;\n        pairs.collisionEnd.length = 0;\n        return pairs;\n    };\n\n})();\n"
  },
  {
    "path": "src/collision/Query.js",
    "content": "/**\n* The `Matter.Query` module contains methods for performing collision queries.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Query\n*/\n\nvar Query = {};\n\nmodule.exports = Query;\n\nvar Vector = require('../geometry/Vector');\nvar Collision = require('./Collision');\nvar Bounds = require('../geometry/Bounds');\nvar Bodies = require('../factory/Bodies');\nvar Vertices = require('../geometry/Vertices');\n\n(function() {\n\n    /**\n     * Returns a list of collisions between `body` and `bodies`.\n     * @method collides\n     * @param {body} body\n     * @param {body[]} bodies\n     * @return {collision[]} Collisions\n     */\n    Query.collides = function(body, bodies) {\n        var collisions = [],\n            bodiesLength = bodies.length,\n            bounds = body.bounds,\n            collides = Collision.collides,\n            overlaps = Bounds.overlaps;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var bodyA = bodies[i],\n                partsALength = bodyA.parts.length,\n                partsAStart = partsALength === 1 ? 0 : 1;\n            \n            if (overlaps(bodyA.bounds, bounds)) {\n                for (var j = partsAStart; j < partsALength; j++) {\n                    var part = bodyA.parts[j];\n\n                    if (overlaps(part.bounds, bounds)) {\n                        var collision = collides(part, body);\n\n                        if (collision) {\n                            collisions.push(collision);\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        return collisions;\n    };\n\n    /**\n     * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided.\n     * @method ray\n     * @param {body[]} bodies\n     * @param {vector} startPoint\n     * @param {vector} endPoint\n     * @param {number} [rayWidth]\n     * @return {collision[]} Collisions\n     */\n    Query.ray = function(bodies, startPoint, endPoint, rayWidth) {\n        rayWidth = rayWidth || 1e-100;\n\n        var rayAngle = Vector.angle(startPoint, endPoint),\n            rayLength = Vector.magnitude(Vector.sub(startPoint, endPoint)),\n            rayX = (endPoint.x + startPoint.x) * 0.5,\n            rayY = (endPoint.y + startPoint.y) * 0.5,\n            ray = Bodies.rectangle(rayX, rayY, rayLength, rayWidth, { angle: rayAngle }),\n            collisions = Query.collides(ray, bodies);\n\n        for (var i = 0; i < collisions.length; i += 1) {\n            var collision = collisions[i];\n            collision.body = collision.bodyB = collision.bodyA;            \n        }\n\n        return collisions;\n    };\n\n    /**\n     * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies.\n     * @method region\n     * @param {body[]} bodies\n     * @param {bounds} bounds\n     * @param {bool} [outside=false]\n     * @return {body[]} The bodies matching the query\n     */\n    Query.region = function(bodies, bounds, outside) {\n        var result = [];\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                overlaps = Bounds.overlaps(body.bounds, bounds);\n            if ((overlaps && !outside) || (!overlaps && outside))\n                result.push(body);\n        }\n\n        return result;\n    };\n\n    /**\n     * Returns all bodies whose vertices contain the given point, from the given set of bodies.\n     * @method point\n     * @param {body[]} bodies\n     * @param {vector} point\n     * @return {body[]} The bodies matching the query\n     */\n    Query.point = function(bodies, point) {\n        var result = [];\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n            \n            if (Bounds.contains(body.bounds, point)) {\n                for (var j = body.parts.length === 1 ? 0 : 1; j < body.parts.length; j++) {\n                    var part = body.parts[j];\n\n                    if (Bounds.contains(part.bounds, point)\n                        && Vertices.contains(part.vertices, point)) {\n                        result.push(body);\n                        break;\n                    }\n                }\n            }\n        }\n\n        return result;\n    };\n\n})();\n"
  },
  {
    "path": "src/collision/Resolver.js",
    "content": "/**\n* The `Matter.Resolver` module contains methods for resolving collision pairs.\n*\n* @class Resolver\n*/\n\nvar Resolver = {};\n\nmodule.exports = Resolver;\n\nvar Vertices = require('../geometry/Vertices');\nvar Common = require('../core/Common');\nvar Bounds = require('../geometry/Bounds');\n\n(function() {\n\n    Resolver._restingThresh = 2;\n    Resolver._restingThreshTangent = Math.sqrt(6);\n    Resolver._positionDampen = 0.9;\n    Resolver._positionWarming = 0.8;\n    Resolver._frictionNormalMultiplier = 5;\n    Resolver._frictionMaxStatic = Number.MAX_VALUE;\n\n    /**\n     * Prepare pairs for position solving.\n     * @method preSolvePosition\n     * @param {pair[]} pairs\n     */\n    Resolver.preSolvePosition = function(pairs) {\n        var i,\n            pair,\n            contactCount,\n            pairsLength = pairs.length;\n\n        // find total contacts on each body\n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n            \n            if (!pair.isActive)\n                continue;\n            \n            contactCount = pair.contactCount;\n            pair.collision.parentA.totalContacts += contactCount;\n            pair.collision.parentB.totalContacts += contactCount;\n        }\n    };\n\n    /**\n     * Find a solution for pair positions.\n     * @method solvePosition\n     * @param {pair[]} pairs\n     * @param {number} delta\n     * @param {number} [damping=1]\n     */\n    Resolver.solvePosition = function(pairs, delta, damping) {\n        var i,\n            pair,\n            collision,\n            bodyA,\n            bodyB,\n            normal,\n            contactShare,\n            positionImpulse,\n            positionDampen = Resolver._positionDampen * (damping || 1),\n            slopDampen = Common.clamp(delta / Common._baseDelta, 0, 1),\n            pairsLength = pairs.length;\n\n        // find impulses required to resolve penetration\n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n\n            collision = pair.collision;\n            bodyA = collision.parentA;\n            bodyB = collision.parentB;\n            normal = collision.normal;\n\n            // get current separation between body edges involved in collision\n            pair.separation = \n                collision.depth + normal.x * (bodyB.positionImpulse.x - bodyA.positionImpulse.x)\n                + normal.y * (bodyB.positionImpulse.y - bodyA.positionImpulse.y);\n        }\n        \n        for (i = 0; i < pairsLength; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            collision = pair.collision;\n            bodyA = collision.parentA;\n            bodyB = collision.parentB;\n            normal = collision.normal;\n            positionImpulse = pair.separation - pair.slop * slopDampen;\n\n            if (bodyA.isStatic || bodyB.isStatic)\n                positionImpulse *= 2;\n            \n            if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                contactShare = positionDampen / bodyA.totalContacts;\n                bodyA.positionImpulse.x += normal.x * positionImpulse * contactShare;\n                bodyA.positionImpulse.y += normal.y * positionImpulse * contactShare;\n            }\n\n            if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                contactShare = positionDampen / bodyB.totalContacts;\n                bodyB.positionImpulse.x -= normal.x * positionImpulse * contactShare;\n                bodyB.positionImpulse.y -= normal.y * positionImpulse * contactShare;\n            }\n        }\n    };\n\n    /**\n     * Apply position resolution.\n     * @method postSolvePosition\n     * @param {body[]} bodies\n     */\n    Resolver.postSolvePosition = function(bodies) {\n        var positionWarming = Resolver._positionWarming,\n            bodiesLength = bodies.length,\n            verticesTranslate = Vertices.translate,\n            boundsUpdate = Bounds.update;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i],\n                positionImpulse = body.positionImpulse,\n                positionImpulseX = positionImpulse.x,\n                positionImpulseY = positionImpulse.y,\n                velocity = body.velocity;\n\n            // reset contact count\n            body.totalContacts = 0;\n\n            if (positionImpulseX !== 0 || positionImpulseY !== 0) {\n                // update body geometry\n                for (var j = 0; j < body.parts.length; j++) {\n                    var part = body.parts[j];\n                    verticesTranslate(part.vertices, positionImpulse);\n                    boundsUpdate(part.bounds, part.vertices, velocity);\n                    part.position.x += positionImpulseX;\n                    part.position.y += positionImpulseY;\n                }\n\n                // move the body without changing velocity\n                body.positionPrev.x += positionImpulseX;\n                body.positionPrev.y += positionImpulseY;\n\n                if (positionImpulseX * velocity.x + positionImpulseY * velocity.y < 0) {\n                    // reset cached impulse if the body has velocity along it\n                    positionImpulse.x = 0;\n                    positionImpulse.y = 0;\n                } else {\n                    // warm the next iteration\n                    positionImpulse.x *= positionWarming;\n                    positionImpulse.y *= positionWarming;\n                }\n            }\n        }\n    };\n\n    /**\n     * Prepare pairs for velocity solving.\n     * @method preSolveVelocity\n     * @param {pair[]} pairs\n     */\n    Resolver.preSolveVelocity = function(pairs) {\n        var pairsLength = pairs.length,\n            i,\n            j;\n        \n        for (i = 0; i < pairsLength; i++) {\n            var pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            var contacts = pair.contacts,\n                contactCount = pair.contactCount,\n                collision = pair.collision,\n                bodyA = collision.parentA,\n                bodyB = collision.parentB,\n                normal = collision.normal,\n                tangent = collision.tangent;\n    \n            // resolve each contact\n            for (j = 0; j < contactCount; j++) {\n                var contact = contacts[j],\n                    contactVertex = contact.vertex,\n                    normalImpulse = contact.normalImpulse,\n                    tangentImpulse = contact.tangentImpulse;\n    \n                if (normalImpulse !== 0 || tangentImpulse !== 0) {\n                    // total impulse from contact\n                    var impulseX = normal.x * normalImpulse + tangent.x * tangentImpulse,\n                        impulseY = normal.y * normalImpulse + tangent.y * tangentImpulse;\n                    \n                    // apply impulse from contact\n                    if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                        bodyA.positionPrev.x += impulseX * bodyA.inverseMass;\n                        bodyA.positionPrev.y += impulseY * bodyA.inverseMass;\n                        bodyA.anglePrev += bodyA.inverseInertia * (\n                            (contactVertex.x - bodyA.position.x) * impulseY\n                            - (contactVertex.y - bodyA.position.y) * impulseX\n                        );\n                    }\n    \n                    if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                        bodyB.positionPrev.x -= impulseX * bodyB.inverseMass;\n                        bodyB.positionPrev.y -= impulseY * bodyB.inverseMass;\n                        bodyB.anglePrev -= bodyB.inverseInertia * (\n                            (contactVertex.x - bodyB.position.x) * impulseY \n                            - (contactVertex.y - bodyB.position.y) * impulseX\n                        );\n                    }\n                }\n            }\n        }\n    };\n\n    /**\n     * Find a solution for pair velocities.\n     * @method solveVelocity\n     * @param {pair[]} pairs\n     * @param {number} delta\n     */\n    Resolver.solveVelocity = function(pairs, delta) {\n        var timeScale = delta / Common._baseDelta,\n            timeScaleSquared = timeScale * timeScale,\n            timeScaleCubed = timeScaleSquared * timeScale,\n            restingThresh = -Resolver._restingThresh * timeScale,\n            restingThreshTangent = Resolver._restingThreshTangent,\n            frictionNormalMultiplier = Resolver._frictionNormalMultiplier * timeScale,\n            frictionMaxStatic = Resolver._frictionMaxStatic,\n            pairsLength = pairs.length,\n            tangentImpulse,\n            maxFriction,\n            i,\n            j;\n\n        for (i = 0; i < pairsLength; i++) {\n            var pair = pairs[i];\n            \n            if (!pair.isActive || pair.isSensor)\n                continue;\n            \n            var collision = pair.collision,\n                bodyA = collision.parentA,\n                bodyB = collision.parentB,\n                normalX = collision.normal.x,\n                normalY = collision.normal.y,\n                tangentX = collision.tangent.x,\n                tangentY = collision.tangent.y,\n                inverseMassTotal = pair.inverseMass,\n                friction = pair.friction * pair.frictionStatic * frictionNormalMultiplier,\n                contacts = pair.contacts,\n                contactCount = pair.contactCount,\n                contactShare = 1 / contactCount;\n\n            // get body velocities\n            var bodyAVelocityX = bodyA.position.x - bodyA.positionPrev.x,\n                bodyAVelocityY = bodyA.position.y - bodyA.positionPrev.y,\n                bodyAAngularVelocity = bodyA.angle - bodyA.anglePrev,\n                bodyBVelocityX = bodyB.position.x - bodyB.positionPrev.x,\n                bodyBVelocityY = bodyB.position.y - bodyB.positionPrev.y,\n                bodyBAngularVelocity = bodyB.angle - bodyB.anglePrev;\n\n            // resolve each contact\n            for (j = 0; j < contactCount; j++) {\n                var contact = contacts[j],\n                    contactVertex = contact.vertex;\n\n                var offsetAX = contactVertex.x - bodyA.position.x,\n                    offsetAY = contactVertex.y - bodyA.position.y,\n                    offsetBX = contactVertex.x - bodyB.position.x,\n                    offsetBY = contactVertex.y - bodyB.position.y;\n \n                var velocityPointAX = bodyAVelocityX - offsetAY * bodyAAngularVelocity,\n                    velocityPointAY = bodyAVelocityY + offsetAX * bodyAAngularVelocity,\n                    velocityPointBX = bodyBVelocityX - offsetBY * bodyBAngularVelocity,\n                    velocityPointBY = bodyBVelocityY + offsetBX * bodyBAngularVelocity;\n\n                var relativeVelocityX = velocityPointAX - velocityPointBX,\n                    relativeVelocityY = velocityPointAY - velocityPointBY;\n\n                var normalVelocity = normalX * relativeVelocityX + normalY * relativeVelocityY,\n                    tangentVelocity = tangentX * relativeVelocityX + tangentY * relativeVelocityY;\n\n                // coulomb friction\n                var normalOverlap = pair.separation + normalVelocity;\n                var normalForce = Math.min(normalOverlap, 1);\n                normalForce = normalOverlap < 0 ? 0 : normalForce;\n\n                var frictionLimit = normalForce * friction;\n\n                if (tangentVelocity < -frictionLimit || tangentVelocity > frictionLimit) {\n                    maxFriction = (tangentVelocity > 0 ? tangentVelocity : -tangentVelocity);\n                    tangentImpulse = pair.friction * (tangentVelocity > 0 ? 1 : -1) * timeScaleCubed;\n                    \n                    if (tangentImpulse < -maxFriction) {\n                        tangentImpulse = -maxFriction;\n                    } else if (tangentImpulse > maxFriction) {\n                        tangentImpulse = maxFriction;\n                    }\n                } else {\n                    tangentImpulse = tangentVelocity;\n                    maxFriction = frictionMaxStatic;\n                }\n\n                // account for mass, inertia and contact offset\n                var oAcN = offsetAX * normalY - offsetAY * normalX,\n                    oBcN = offsetBX * normalY - offsetBY * normalX,\n                    share = contactShare / (inverseMassTotal + bodyA.inverseInertia * oAcN * oAcN + bodyB.inverseInertia * oBcN * oBcN);\n\n                // raw impulses\n                var normalImpulse = (1 + pair.restitution) * normalVelocity * share;\n                tangentImpulse *= share;\n\n                // handle high velocity and resting collisions separately\n                if (normalVelocity < restingThresh) {\n                    // high normal velocity so clear cached contact normal impulse\n                    contact.normalImpulse = 0;\n                } else {\n                    // solve resting collision constraints using Erin Catto's method (GDC08)\n                    // impulse constraint tends to 0\n                    var contactNormalImpulse = contact.normalImpulse;\n                    contact.normalImpulse += normalImpulse;\n                    if (contact.normalImpulse > 0) contact.normalImpulse = 0;\n                    normalImpulse = contact.normalImpulse - contactNormalImpulse;\n                }\n\n                // handle high velocity and resting collisions separately\n                if (tangentVelocity < -restingThreshTangent || tangentVelocity > restingThreshTangent) {\n                    // high tangent velocity so clear cached contact tangent impulse\n                    contact.tangentImpulse = 0;\n                } else {\n                    // solve resting collision constraints using Erin Catto's method (GDC08)\n                    // tangent impulse tends to -tangentSpeed or +tangentSpeed\n                    var contactTangentImpulse = contact.tangentImpulse;\n                    contact.tangentImpulse += tangentImpulse;\n                    if (contact.tangentImpulse < -maxFriction) contact.tangentImpulse = -maxFriction;\n                    if (contact.tangentImpulse > maxFriction) contact.tangentImpulse = maxFriction;\n                    tangentImpulse = contact.tangentImpulse - contactTangentImpulse;\n                }\n\n                // total impulse from contact\n                var impulseX = normalX * normalImpulse + tangentX * tangentImpulse,\n                    impulseY = normalY * normalImpulse + tangentY * tangentImpulse;\n                \n                // apply impulse from contact\n                if (!(bodyA.isStatic || bodyA.isSleeping)) {\n                    bodyA.positionPrev.x += impulseX * bodyA.inverseMass;\n                    bodyA.positionPrev.y += impulseY * bodyA.inverseMass;\n                    bodyA.anglePrev += (offsetAX * impulseY - offsetAY * impulseX) * bodyA.inverseInertia;\n                }\n\n                if (!(bodyB.isStatic || bodyB.isSleeping)) {\n                    bodyB.positionPrev.x -= impulseX * bodyB.inverseMass;\n                    bodyB.positionPrev.y -= impulseY * bodyB.inverseMass;\n                    bodyB.anglePrev -= (offsetBX * impulseY - offsetBY * impulseX) * bodyB.inverseInertia;\n                }\n            }\n        }\n    };\n\n})();\n"
  },
  {
    "path": "src/collision/SAT.js",
    "content": "/**\n* This module has now been replaced by `Matter.Collision`.\n*\n* All usage should be migrated to `Matter.Collision`.\n* For back-compatibility purposes this module will remain for a short term and then later removed in a future release.\n*\n* The `Matter.SAT` module contains methods for detecting collisions using the Separating Axis Theorem.\n*\n* @class SAT\n* @deprecated\n*/\n\nvar SAT = {};\n\nmodule.exports = SAT;\n\nvar Collision = require('./Collision');\nvar Common = require('../core/Common');\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Detect collision between two bodies using the Separating Axis Theorem.\n     * @deprecated replaced by Collision.collides\n     * @method collides\n     * @param {body} bodyA\n     * @param {body} bodyB\n     * @return {collision} collision\n     */\n    SAT.collides = function(bodyA, bodyB) {\n        return Collision.collides(bodyA, bodyB);\n    };\n\n    deprecated(SAT, 'collides', 'SAT.collides ➤ replaced by Collision.collides');\n\n})();\n"
  },
  {
    "path": "src/constraint/Constraint.js",
    "content": "/**\n* The `Matter.Constraint` module contains methods for creating and manipulating constraints.\n* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).\n* The stiffness of constraints can be modified to create springs or elastic.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Constraint\n*/\n\nvar Constraint = {};\n\nmodule.exports = Constraint;\n\nvar Vertices = require('../geometry/Vertices');\nvar Vector = require('../geometry/Vector');\nvar Sleeping = require('../core/Sleeping');\nvar Bounds = require('../geometry/Bounds');\nvar Axes = require('../geometry/Axes');\nvar Common = require('../core/Common');\n\n(function() {\n\n    Constraint._warming = 0.4;\n    Constraint._torqueDampen = 1;\n    Constraint._minLength = 0.000001;\n\n    /**\n     * Creates a new constraint.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * To simulate a revolute constraint (or pin joint) set `length: 0` and a high `stiffness` value (e.g. `0.7` or above).\n     * If the constraint is unstable, try lowering the `stiffness` value and / or increasing `engine.constraintIterations`.\n     * For compound bodies, constraints must be applied to the parent body (not one of its parts).\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     * @return {constraint} constraint\n     */\n    Constraint.create = function(options) {\n        var constraint = options;\n\n        // if bodies defined but no points, use body centre\n        if (constraint.bodyA && !constraint.pointA)\n            constraint.pointA = { x: 0, y: 0 };\n        if (constraint.bodyB && !constraint.pointB)\n            constraint.pointB = { x: 0, y: 0 };\n\n        // calculate static length using initial world space points\n        var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA,\n            initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB,\n            length = Vector.magnitude(Vector.sub(initialPointA, initialPointB));\n    \n        constraint.length = typeof constraint.length !== 'undefined' ? constraint.length : length;\n\n        // option defaults\n        constraint.id = constraint.id || Common.nextId();\n        constraint.label = constraint.label || 'Constraint';\n        constraint.type = 'constraint';\n        constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : 0.7);\n        constraint.damping = constraint.damping || 0;\n        constraint.angularStiffness = constraint.angularStiffness || 0;\n        constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA;\n        constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB;\n        constraint.plugin = {};\n\n        // render\n        var render = {\n            visible: true,\n            lineWidth: 2,\n            strokeStyle: '#ffffff',\n            type: 'line',\n            anchors: true\n        };\n\n        if (constraint.length === 0 && constraint.stiffness > 0.1) {\n            render.type = 'pin';\n            render.anchors = false;\n        } else if (constraint.stiffness < 0.9) {\n            render.type = 'spring';\n        }\n\n        constraint.render = Common.extend(render, constraint.render);\n\n        return constraint;\n    };\n\n    /**\n     * Prepares for solving by constraint warming.\n     * @private\n     * @method preSolveAll\n     * @param {body[]} bodies\n     */\n    Constraint.preSolveAll = function(bodies) {\n        for (var i = 0; i < bodies.length; i += 1) {\n            var body = bodies[i],\n                impulse = body.constraintImpulse;\n\n            if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {\n                continue;\n            }\n\n            body.position.x += impulse.x;\n            body.position.y += impulse.y;\n            body.angle += impulse.angle;\n        }\n    };\n\n    /**\n     * Solves all constraints in a list of collisions.\n     * @private\n     * @method solveAll\n     * @param {constraint[]} constraints\n     * @param {number} delta\n     */\n    Constraint.solveAll = function(constraints, delta) {\n        var timeScale = Common.clamp(delta / Common._baseDelta, 0, 1);\n\n        // Solve fixed constraints first.\n        for (var i = 0; i < constraints.length; i += 1) {\n            var constraint = constraints[i],\n                fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic),\n                fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);\n\n            if (fixedA || fixedB) {\n                Constraint.solve(constraints[i], timeScale);\n            }\n        }\n\n        // Solve free constraints last.\n        for (i = 0; i < constraints.length; i += 1) {\n            constraint = constraints[i];\n            fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic);\n            fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic);\n\n            if (!fixedA && !fixedB) {\n                Constraint.solve(constraints[i], timeScale);\n            }\n        }\n    };\n\n    /**\n     * Solves a distance constraint with Gauss-Siedel method.\n     * @private\n     * @method solve\n     * @param {constraint} constraint\n     * @param {number} timeScale\n     */\n    Constraint.solve = function(constraint, timeScale) {\n        var bodyA = constraint.bodyA,\n            bodyB = constraint.bodyB,\n            pointA = constraint.pointA,\n            pointB = constraint.pointB;\n\n        if (!bodyA && !bodyB)\n            return;\n\n        // update reference angle\n        if (bodyA && !bodyA.isStatic) {\n            Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA);\n            constraint.angleA = bodyA.angle;\n        }\n        \n        // update reference angle\n        if (bodyB && !bodyB.isStatic) {\n            Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB);\n            constraint.angleB = bodyB.angle;\n        }\n\n        var pointAWorld = pointA,\n            pointBWorld = pointB;\n\n        if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA);\n        if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB);\n\n        if (!pointAWorld || !pointBWorld)\n            return;\n\n        var delta = Vector.sub(pointAWorld, pointBWorld),\n            currentLength = Vector.magnitude(delta);\n\n        // prevent singularity\n        if (currentLength < Constraint._minLength) {\n            currentLength = Constraint._minLength;\n        }\n\n        // solve distance constraint with Gauss-Siedel method\n        var difference = (currentLength - constraint.length) / currentLength,\n            isRigid = constraint.stiffness >= 1 || constraint.length === 0,\n            stiffness = isRigid ? constraint.stiffness * timeScale \n                : constraint.stiffness * timeScale * timeScale,\n            damping = constraint.damping * timeScale,\n            force = Vector.mult(delta, difference * stiffness),\n            massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0),\n            inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0),\n            resistanceTotal = massTotal + inertiaTotal,\n            torque,\n            share,\n            normal,\n            normalVelocity,\n            relativeVelocity;\n    \n        if (damping > 0) {\n            var zero = Vector.create();\n            normal = Vector.div(delta, currentLength);\n\n            relativeVelocity = Vector.sub(\n                bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero,\n                bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero\n            );\n\n            normalVelocity = Vector.dot(normal, relativeVelocity);\n        }\n\n        if (bodyA && !bodyA.isStatic) {\n            share = bodyA.inverseMass / massTotal;\n\n            // keep track of applied impulses for post solving\n            bodyA.constraintImpulse.x -= force.x * share;\n            bodyA.constraintImpulse.y -= force.y * share;\n\n            // apply forces\n            bodyA.position.x -= force.x * share;\n            bodyA.position.y -= force.y * share;\n\n            // apply damping\n            if (damping > 0) {\n                bodyA.positionPrev.x -= damping * normal.x * normalVelocity * share;\n                bodyA.positionPrev.y -= damping * normal.y * normalVelocity * share;\n            }\n\n            // apply torque\n            torque = (Vector.cross(pointA, force) / resistanceTotal) * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness);\n            bodyA.constraintImpulse.angle -= torque;\n            bodyA.angle -= torque;\n        }\n\n        if (bodyB && !bodyB.isStatic) {\n            share = bodyB.inverseMass / massTotal;\n\n            // keep track of applied impulses for post solving\n            bodyB.constraintImpulse.x += force.x * share;\n            bodyB.constraintImpulse.y += force.y * share;\n            \n            // apply forces\n            bodyB.position.x += force.x * share;\n            bodyB.position.y += force.y * share;\n\n            // apply damping\n            if (damping > 0) {\n                bodyB.positionPrev.x += damping * normal.x * normalVelocity * share;\n                bodyB.positionPrev.y += damping * normal.y * normalVelocity * share;\n            }\n\n            // apply torque\n            torque = (Vector.cross(pointB, force) / resistanceTotal) * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness);\n            bodyB.constraintImpulse.angle += torque;\n            bodyB.angle += torque;\n        }\n\n    };\n\n    /**\n     * Performs body updates required after solving constraints.\n     * @private\n     * @method postSolveAll\n     * @param {body[]} bodies\n     */\n    Constraint.postSolveAll = function(bodies) {\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                impulse = body.constraintImpulse;\n\n            if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) {\n                continue;\n            }\n\n            Sleeping.set(body, false);\n\n            // update geometry and reset\n            for (var j = 0; j < body.parts.length; j++) {\n                var part = body.parts[j];\n                \n                Vertices.translate(part.vertices, impulse);\n\n                if (j > 0) {\n                    part.position.x += impulse.x;\n                    part.position.y += impulse.y;\n                }\n\n                if (impulse.angle !== 0) {\n                    Vertices.rotate(part.vertices, impulse.angle, body.position);\n                    Axes.rotate(part.axes, impulse.angle);\n                    if (j > 0) {\n                        Vector.rotateAbout(part.position, impulse.angle, body.position, part.position);\n                    }\n                }\n\n                Bounds.update(part.bounds, part.vertices, body.velocity);\n            }\n\n            // dampen the cached impulse for warming next step\n            impulse.angle *= Constraint._warming;\n            impulse.x *= Constraint._warming;\n            impulse.y *= Constraint._warming;\n        }\n    };\n\n    /**\n     * Returns the world-space position of `constraint.pointA`, accounting for `constraint.bodyA`.\n     * @method pointAWorld\n     * @param {constraint} constraint\n     * @returns {vector} the world-space position\n     */\n    Constraint.pointAWorld = function(constraint) {\n        return {\n            x: (constraint.bodyA ? constraint.bodyA.position.x : 0) \n                + (constraint.pointA ? constraint.pointA.x : 0),\n            y: (constraint.bodyA ? constraint.bodyA.position.y : 0) \n                + (constraint.pointA ? constraint.pointA.y : 0)\n        };\n    };\n\n    /**\n     * Returns the world-space position of `constraint.pointB`, accounting for `constraint.bodyB`.\n     * @method pointBWorld\n     * @param {constraint} constraint\n     * @returns {vector} the world-space position\n     */\n    Constraint.pointBWorld = function(constraint) {\n        return {\n            x: (constraint.bodyB ? constraint.bodyB.position.x : 0) \n                + (constraint.pointB ? constraint.pointB.x : 0),\n            y: (constraint.bodyB ? constraint.bodyB.position.y : 0) \n                + (constraint.pointB ? constraint.pointB.y : 0)\n        };\n    };\n\n    /**\n     * Returns the current length of the constraint. \n     * This is the distance between both of the constraint's end points.\n     * See `constraint.length` for the target rest length.\n     * @method currentLength\n     * @param {constraint} constraint\n     * @returns {number} the current length\n     */\n    Constraint.currentLength = function(constraint) {\n        var pointAX = (constraint.bodyA ? constraint.bodyA.position.x : 0) \n            + (constraint.pointA ? constraint.pointA.x : 0);\n\n        var pointAY = (constraint.bodyA ? constraint.bodyA.position.y : 0) \n            + (constraint.pointA ? constraint.pointA.y : 0);\n\n        var pointBX = (constraint.bodyB ? constraint.bodyB.position.x : 0) \n            + (constraint.pointB ? constraint.pointB.x : 0);\n            \n        var pointBY = (constraint.bodyB ? constraint.bodyB.position.y : 0) \n            + (constraint.pointB ? constraint.pointB.y : 0);\n\n        var deltaX = pointAX - pointBX;\n        var deltaY = pointAY - pointBY;\n\n        return Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n    };\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.\n     *\n     * @property id\n     * @type number\n     */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"constraint\"\n     * @readOnly\n     */\n\n    /**\n     * An arbitrary `String` name to help the user identify and manage bodies.\n     *\n     * @property label\n     * @type string\n     * @default \"Constraint\"\n     */\n\n    /**\n     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.\n     *\n     * @property render\n     * @type object\n     */\n\n    /**\n     * A flag that indicates if the constraint should be rendered.\n     *\n     * @property render.visible\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A `Number` that defines the line width to use when rendering the constraint outline.\n     * A value of `0` means no outline will be rendered.\n     *\n     * @property render.lineWidth\n     * @type number\n     * @default 2\n     */\n\n    /**\n     * A `String` that defines the stroke style to use when rendering the constraint outline.\n     * It is the same as when using a canvas, so it accepts CSS style property values.\n     *\n     * @property render.strokeStyle\n     * @type string\n     * @default a random colour\n     */\n\n    /**\n     * A `String` that defines the constraint rendering type. \n     * The possible values are 'line', 'pin', 'spring'.\n     * An appropriate render type will be automatically chosen unless one is given in options.\n     *\n     * @property render.type\n     * @type string\n     * @default 'line'\n     */\n\n    /**\n     * A `Boolean` that defines if the constraint's anchor points should be rendered.\n     *\n     * @property render.anchors\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * The first possible `Body` that this constraint is attached to.\n     *\n     * @property bodyA\n     * @type body\n     * @default null\n     */\n\n    /**\n     * The second possible `Body` that this constraint is attached to.\n     *\n     * @property bodyB\n     * @type body\n     * @default null\n     */\n\n    /**\n     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.\n     *\n     * @property pointA\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position.\n     *\n     * @property pointB\n     * @type vector\n     * @default { x: 0, y: 0 }\n     */\n\n    /**\n     * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`.\n     * A value of `1` means the constraint should be very stiff.\n     * A value of `0.2` means the constraint acts like a soft spring.\n     *\n     * @property stiffness\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that specifies the damping of the constraint, \n     * i.e. the amount of resistance applied to each body based on their velocities to limit the amount of oscillation.\n     * Damping will only be apparent when the constraint also has a very low `stiffness`.\n     * A value of `0.1` means the constraint will apply heavy damping, resulting in little to no oscillation.\n     * A value of `0` means the constraint will apply no damping.\n     *\n     * @property damping\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that specifies the target resting length of the constraint. \n     * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`.\n     *\n     * @property length\n     * @type number\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n})();\n"
  },
  {
    "path": "src/constraint/MouseConstraint.js",
    "content": "/**\n* The `Matter.MouseConstraint` module contains methods for creating mouse constraints.\n* Mouse constraints are used for allowing user interaction, providing the ability to move bodies via the mouse or touch.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class MouseConstraint\n*/\n\nvar MouseConstraint = {};\n\nmodule.exports = MouseConstraint;\n\nvar Vertices = require('../geometry/Vertices');\nvar Sleeping = require('../core/Sleeping');\nvar Mouse = require('../core/Mouse');\nvar Events = require('../core/Events');\nvar Detector = require('../collision/Detector');\nvar Constraint = require('./Constraint');\nvar Composite = require('../body/Composite');\nvar Common = require('../core/Common');\nvar Bounds = require('../geometry/Bounds');\n\n(function() {\n\n    /**\n     * Creates a new mouse constraint.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {engine} engine\n     * @param {} options\n     * @return {MouseConstraint} A new MouseConstraint\n     */\n    MouseConstraint.create = function(engine, options) {\n        var mouse = (engine ? engine.mouse : null) || (options ? options.mouse : null);\n\n        if (!mouse) {\n            if (engine && engine.render && engine.render.canvas) {\n                mouse = Mouse.create(engine.render.canvas);\n            } else if (options && options.element) {\n                mouse = Mouse.create(options.element);\n            } else {\n                mouse = Mouse.create();\n                Common.warn('MouseConstraint.create: options.mouse was undefined, options.element was undefined, may not function as expected');\n            }\n        }\n\n        var constraint = Constraint.create({ \n            label: 'Mouse Constraint',\n            pointA: mouse.position,\n            pointB: { x: 0, y: 0 },\n            length: 0.01, \n            stiffness: 0.1,\n            angularStiffness: 1,\n            render: {\n                strokeStyle: '#90EE90',\n                lineWidth: 3\n            }\n        });\n\n        var defaults = {\n            type: 'mouseConstraint',\n            mouse: mouse,\n            element: null,\n            body: null,\n            constraint: constraint,\n            collisionFilter: {\n                category: 0x0001,\n                mask: 0xFFFFFFFF,\n                group: 0\n            }\n        };\n\n        var mouseConstraint = Common.extend(defaults, options);\n\n        Events.on(engine, 'beforeUpdate', function() {\n            var allBodies = Composite.allBodies(engine.world);\n            MouseConstraint.update(mouseConstraint, allBodies);\n            MouseConstraint._triggerEvents(mouseConstraint);\n        });\n\n        return mouseConstraint;\n    };\n\n    /**\n     * Updates the given mouse constraint.\n     * @private\n     * @method update\n     * @param {MouseConstraint} mouseConstraint\n     * @param {body[]} bodies\n     */\n    MouseConstraint.update = function(mouseConstraint, bodies) {\n        var mouse = mouseConstraint.mouse,\n            constraint = mouseConstraint.constraint,\n            body = mouseConstraint.body;\n\n        if (mouse.button === 0) {\n            if (!constraint.bodyB) {\n                for (var i = 0; i < bodies.length; i++) {\n                    body = bodies[i];\n                    if (Bounds.contains(body.bounds, mouse.position) \n                            && Detector.canCollide(body.collisionFilter, mouseConstraint.collisionFilter)) {\n                        for (var j = body.parts.length > 1 ? 1 : 0; j < body.parts.length; j++) {\n                            var part = body.parts[j];\n                            if (Vertices.contains(part.vertices, mouse.position)) {\n                                constraint.pointA = mouse.position;\n                                constraint.bodyB = mouseConstraint.body = body;\n                                constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y };\n                                constraint.angleB = body.angle;\n\n                                Sleeping.set(body, false);\n                                Events.trigger(mouseConstraint, 'startdrag', { mouse: mouse, body: body });\n\n                                break;\n                            }\n                        }\n                    }\n                }\n            } else {\n                Sleeping.set(constraint.bodyB, false);\n                constraint.pointA = mouse.position;\n            }\n        } else {\n            constraint.bodyB = mouseConstraint.body = null;\n            constraint.pointB = null;\n\n            if (body)\n                Events.trigger(mouseConstraint, 'enddrag', { mouse: mouse, body: body });\n        }\n    };\n\n    /**\n     * Triggers mouse constraint events.\n     * @method _triggerEvents\n     * @private\n     * @param {mouse} mouseConstraint\n     */\n    MouseConstraint._triggerEvents = function(mouseConstraint) {\n        var mouse = mouseConstraint.mouse,\n            mouseEvents = mouse.sourceEvents;\n\n        if (mouseEvents.mousemove)\n            Events.trigger(mouseConstraint, 'mousemove', { mouse: mouse });\n\n        if (mouseEvents.mousedown)\n            Events.trigger(mouseConstraint, 'mousedown', { mouse: mouse });\n\n        if (mouseEvents.mouseup)\n            Events.trigger(mouseConstraint, 'mouseup', { mouse: mouse });\n\n        // reset the mouse state ready for the next step\n        Mouse.clearSourceEvents(mouse);\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired when the mouse has moved (or a touch moves) during the last step\n    *\n    * @event mousemove\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the mouse is down (or a touch has started) during the last step\n    *\n    * @event mousedown\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the mouse is up (or a touch has ended) during the last step\n    *\n    * @event mouseup\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the user starts dragging a body\n    *\n    * @event startdrag\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {body} event.body The body being dragged\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired when the user ends dragging a body\n    *\n    * @event enddrag\n    * @param {} event An event object\n    * @param {mouse} event.mouse The engine's mouse instance\n    * @param {body} event.body The body that has stopped being dragged\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A `String` denoting the type of object.\n     *\n     * @property type\n     * @type string\n     * @default \"constraint\"\n     * @readOnly\n     */\n\n    /**\n     * The `Mouse` instance in use. If not supplied in `MouseConstraint.create`, one will be created.\n     *\n     * @property mouse\n     * @type mouse\n     * @default mouse\n     */\n\n    /**\n     * The `Body` that is currently being moved by the user, or `null` if no body.\n     *\n     * @property body\n     * @type body\n     * @default null\n     */\n\n    /**\n     * The `Constraint` object that is used to move the body during interaction.\n     *\n     * @property constraint\n     * @type constraint\n     */\n\n    /**\n     * An `Object` that specifies the collision filter properties.\n     * The collision filter allows the user to define which types of body this mouse constraint can interact with.\n     * See `body.collisionFilter` for more information.\n     *\n     * @property collisionFilter\n     * @type object\n     */\n\n})();\n"
  },
  {
    "path": "src/core/Common.js",
    "content": "/**\n* The `Matter.Common` module contains utility functions that are common to all modules.\n*\n* @class Common\n*/\n\nvar Common = {};\n\nmodule.exports = Common;\n\n(function() {\n\n    Common._baseDelta = 1000 / 60;\n    Common._nextId = 0;\n    Common._seed = 0;\n    Common._nowStartTime = +(new Date());\n    Common._warnedOnce = {};\n    Common._decomp = null;\n    \n    /**\n     * Extends the object in the first argument using the object in the second argument.\n     * @method extend\n     * @param {} obj\n     * @param {boolean} deep\n     * @return {} obj extended\n     */\n    Common.extend = function(obj, deep) {\n        var argsStart,\n            args,\n            deepClone;\n\n        if (typeof deep === 'boolean') {\n            argsStart = 2;\n            deepClone = deep;\n        } else {\n            argsStart = 1;\n            deepClone = true;\n        }\n\n        for (var i = argsStart; i < arguments.length; i++) {\n            var source = arguments[i];\n\n            if (source) {\n                for (var prop in source) {\n                    if (deepClone && source[prop] && source[prop].constructor === Object) {\n                        if (!obj[prop] || obj[prop].constructor === Object) {\n                            obj[prop] = obj[prop] || {};\n                            Common.extend(obj[prop], deepClone, source[prop]);\n                        } else {\n                            obj[prop] = source[prop];\n                        }\n                    } else {\n                        obj[prop] = source[prop];\n                    }\n                }\n            }\n        }\n        \n        return obj;\n    };\n\n    /**\n     * Creates a new clone of the object, if deep is true references will also be cloned.\n     * @method clone\n     * @param {} obj\n     * @param {bool} deep\n     * @return {} obj cloned\n     */\n    Common.clone = function(obj, deep) {\n        return Common.extend({}, deep, obj);\n    };\n\n    /**\n     * Returns the list of keys for the given object.\n     * @method keys\n     * @param {} obj\n     * @return {string[]} keys\n     */\n    Common.keys = function(obj) {\n        if (Object.keys)\n            return Object.keys(obj);\n\n        // avoid hasOwnProperty for performance\n        var keys = [];\n        for (var key in obj)\n            keys.push(key);\n        return keys;\n    };\n\n    /**\n     * Returns the list of values for the given object.\n     * @method values\n     * @param {} obj\n     * @return {array} Array of the objects property values\n     */\n    Common.values = function(obj) {\n        var values = [];\n        \n        if (Object.keys) {\n            var keys = Object.keys(obj);\n            for (var i = 0; i < keys.length; i++) {\n                values.push(obj[keys[i]]);\n            }\n            return values;\n        }\n        \n        // avoid hasOwnProperty for performance\n        for (var key in obj)\n            values.push(obj[key]);\n        return values;\n    };\n\n    /**\n     * Gets a value from `base` relative to the `path` string.\n     * @method get\n     * @param {} obj The base object\n     * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'\n     * @param {number} [begin] Path slice begin\n     * @param {number} [end] Path slice end\n     * @return {} The object at the given path\n     */\n    Common.get = function(obj, path, begin, end) {\n        path = path.split('.').slice(begin, end);\n\n        for (var i = 0; i < path.length; i += 1) {\n            obj = obj[path[i]];\n        }\n\n        return obj;\n    };\n\n    /**\n     * Sets a value on `base` relative to the given `path` string.\n     * @method set\n     * @param {} obj The base object\n     * @param {string} path The path relative to `base`, e.g. 'Foo.Bar.baz'\n     * @param {} val The value to set\n     * @param {number} [begin] Path slice begin\n     * @param {number} [end] Path slice end\n     * @return {} Pass through `val` for chaining\n     */\n    Common.set = function(obj, path, val, begin, end) {\n        var parts = path.split('.').slice(begin, end);\n        Common.get(obj, path, 0, -1)[parts[parts.length - 1]] = val;\n        return val;\n    };\n\n    /**\n     * Shuffles the given array in-place.\n     * The function uses a seeded random generator.\n     * @method shuffle\n     * @param {array} array\n     * @return {array} array shuffled randomly\n     */\n    Common.shuffle = function(array) {\n        for (var i = array.length - 1; i > 0; i--) {\n            var j = Math.floor(Common.random() * (i + 1));\n            var temp = array[i];\n            array[i] = array[j];\n            array[j] = temp;\n        }\n        return array;\n    };\n\n    /**\n     * Randomly chooses a value from a list with equal probability.\n     * The function uses a seeded random generator.\n     * @method choose\n     * @param {array} choices\n     * @return {object} A random choice object from the array\n     */\n    Common.choose = function(choices) {\n        return choices[Math.floor(Common.random() * choices.length)];\n    };\n\n    /**\n     * Returns true if the object is a HTMLElement, otherwise false.\n     * @method isElement\n     * @param {object} obj\n     * @return {boolean} True if the object is a HTMLElement, otherwise false\n     */\n    Common.isElement = function(obj) {\n        if (typeof HTMLElement !== 'undefined') {\n            return obj instanceof HTMLElement;\n        }\n\n        return !!(obj && obj.nodeType && obj.nodeName);\n    };\n\n    /**\n     * Returns true if the object is an array.\n     * @method isArray\n     * @param {object} obj\n     * @return {boolean} True if the object is an array, otherwise false\n     */\n    Common.isArray = function(obj) {\n        return Object.prototype.toString.call(obj) === '[object Array]';\n    };\n\n    /**\n     * Returns true if the object is a function.\n     * @method isFunction\n     * @param {object} obj\n     * @return {boolean} True if the object is a function, otherwise false\n     */\n    Common.isFunction = function(obj) {\n        return typeof obj === \"function\";\n    };\n\n    /**\n     * Returns true if the object is a plain object.\n     * @method isPlainObject\n     * @param {object} obj\n     * @return {boolean} True if the object is a plain object, otherwise false\n     */\n    Common.isPlainObject = function(obj) {\n        return typeof obj === 'object' && obj.constructor === Object;\n    };\n\n    /**\n     * Returns true if the object is a string.\n     * @method isString\n     * @param {object} obj\n     * @return {boolean} True if the object is a string, otherwise false\n     */\n    Common.isString = function(obj) {\n        return toString.call(obj) === '[object String]';\n    };\n    \n    /**\n     * Returns the given value clamped between a minimum and maximum value.\n     * @method clamp\n     * @param {number} value\n     * @param {number} min\n     * @param {number} max\n     * @return {number} The value clamped between min and max inclusive\n     */\n    Common.clamp = function(value, min, max) {\n        if (value < min)\n            return min;\n        if (value > max)\n            return max;\n        return value;\n    };\n    \n    /**\n     * Returns the sign of the given value.\n     * @method sign\n     * @param {number} value\n     * @return {number} -1 if negative, +1 if 0 or positive\n     */\n    Common.sign = function(value) {\n        return value < 0 ? -1 : 1;\n    };\n    \n    /**\n     * Returns the current timestamp since the time origin (e.g. from page load).\n     * The result is in milliseconds and will use high-resolution timing if available.\n     * @method now\n     * @return {number} the current timestamp in milliseconds\n     */\n    Common.now = function() {\n        if (typeof window !== 'undefined' && window.performance) {\n            if (window.performance.now) {\n                return window.performance.now();\n            } else if (window.performance.webkitNow) {\n                return window.performance.webkitNow();\n            }\n        }\n\n        if (Date.now) {\n            return Date.now();\n        }\n\n        return (new Date()) - Common._nowStartTime;\n    };\n    \n    /**\n     * Returns a random value between a minimum and a maximum value inclusive.\n     * The function uses a seeded random generator.\n     * @method random\n     * @param {number} min\n     * @param {number} max\n     * @return {number} A random number between min and max inclusive\n     */\n    Common.random = function(min, max) {\n        min = (typeof min !== \"undefined\") ? min : 0;\n        max = (typeof max !== \"undefined\") ? max : 1;\n        return min + _seededRandom() * (max - min);\n    };\n\n    var _seededRandom = function() {\n        // https://en.wikipedia.org/wiki/Linear_congruential_generator\n        Common._seed = (Common._seed * 9301 + 49297) % 233280;\n        return Common._seed / 233280;\n    };\n\n    /**\n     * Converts a CSS hex colour string into an integer.\n     * @method colorToNumber\n     * @param {string} colorString\n     * @return {number} An integer representing the CSS hex string\n     */\n    Common.colorToNumber = function(colorString) {\n        colorString = colorString.replace('#','');\n\n        if (colorString.length == 3) {\n            colorString = colorString.charAt(0) + colorString.charAt(0)\n                        + colorString.charAt(1) + colorString.charAt(1)\n                        + colorString.charAt(2) + colorString.charAt(2);\n        }\n\n        return parseInt(colorString, 16);\n    };\n\n    /**\n     * The console logging level to use, where each level includes all levels above and excludes the levels below.\n     * The default level is 'debug' which shows all console messages.  \n     *\n     * Possible level values are:\n     * - 0 = None\n     * - 1 = Debug\n     * - 2 = Info\n     * - 3 = Warn\n     * - 4 = Error\n     * @static\n     * @property logLevel\n     * @type {Number}\n     * @default 1\n     */\n    Common.logLevel = 1;\n\n    /**\n     * Shows a `console.log` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method log\n     * @param ...objs {} The objects to log.\n     */\n    Common.log = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 3) {\n            console.log.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Shows a `console.info` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method info\n     * @param ...objs {} The objects to log.\n     */\n    Common.info = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 2) {\n            console.info.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Shows a `console.warn` message only if the current `Common.logLevel` allows it.\n     * The message will be prefixed with 'matter-js' to make it easily identifiable.\n     * @method warn\n     * @param ...objs {} The objects to log.\n     */\n    Common.warn = function() {\n        if (console && Common.logLevel > 0 && Common.logLevel <= 3) {\n            console.warn.apply(console, ['matter-js:'].concat(Array.prototype.slice.call(arguments)));\n        }\n    };\n\n    /**\n     * Uses `Common.warn` to log the given message one time only.\n     * @method warnOnce\n     * @param ...objs {} The objects to log.\n     */\n    Common.warnOnce = function() {\n        var message = Array.prototype.slice.call(arguments).join(' ');\n\n        if (!Common._warnedOnce[message]) {\n            Common.warn(message);\n            Common._warnedOnce[message] = true;\n        }\n    };\n\n    /**\n     * Shows a deprecated console warning when the function on the given object is called.\n     * The target function will be replaced with a new function that first shows the warning\n     * and then calls the original function.\n     * @method deprecated\n     * @param {object} obj The object or module\n     * @param {string} name The property name of the function on obj\n     * @param {string} warning The one-time message to show if the function is called\n     */\n    Common.deprecated = function(obj, prop, warning) {\n        obj[prop] = Common.chain(function() {\n            Common.warnOnce('🔅 deprecated 🔅', warning);\n        }, obj[prop]);\n    };\n\n    /**\n     * Returns the next unique sequential ID.\n     * @method nextId\n     * @return {Number} Unique sequential ID\n     */\n    Common.nextId = function() {\n        return Common._nextId++;\n    };\n\n    /**\n     * A cross browser compatible indexOf implementation.\n     * @method indexOf\n     * @param {array} haystack\n     * @param {object} needle\n     * @return {number} The position of needle in haystack, otherwise -1.\n     */\n    Common.indexOf = function(haystack, needle) {\n        if (haystack.indexOf)\n            return haystack.indexOf(needle);\n\n        for (var i = 0; i < haystack.length; i++) {\n            if (haystack[i] === needle)\n                return i;\n        }\n\n        return -1;\n    };\n\n    /**\n     * A cross browser compatible array map implementation.\n     * @method map\n     * @param {array} list\n     * @param {function} func\n     * @return {array} Values from list transformed by func.\n     */\n    Common.map = function(list, func) {\n        if (list.map) {\n            return list.map(func);\n        }\n\n        var mapped = [];\n\n        for (var i = 0; i < list.length; i += 1) {\n            mapped.push(func(list[i]));\n        }\n\n        return mapped;\n    };\n\n    /**\n     * Takes a directed graph and returns the partially ordered set of vertices in topological order.\n     * Circular dependencies are allowed.\n     * @method topologicalSort\n     * @param {object} graph\n     * @return {array} Partially ordered set of vertices in topological order.\n     */\n    Common.topologicalSort = function(graph) {\n        // https://github.com/mgechev/javascript-algorithms\n        // Copyright (c) Minko Gechev (MIT license)\n        // Modifications: tidy formatting and naming\n        var result = [],\n            visited = [],\n            temp = [];\n\n        for (var node in graph) {\n            if (!visited[node] && !temp[node]) {\n                Common._topologicalSort(node, visited, temp, graph, result);\n            }\n        }\n\n        return result;\n    };\n\n    Common._topologicalSort = function(node, visited, temp, graph, result) {\n        var neighbors = graph[node] || [];\n        temp[node] = true;\n\n        for (var i = 0; i < neighbors.length; i += 1) {\n            var neighbor = neighbors[i];\n\n            if (temp[neighbor]) {\n                // skip circular dependencies\n                continue;\n            }\n\n            if (!visited[neighbor]) {\n                Common._topologicalSort(neighbor, visited, temp, graph, result);\n            }\n        }\n\n        temp[node] = false;\n        visited[node] = true;\n\n        result.push(node);\n    };\n\n    /**\n     * Takes _n_ functions as arguments and returns a new function that calls them in order.\n     * The arguments applied when calling the new function will also be applied to every function passed.\n     * The value of `this` refers to the last value returned in the chain that was not `undefined`.\n     * Therefore if a passed function does not return a value, the previously returned value is maintained.\n     * After all passed functions have been called the new function returns the last returned value (if any).\n     * If any of the passed functions are a chain, then the chain will be flattened.\n     * @method chain\n     * @param ...funcs {function} The functions to chain.\n     * @return {function} A new function that calls the passed functions in order.\n     */\n    Common.chain = function() {\n        var funcs = [];\n\n        for (var i = 0; i < arguments.length; i += 1) {\n            var func = arguments[i];\n\n            if (func._chained) {\n                // flatten already chained functions\n                funcs.push.apply(funcs, func._chained);\n            } else {\n                funcs.push(func);\n            }\n        }\n\n        var chain = function() {\n            // https://github.com/GoogleChrome/devtools-docs/issues/53#issuecomment-51941358\n            var lastResult,\n                args = new Array(arguments.length);\n\n            for (var i = 0, l = arguments.length; i < l; i++) {\n                args[i] = arguments[i];\n            }\n\n            for (i = 0; i < funcs.length; i += 1) {\n                var result = funcs[i].apply(lastResult, args);\n\n                if (typeof result !== 'undefined') {\n                    lastResult = result;\n                }\n            }\n\n            return lastResult;\n        };\n\n        chain._chained = funcs;\n\n        return chain;\n    };\n\n    /**\n     * Chains a function to excute before the original function on the given `path` relative to `base`.\n     * See also docs for `Common.chain`.\n     * @method chainPathBefore\n     * @param {} base The base object\n     * @param {string} path The path relative to `base`\n     * @param {function} func The function to chain before the original\n     * @return {function} The chained function that replaced the original\n     */\n    Common.chainPathBefore = function(base, path, func) {\n        return Common.set(base, path, Common.chain(\n            func,\n            Common.get(base, path)\n        ));\n    };\n\n    /**\n     * Chains a function to excute after the original function on the given `path` relative to `base`.\n     * See also docs for `Common.chain`.\n     * @method chainPathAfter\n     * @param {} base The base object\n     * @param {string} path The path relative to `base`\n     * @param {function} func The function to chain after the original\n     * @return {function} The chained function that replaced the original\n     */\n    Common.chainPathAfter = function(base, path, func) {\n        return Common.set(base, path, Common.chain(\n            Common.get(base, path),\n            func\n        ));\n    };\n\n    /**\n     * Provide the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module to enable\n     * concave vertex decomposition support when using `Bodies.fromVertices` e.g. `Common.setDecomp(require('poly-decomp'))`.\n     * @method setDecomp\n     * @param {} decomp The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module.\n     */\n    Common.setDecomp = function(decomp) {\n        Common._decomp = decomp;\n    };\n\n    /**\n     * Returns the [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module provided through `Common.setDecomp`,\n     * otherwise returns the global `decomp` if set.\n     * @method getDecomp\n     * @return {} The [poly-decomp](https://github.com/schteppe/poly-decomp.js) library module if provided.\n     */\n    Common.getDecomp = function() {\n        // get user provided decomp if set\n        var decomp = Common._decomp;\n\n        try {\n            // otherwise from window global\n            if (!decomp && typeof window !== 'undefined') {\n                decomp = window.decomp;\n            }\n    \n            // otherwise from node global\n            if (!decomp && typeof global !== 'undefined') {\n                decomp = global.decomp;\n            }\n        } catch (e) {\n            // decomp not available\n            decomp = null;\n        }\n\n        return decomp;\n    };\n})();\n"
  },
  {
    "path": "src/core/Engine.js",
    "content": "/**\n* The `Matter.Engine` module contains methods for creating and manipulating engines.\n* An engine is a controller that manages updating the simulation of the world.\n* See `Matter.Runner` for an optional game loop utility.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Engine\n*/\n\nvar Engine = {};\n\nmodule.exports = Engine;\n\nvar Sleeping = require('./Sleeping');\nvar Resolver = require('../collision/Resolver');\nvar Detector = require('../collision/Detector');\nvar Pairs = require('../collision/Pairs');\nvar Events = require('./Events');\nvar Composite = require('../body/Composite');\nvar Constraint = require('../constraint/Constraint');\nvar Common = require('./Common');\nvar Body = require('../body/Body');\n\n(function() {\n\n    Engine._deltaMax = 1000 / 60;\n\n    /**\n     * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {object} [options]\n     * @return {engine} engine\n     */\n    Engine.create = function(options) {\n        options = options || {};\n\n        var defaults = {\n            positionIterations: 6,\n            velocityIterations: 4,\n            constraintIterations: 2,\n            enableSleeping: false,\n            events: [],\n            plugin: {},\n            gravity: {\n                x: 0,\n                y: 1,\n                scale: 0.001\n            },\n            timing: {\n                timestamp: 0,\n                timeScale: 1,\n                lastDelta: 0,\n                lastElapsed: 0,\n                lastUpdatesPerFrame: 0\n            }\n        };\n\n        var engine = Common.extend(defaults, options);\n\n        engine.world = options.world || Composite.create({ label: 'World' });\n        engine.pairs = options.pairs || Pairs.create();\n        engine.detector = options.detector || Detector.create();\n        engine.detector.pairs = engine.pairs;\n\n        // for temporary back compatibility only\n        engine.grid = { buckets: [] };\n        engine.world.gravity = engine.gravity;\n        engine.broadphase = engine.grid;\n        engine.metrics = {};\n        \n        return engine;\n    };\n\n    /**\n     * Moves the simulation forward in time by `delta` milliseconds.\n     * Triggers `beforeUpdate`, `beforeSolve` and `afterUpdate` events.\n     * Triggers `collisionStart`, `collisionActive` and `collisionEnd` events.\n     * @method update\n     * @param {engine} engine\n     * @param {number} [delta=16.666]\n     */\n    Engine.update = function(engine, delta) {\n        var startTime = Common.now();\n\n        var world = engine.world,\n            detector = engine.detector,\n            pairs = engine.pairs,\n            timing = engine.timing,\n            timestamp = timing.timestamp,\n            i;\n\n        // warn if high delta\n        if (delta > Engine._deltaMax) {\n            Common.warnOnce(\n                'Matter.Engine.update: delta argument is recommended to be less than or equal to', Engine._deltaMax.toFixed(3), 'ms.'\n            );\n        }\n\n        delta = typeof delta !== 'undefined' ? delta : Common._baseDelta;\n        delta *= timing.timeScale;\n\n        // increment timestamp\n        timing.timestamp += delta;\n        timing.lastDelta = delta;\n\n        // create an event object\n        var event = {\n            timestamp: timing.timestamp,\n            delta: delta\n        };\n\n        Events.trigger(engine, 'beforeUpdate', event);\n\n        // get all bodies and all constraints in the world\n        var allBodies = Composite.allBodies(world),\n            allConstraints = Composite.allConstraints(world);\n\n        // if the world has changed\n        if (world.isModified) {\n            // update the detector bodies\n            Detector.setBodies(detector, allBodies);\n\n            // reset all composite modified flags\n            Composite.setModified(world, false, false, true);\n        }\n\n        // update sleeping if enabled\n        if (engine.enableSleeping)\n            Sleeping.update(allBodies, delta);\n\n        // apply gravity to all bodies\n        Engine._bodiesApplyGravity(allBodies, engine.gravity);\n\n        // update all body position and rotation by integration\n        if (delta > 0) {\n            Engine._bodiesUpdate(allBodies, delta);\n        }\n\n        Events.trigger(engine, 'beforeSolve', event);\n\n        // update all constraints (first pass)\n        Constraint.preSolveAll(allBodies);\n        for (i = 0; i < engine.constraintIterations; i++) {\n            Constraint.solveAll(allConstraints, delta);\n        }\n        Constraint.postSolveAll(allBodies);\n\n        // find all collisions\n        var collisions = Detector.collisions(detector);\n\n        // update collision pairs\n        Pairs.update(pairs, collisions, timestamp);\n\n        // wake up bodies involved in collisions\n        if (engine.enableSleeping)\n            Sleeping.afterCollisions(pairs.list);\n\n        // trigger collision events\n        if (pairs.collisionStart.length > 0) {\n            Events.trigger(engine, 'collisionStart', { \n                pairs: pairs.collisionStart,\n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        // iteratively resolve position between collisions\n        var positionDamping = Common.clamp(20 / engine.positionIterations, 0, 1);\n        \n        Resolver.preSolvePosition(pairs.list);\n        for (i = 0; i < engine.positionIterations; i++) {\n            Resolver.solvePosition(pairs.list, delta, positionDamping);\n        }\n        Resolver.postSolvePosition(allBodies);\n\n        // update all constraints (second pass)\n        Constraint.preSolveAll(allBodies);\n        for (i = 0; i < engine.constraintIterations; i++) {\n            Constraint.solveAll(allConstraints, delta);\n        }\n        Constraint.postSolveAll(allBodies);\n\n        // iteratively resolve velocity between collisions\n        Resolver.preSolveVelocity(pairs.list);\n        for (i = 0; i < engine.velocityIterations; i++) {\n            Resolver.solveVelocity(pairs.list, delta);\n        }\n\n        // update body speed and velocity properties\n        Engine._bodiesUpdateVelocities(allBodies);\n\n        // trigger collision events\n        if (pairs.collisionActive.length > 0) {\n            Events.trigger(engine, 'collisionActive', { \n                pairs: pairs.collisionActive, \n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        if (pairs.collisionEnd.length > 0) {\n            Events.trigger(engine, 'collisionEnd', {\n                pairs: pairs.collisionEnd,\n                timestamp: timing.timestamp,\n                delta: delta\n            });\n        }\n\n        // clear force buffers\n        Engine._bodiesClearForces(allBodies);\n\n        Events.trigger(engine, 'afterUpdate', event);\n\n        // log the time elapsed computing this update\n        engine.timing.lastElapsed = Common.now() - startTime;\n\n        return engine;\n    };\n    \n    /**\n     * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`.\n     * @method merge\n     * @param {engine} engineA\n     * @param {engine} engineB\n     */\n    Engine.merge = function(engineA, engineB) {\n        Common.extend(engineA, engineB);\n        \n        if (engineB.world) {\n            engineA.world = engineB.world;\n\n            Engine.clear(engineA);\n\n            var bodies = Composite.allBodies(engineA.world);\n\n            for (var i = 0; i < bodies.length; i++) {\n                var body = bodies[i];\n                Sleeping.set(body, false);\n                body.id = Common.nextId();\n            }\n        }\n    };\n\n    /**\n     * Clears the engine pairs and detector.\n     * @method clear\n     * @param {engine} engine\n     */\n    Engine.clear = function(engine) {\n        Pairs.clear(engine.pairs);\n        Detector.clear(engine.detector);\n    };\n\n    /**\n     * Zeroes the `body.force` and `body.torque` force buffers.\n     * @method _bodiesClearForces\n     * @private\n     * @param {body[]} bodies\n     */\n    Engine._bodiesClearForces = function(bodies) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            // reset force buffers\n            body.force.x = 0;\n            body.force.y = 0;\n            body.torque = 0;\n        }\n    };\n\n    /**\n     * Applies gravitational acceleration to all `bodies`.\n     * This models a [uniform gravitational field](https://en.wikipedia.org/wiki/Gravity_of_Earth), similar to near the surface of a planet.\n     * \n     * @method _bodiesApplyGravity\n     * @private\n     * @param {body[]} bodies\n     * @param {vector} gravity\n     */\n    Engine._bodiesApplyGravity = function(bodies, gravity) {\n        var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001,\n            bodiesLength = bodies.length;\n\n        if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) {\n            return;\n        }\n        \n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            if (body.isStatic || body.isSleeping)\n                continue;\n\n            // add the resultant force of gravity\n            body.force.y += body.mass * gravity.y * gravityScale;\n            body.force.x += body.mass * gravity.x * gravityScale;\n        }\n    };\n\n    /**\n     * Applies `Body.update` to all given `bodies`.\n     * @method _bodiesUpdate\n     * @private\n     * @param {body[]} bodies\n     * @param {number} delta The amount of time elapsed between updates\n     */\n    Engine._bodiesUpdate = function(bodies, delta) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            var body = bodies[i];\n\n            if (body.isStatic || body.isSleeping)\n                continue;\n\n            Body.update(body, delta);\n        }\n    };\n\n    /**\n     * Applies `Body.updateVelocities` to all given `bodies`.\n     * @method _bodiesUpdateVelocities\n     * @private\n     * @param {body[]} bodies\n     */\n    Engine._bodiesUpdateVelocities = function(bodies) {\n        var bodiesLength = bodies.length;\n\n        for (var i = 0; i < bodiesLength; i++) {\n            Body.updateVelocities(bodies[i]);\n        }\n    };\n\n    /**\n     * A deprecated alias for `Runner.run`, use `Matter.Runner.run(engine)` instead and see `Matter.Runner` for more information.\n     * @deprecated use Matter.Runner.run(engine) instead\n     * @method run\n     * @param {engine} engine\n     */\n\n    /**\n    * Fired just before an update\n    *\n    * @event beforeUpdate\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after bodies updated based on their velocity and forces, but before any collision detection, constraints and resolving etc.\n    *\n    * @event beforeSolve\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update and all collision events\n    *\n    * @event afterUpdate\n    * @param {object} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any)\n    *\n    * @event collisionStart\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any)\n    *\n    * @event collisionActive\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /**\n    * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any)\n    *\n    * @event collisionEnd\n    * @param {object} event An event object\n    * @param {pair[]} event.pairs List of affected pairs\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {number} event.delta The delta time in milliseconds value used in the update\n    * @param {engine} event.source The source object of the event\n    * @param {string} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * An integer `Number` that specifies the number of position iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     *\n     * @property positionIterations\n     * @type number\n     * @default 6\n     */\n\n    /**\n     * An integer `Number` that specifies the number of velocity iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     *\n     * @property velocityIterations\n     * @type number\n     * @default 4\n     */\n\n    /**\n     * An integer `Number` that specifies the number of constraint iterations to perform each update.\n     * The higher the value, the higher quality the simulation will be at the expense of performance.\n     * The default value of `2` is usually very adequate.\n     *\n     * @property constraintIterations\n     * @type number\n     * @default 2\n     */\n\n    /**\n     * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module.\n     * Sleeping can improve stability and performance, but often at the expense of accuracy.\n     *\n     * @property enableSleeping\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * An `Object` containing properties regarding the timing systems of the engine. \n     *\n     * @property timing\n     * @type object\n     */\n\n    /**\n     * A `Number` that specifies the global scaling factor of time for all bodies.\n     * A value of `0` freezes the simulation.\n     * A value of `0.1` gives a slow-motion effect.\n     * A value of `1.2` gives a speed-up effect.\n     *\n     * @property timing.timeScale\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. \n     * It is incremented on every `Engine.update` by the given `delta` argument. \n     * \n     * @property timing.timestamp\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that represents the total execution time elapsed during the last `Engine.update` in milliseconds.\n     * It is updated by timing from the start of the last `Engine.update` call until it ends.\n     *\n     * This value will also include the total execution time of all event handlers directly or indirectly triggered by the engine update.\n     * \n     * @property timing.lastElapsed\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Number` that represents the `delta` value used in the last engine update.\n     * \n     * @property timing.lastDelta\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * A `Matter.Detector` instance.\n     *\n     * @property detector\n     * @type detector\n     * @default a Matter.Detector instance\n     */\n\n    /**\n     * A `Matter.Grid` instance.\n     *\n     * @deprecated replaced by `engine.detector`\n     * @property grid\n     * @type grid\n     * @default a Matter.Grid instance\n     */\n\n    /**\n     * Replaced by and now alias for `engine.grid`.\n     *\n     * @deprecated replaced by `engine.detector`\n     * @property broadphase\n     * @type grid\n     * @default a Matter.Grid instance\n     */\n\n    /**\n     * The root `Matter.Composite` instance that will contain all bodies, constraints and other composites to be simulated by this engine.\n     *\n     * @property world\n     * @type composite\n     * @default a Matter.Composite instance\n     */\n\n    /**\n     * An object reserved for storing plugin-specific properties.\n     *\n     * @property plugin\n     * @type {}\n     */\n\n    /**\n     * An optional gravitational acceleration applied to all bodies in `engine.world` on every update.\n     * \n     * This models a [uniform gravitational field](https://en.wikipedia.org/wiki/Gravity_of_Earth), similar to near the surface of a planet. For gravity in other contexts, disable this and apply forces as needed.\n     * \n     * To disable set the `scale` component to `0`.\n     * \n     * This is split into three components for ease of use:  \n     * a normalised direction (`x` and `y`) and magnitude (`scale`).\n     *\n     * @property gravity\n     * @type object\n     */\n\n    /**\n     * The gravitational direction normal `x` component, to be multiplied by `gravity.scale`.\n     * \n     * @property gravity.x\n     * @type object\n     * @default 0\n     */\n\n    /**\n     * The gravitational direction normal `y` component, to be multiplied by `gravity.scale`.\n     *\n     * @property gravity.y\n     * @type object\n     * @default 1\n     */\n\n    /**\n     * The magnitude of the gravitational acceleration.\n     * \n     * @property gravity.scale\n     * @type object\n     * @default 0.001\n     */\n\n})();\n"
  },
  {
    "path": "src/core/Events.js",
    "content": "/**\n* The `Matter.Events` module contains methods to fire and listen to events on other objects.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Events\n*/\n\nvar Events = {};\n\nmodule.exports = Events;\n\nvar Common = require('./Common');\n\n(function() {\n\n    /**\n     * Subscribes a callback function to the given object's `eventName`.\n     * @method on\n     * @param {} object\n     * @param {string} eventNames\n     * @param {function} callback\n     */\n    Events.on = function(object, eventNames, callback) {\n        var names = eventNames.split(' '),\n            name;\n\n        for (var i = 0; i < names.length; i++) {\n            name = names[i];\n            object.events = object.events || {};\n            object.events[name] = object.events[name] || [];\n            object.events[name].push(callback);\n        }\n\n        return callback;\n    };\n\n    /**\n     * Removes the given event callback. If no callback, clears all callbacks in `eventNames`. If no `eventNames`, clears all events.\n     * @method off\n     * @param {} object\n     * @param {string} eventNames\n     * @param {function} callback\n     */\n    Events.off = function(object, eventNames, callback) {\n        if (!eventNames) {\n            object.events = {};\n            return;\n        }\n\n        // handle Events.off(object, callback)\n        if (typeof eventNames === 'function') {\n            callback = eventNames;\n            eventNames = Common.keys(object.events).join(' ');\n        }\n\n        var names = eventNames.split(' ');\n\n        for (var i = 0; i < names.length; i++) {\n            var callbacks = object.events[names[i]],\n                newCallbacks = [];\n\n            if (callback && callbacks) {\n                for (var j = 0; j < callbacks.length; j++) {\n                    if (callbacks[j] !== callback)\n                        newCallbacks.push(callbacks[j]);\n                }\n            }\n\n            object.events[names[i]] = newCallbacks;\n        }\n    };\n\n    /**\n     * Fires all the callbacks subscribed to the given object's `eventName`, in the order they subscribed, if any.\n     * @method trigger\n     * @param {} object\n     * @param {string} eventNames\n     * @param {} event\n     */\n    Events.trigger = function(object, eventNames, event) {\n        var names,\n            name,\n            callbacks,\n            eventClone;\n\n        var events = object.events;\n        \n        if (events && Common.keys(events).length > 0) {\n            if (!event)\n                event = {};\n\n            names = eventNames.split(' ');\n\n            for (var i = 0; i < names.length; i++) {\n                name = names[i];\n                callbacks = events[name];\n\n                if (callbacks) {\n                    eventClone = Common.clone(event, false);\n                    eventClone.name = name;\n                    eventClone.source = object;\n\n                    for (var j = 0; j < callbacks.length; j++) {\n                        callbacks[j].apply(object, [eventClone]);\n                    }\n                }\n            }\n        }\n    };\n\n})();\n"
  },
  {
    "path": "src/core/Matter.js",
    "content": "/**\r\n* The `Matter` module is the top level namespace. It also includes a function for installing plugins on top of the library.\r\n*\r\n* @class Matter\r\n*/\r\n\r\nvar Matter = {};\r\n\r\nmodule.exports = Matter;\r\n\r\nvar Plugin = require('./Plugin');\r\nvar Common = require('./Common');\r\n\r\n(function() {\r\n\r\n    /**\r\n     * The library name.\r\n     * @property name\r\n     * @readOnly\r\n     * @type {String}\r\n     */\r\n    Matter.name = 'matter-js';\r\n\r\n    /**\r\n     * The library version.\r\n     * @property version\r\n     * @readOnly\r\n     * @type {String}\r\n     */\r\n    Matter.version = typeof __MATTER_VERSION__ !== 'undefined' ? __MATTER_VERSION__ : '*';\r\n\r\n    /**\r\n     * A list of plugin dependencies to be installed. These are normally set and installed through `Matter.use`.\r\n     * Alternatively you may set `Matter.uses` manually and install them by calling `Plugin.use(Matter)`.\r\n     * @property uses\r\n     * @type {Array}\r\n     */\r\n    Matter.uses = [];\r\n\r\n    /**\r\n     * The plugins that have been installed through `Matter.Plugin.install`. Read only.\r\n     * @property used\r\n     * @readOnly\r\n     * @type {Array}\r\n     */\r\n    Matter.used = [];\r\n\r\n    /**\r\n     * Installs the given plugins on the `Matter` namespace.\r\n     * This is a short-hand for `Plugin.use`, see it for more information.\r\n     * Call this function once at the start of your code, with all of the plugins you wish to install as arguments.\r\n     * Avoid calling this function multiple times unless you intend to manually control installation order.\r\n     * @method use\r\n     * @param ...plugin {Function} The plugin(s) to install on `base` (multi-argument).\r\n     */\r\n    Matter.use = function() {\r\n        Plugin.use(Matter, Array.prototype.slice.call(arguments));\r\n    };\r\n\r\n    /**\r\n     * Chains a function to excute before the original function on the given `path` relative to `Matter`.\r\n     * See also docs for `Common.chain`.\r\n     * @method before\r\n     * @param {string} path The path relative to `Matter`\r\n     * @param {function} func The function to chain before the original\r\n     * @return {function} The chained function that replaced the original\r\n     */\r\n    Matter.before = function(path, func) {\r\n        path = path.replace(/^Matter./, '');\r\n        return Common.chainPathBefore(Matter, path, func);\r\n    };\r\n\r\n    /**\r\n     * Chains a function to excute after the original function on the given `path` relative to `Matter`.\r\n     * See also docs for `Common.chain`.\r\n     * @method after\r\n     * @param {string} path The path relative to `Matter`\r\n     * @param {function} func The function to chain after the original\r\n     * @return {function} The chained function that replaced the original\r\n     */\r\n    Matter.after = function(path, func) {\r\n        path = path.replace(/^Matter./, '');\r\n        return Common.chainPathAfter(Matter, path, func);\r\n    };\r\n\r\n})();\r\n"
  },
  {
    "path": "src/core/Mouse.js",
    "content": "/**\n* The `Matter.Mouse` module contains methods for creating and manipulating mouse inputs.\n*\n* @class Mouse\n*/\n\nvar Mouse = {};\n\nmodule.exports = Mouse;\n\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * Creates a mouse input.\n     * @method create\n     * @param {HTMLElement} element\n     * @return {mouse} A new mouse\n     */\n    Mouse.create = function(element) {\n        var mouse = {};\n\n        if (!element) {\n            Common.log('Mouse.create: element was undefined, defaulting to document.body', 'warn');\n        }\n        \n        mouse.element = element || document.body;\n        mouse.absolute = { x: 0, y: 0 };\n        mouse.position = { x: 0, y: 0 };\n        mouse.mousedownPosition = { x: 0, y: 0 };\n        mouse.mouseupPosition = { x: 0, y: 0 };\n        mouse.offset = { x: 0, y: 0 };\n        mouse.scale = { x: 1, y: 1 };\n        mouse.wheelDelta = 0;\n        mouse.button = -1;\n        mouse.pixelRatio = parseInt(mouse.element.getAttribute('data-pixel-ratio'), 10) || 1;\n\n        mouse.sourceEvents = {\n            mousemove: null,\n            mousedown: null,\n            mouseup: null,\n            mousewheel: null\n        };\n        \n        mouse.mousemove = function(event) { \n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                mouse.button = 0;\n                event.preventDefault();\n            }\n\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.sourceEvents.mousemove = event;\n        };\n        \n        mouse.mousedown = function(event) {\n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                mouse.button = 0;\n                event.preventDefault();\n            } else {\n                mouse.button = event.button;\n            }\n\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.mousedownPosition.x = mouse.position.x;\n            mouse.mousedownPosition.y = mouse.position.y;\n            mouse.sourceEvents.mousedown = event;\n        };\n        \n        mouse.mouseup = function(event) {\n            var position = Mouse._getRelativeMousePosition(event, mouse.element, mouse.pixelRatio),\n                touches = event.changedTouches;\n\n            if (touches) {\n                event.preventDefault();\n            }\n            \n            mouse.button = -1;\n            mouse.absolute.x = position.x;\n            mouse.absolute.y = position.y;\n            mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n            mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n            mouse.mouseupPosition.x = mouse.position.x;\n            mouse.mouseupPosition.y = mouse.position.y;\n            mouse.sourceEvents.mouseup = event;\n        };\n\n        mouse.mousewheel = function(event) {\n            mouse.wheelDelta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail));\n            event.preventDefault();\n            mouse.sourceEvents.mousewheel = event;\n        };\n\n        Mouse.setElement(mouse, mouse.element);\n\n        return mouse;\n    };\n\n    /**\n     * Sets the element the mouse is bound to (and relative to).\n     * @method setElement\n     * @param {mouse} mouse\n     * @param {HTMLElement} element\n     */\n    Mouse.setElement = function(mouse, element) {\n        mouse.element = element;\n\n        element.addEventListener('mousemove', mouse.mousemove, { passive: true });\n        element.addEventListener('mousedown', mouse.mousedown, { passive: true });\n        element.addEventListener('mouseup', mouse.mouseup, { passive: true });\n        \n        element.addEventListener('wheel', mouse.mousewheel, { passive: false });\n        \n        element.addEventListener('touchmove', mouse.mousemove, { passive: false });\n        element.addEventListener('touchstart', mouse.mousedown, { passive: false });\n        element.addEventListener('touchend', mouse.mouseup, { passive: false });\n    };\n\n    /**\n     * Clears all captured source events.\n     * @method clearSourceEvents\n     * @param {mouse} mouse\n     */\n    Mouse.clearSourceEvents = function(mouse) {\n        mouse.sourceEvents.mousemove = null;\n        mouse.sourceEvents.mousedown = null;\n        mouse.sourceEvents.mouseup = null;\n        mouse.sourceEvents.mousewheel = null;\n        mouse.wheelDelta = 0;\n    };\n\n    /**\n     * Sets the mouse position offset.\n     * @method setOffset\n     * @param {mouse} mouse\n     * @param {vector} offset\n     */\n    Mouse.setOffset = function(mouse, offset) {\n        mouse.offset.x = offset.x;\n        mouse.offset.y = offset.y;\n        mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n        mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n    };\n\n    /**\n     * Sets the mouse position scale.\n     * @method setScale\n     * @param {mouse} mouse\n     * @param {vector} scale\n     */\n    Mouse.setScale = function(mouse, scale) {\n        mouse.scale.x = scale.x;\n        mouse.scale.y = scale.y;\n        mouse.position.x = mouse.absolute.x * mouse.scale.x + mouse.offset.x;\n        mouse.position.y = mouse.absolute.y * mouse.scale.y + mouse.offset.y;\n    };\n    \n    /**\n     * Gets the mouse position relative to an element given a screen pixel ratio.\n     * @method _getRelativeMousePosition\n     * @private\n     * @param {} event\n     * @param {} element\n     * @param {number} pixelRatio\n     * @return {}\n     */\n    Mouse._getRelativeMousePosition = function(event, element, pixelRatio) {\n        var elementBounds = element.getBoundingClientRect(),\n            rootNode = (document.documentElement || document.body.parentNode || document.body),\n            scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset : rootNode.scrollLeft,\n            scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset : rootNode.scrollTop,\n            touches = event.changedTouches,\n            x, y;\n        \n        if (touches) {\n            x = touches[0].pageX - elementBounds.left - scrollX;\n            y = touches[0].pageY - elementBounds.top - scrollY;\n        } else {\n            x = event.pageX - elementBounds.left - scrollX;\n            y = event.pageY - elementBounds.top - scrollY;\n        }\n\n        return { \n            x: x / (element.clientWidth / (element.width || element.clientWidth) * pixelRatio),\n            y: y / (element.clientHeight / (element.height || element.clientHeight) * pixelRatio)\n        };\n    };\n\n})();\n"
  },
  {
    "path": "src/core/Plugin.js",
    "content": "/**\n* The `Matter.Plugin` module contains functions for registering and installing plugins on modules.\n*\n* @class Plugin\n*/\n\nvar Plugin = {};\n\nmodule.exports = Plugin;\n\nvar Common = require('./Common');\n\n(function() {\n\n    Plugin._registry = {};\n\n    /**\n     * Registers a plugin object so it can be resolved later by name.\n     * @method register\n     * @param plugin {} The plugin to register.\n     * @return {object} The plugin.\n     */\n    Plugin.register = function(plugin) {\n        if (!Plugin.isPlugin(plugin)) {\n            Common.warn('Plugin.register:', Plugin.toString(plugin), 'does not implement all required fields.');\n        }\n\n        if (plugin.name in Plugin._registry) {\n            var registered = Plugin._registry[plugin.name],\n                pluginVersion = Plugin.versionParse(plugin.version).number,\n                registeredVersion = Plugin.versionParse(registered.version).number;\n\n            if (pluginVersion > registeredVersion) {\n                Common.warn('Plugin.register:', Plugin.toString(registered), 'was upgraded to', Plugin.toString(plugin));\n                Plugin._registry[plugin.name] = plugin;\n            } else if (pluginVersion < registeredVersion) {\n                Common.warn('Plugin.register:', Plugin.toString(registered), 'can not be downgraded to', Plugin.toString(plugin));\n            } else if (plugin !== registered) {\n                Common.warn('Plugin.register:', Plugin.toString(plugin), 'is already registered to different plugin object');\n            }\n        } else {\n            Plugin._registry[plugin.name] = plugin;\n        }\n\n        return plugin;\n    };\n\n    /**\n     * Resolves a dependency to a plugin object from the registry if it exists. \n     * The `dependency` may contain a version, but only the name matters when resolving.\n     * @method resolve\n     * @param dependency {string} The dependency.\n     * @return {object} The plugin if resolved, otherwise `undefined`.\n     */\n    Plugin.resolve = function(dependency) {\n        return Plugin._registry[Plugin.dependencyParse(dependency).name];\n    };\n\n    /**\n     * Returns a pretty printed plugin name and version.\n     * @method toString\n     * @param plugin {} The plugin.\n     * @return {string} Pretty printed plugin name and version.\n     */\n    Plugin.toString = function(plugin) {\n        return typeof plugin === 'string' ? plugin : (plugin.name || 'anonymous') + '@' + (plugin.version || plugin.range || '0.0.0');\n    };\n\n    /**\n     * Returns `true` if the object meets the minimum standard to be considered a plugin.\n     * This means it must define the following properties:\n     * - `name`\n     * - `version`\n     * - `install`\n     * @method isPlugin\n     * @param obj {} The obj to test.\n     * @return {boolean} `true` if the object can be considered a plugin otherwise `false`.\n     */\n    Plugin.isPlugin = function(obj) {\n        return obj && obj.name && obj.version && obj.install;\n    };\n\n    /**\n     * Returns `true` if a plugin with the given `name` been installed on `module`.\n     * @method isUsed\n     * @param module {} The module.\n     * @param name {string} The plugin name.\n     * @return {boolean} `true` if a plugin with the given `name` been installed on `module`, otherwise `false`.\n     */\n    Plugin.isUsed = function(module, name) {\n        return module.used.indexOf(name) > -1;\n    };\n\n    /**\n     * Returns `true` if `plugin.for` is applicable to `module` by comparing against `module.name` and `module.version`.\n     * If `plugin.for` is not specified then it is assumed to be applicable.\n     * The value of `plugin.for` is a string of the format `'module-name'` or `'module-name@version'`.\n     * @method isFor\n     * @param plugin {} The plugin.\n     * @param module {} The module.\n     * @return {boolean} `true` if `plugin.for` is applicable to `module`, otherwise `false`.\n     */\n    Plugin.isFor = function(plugin, module) {\n        var parsed = plugin.for && Plugin.dependencyParse(plugin.for);\n        return !plugin.for || (module.name === parsed.name && Plugin.versionSatisfies(module.version, parsed.range));\n    };\n\n    /**\n     * Installs the plugins by calling `plugin.install` on each plugin specified in `plugins` if passed, otherwise `module.uses`.\n     * For installing plugins on `Matter` see the convenience function `Matter.use`.\n     * Plugins may be specified either by their name or a reference to the plugin object.\n     * Plugins themselves may specify further dependencies, but each plugin is installed only once.\n     * Order is important, a topological sort is performed to find the best resulting order of installation.\n     * This sorting attempts to satisfy every dependency's requested ordering, but may not be exact in all cases.\n     * This function logs the resulting status of each dependency in the console, along with any warnings.\n     * - A green tick ✅ indicates a dependency was resolved and installed.\n     * - An orange diamond 🔶 indicates a dependency was resolved but a warning was thrown for it or one if its dependencies.\n     * - A red cross ❌ indicates a dependency could not be resolved.\n     * Avoid calling this function multiple times on the same module unless you intend to manually control installation order.\n     * @method use\n     * @param module {} The module install plugins on.\n     * @param [plugins=module.uses] {} The plugins to install on module (optional, defaults to `module.uses`).\n     */\n    Plugin.use = function(module, plugins) {\n        module.uses = (module.uses || []).concat(plugins || []);\n\n        if (module.uses.length === 0) {\n            Common.warn('Plugin.use:', Plugin.toString(module), 'does not specify any dependencies to install.');\n            return;\n        }\n\n        var dependencies = Plugin.dependencies(module),\n            sortedDependencies = Common.topologicalSort(dependencies),\n            status = [];\n\n        for (var i = 0; i < sortedDependencies.length; i += 1) {\n            if (sortedDependencies[i] === module.name) {\n                continue;\n            }\n\n            var plugin = Plugin.resolve(sortedDependencies[i]);\n\n            if (!plugin) {\n                status.push('❌ ' + sortedDependencies[i]);\n                continue;\n            }\n\n            if (Plugin.isUsed(module, plugin.name)) {\n                continue;\n            }\n\n            if (!Plugin.isFor(plugin, module)) {\n                Common.warn('Plugin.use:', Plugin.toString(plugin), 'is for', plugin.for, 'but installed on', Plugin.toString(module) + '.');\n                plugin._warned = true;\n            }\n\n            if (plugin.install) {\n                plugin.install(module);\n            } else {\n                Common.warn('Plugin.use:', Plugin.toString(plugin), 'does not specify an install function.');\n                plugin._warned = true;\n            }\n\n            if (plugin._warned) {\n                status.push('🔶 ' + Plugin.toString(plugin));\n                delete plugin._warned;\n            } else {\n                status.push('✅ ' + Plugin.toString(plugin));\n            }\n\n            module.used.push(plugin.name);\n        }\n\n        if (status.length > 0) {\n            Common.info(status.join('  '));\n        }\n    };\n\n    /**\n     * Recursively finds all of a module's dependencies and returns a flat dependency graph.\n     * @method dependencies\n     * @param module {} The module.\n     * @return {object} A dependency graph.\n     */\n    Plugin.dependencies = function(module, tracked) {\n        var parsedBase = Plugin.dependencyParse(module),\n            name = parsedBase.name;\n\n        tracked = tracked || {};\n\n        if (name in tracked) {\n            return;\n        }\n\n        module = Plugin.resolve(module) || module;\n\n        tracked[name] = Common.map(module.uses || [], function(dependency) {\n            if (Plugin.isPlugin(dependency)) {\n                Plugin.register(dependency);\n            }\n\n            var parsed = Plugin.dependencyParse(dependency),\n                resolved = Plugin.resolve(dependency);\n\n            if (resolved && !Plugin.versionSatisfies(resolved.version, parsed.range)) {\n                Common.warn(\n                    'Plugin.dependencies:', Plugin.toString(resolved), 'does not satisfy',\n                    Plugin.toString(parsed), 'used by', Plugin.toString(parsedBase) + '.'\n                );\n\n                resolved._warned = true;\n                module._warned = true;\n            } else if (!resolved) {\n                Common.warn(\n                    'Plugin.dependencies:', Plugin.toString(dependency), 'used by',\n                    Plugin.toString(parsedBase), 'could not be resolved.'\n                );\n\n                module._warned = true;\n            }\n\n            return parsed.name;\n        });\n\n        for (var i = 0; i < tracked[name].length; i += 1) {\n            Plugin.dependencies(tracked[name][i], tracked);\n        }\n\n        return tracked;\n    };\n\n    /**\n     * Parses a dependency string into its components.\n     * The `dependency` is a string of the format `'module-name'` or `'module-name@version'`.\n     * See documentation for `Plugin.versionParse` for a description of the format.\n     * This function can also handle dependencies that are already resolved (e.g. a module object).\n     * @method dependencyParse\n     * @param dependency {string} The dependency of the format `'module-name'` or `'module-name@version'`.\n     * @return {object} The dependency parsed into its components.\n     */\n    Plugin.dependencyParse = function(dependency) {\n        if (Common.isString(dependency)) {\n            var pattern = /^[\\w-]+(@(\\*|[\\^~]?\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z-+]+)?))?$/;\n\n            if (!pattern.test(dependency)) {\n                Common.warn('Plugin.dependencyParse:', dependency, 'is not a valid dependency string.');\n            }\n\n            return {\n                name: dependency.split('@')[0],\n                range: dependency.split('@')[1] || '*'\n            };\n        }\n\n        return {\n            name: dependency.name,\n            range: dependency.range || dependency.version\n        };\n    };\n\n    /**\n     * Parses a version string into its components.  \n     * Versions are strictly of the format `x.y.z` (as in [semver](http://semver.org/)).\n     * Versions may optionally have a prerelease tag in the format `x.y.z-alpha`.\n     * Ranges are a strict subset of [npm ranges](https://docs.npmjs.com/misc/semver#advanced-range-syntax).\n     * Only the following range types are supported:\n     * - Tilde ranges e.g. `~1.2.3`\n     * - Caret ranges e.g. `^1.2.3`\n     * - Greater than ranges e.g. `>1.2.3`\n     * - Greater than or equal ranges e.g. `>=1.2.3`\n     * - Exact version e.g. `1.2.3`\n     * - Any version `*`\n     * @method versionParse\n     * @param range {string} The version string.\n     * @return {object} The version range parsed into its components.\n     */\n    Plugin.versionParse = function(range) {\n        var pattern = /^(\\*)|(\\^|~|>=|>)?\\s*((\\d+)\\.(\\d+)\\.(\\d+))(-[0-9A-Za-z-+]+)?$/;\n\n        if (!pattern.test(range)) {\n            Common.warn('Plugin.versionParse:', range, 'is not a valid version or range.');\n        }\n\n        var parts = pattern.exec(range);\n        var major = Number(parts[4]);\n        var minor = Number(parts[5]);\n        var patch = Number(parts[6]);\n\n        return {\n            isRange: Boolean(parts[1] || parts[2]),\n            version: parts[3],\n            range: range,\n            operator: parts[1] || parts[2] || '',\n            major: major,\n            minor: minor,\n            patch: patch,\n            parts: [major, minor, patch],\n            prerelease: parts[7],\n            number: major * 1e8 + minor * 1e4 + patch\n        };\n    };\n\n    /**\n     * Returns `true` if `version` satisfies the given `range`.\n     * See documentation for `Plugin.versionParse` for a description of the format.\n     * If a version or range is not specified, then any version (`*`) is assumed to satisfy.\n     * @method versionSatisfies\n     * @param version {string} The version string.\n     * @param range {string} The range string.\n     * @return {boolean} `true` if `version` satisfies `range`, otherwise `false`.\n     */\n    Plugin.versionSatisfies = function(version, range) {\n        range = range || '*';\n\n        var r = Plugin.versionParse(range),\n            v = Plugin.versionParse(version);\n\n        if (r.isRange) {\n            if (r.operator === '*' || version === '*') {\n                return true;\n            }\n\n            if (r.operator === '>') {\n                return v.number > r.number;\n            }\n\n            if (r.operator === '>=') {\n                return v.number >= r.number;\n            }\n\n            if (r.operator === '~') {\n                return v.major === r.major && v.minor === r.minor && v.patch >= r.patch;\n            }\n\n            if (r.operator === '^') {\n                if (r.major > 0) {\n                    return v.major === r.major && v.number >= r.number;\n                }\n\n                if (r.minor > 0) {\n                    return v.minor === r.minor && v.patch >= r.patch;\n                }\n\n                return v.patch === r.patch;\n            }\n        }\n\n        return version === range || version === '*';\n    };\n\n})();\n"
  },
  {
    "path": "src/core/Runner.js",
    "content": "/**\n* The `Matter.Runner` module is an optional utility that provides a game loop for running a `Matter.Engine` inside a browser environment.\n* A runner will continuously update a `Matter.Engine` whilst synchronising engine updates with the browser frame rate.\n* This runner favours a smoother user experience over perfect time keeping.\n* This runner is optional and is used for development and debugging but could be useful as a starting point for implementing some games and experiences.\n* Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation as may be needed inside other environments.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Runner\n*/\n\nvar Runner = {};\n\nmodule.exports = Runner;\n\nvar Events = require('./Events');\nvar Engine = require('./Engine');\nvar Common = require('./Common');\n\n(function() {\n\n    Runner._maxFrameDelta = 1000 / 15;\n    Runner._frameDeltaFallback = 1000 / 60;\n    Runner._timeBufferMargin = 1.5;\n    Runner._elapsedNextEstimate = 1;\n    Runner._smoothingLowerBound = 0.1;\n    Runner._smoothingUpperBound = 0.9;\n\n    /**\n     * Creates a new Runner. \n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {} options\n     */\n    Runner.create = function(options) {\n        var defaults = {\n            delta: 1000 / 60,\n            frameDelta: null,\n            frameDeltaSmoothing: true,\n            frameDeltaSnapping: true,\n            frameDeltaHistory: [],\n            frameDeltaHistorySize: 100,\n            frameRequestId: null,\n            timeBuffer: 0,\n            timeLastTick: null,\n            maxUpdates: null,\n            maxFrameTime: 1000 / 30,\n            lastUpdatesDeferred: 0,\n            enabled: true\n        };\n\n        var runner = Common.extend(defaults, options);\n\n        // for temporary back compatibility only\n        runner.fps = 0;\n\n        return runner;\n    };\n\n    /**\n     * Runs a `Matter.Engine` whilst synchronising engine updates with the browser frame rate. \n     * See module and properties descriptions for more information on this runner.\n     * Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation.\n     * @method run\n     * @param {runner} runner\n     * @param {engine} [engine]\n     * @return {runner} runner\n     */\n    Runner.run = function(runner, engine) {\n        // initial time buffer for the first frame\n        runner.timeBuffer = Runner._frameDeltaFallback;\n\n        (function onFrame(time){\n            runner.frameRequestId = Runner._onNextFrame(runner, onFrame);\n\n            if (time && runner.enabled) {\n                Runner.tick(runner, engine, time);\n            }\n        })();\n\n        return runner;\n    };\n\n    /**\n     * Performs a single runner tick as used inside `Runner.run`.\n     * See module and properties descriptions for more information on this runner.\n     * Alternatively see `Engine.update` to step the engine directly inside your own game loop implementation.\n     * @method tick\n     * @param {runner} runner\n     * @param {engine} engine\n     * @param {number} time\n     */\n    Runner.tick = function(runner, engine, time) {\n        var tickStartTime = Common.now(),\n            engineDelta = runner.delta,\n            updateCount = 0;\n\n        // find frame delta time since last call\n        var frameDelta = time - runner.timeLastTick;\n\n        // fallback for unusable frame delta values (e.g. 0, NaN, on first frame or long pauses)\n        if (!frameDelta || !runner.timeLastTick || frameDelta > Math.max(Runner._maxFrameDelta, runner.maxFrameTime)) {\n            // reuse last accepted frame delta else fallback\n            frameDelta = runner.frameDelta || Runner._frameDeltaFallback;\n        }\n\n        if (runner.frameDeltaSmoothing) {\n            // record frame delta over a number of frames\n            runner.frameDeltaHistory.push(frameDelta);\n            runner.frameDeltaHistory = runner.frameDeltaHistory.slice(-runner.frameDeltaHistorySize);\n\n            // sort frame delta history\n            var deltaHistorySorted = runner.frameDeltaHistory.slice(0).sort();\n\n            // sample a central window to limit outliers\n            var deltaHistoryWindow = runner.frameDeltaHistory.slice(\n                deltaHistorySorted.length * Runner._smoothingLowerBound, \n                deltaHistorySorted.length * Runner._smoothingUpperBound\n            );\n\n            // take the mean of the central window\n            var frameDeltaSmoothed = _mean(deltaHistoryWindow);\n            frameDelta = frameDeltaSmoothed || frameDelta;\n        }\n\n        if (runner.frameDeltaSnapping) {\n            // snap frame delta to the nearest 1 Hz\n            frameDelta = 1000 / Math.round(1000 / frameDelta);\n        }\n\n        // update runner values for next call\n        runner.frameDelta = frameDelta;\n        runner.timeLastTick = time;\n\n        // accumulate elapsed time\n        runner.timeBuffer += runner.frameDelta;\n\n        // limit time buffer size to a single frame of updates\n        runner.timeBuffer = Common.clamp(\n            runner.timeBuffer, 0, runner.frameDelta + engineDelta * Runner._timeBufferMargin\n        );\n\n        // reset count of over budget updates\n        runner.lastUpdatesDeferred = 0;\n\n        // get max updates per frame\n        var maxUpdates = runner.maxUpdates || Math.ceil(runner.maxFrameTime / engineDelta);\n\n        // create event object\n        var event = {\n            timestamp: engine.timing.timestamp\n        };\n\n        // tick events before update\n        Events.trigger(runner, 'beforeTick', event);\n        Events.trigger(runner, 'tick', event);\n\n        var updateStartTime = Common.now();\n\n        // simulate time elapsed between calls\n        while (engineDelta > 0 && runner.timeBuffer >= engineDelta * Runner._timeBufferMargin) {\n            // update the engine\n            Events.trigger(runner, 'beforeUpdate', event);\n            Engine.update(engine, engineDelta);\n            Events.trigger(runner, 'afterUpdate', event);\n\n            // consume time simulated from buffer\n            runner.timeBuffer -= engineDelta;\n            updateCount += 1;\n\n            // find elapsed time during this tick\n            var elapsedTimeTotal = Common.now() - tickStartTime,\n                elapsedTimeUpdates = Common.now() - updateStartTime,\n                elapsedNextEstimate = elapsedTimeTotal + Runner._elapsedNextEstimate * elapsedTimeUpdates / updateCount;\n\n            // defer updates if over performance budgets for this frame\n            if (updateCount >= maxUpdates || elapsedNextEstimate > runner.maxFrameTime) {\n                runner.lastUpdatesDeferred = Math.round(Math.max(0, (runner.timeBuffer / engineDelta) - Runner._timeBufferMargin));\n                break;\n            }\n        }\n\n        // track timing metrics\n        engine.timing.lastUpdatesPerFrame = updateCount;\n\n        // tick events after update\n        Events.trigger(runner, 'afterTick', event);\n\n        // show useful warnings if needed\n        if (runner.frameDeltaHistory.length >= 100) {\n            if (runner.lastUpdatesDeferred && Math.round(runner.frameDelta / engineDelta) > maxUpdates) {\n                Common.warnOnce('Matter.Runner: runner reached runner.maxUpdates, see docs.');\n            } else if (runner.lastUpdatesDeferred) {\n                Common.warnOnce('Matter.Runner: runner reached runner.maxFrameTime, see docs.');\n            }\n\n            if (typeof runner.isFixed !== 'undefined') {\n                Common.warnOnce('Matter.Runner: runner.isFixed is now redundant, see docs.');\n            }\n\n            if (runner.deltaMin || runner.deltaMax) {\n                Common.warnOnce('Matter.Runner: runner.deltaMin and runner.deltaMax were removed, see docs.');\n            }\n\n            if (runner.fps !== 0) {\n                Common.warnOnce('Matter.Runner: runner.fps was replaced by runner.delta, see docs.');\n            }\n        }\n    };\n\n    /**\n     * Ends execution of `Runner.run` on the given `runner` by canceling the frame loop.\n     * Alternatively to temporarily pause the runner, see `runner.enabled`.\n     * @method stop\n     * @param {runner} runner\n     */\n    Runner.stop = function(runner) {\n        Runner._cancelNextFrame(runner);\n    };\n\n    /**\n     * Schedules the `callback` on this `runner` for the next animation frame.\n     * @private\n     * @method _onNextFrame\n     * @param {runner} runner\n     * @param {function} callback\n     * @return {number} frameRequestId\n     */\n    Runner._onNextFrame = function(runner, callback) {\n        if (typeof window !== 'undefined' && window.requestAnimationFrame) {\n            runner.frameRequestId = window.requestAnimationFrame(callback);\n        } else {\n            throw new Error('Matter.Runner: missing required global window.requestAnimationFrame.');\n        }\n\n        return runner.frameRequestId;\n    };\n\n    /**\n     * Cancels the last callback scheduled by `Runner._onNextFrame` on this `runner`.\n     * @private\n     * @method _cancelNextFrame\n     * @param {runner} runner\n     */\n    Runner._cancelNextFrame = function(runner) {\n        if (typeof window !== 'undefined' && window.cancelAnimationFrame) {\n            window.cancelAnimationFrame(runner.frameRequestId);\n        } else {\n            throw new Error('Matter.Runner: missing required global window.cancelAnimationFrame.');\n        }\n    };\n\n    /**\n     * Returns the mean of the given numbers.\n     * @method _mean\n     * @private\n     * @param {Number[]} values\n     * @return {Number} the mean of given values.\n     */\n    var _mean = function(values) {\n        var result = 0,\n            valuesLength = values.length;\n\n        for (var i = 0; i < valuesLength; i += 1) {\n            result += values[i];\n        }\n\n        return (result / valuesLength) || 0;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired once at the start of the browser frame, before any engine updates.\n    *\n    * @event beforeTick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired once at the start of the browser frame, after `beforeTick`.\n    *\n    * @event tick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired once at the end of the browser frame, after `beforeTick`, `tick` and after any engine updates.\n    *\n    * @event afterTick\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired before each and every engine update in this browser frame (if any). \n    * There may be multiple engine update calls per browser frame (or none) depending on framerate and timestep delta.\n    *\n    * @event beforeUpdate\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired after each and every engine update in this browser frame (if any). \n    * There may be multiple engine update calls per browser frame (or none) depending on framerate and timestep delta.\n    *\n    * @event afterUpdate\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * The fixed timestep size used for `Engine.update` calls in milliseconds, known as `delta`.\n     * \n     * This value is recommended to be `1000 / 60` ms or smaller (i.e. equivalent to at least 60hz).\n     * \n     * Smaller `delta` values provide higher quality results at the cost of performance.\n     * \n     * You should usually avoid changing `delta` during running, otherwise quality may be affected. \n     * \n     * For smoother frame pacing choose a `delta` that is an even multiple of each display FPS you target, i.e. `1000 / (n * fps)` as this helps distribute an equal number of updates over each display frame.\n     * \n     * For example with a 60 Hz `delta` i.e. `1000 / 60` the runner will on average perform one update per frame on displays running 60 FPS and one update every two frames on displays running 120 FPS, etc.\n     * \n     * Where as e.g. using a 240 Hz `delta` i.e. `1000 / 240` the runner will on average perform four updates per frame on displays running 60 FPS and two updates per frame on displays running 120 FPS, etc.\n     * \n     * Therefore `Runner.run` will call multiple engine updates (or none) as needed to simulate the time elapsed between browser frames. \n     * \n     * In practice the number of updates in any particular frame may be restricted to respect the runner's performance budgets. These are specified by `runner.maxFrameTime` and `runner.maxUpdates`, see those properties for details.\n     * \n     * @property delta\n     * @type number\n     * @default 1000 / 60\n     */\n\n    /**\n     * A flag that can be toggled to enable or disable tick calls on this runner, therefore pausing engine updates and events while the runner loop remains running.\n     *\n     * @property enabled\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * The accumulated time elapsed that has yet to be simulated in milliseconds.\n     * This value is clamped within certain limits (see `Runner.tick` code).\n     *\n     * @private\n     * @property timeBuffer\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * The measured time elapsed between the last two browser frames measured in milliseconds.\n     * This is useful e.g. to estimate the current browser FPS using `1000 / runner.frameDelta`.\n     *\n     * @readonly\n     * @property frameDelta\n     * @type number\n     */\n\n    /**\n     * Enables averaging to smooth frame rate measurements and therefore stabilise play rate.\n     *\n     * @property frameDeltaSmoothing\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * Rounds measured browser frame delta to the nearest 1 Hz.\n     * This option can help smooth frame rate measurements and simplify handling hardware timing differences e.g. 59.94Hz and 60Hz displays.\n     * For best results you should also round your `runner.delta` equivalent to the nearest 1 Hz.\n     *\n     * @property frameDeltaSnapping\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A performance budget that limits execution time allowed for this runner per browser frame in milliseconds.\n     * \n     * To calculate the effective browser FPS at which this throttle is applied use `1000 / runner.maxFrameTime`.\n     * \n     * This performance budget is intended to help maintain browser interactivity and help improve framerate recovery during temporary high CPU usage.\n     * \n     * This budget only covers the measured time elapsed executing the functions called in the scope of the runner tick, including `Engine.update` and its related user event callbacks.\n     * \n     * You may also reduce this budget to allow for any significant additional processing you perform on the same thread outside the scope of this runner tick, e.g. rendering time.\n     * \n     * See also `runner.maxUpdates`.\n     *\n     * @property maxFrameTime\n     * @type number\n     * @default 1000 / 30\n     */\n\n    /**\n     * An optional limit for maximum engine update count allowed per frame tick in addition to `runner.maxFrameTime`.\n     * \n     * Unless you set a value it is automatically chosen based on `runner.delta` and `runner.maxFrameTime`.\n     * \n     * See also `runner.maxFrameTime`.\n     * \n     * @property maxUpdates\n     * @type number\n     * @default null\n     */\n\n    /**\n     * The timestamp of the last call to `Runner.tick` used to measure `frameDelta`.\n     *\n     * @private\n     * @property timeLastTick\n     * @type number\n     * @default 0\n     */\n\n    /**\n     * The id of the last call to `Runner._onNextFrame`.\n     *\n     * @private\n     * @property frameRequestId\n     * @type number\n     * @default null\n     */\n\n})();\n"
  },
  {
    "path": "src/core/Sleeping.js",
    "content": "/**\n* The `Matter.Sleeping` module contains methods to manage the sleeping state of bodies.\n*\n* @class Sleeping\n*/\n\nvar Sleeping = {};\n\nmodule.exports = Sleeping;\n\nvar Body = require('../body/Body');\nvar Events = require('./Events');\nvar Common = require('./Common');\n\n(function() {\n\n    Sleeping._motionWakeThreshold = 0.18;\n    Sleeping._motionSleepThreshold = 0.08;\n    Sleeping._minBias = 0.9;\n\n    /**\n     * Puts bodies to sleep or wakes them up depending on their motion.\n     * @method update\n     * @param {body[]} bodies\n     * @param {number} delta\n     */\n    Sleeping.update = function(bodies, delta) {\n        var timeScale = delta / Common._baseDelta,\n            motionSleepThreshold = Sleeping._motionSleepThreshold;\n        \n        // update bodies sleeping status\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                speed = Body.getSpeed(body),\n                angularSpeed = Body.getAngularSpeed(body),\n                motion = speed * speed + angularSpeed * angularSpeed;\n\n            // wake up bodies if they have a force applied\n            if (body.force.x !== 0 || body.force.y !== 0) {\n                Sleeping.set(body, false);\n                continue;\n            }\n\n            var minMotion = Math.min(body.motion, motion),\n                maxMotion = Math.max(body.motion, motion);\n        \n            // biased average motion estimation between frames\n            body.motion = Sleeping._minBias * minMotion + (1 - Sleeping._minBias) * maxMotion;\n\n            if (body.sleepThreshold > 0 && body.motion < motionSleepThreshold) {\n                body.sleepCounter += 1;\n                \n                if (body.sleepCounter >= body.sleepThreshold / timeScale) {\n                    Sleeping.set(body, true);\n                }\n            } else if (body.sleepCounter > 0) {\n                body.sleepCounter -= 1;\n            }\n        }\n    };\n\n    /**\n     * Given a set of colliding pairs, wakes the sleeping bodies involved.\n     * @method afterCollisions\n     * @param {pair[]} pairs\n     */\n    Sleeping.afterCollisions = function(pairs) {\n        var motionSleepThreshold = Sleeping._motionSleepThreshold;\n\n        // wake up bodies involved in collisions\n        for (var i = 0; i < pairs.length; i++) {\n            var pair = pairs[i];\n            \n            // don't wake inactive pairs\n            if (!pair.isActive)\n                continue;\n\n            var collision = pair.collision,\n                bodyA = collision.bodyA.parent, \n                bodyB = collision.bodyB.parent;\n        \n            // don't wake if at least one body is static\n            if ((bodyA.isSleeping && bodyB.isSleeping) || bodyA.isStatic || bodyB.isStatic)\n                continue;\n        \n            if (bodyA.isSleeping || bodyB.isSleeping) {\n                var sleepingBody = (bodyA.isSleeping && !bodyA.isStatic) ? bodyA : bodyB,\n                    movingBody = sleepingBody === bodyA ? bodyB : bodyA;\n\n                if (!sleepingBody.isStatic && movingBody.motion > motionSleepThreshold) {\n                    Sleeping.set(sleepingBody, false);\n                }\n            }\n        }\n    };\n  \n    /**\n     * Set a body as sleeping or awake.\n     * @method set\n     * @param {body} body\n     * @param {boolean} isSleeping\n     */\n    Sleeping.set = function(body, isSleeping) {\n        var wasSleeping = body.isSleeping;\n\n        if (isSleeping) {\n            body.isSleeping = true;\n            body.sleepCounter = body.sleepThreshold;\n\n            body.positionImpulse.x = 0;\n            body.positionImpulse.y = 0;\n\n            body.positionPrev.x = body.position.x;\n            body.positionPrev.y = body.position.y;\n\n            body.anglePrev = body.angle;\n            body.speed = 0;\n            body.angularSpeed = 0;\n            body.motion = 0;\n\n            if (!wasSleeping) {\n                Events.trigger(body, 'sleepStart');\n            }\n        } else {\n            body.isSleeping = false;\n            body.sleepCounter = 0;\n\n            if (wasSleeping) {\n                Events.trigger(body, 'sleepEnd');\n            }\n        }\n    };\n\n})();\n"
  },
  {
    "path": "src/factory/Bodies.js",
    "content": "/**\n* The `Matter.Bodies` module contains factory methods for creating rigid body models \n* with commonly used body configurations (such as rectangles, circles and other polygons).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Bodies\n*/\n\n// TODO: true circle bodies\n\nvar Bodies = {};\n\nmodule.exports = Bodies;\n\nvar Vertices = require('../geometry/Vertices');\nvar Common = require('../core/Common');\nvar Body = require('../body/Body');\nvar Bounds = require('../geometry/Bounds');\nvar Vector = require('../geometry/Vector');\n\n(function() {\n\n    /**\n     * Creates a new rigid body model with a rectangle hull. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method rectangle\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {object} [options]\n     * @return {body} A new rectangle body\n     */\n    Bodies.rectangle = function(x, y, width, height, options) {\n        options = options || {};\n\n        var rectangle = { \n            label: 'Rectangle Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath('L 0 0 L ' + width + ' 0 L ' + width + ' ' + height + ' L 0 ' + height)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            rectangle.vertices = Vertices.chamfer(rectangle.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, rectangle, options));\n    };\n    \n    /**\n     * Creates a new rigid body model with a trapezoid hull. \n     * The `slope` is parameterised as a fraction of `width` and must be < 1 to form a valid trapezoid. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method trapezoid\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {number} slope Must be a number < 1.\n     * @param {object} [options]\n     * @return {body} A new trapezoid body\n     */\n    Bodies.trapezoid = function(x, y, width, height, slope, options) {\n        options = options || {};\n\n        if (slope >= 1) {\n            Common.warn('Bodies.trapezoid: slope parameter must be < 1.');\n        }\n\n        slope *= 0.5;\n        var roof = (1 - (slope * 2)) * width;\n        \n        var x1 = width * slope,\n            x2 = x1 + roof,\n            x3 = x2 + x1,\n            verticesPath;\n\n        if (slope < 0.5) {\n            verticesPath = 'L 0 0 L ' + x1 + ' ' + (-height) + ' L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';\n        } else {\n            verticesPath = 'L 0 0 L ' + x2 + ' ' + (-height) + ' L ' + x3 + ' 0';\n        }\n\n        var trapezoid = { \n            label: 'Trapezoid Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath(verticesPath)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            trapezoid.vertices = Vertices.chamfer(trapezoid.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, trapezoid, options));\n    };\n\n    /**\n     * Creates a new rigid body model with a circle hull. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method circle\n     * @param {number} x\n     * @param {number} y\n     * @param {number} radius\n     * @param {object} [options]\n     * @param {number} [maxSides]\n     * @return {body} A new circle body\n     */\n    Bodies.circle = function(x, y, radius, options, maxSides) {\n        options = options || {};\n\n        var circle = {\n            label: 'Circle Body',\n            circleRadius: radius\n        };\n        \n        // approximate circles with polygons until true circles implemented in SAT\n        maxSides = maxSides || 25;\n        var sides = Math.ceil(Math.max(10, Math.min(maxSides, radius)));\n\n        // optimisation: always use even number of sides (half the number of unique axes)\n        if (sides % 2 === 1)\n            sides += 1;\n\n        return Bodies.polygon(x, y, sides, radius, Common.extend({}, circle, options));\n    };\n\n    /**\n     * Creates a new rigid body model with a regular polygon hull with the given number of sides. \n     * The options parameter is an object that specifies any properties you wish to override the defaults.\n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method polygon\n     * @param {number} x\n     * @param {number} y\n     * @param {number} sides\n     * @param {number} radius\n     * @param {object} [options]\n     * @return {body} A new regular polygon body\n     */\n    Bodies.polygon = function(x, y, sides, radius, options) {\n        options = options || {};\n\n        if (sides < 3)\n            return Bodies.circle(x, y, radius, options);\n\n        var theta = 2 * Math.PI / sides,\n            path = '',\n            offset = theta * 0.5;\n\n        for (var i = 0; i < sides; i += 1) {\n            var angle = offset + (i * theta),\n                xx = Math.cos(angle) * radius,\n                yy = Math.sin(angle) * radius;\n\n            path += 'L ' + xx.toFixed(3) + ' ' + yy.toFixed(3) + ' ';\n        }\n\n        var polygon = { \n            label: 'Polygon Body',\n            position: { x: x, y: y },\n            vertices: Vertices.fromPath(path)\n        };\n\n        if (options.chamfer) {\n            var chamfer = options.chamfer;\n            polygon.vertices = Vertices.chamfer(polygon.vertices, chamfer.radius, \n                chamfer.quality, chamfer.qualityMin, chamfer.qualityMax);\n            delete options.chamfer;\n        }\n\n        return Body.create(Common.extend({}, polygon, options));\n    };\n\n    /**\n     * Utility to create a compound body based on set(s) of vertices.\n     * \n     * _Note:_ To optionally enable automatic concave vertices decomposition the [poly-decomp](https://github.com/schteppe/poly-decomp.js) \n     * package must be first installed and provided see `Common.setDecomp`, otherwise the convex hull of each vertex set will be used.\n     * \n     * The resulting vertices are reorientated about their centre of mass,\n     * and offset such that `body.position` corresponds to this point.\n     * \n     * The resulting offset may be found if needed by subtracting `body.bounds` from the original input bounds.\n     * To later move the centre of mass see `Body.setCentre`.\n     * \n     * Note that automatic conconcave decomposition results are not always optimal. \n     * For best results, simplify the input vertices as much as possible first.\n     * By default this function applies some addtional simplification to help.\n     * \n     * Some outputs may also require further manual processing afterwards to be robust.\n     * In particular some parts may need to be overlapped to avoid collision gaps.\n     * Thin parts and sharp points should be avoided or removed where possible.\n     *\n     * The options parameter object specifies any `Matter.Body` properties you wish to override the defaults.\n     * \n     * See the properties section of the `Matter.Body` module for detailed information on what you can pass via the `options` object.\n     * @method fromVertices\n     * @param {number} x\n     * @param {number} y\n     * @param {array} vertexSets One or more arrays of vertex points e.g. `[[{ x: 0, y: 0 }...], ...]`.\n     * @param {object} [options] The body options.\n     * @param {bool} [flagInternal=false] Optionally marks internal edges with `isInternal`.\n     * @param {number} [removeCollinear=0.01] Threshold when simplifying vertices along the same edge.\n     * @param {number} [minimumArea=10] Threshold when removing small parts.\n     * @param {number} [removeDuplicatePoints=0.01] Threshold when simplifying nearby vertices.\n     * @return {body}\n     */\n    Bodies.fromVertices = function(x, y, vertexSets, options, flagInternal, removeCollinear, minimumArea, removeDuplicatePoints) {\n        var decomp = Common.getDecomp(),\n            canDecomp,\n            body,\n            parts,\n            isConvex,\n            isConcave,\n            vertices,\n            i,\n            j,\n            k,\n            v,\n            z;\n\n        // check decomp is as expected\n        canDecomp = Boolean(decomp && decomp.quickDecomp);\n\n        options = options || {};\n        parts = [];\n\n        flagInternal = typeof flagInternal !== 'undefined' ? flagInternal : false;\n        removeCollinear = typeof removeCollinear !== 'undefined' ? removeCollinear : 0.01;\n        minimumArea = typeof minimumArea !== 'undefined' ? minimumArea : 10;\n        removeDuplicatePoints = typeof removeDuplicatePoints !== 'undefined' ? removeDuplicatePoints : 0.01;\n\n        // ensure vertexSets is an array of arrays\n        if (!Common.isArray(vertexSets[0])) {\n            vertexSets = [vertexSets];\n        }\n\n        for (v = 0; v < vertexSets.length; v += 1) {\n            vertices = vertexSets[v];\n            isConvex = Vertices.isConvex(vertices);\n            isConcave = !isConvex;\n\n            if (isConcave && !canDecomp) {\n                Common.warnOnce(\n                    'Bodies.fromVertices: Install the \\'poly-decomp\\' library and use Common.setDecomp or provide \\'decomp\\' as a global to decompose concave vertices.'\n                );\n            }\n\n            if (isConvex || !canDecomp) {\n                if (isConvex) {\n                    vertices = Vertices.clockwiseSort(vertices);\n                } else {\n                    // fallback to convex hull when decomposition is not possible\n                    vertices = Vertices.hull(vertices);\n                }\n\n                parts.push({\n                    position: { x: x, y: y },\n                    vertices: vertices\n                });\n            } else {\n                // initialise a decomposition\n                var concave = vertices.map(function(vertex) {\n                    return [vertex.x, vertex.y];\n                });\n\n                // vertices are concave and simple, we can decompose into parts\n                decomp.makeCCW(concave);\n                if (removeCollinear !== false)\n                    decomp.removeCollinearPoints(concave, removeCollinear);\n                if (removeDuplicatePoints !== false && decomp.removeDuplicatePoints)\n                    decomp.removeDuplicatePoints(concave, removeDuplicatePoints);\n\n                // use the quick decomposition algorithm (Bayazit)\n                var decomposed = decomp.quickDecomp(concave);\n\n                // for each decomposed chunk\n                for (i = 0; i < decomposed.length; i++) {\n                    var chunk = decomposed[i];\n\n                    // convert vertices into the correct structure\n                    var chunkVertices = chunk.map(function(vertices) {\n                        return {\n                            x: vertices[0],\n                            y: vertices[1]\n                        };\n                    });\n\n                    // skip small chunks\n                    if (minimumArea > 0 && Vertices.area(chunkVertices) < minimumArea)\n                        continue;\n\n                    // create a compound part\n                    parts.push({\n                        position: Vertices.centre(chunkVertices),\n                        vertices: chunkVertices\n                    });\n                }\n            }\n        }\n\n        // create body parts\n        for (i = 0; i < parts.length; i++) {\n            parts[i] = Body.create(Common.extend(parts[i], options));\n        }\n\n        // flag internal edges (coincident part edges)\n        if (flagInternal) {\n            var coincident_max_dist = 5;\n\n            for (i = 0; i < parts.length; i++) {\n                var partA = parts[i];\n\n                for (j = i + 1; j < parts.length; j++) {\n                    var partB = parts[j];\n\n                    if (Bounds.overlaps(partA.bounds, partB.bounds)) {\n                        var pav = partA.vertices,\n                            pbv = partB.vertices;\n\n                        // iterate vertices of both parts\n                        for (k = 0; k < partA.vertices.length; k++) {\n                            for (z = 0; z < partB.vertices.length; z++) {\n                                // find distances between the vertices\n                                var da = Vector.magnitudeSquared(Vector.sub(pav[(k + 1) % pav.length], pbv[z])),\n                                    db = Vector.magnitudeSquared(Vector.sub(pav[k], pbv[(z + 1) % pbv.length]));\n\n                                // if both vertices are very close, consider the edge concident (internal)\n                                if (da < coincident_max_dist && db < coincident_max_dist) {\n                                    pav[k].isInternal = true;\n                                    pbv[z].isInternal = true;\n                                }\n                            }\n                        }\n\n                    }\n                }\n            }\n        }\n\n        if (parts.length > 1) {\n            // create the parent body to be returned, that contains generated compound parts\n            body = Body.create(Common.extend({ parts: parts.slice(0) }, options));\n\n            // offset such that body.position is at the centre off mass\n            Body.setPosition(body, { x: x, y: y });\n\n            return body;\n        } else {\n            return parts[0];\n        }\n    };\n\n})();\n"
  },
  {
    "path": "src/factory/Composites.js",
    "content": "/**\n* The `Matter.Composites` module contains factory methods for creating composite bodies\n* with commonly used configurations (such as stacks and chains).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Composites\n*/\n\nvar Composites = {};\n\nmodule.exports = Composites;\n\nvar Composite = require('../body/Composite');\nvar Constraint = require('../constraint/Constraint');\nvar Common = require('../core/Common');\nvar Body = require('../body/Body');\nvar Bodies = require('./Bodies');\nvar deprecated = Common.deprecated;\n\n(function() {\n\n    /**\n     * Create a new composite containing bodies created in the callback in a grid arrangement.\n     * This function uses the body's bounds to prevent overlaps.\n     * @method stack\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {function} callback\n     * @return {composite} A new composite containing objects created in the callback\n     */\n    Composites.stack = function(x, y, columns, rows, columnGap, rowGap, callback) {\n        var stack = Composite.create({ label: 'Stack' }),\n            currentX = x,\n            currentY = y,\n            lastBody,\n            i = 0;\n\n        for (var row = 0; row < rows; row++) {\n            var maxHeight = 0;\n            \n            for (var column = 0; column < columns; column++) {\n                var body = callback(currentX, currentY, column, row, lastBody, i);\n                    \n                if (body) {\n                    var bodyHeight = body.bounds.max.y - body.bounds.min.y,\n                        bodyWidth = body.bounds.max.x - body.bounds.min.x; \n\n                    if (bodyHeight > maxHeight)\n                        maxHeight = bodyHeight;\n                    \n                    Body.translate(body, { x: bodyWidth * 0.5, y: bodyHeight * 0.5 });\n\n                    currentX = body.bounds.max.x + columnGap;\n\n                    Composite.addBody(stack, body);\n                    \n                    lastBody = body;\n                    i += 1;\n                } else {\n                    currentX += columnGap;\n                }\n            }\n            \n            currentY += maxHeight + rowGap;\n            currentX = x;\n        }\n\n        return stack;\n    };\n    \n    /**\n     * Chains all bodies in the given composite together using constraints.\n     * @method chain\n     * @param {composite} composite\n     * @param {number} xOffsetA\n     * @param {number} yOffsetA\n     * @param {number} xOffsetB\n     * @param {number} yOffsetB\n     * @param {object} options\n     * @return {composite} A new composite containing objects chained together with constraints\n     */\n    Composites.chain = function(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) {\n        var bodies = composite.bodies;\n        \n        for (var i = 1; i < bodies.length; i++) {\n            var bodyA = bodies[i - 1],\n                bodyB = bodies[i],\n                bodyAHeight = bodyA.bounds.max.y - bodyA.bounds.min.y,\n                bodyAWidth = bodyA.bounds.max.x - bodyA.bounds.min.x, \n                bodyBHeight = bodyB.bounds.max.y - bodyB.bounds.min.y,\n                bodyBWidth = bodyB.bounds.max.x - bodyB.bounds.min.x;\n        \n            var defaults = {\n                bodyA: bodyA,\n                pointA: { x: bodyAWidth * xOffsetA, y: bodyAHeight * yOffsetA },\n                bodyB: bodyB,\n                pointB: { x: bodyBWidth * xOffsetB, y: bodyBHeight * yOffsetB }\n            };\n            \n            var constraint = Common.extend(defaults, options);\n        \n            Composite.addConstraint(composite, Constraint.create(constraint));\n        }\n\n        composite.label += ' Chain';\n        \n        return composite;\n    };\n\n    /**\n     * Connects bodies in the composite with constraints in a grid pattern, with optional cross braces.\n     * @method mesh\n     * @param {composite} composite\n     * @param {number} columns\n     * @param {number} rows\n     * @param {boolean} crossBrace\n     * @param {object} options\n     * @return {composite} The composite containing objects meshed together with constraints\n     */\n    Composites.mesh = function(composite, columns, rows, crossBrace, options) {\n        var bodies = composite.bodies,\n            row,\n            col,\n            bodyA,\n            bodyB,\n            bodyC;\n        \n        for (row = 0; row < rows; row++) {\n            for (col = 1; col < columns; col++) {\n                bodyA = bodies[(col - 1) + (row * columns)];\n                bodyB = bodies[col + (row * columns)];\n                Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options)));\n            }\n\n            if (row > 0) {\n                for (col = 0; col < columns; col++) {\n                    bodyA = bodies[col + ((row - 1) * columns)];\n                    bodyB = bodies[col + (row * columns)];\n                    Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyA, bodyB: bodyB }, options)));\n\n                    if (crossBrace && col > 0) {\n                        bodyC = bodies[(col - 1) + ((row - 1) * columns)];\n                        Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options)));\n                    }\n\n                    if (crossBrace && col < columns - 1) {\n                        bodyC = bodies[(col + 1) + ((row - 1) * columns)];\n                        Composite.addConstraint(composite, Constraint.create(Common.extend({ bodyA: bodyC, bodyB: bodyB }, options)));\n                    }\n                }\n            }\n        }\n\n        composite.label += ' Mesh';\n        \n        return composite;\n    };\n    \n    /**\n     * Create a new composite containing bodies created in the callback in a pyramid arrangement.\n     * This function uses the body's bounds to prevent overlaps.\n     * @method pyramid\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {function} callback\n     * @return {composite} A new composite containing objects created in the callback\n     */\n    Composites.pyramid = function(x, y, columns, rows, columnGap, rowGap, callback) {\n        return Composites.stack(x, y, columns, rows, columnGap, rowGap, function(stackX, stackY, column, row, lastBody, i) {\n            var actualRows = Math.min(rows, Math.ceil(columns / 2)),\n                lastBodyWidth = lastBody ? lastBody.bounds.max.x - lastBody.bounds.min.x : 0;\n            \n            if (row > actualRows)\n                return;\n            \n            // reverse row order\n            row = actualRows - row;\n            \n            var start = row,\n                end = columns - 1 - row;\n\n            if (column < start || column > end)\n                return;\n            \n            // retroactively fix the first body's position, since width was unknown\n            if (i === 1) {\n                Body.translate(lastBody, { x: (column + (columns % 2 === 1 ? 1 : -1)) * lastBodyWidth, y: 0 });\n            }\n\n            var xOffset = lastBody ? column * lastBodyWidth : 0;\n            \n            return callback(x + xOffset + column * columnGap, stackY, column, row, lastBody, i);\n        });\n    };\n\n    /**\n     * This has now moved to the [newtonsCradle example](https://github.com/liabru/matter-js/blob/master/examples/newtonsCradle.js), follow that instead as this function is deprecated here.\n     * @deprecated moved to newtonsCradle example\n     * @method newtonsCradle\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} number\n     * @param {number} size\n     * @param {number} length\n     * @return {composite} A new composite newtonsCradle body\n     */\n    Composites.newtonsCradle = function(x, y, number, size, length) {\n        var newtonsCradle = Composite.create({ label: 'Newtons Cradle' });\n\n        for (var i = 0; i < number; i++) {\n            var separation = 1.9,\n                circle = Bodies.circle(x + i * (size * separation), y + length, size, \n                    { inertia: Infinity, restitution: 1, friction: 0, frictionAir: 0.0001, slop: 1 }),\n                constraint = Constraint.create({ pointA: { x: x + i * (size * separation), y: y }, bodyB: circle });\n\n            Composite.addBody(newtonsCradle, circle);\n            Composite.addConstraint(newtonsCradle, constraint);\n        }\n\n        return newtonsCradle;\n    };\n\n    deprecated(Composites, 'newtonsCradle', 'Composites.newtonsCradle ➤ moved to newtonsCradle example');\n    \n    /**\n     * This has now moved to the [car example](https://github.com/liabru/matter-js/blob/master/examples/car.js), follow that instead as this function is deprecated here.\n     * @deprecated moved to car example\n     * @method car\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} width\n     * @param {number} height\n     * @param {number} wheelSize\n     * @return {composite} A new composite car body\n     */\n    Composites.car = function(x, y, width, height, wheelSize) {\n        var group = Body.nextGroup(true),\n            wheelBase = 20,\n            wheelAOffset = -width * 0.5 + wheelBase,\n            wheelBOffset = width * 0.5 - wheelBase,\n            wheelYOffset = 0;\n    \n        var car = Composite.create({ label: 'Car' }),\n            body = Bodies.rectangle(x, y, width, height, { \n                collisionFilter: {\n                    group: group\n                },\n                chamfer: {\n                    radius: height * 0.5\n                },\n                density: 0.0002\n            });\n    \n        var wheelA = Bodies.circle(x + wheelAOffset, y + wheelYOffset, wheelSize, { \n            collisionFilter: {\n                group: group\n            },\n            friction: 0.8\n        });\n                    \n        var wheelB = Bodies.circle(x + wheelBOffset, y + wheelYOffset, wheelSize, { \n            collisionFilter: {\n                group: group\n            },\n            friction: 0.8\n        });\n                    \n        var axelA = Constraint.create({\n            bodyB: body,\n            pointB: { x: wheelAOffset, y: wheelYOffset },\n            bodyA: wheelA,\n            stiffness: 1,\n            length: 0\n        });\n                        \n        var axelB = Constraint.create({\n            bodyB: body,\n            pointB: { x: wheelBOffset, y: wheelYOffset },\n            bodyA: wheelB,\n            stiffness: 1,\n            length: 0\n        });\n        \n        Composite.addBody(car, body);\n        Composite.addBody(car, wheelA);\n        Composite.addBody(car, wheelB);\n        Composite.addConstraint(car, axelA);\n        Composite.addConstraint(car, axelB);\n\n        return car;\n    };\n\n    deprecated(Composites, 'car', 'Composites.car ➤ moved to car example');\n\n    /**\n     * This has now moved to the [softBody example](https://github.com/liabru/matter-js/blob/master/examples/softBody.js)\n     * and the [cloth example](https://github.com/liabru/matter-js/blob/master/examples/cloth.js), follow those instead as this function is deprecated here.\n     * @deprecated moved to softBody and cloth examples\n     * @method softBody\n     * @param {number} x Starting position in X.\n     * @param {number} y Starting position in Y.\n     * @param {number} columns\n     * @param {number} rows\n     * @param {number} columnGap\n     * @param {number} rowGap\n     * @param {boolean} crossBrace\n     * @param {number} particleRadius\n     * @param {} particleOptions\n     * @param {} constraintOptions\n     * @return {composite} A new composite softBody\n     */\n    Composites.softBody = function(x, y, columns, rows, columnGap, rowGap, crossBrace, particleRadius, particleOptions, constraintOptions) {\n        particleOptions = Common.extend({ inertia: Infinity }, particleOptions);\n        constraintOptions = Common.extend({ stiffness: 0.2, render: { type: 'line', anchors: false } }, constraintOptions);\n\n        var softBody = Composites.stack(x, y, columns, rows, columnGap, rowGap, function(stackX, stackY) {\n            return Bodies.circle(stackX, stackY, particleRadius, particleOptions);\n        });\n\n        Composites.mesh(softBody, columns, rows, crossBrace, constraintOptions);\n\n        softBody.label = 'Soft Body';\n\n        return softBody;\n    };\n\n    deprecated(Composites, 'softBody', 'Composites.softBody ➤ moved to softBody and cloth examples');\n})();\n"
  },
  {
    "path": "src/geometry/Axes.js",
    "content": "/**\n* The `Matter.Axes` module contains methods for creating and manipulating sets of axes.\n*\n* @class Axes\n*/\n\nvar Axes = {};\n\nmodule.exports = Axes;\n\nvar Vector = require('../geometry/Vector');\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * Creates a new set of axes from the given vertices.\n     * @method fromVertices\n     * @param {vertices} vertices\n     * @return {axes} A new axes from the given vertices\n     */\n    Axes.fromVertices = function(vertices) {\n        var axes = {};\n\n        // find the unique axes, using edge normal gradients\n        for (var i = 0; i < vertices.length; i++) {\n            var j = (i + 1) % vertices.length, \n                normal = Vector.normalise({ \n                    x: vertices[j].y - vertices[i].y, \n                    y: vertices[i].x - vertices[j].x\n                }),\n                gradient = (normal.y === 0) ? Infinity : (normal.x / normal.y);\n            \n            // limit precision\n            gradient = gradient.toFixed(3).toString();\n            axes[gradient] = normal;\n        }\n\n        return Common.values(axes);\n    };\n\n    /**\n     * Rotates a set of axes by the given angle.\n     * @method rotate\n     * @param {axes} axes\n     * @param {number} angle\n     */\n    Axes.rotate = function(axes, angle) {\n        if (angle === 0)\n            return;\n        \n        var cos = Math.cos(angle),\n            sin = Math.sin(angle);\n\n        for (var i = 0; i < axes.length; i++) {\n            var axis = axes[i],\n                xx;\n            xx = axis.x * cos - axis.y * sin;\n            axis.y = axis.x * sin + axis.y * cos;\n            axis.x = xx;\n        }\n    };\n\n})();\n"
  },
  {
    "path": "src/geometry/Bounds.js",
    "content": "/**\n* The `Matter.Bounds` module contains methods for creating and manipulating axis-aligned bounding boxes (AABB).\n*\n* @class Bounds\n*/\n\nvar Bounds = {};\n\nmodule.exports = Bounds;\n\n(function() {\n\n    /**\n     * Creates a new axis-aligned bounding box (AABB) for the given vertices.\n     * @method create\n     * @param {vertices} vertices\n     * @return {bounds} A new bounds object\n     */\n    Bounds.create = function(vertices) {\n        var bounds = { \n            min: { x: 0, y: 0 }, \n            max: { x: 0, y: 0 }\n        };\n\n        if (vertices)\n            Bounds.update(bounds, vertices);\n        \n        return bounds;\n    };\n\n    /**\n     * Updates bounds using the given vertices and extends the bounds given a velocity.\n     * @method update\n     * @param {bounds} bounds\n     * @param {vertices} vertices\n     * @param {vector} velocity\n     */\n    Bounds.update = function(bounds, vertices, velocity) {\n        bounds.min.x = Infinity;\n        bounds.max.x = -Infinity;\n        bounds.min.y = Infinity;\n        bounds.max.y = -Infinity;\n\n        for (var i = 0; i < vertices.length; i++) {\n            var vertex = vertices[i];\n            if (vertex.x > bounds.max.x) bounds.max.x = vertex.x;\n            if (vertex.x < bounds.min.x) bounds.min.x = vertex.x;\n            if (vertex.y > bounds.max.y) bounds.max.y = vertex.y;\n            if (vertex.y < bounds.min.y) bounds.min.y = vertex.y;\n        }\n        \n        if (velocity) {\n            if (velocity.x > 0) {\n                bounds.max.x += velocity.x;\n            } else {\n                bounds.min.x += velocity.x;\n            }\n            \n            if (velocity.y > 0) {\n                bounds.max.y += velocity.y;\n            } else {\n                bounds.min.y += velocity.y;\n            }\n        }\n    };\n\n    /**\n     * Returns true if the bounds contains the given point.\n     * @method contains\n     * @param {bounds} bounds\n     * @param {vector} point\n     * @return {boolean} True if the bounds contain the point, otherwise false\n     */\n    Bounds.contains = function(bounds, point) {\n        return point.x >= bounds.min.x && point.x <= bounds.max.x \n               && point.y >= bounds.min.y && point.y <= bounds.max.y;\n    };\n\n    /**\n     * Returns true if the two bounds intersect.\n     * @method overlaps\n     * @param {bounds} boundsA\n     * @param {bounds} boundsB\n     * @return {boolean} True if the bounds overlap, otherwise false\n     */\n    Bounds.overlaps = function(boundsA, boundsB) {\n        return (boundsA.min.x <= boundsB.max.x && boundsA.max.x >= boundsB.min.x\n                && boundsA.max.y >= boundsB.min.y && boundsA.min.y <= boundsB.max.y);\n    };\n\n    /**\n     * Translates the bounds by the given vector.\n     * @method translate\n     * @param {bounds} bounds\n     * @param {vector} vector\n     */\n    Bounds.translate = function(bounds, vector) {\n        bounds.min.x += vector.x;\n        bounds.max.x += vector.x;\n        bounds.min.y += vector.y;\n        bounds.max.y += vector.y;\n    };\n\n    /**\n     * Shifts the bounds to the given position.\n     * @method shift\n     * @param {bounds} bounds\n     * @param {vector} position\n     */\n    Bounds.shift = function(bounds, position) {\n        var deltaX = bounds.max.x - bounds.min.x,\n            deltaY = bounds.max.y - bounds.min.y;\n            \n        bounds.min.x = position.x;\n        bounds.max.x = position.x + deltaX;\n        bounds.min.y = position.y;\n        bounds.max.y = position.y + deltaY;\n    };\n    \n})();\n"
  },
  {
    "path": "src/geometry/Svg.js",
    "content": "/**\n* The `Matter.Svg` module contains methods for converting SVG images into an array of vector points.\n*\n* To use this module you also need the SVGPathSeg polyfill: https://github.com/progers/pathseg\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Svg\n*/\n\nvar Svg = {};\n\nmodule.exports = Svg;\n\nvar Bounds = require('../geometry/Bounds');\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * Converts an SVG path into an array of vector points.\n     * If the input path forms a concave shape, you must decompose the result into convex parts before use.\n     * See `Bodies.fromVertices` which provides support for this.\n     * Note that this function is not guaranteed to support complex paths (such as those with holes).\n     * You must load the `pathseg.js` polyfill on newer browsers.\n     * @method pathToVertices\n     * @param {SVGPathElement} path\n     * @param {Number} [sampleLength=15]\n     * @return {Vector[]} points\n     */\n    Svg.pathToVertices = function(path, sampleLength) {\n        if (typeof window !== 'undefined' && !('SVGPathSeg' in window)) {\n            Common.warn('Svg.pathToVertices: SVGPathSeg not defined, a polyfill is required.');\n        }\n\n        // https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js\n        var i, il, total, point, segment, segments, \n            segmentsQueue, lastSegment, \n            lastPoint, segmentIndex, points = [],\n            lx, ly, length = 0, x = 0, y = 0;\n\n        sampleLength = sampleLength || 15;\n\n        var addPoint = function(px, py, pathSegType) {\n            // all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1)\n            var isRelative = pathSegType % 2 === 1 && pathSegType > 1;\n\n            // when the last point doesn't equal the current point add the current point\n            if (!lastPoint || px != lastPoint.x || py != lastPoint.y) {\n                if (lastPoint && isRelative) {\n                    lx = lastPoint.x;\n                    ly = lastPoint.y;\n                } else {\n                    lx = 0;\n                    ly = 0;\n                }\n\n                var point = {\n                    x: lx + px,\n                    y: ly + py\n                };\n\n                // set last point\n                if (isRelative || !lastPoint) {\n                    lastPoint = point;\n                }\n\n                points.push(point);\n\n                x = lx + px;\n                y = ly + py;\n            }\n        };\n\n        var addSegmentPoint = function(segment) {\n            var segType = segment.pathSegTypeAsLetter.toUpperCase();\n\n            // skip path ends\n            if (segType === 'Z') \n                return;\n\n            // map segment to x and y\n            switch (segType) {\n\n            case 'M':\n            case 'L':\n            case 'T':\n            case 'C':\n            case 'S':\n            case 'Q':\n                x = segment.x;\n                y = segment.y;\n                break;\n            case 'H':\n                x = segment.x;\n                break;\n            case 'V':\n                y = segment.y;\n                break;\n            }\n\n            addPoint(x, y, segment.pathSegType);\n        };\n\n        // ensure path is absolute\n        Svg._svgPathToAbsolute(path);\n\n        // get total length\n        total = path.getTotalLength();\n\n        // queue segments\n        segments = [];\n        for (i = 0; i < path.pathSegList.numberOfItems; i += 1)\n            segments.push(path.pathSegList.getItem(i));\n\n        segmentsQueue = segments.concat();\n\n        // sample through path\n        while (length < total) {\n            // get segment at position\n            segmentIndex = path.getPathSegAtLength(length);\n            segment = segments[segmentIndex];\n\n            // new segment\n            if (segment != lastSegment) {\n                while (segmentsQueue.length && segmentsQueue[0] != segment)\n                    addSegmentPoint(segmentsQueue.shift());\n\n                lastSegment = segment;\n            }\n\n            // add points in between when curving\n            // TODO: adaptive sampling\n            switch (segment.pathSegTypeAsLetter.toUpperCase()) {\n\n            case 'C':\n            case 'T':\n            case 'S':\n            case 'Q':\n            case 'A':\n                point = path.getPointAtLength(length);\n                addPoint(point.x, point.y, 0);\n                break;\n\n            }\n\n            // increment by sample value\n            length += sampleLength;\n        }\n\n        // add remaining segments not passed by sampling\n        for (i = 0, il = segmentsQueue.length; i < il; ++i)\n            addSegmentPoint(segmentsQueue[i]);\n\n        return points;\n    };\n\n    Svg._svgPathToAbsolute = function(path) {\n        // http://phrogz.net/convert-svg-path-to-all-absolute-commands\n        // Copyright (c) Gavin Kistner\n        // http://phrogz.net/js/_ReuseLicense.txt\n        // Modifications: tidy formatting and naming\n        var x0, y0, x1, y1, x2, y2, segs = path.pathSegList,\n            x = 0, y = 0, len = segs.numberOfItems;\n\n        for (var i = 0; i < len; ++i) {\n            var seg = segs.getItem(i),\n                segType = seg.pathSegTypeAsLetter;\n\n            if (/[MLHVCSQTA]/.test(segType)) {\n                if ('x' in seg) x = seg.x;\n                if ('y' in seg) y = seg.y;\n            } else {\n                if ('x1' in seg) x1 = x + seg.x1;\n                if ('x2' in seg) x2 = x + seg.x2;\n                if ('y1' in seg) y1 = y + seg.y1;\n                if ('y2' in seg) y2 = y + seg.y2;\n                if ('x' in seg) x += seg.x;\n                if ('y' in seg) y += seg.y;\n\n                switch (segType) {\n\n                case 'm':\n                    segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i);\n                    break;\n                case 'l':\n                    segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i);\n                    break;\n                case 'h':\n                    segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i);\n                    break;\n                case 'v':\n                    segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i);\n                    break;\n                case 'c':\n                    segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i);\n                    break;\n                case 's':\n                    segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i);\n                    break;\n                case 'q':\n                    segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i);\n                    break;\n                case 't':\n                    segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i);\n                    break;\n                case 'a':\n                    segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i);\n                    break;\n                case 'z':\n                case 'Z':\n                    x = x0;\n                    y = y0;\n                    break;\n\n                }\n            }\n\n            if (segType == 'M' || segType == 'm') {\n                x0 = x;\n                y0 = y;\n            }\n        }\n    };\n\n})();"
  },
  {
    "path": "src/geometry/Vector.js",
    "content": "/**\n* The `Matter.Vector` module contains methods for creating and manipulating vectors.\n* Vectors are the basis of all the geometry related operations in the engine.\n* A `Matter.Vector` object is of the form `{ x: 0, y: 0 }`.\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Vector\n*/\n\n// TODO: consider params for reusing vector objects\n\nvar Vector = {};\n\nmodule.exports = Vector;\n\n(function() {\n\n    /**\n     * Creates a new vector.\n     * @method create\n     * @param {number} x\n     * @param {number} y\n     * @return {vector} A new vector\n     */\n    Vector.create = function(x, y) {\n        return { x: x || 0, y: y || 0 };\n    };\n\n    /**\n     * Returns a new vector with `x` and `y` copied from the given `vector`.\n     * @method clone\n     * @param {vector} vector\n     * @return {vector} A new cloned vector\n     */\n    Vector.clone = function(vector) {\n        return { x: vector.x, y: vector.y };\n    };\n\n    /**\n     * Returns the magnitude (length) of a vector.\n     * @method magnitude\n     * @param {vector} vector\n     * @return {number} The magnitude of the vector\n     */\n    Vector.magnitude = function(vector) {\n        return Math.sqrt((vector.x * vector.x) + (vector.y * vector.y));\n    };\n\n    /**\n     * Returns the magnitude (length) of a vector (therefore saving a `sqrt` operation).\n     * @method magnitudeSquared\n     * @param {vector} vector\n     * @return {number} The squared magnitude of the vector\n     */\n    Vector.magnitudeSquared = function(vector) {\n        return (vector.x * vector.x) + (vector.y * vector.y);\n    };\n\n    /**\n     * Rotates the vector about (0, 0) by specified angle.\n     * @method rotate\n     * @param {vector} vector\n     * @param {number} angle\n     * @param {vector} [output]\n     * @return {vector} The vector rotated about (0, 0)\n     */\n    Vector.rotate = function(vector, angle, output) {\n        var cos = Math.cos(angle), sin = Math.sin(angle);\n        if (!output) output = {};\n        var x = vector.x * cos - vector.y * sin;\n        output.y = vector.x * sin + vector.y * cos;\n        output.x = x;\n        return output;\n    };\n\n    /**\n     * Rotates the vector about a specified point by specified angle.\n     * @method rotateAbout\n     * @param {vector} vector\n     * @param {number} angle\n     * @param {vector} point\n     * @param {vector} [output]\n     * @return {vector} A new vector rotated about the point\n     */\n    Vector.rotateAbout = function(vector, angle, point, output) {\n        var cos = Math.cos(angle), sin = Math.sin(angle);\n        if (!output) output = {};\n        var x = point.x + ((vector.x - point.x) * cos - (vector.y - point.y) * sin);\n        output.y = point.y + ((vector.x - point.x) * sin + (vector.y - point.y) * cos);\n        output.x = x;\n        return output;\n    };\n\n    /**\n     * Normalises a vector (such that its magnitude is `1`).\n     * @method normalise\n     * @param {vector} vector\n     * @return {vector} A new vector normalised\n     */\n    Vector.normalise = function(vector) {\n        var magnitude = Vector.magnitude(vector);\n        if (magnitude === 0)\n            return { x: 0, y: 0 };\n        return { x: vector.x / magnitude, y: vector.y / magnitude };\n    };\n\n    /**\n     * Returns the dot-product of two vectors.\n     * @method dot\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The dot product of the two vectors\n     */\n    Vector.dot = function(vectorA, vectorB) {\n        return (vectorA.x * vectorB.x) + (vectorA.y * vectorB.y);\n    };\n\n    /**\n     * Returns the cross-product of two vectors.\n     * @method cross\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The cross product of the two vectors\n     */\n    Vector.cross = function(vectorA, vectorB) {\n        return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x);\n    };\n\n    /**\n     * Returns the cross-product of three vectors.\n     * @method cross3\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} vectorC\n     * @return {number} The cross product of the three vectors\n     */\n    Vector.cross3 = function(vectorA, vectorB, vectorC) {\n        return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x);\n    };\n\n    /**\n     * Adds the two vectors.\n     * @method add\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} [output]\n     * @return {vector} A new vector of vectorA and vectorB added\n     */\n    Vector.add = function(vectorA, vectorB, output) {\n        if (!output) output = {};\n        output.x = vectorA.x + vectorB.x;\n        output.y = vectorA.y + vectorB.y;\n        return output;\n    };\n\n    /**\n     * Subtracts the two vectors.\n     * @method sub\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @param {vector} [output]\n     * @return {vector} A new vector of vectorA and vectorB subtracted\n     */\n    Vector.sub = function(vectorA, vectorB, output) {\n        if (!output) output = {};\n        output.x = vectorA.x - vectorB.x;\n        output.y = vectorA.y - vectorB.y;\n        return output;\n    };\n\n    /**\n     * Multiplies a vector and a scalar.\n     * @method mult\n     * @param {vector} vector\n     * @param {number} scalar\n     * @return {vector} A new vector multiplied by scalar\n     */\n    Vector.mult = function(vector, scalar) {\n        return { x: vector.x * scalar, y: vector.y * scalar };\n    };\n\n    /**\n     * Divides a vector and a scalar.\n     * @method div\n     * @param {vector} vector\n     * @param {number} scalar\n     * @return {vector} A new vector divided by scalar\n     */\n    Vector.div = function(vector, scalar) {\n        return { x: vector.x / scalar, y: vector.y / scalar };\n    };\n\n    /**\n     * Returns the perpendicular vector. Set `negate` to true for the perpendicular in the opposite direction.\n     * @method perp\n     * @param {vector} vector\n     * @param {bool} [negate=false]\n     * @return {vector} The perpendicular vector\n     */\n    Vector.perp = function(vector, negate) {\n        negate = negate === true ? -1 : 1;\n        return { x: negate * -vector.y, y: negate * vector.x };\n    };\n\n    /**\n     * Negates both components of a vector such that it points in the opposite direction.\n     * @method neg\n     * @param {vector} vector\n     * @return {vector} The negated vector\n     */\n    Vector.neg = function(vector) {\n        return { x: -vector.x, y: -vector.y };\n    };\n\n    /**\n     * Returns the angle between the vector `vectorB - vectorA` and the x-axis in radians.\n     * @method angle\n     * @param {vector} vectorA\n     * @param {vector} vectorB\n     * @return {number} The angle in radians\n     */\n    Vector.angle = function(vectorA, vectorB) {\n        return Math.atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x);\n    };\n\n    /**\n     * Temporary vector pool (not thread-safe).\n     * @property _temp\n     * @type {vector[]}\n     * @private\n     */\n    Vector._temp = [\n        Vector.create(), Vector.create(), \n        Vector.create(), Vector.create(), \n        Vector.create(), Vector.create()\n    ];\n\n})();"
  },
  {
    "path": "src/geometry/Vertices.js",
    "content": "/**\n* The `Matter.Vertices` module contains methods for creating and manipulating sets of vertices.\n* A set of vertices is an array of `Matter.Vector` with additional indexing properties inserted by `Vertices.create`.\n* A `Matter.Body` maintains a set of vertices to represent the shape of the object (its convex hull).\n*\n* See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples).\n*\n* @class Vertices\n*/\n\nvar Vertices = {};\n\nmodule.exports = Vertices;\n\nvar Vector = require('../geometry/Vector');\nvar Common = require('../core/Common');\n\n(function() {\n\n    /**\n     * Creates a new set of `Matter.Body` compatible vertices.\n     * The `points` argument accepts an array of `Matter.Vector` points orientated around the origin `(0, 0)`, for example:\n     *\n     *     [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]\n     *\n     * The `Vertices.create` method returns a new array of vertices, which are similar to Matter.Vector objects,\n     * but with some additional references required for efficient collision detection routines.\n     *\n     * Vertices must be specified in clockwise order.\n     *\n     * Note that the `body` argument is not optional, a `Matter.Body` reference must be provided.\n     *\n     * @method create\n     * @param {vector[]} points\n     * @param {body} body\n     */\n    Vertices.create = function(points, body) {\n        var vertices = [];\n\n        for (var i = 0; i < points.length; i++) {\n            var point = points[i],\n                vertex = {\n                    x: point.x,\n                    y: point.y,\n                    index: i,\n                    body: body,\n                    isInternal: false\n                };\n\n            vertices.push(vertex);\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Parses a string containing ordered x y pairs separated by spaces (and optionally commas), \n     * into a `Matter.Vertices` object for the given `Matter.Body`.\n     * For parsing SVG paths, see `Svg.pathToVertices`.\n     * @method fromPath\n     * @param {string} path\n     * @param {body} body\n     * @return {vertices} vertices\n     */\n    Vertices.fromPath = function(path, body) {\n        var pathPattern = /L?\\s*([-\\d.e]+)[\\s,]*([-\\d.e]+)*/ig,\n            points = [];\n\n        path.replace(pathPattern, function(match, x, y) {\n            points.push({ x: parseFloat(x), y: parseFloat(y) });\n        });\n\n        return Vertices.create(points, body);\n    };\n\n    /**\n     * Returns the centre (centroid) of the set of vertices.\n     * @method centre\n     * @param {vertices} vertices\n     * @return {vector} The centre point\n     */\n    Vertices.centre = function(vertices) {\n        var area = Vertices.area(vertices, true),\n            centre = { x: 0, y: 0 },\n            cross,\n            temp,\n            j;\n\n        for (var i = 0; i < vertices.length; i++) {\n            j = (i + 1) % vertices.length;\n            cross = Vector.cross(vertices[i], vertices[j]);\n            temp = Vector.mult(Vector.add(vertices[i], vertices[j]), cross);\n            centre = Vector.add(centre, temp);\n        }\n\n        return Vector.div(centre, 6 * area);\n    };\n\n    /**\n     * Returns the average (mean) of the set of vertices.\n     * @method mean\n     * @param {vertices} vertices\n     * @return {vector} The average point\n     */\n    Vertices.mean = function(vertices) {\n        var average = { x: 0, y: 0 };\n\n        for (var i = 0; i < vertices.length; i++) {\n            average.x += vertices[i].x;\n            average.y += vertices[i].y;\n        }\n\n        return Vector.div(average, vertices.length);\n    };\n\n    /**\n     * Returns the area of the set of vertices.\n     * @method area\n     * @param {vertices} vertices\n     * @param {bool} signed\n     * @return {number} The area\n     */\n    Vertices.area = function(vertices, signed) {\n        var area = 0,\n            j = vertices.length - 1;\n\n        for (var i = 0; i < vertices.length; i++) {\n            area += (vertices[j].x - vertices[i].x) * (vertices[j].y + vertices[i].y);\n            j = i;\n        }\n\n        if (signed)\n            return area / 2;\n\n        return Math.abs(area) / 2;\n    };\n\n    /**\n     * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass.\n     * @method inertia\n     * @param {vertices} vertices\n     * @param {number} mass\n     * @return {number} The polygon's moment of inertia\n     */\n    Vertices.inertia = function(vertices, mass) {\n        var numerator = 0,\n            denominator = 0,\n            v = vertices,\n            cross,\n            j;\n\n        // find the polygon's moment of inertia, using second moment of area\n        // from equations at http://www.physicsforums.com/showthread.php?t=25293\n        for (var n = 0; n < v.length; n++) {\n            j = (n + 1) % v.length;\n            cross = Math.abs(Vector.cross(v[j], v[n]));\n            numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n]));\n            denominator += cross;\n        }\n\n        return (mass / 6) * (numerator / denominator);\n    };\n\n    /**\n     * Translates the set of vertices in-place.\n     * @method translate\n     * @param {vertices} vertices\n     * @param {vector} vector\n     * @param {number} scalar\n     */\n    Vertices.translate = function(vertices, vector, scalar) {\n        scalar = typeof scalar !== 'undefined' ? scalar : 1;\n\n        var verticesLength = vertices.length,\n            translateX = vector.x * scalar,\n            translateY = vector.y * scalar,\n            i;\n        \n        for (i = 0; i < verticesLength; i++) {\n            vertices[i].x += translateX;\n            vertices[i].y += translateY;\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Rotates the set of vertices in-place.\n     * @method rotate\n     * @param {vertices} vertices\n     * @param {number} angle\n     * @param {vector} point\n     */\n    Vertices.rotate = function(vertices, angle, point) {\n        if (angle === 0)\n            return;\n\n        var cos = Math.cos(angle),\n            sin = Math.sin(angle),\n            pointX = point.x,\n            pointY = point.y,\n            verticesLength = vertices.length,\n            vertex,\n            dx,\n            dy,\n            i;\n\n        for (i = 0; i < verticesLength; i++) {\n            vertex = vertices[i];\n            dx = vertex.x - pointX;\n            dy = vertex.y - pointY;\n            vertex.x = pointX + (dx * cos - dy * sin);\n            vertex.y = pointY + (dx * sin + dy * cos);\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Returns `true` if the `point` is inside the set of `vertices`.\n     * @method contains\n     * @param {vertices} vertices\n     * @param {vector} point\n     * @return {boolean} True if the vertices contains point, otherwise false\n     */\n    Vertices.contains = function(vertices, point) {\n        var pointX = point.x,\n            pointY = point.y,\n            verticesLength = vertices.length,\n            vertex = vertices[verticesLength - 1],\n            nextVertex;\n\n        for (var i = 0; i < verticesLength; i++) {\n            nextVertex = vertices[i];\n\n            if ((pointX - vertex.x) * (nextVertex.y - vertex.y) \n                + (pointY - vertex.y) * (vertex.x - nextVertex.x) > 0) {\n                return false;\n            }\n\n            vertex = nextVertex;\n        }\n\n        return true;\n    };\n\n    /**\n     * Scales the vertices from a point (default is centre) in-place.\n     * @method scale\n     * @param {vertices} vertices\n     * @param {number} scaleX\n     * @param {number} scaleY\n     * @param {vector} point\n     */\n    Vertices.scale = function(vertices, scaleX, scaleY, point) {\n        if (scaleX === 1 && scaleY === 1)\n            return vertices;\n\n        point = point || Vertices.centre(vertices);\n\n        var vertex,\n            delta;\n\n        for (var i = 0; i < vertices.length; i++) {\n            vertex = vertices[i];\n            delta = Vector.sub(vertex, point);\n            vertices[i].x = point.x + delta.x * scaleX;\n            vertices[i].y = point.y + delta.y * scaleY;\n        }\n\n        return vertices;\n    };\n\n    /**\n     * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices.\n     * The radius parameter is a single number or an array to specify the radius for each vertex.\n     * @method chamfer\n     * @param {vertices} vertices\n     * @param {number[]} radius\n     * @param {number} quality\n     * @param {number} qualityMin\n     * @param {number} qualityMax\n     */\n    Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {\n        if (typeof radius === 'number') {\n            radius = [radius];\n        } else {\n            radius = radius || [8];\n        }\n\n        // quality defaults to -1, which is auto\n        quality = (typeof quality !== 'undefined') ? quality : -1;\n        qualityMin = qualityMin || 2;\n        qualityMax = qualityMax || 14;\n\n        var newVertices = [];\n\n        for (var i = 0; i < vertices.length; i++) {\n            var prevVertex = vertices[i - 1 >= 0 ? i - 1 : vertices.length - 1],\n                vertex = vertices[i],\n                nextVertex = vertices[(i + 1) % vertices.length],\n                currentRadius = radius[i < radius.length ? i : radius.length - 1];\n\n            if (currentRadius === 0) {\n                newVertices.push(vertex);\n                continue;\n            }\n\n            var prevNormal = Vector.normalise({ \n                x: vertex.y - prevVertex.y, \n                y: prevVertex.x - vertex.x\n            });\n\n            var nextNormal = Vector.normalise({ \n                x: nextVertex.y - vertex.y, \n                y: vertex.x - nextVertex.x\n            });\n\n            var diagonalRadius = Math.sqrt(2 * Math.pow(currentRadius, 2)),\n                radiusVector = Vector.mult(Common.clone(prevNormal), currentRadius),\n                midNormal = Vector.normalise(Vector.mult(Vector.add(prevNormal, nextNormal), 0.5)),\n                scaledVertex = Vector.sub(vertex, Vector.mult(midNormal, diagonalRadius));\n\n            var precision = quality;\n\n            if (quality === -1) {\n                // automatically decide precision\n                precision = Math.pow(currentRadius, 0.32) * 1.75;\n            }\n\n            precision = Common.clamp(precision, qualityMin, qualityMax);\n\n            // use an even value for precision, more likely to reduce axes by using symmetry\n            if (precision % 2 === 1)\n                precision += 1;\n\n            var alpha = Math.acos(Vector.dot(prevNormal, nextNormal)),\n                theta = alpha / precision;\n\n            for (var j = 0; j < precision; j++) {\n                newVertices.push(Vector.add(Vector.rotate(radiusVector, theta * j), scaledVertex));\n            }\n        }\n\n        return newVertices;\n    };\n\n    /**\n     * Sorts the input vertices into clockwise order in place.\n     * @method clockwiseSort\n     * @param {vertices} vertices\n     * @return {vertices} vertices\n     */\n    Vertices.clockwiseSort = function(vertices) {\n        var centre = Vertices.mean(vertices);\n\n        vertices.sort(function(vertexA, vertexB) {\n            return Vector.angle(centre, vertexA) - Vector.angle(centre, vertexB);\n        });\n\n        return vertices;\n    };\n\n    /**\n     * Returns true if the vertices form a convex shape (vertices must be in clockwise order).\n     * @method isConvex\n     * @param {vertices} vertices\n     * @return {bool} `true` if the `vertices` are convex, `false` if not (or `null` if not computable).\n     */\n    Vertices.isConvex = function(vertices) {\n        // http://paulbourke.net/geometry/polygonmesh/\n        // Copyright (c) Paul Bourke (use permitted)\n\n        var flag = 0,\n            n = vertices.length,\n            i,\n            j,\n            k,\n            z;\n\n        if (n < 3)\n            return null;\n\n        for (i = 0; i < n; i++) {\n            j = (i + 1) % n;\n            k = (i + 2) % n;\n            z = (vertices[j].x - vertices[i].x) * (vertices[k].y - vertices[j].y);\n            z -= (vertices[j].y - vertices[i].y) * (vertices[k].x - vertices[j].x);\n\n            if (z < 0) {\n                flag |= 1;\n            } else if (z > 0) {\n                flag |= 2;\n            }\n\n            if (flag === 3) {\n                return false;\n            }\n        }\n\n        if (flag !== 0){\n            return true;\n        } else {\n            return null;\n        }\n    };\n\n    /**\n     * Returns the convex hull of the input vertices as a new array of points.\n     * @method hull\n     * @param {vertices} vertices\n     * @return [vertex] vertices\n     */\n    Vertices.hull = function(vertices) {\n        // http://geomalgorithms.com/a10-_hull-1.html\n\n        var upper = [],\n            lower = [], \n            vertex,\n            i;\n\n        // sort vertices on x-axis (y-axis for ties)\n        vertices = vertices.slice(0);\n        vertices.sort(function(vertexA, vertexB) {\n            var dx = vertexA.x - vertexB.x;\n            return dx !== 0 ? dx : vertexA.y - vertexB.y;\n        });\n\n        // build lower hull\n        for (i = 0; i < vertices.length; i += 1) {\n            vertex = vertices[i];\n\n            while (lower.length >= 2 \n                   && Vector.cross3(lower[lower.length - 2], lower[lower.length - 1], vertex) <= 0) {\n                lower.pop();\n            }\n\n            lower.push(vertex);\n        }\n\n        // build upper hull\n        for (i = vertices.length - 1; i >= 0; i -= 1) {\n            vertex = vertices[i];\n\n            while (upper.length >= 2 \n                   && Vector.cross3(upper[upper.length - 2], upper[upper.length - 1], vertex) <= 0) {\n                upper.pop();\n            }\n\n            upper.push(vertex);\n        }\n\n        // concatenation of the lower and upper hulls gives the convex hull\n        // omit last points because they are repeated at the beginning of the other list\n        upper.pop();\n        lower.pop();\n\n        return upper.concat(lower);\n    };\n\n})();\n"
  },
  {
    "path": "src/module/license.js",
    "content": "/**\n * The MIT License (MIT)\n * \n * Copyright (c) Liam Brummitt and contributors.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */"
  },
  {
    "path": "src/module/main.js",
    "content": "var Matter = module.exports = require('../core/Matter');\r\n\r\nMatter.Axes = require('../geometry/Axes');\r\nMatter.Bodies = require('../factory/Bodies');\r\nMatter.Body = require('../body/Body');\r\nMatter.Bounds = require('../geometry/Bounds');\r\nMatter.Collision = require('../collision/Collision');\r\nMatter.Common = require('../core/Common');\r\nMatter.Composite = require('../body/Composite');\r\nMatter.Composites = require('../factory/Composites');\r\nMatter.Constraint = require('../constraint/Constraint');\r\nMatter.Contact = require('../collision/Contact');\r\nMatter.Detector = require('../collision/Detector');\r\nMatter.Engine = require('../core/Engine');\r\nMatter.Events = require('../core/Events');\r\nMatter.Grid = require('../collision/Grid');\r\nMatter.Mouse = require('../core/Mouse');\r\nMatter.MouseConstraint = require('../constraint/MouseConstraint');\r\nMatter.Pair = require('../collision/Pair');\r\nMatter.Pairs = require('../collision/Pairs');\r\nMatter.Plugin = require('../core/Plugin');\r\nMatter.Query = require('../collision/Query');\r\nMatter.Render = require('../render/Render');\r\nMatter.Resolver = require('../collision/Resolver');\r\nMatter.Runner = require('../core/Runner');\r\nMatter.SAT = require('../collision/SAT');\r\nMatter.Sleeping = require('../core/Sleeping');\r\nMatter.Svg = require('../geometry/Svg');\r\nMatter.Vector = require('../geometry/Vector');\r\nMatter.Vertices = require('../geometry/Vertices');\r\nMatter.World = require('../body/World');\r\n\r\n// temporary back compatibility\r\nMatter.Engine.run = Matter.Runner.run;\r\nMatter.Common.deprecated(Matter.Engine, 'run', 'Engine.run ➤ use Matter.Runner.run(engine) instead');\r\n"
  },
  {
    "path": "src/render/Render.js",
    "content": "/**\n* The `Matter.Render` module is a lightweight, optional utility which provides a simple canvas based renderer for visualising instances of `Matter.Engine`.\n* It is intended for development and debugging purposes, but may also be suitable for simple games.\n* It includes a number of drawing options including wireframe, vector with support for sprites and viewports.\n*\n* @class Render\n*/\n\nvar Render = {};\n\nmodule.exports = Render;\n\nvar Body = require('../body/Body');\nvar Common = require('../core/Common');\nvar Composite = require('../body/Composite');\nvar Bounds = require('../geometry/Bounds');\nvar Events = require('../core/Events');\nvar Vector = require('../geometry/Vector');\nvar Mouse = require('../core/Mouse');\n\n(function() {\n\n    var _requestAnimationFrame,\n        _cancelAnimationFrame;\n\n    if (typeof window !== 'undefined') {\n        _requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame\n                                      || window.mozRequestAnimationFrame || window.msRequestAnimationFrame\n                                      || function(callback){ window.setTimeout(function() { callback(Common.now()); }, 1000 / 60); };\n\n        _cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame\n                                      || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;\n    }\n\n    Render._goodFps = 30;\n    Render._goodDelta = 1000 / 60;\n\n    /**\n     * Creates a new renderer. The options parameter is an object that specifies any properties you wish to override the defaults.\n     * All properties have default values, and many are pre-calculated automatically based on other properties.\n     * See the properties section below for detailed information on what you can pass via the `options` object.\n     * @method create\n     * @param {object} [options]\n     * @return {render} A new renderer\n     */\n    Render.create = function(options) {\n        var defaults = {\n            engine: null,\n            element: null,\n            canvas: null,\n            mouse: null,\n            frameRequestId: null,\n            timing: {\n                historySize: 60,\n                delta: 0,\n                deltaHistory: [],\n                lastTime: 0,\n                lastTimestamp: 0,\n                lastElapsed: 0,\n                timestampElapsed: 0,\n                timestampElapsedHistory: [],\n                engineDeltaHistory: [],\n                engineElapsedHistory: [],\n                engineUpdatesHistory: [],\n                elapsedHistory: []\n            },\n            options: {\n                width: 800,\n                height: 600,\n                pixelRatio: 1,\n                background: '#14151f',\n                wireframeBackground: '#14151f',\n                wireframeStrokeStyle: '#bbb',\n                hasBounds: !!options.bounds,\n                enabled: true,\n                wireframes: true,\n                showSleeping: true,\n                showDebug: false,\n                showStats: false,\n                showPerformance: false,\n                showBounds: false,\n                showVelocity: false,\n                showCollisions: false,\n                showSeparations: false,\n                showAxes: false,\n                showPositions: false,\n                showAngleIndicator: false,\n                showIds: false,\n                showVertexNumbers: false,\n                showConvexHulls: false,\n                showInternalEdges: false,\n                showMousePosition: false\n            }\n        };\n\n        var render = Common.extend(defaults, options);\n\n        if (render.canvas) {\n            render.canvas.width = render.options.width || render.canvas.width;\n            render.canvas.height = render.options.height || render.canvas.height;\n        }\n\n        render.mouse = options.mouse;\n        render.engine = options.engine;\n        render.canvas = render.canvas || _createCanvas(render.options.width, render.options.height);\n        render.context = render.canvas.getContext('2d');\n        render.textures = {};\n\n        render.bounds = render.bounds || {\n            min: {\n                x: 0,\n                y: 0\n            },\n            max: {\n                x: render.canvas.width,\n                y: render.canvas.height\n            }\n        };\n\n        // for temporary back compatibility only\n        render.controller = Render;\n        render.options.showBroadphase = false;\n\n        if (render.options.pixelRatio !== 1) {\n            Render.setPixelRatio(render, render.options.pixelRatio);\n        }\n\n        if (Common.isElement(render.element)) {\n            render.element.appendChild(render.canvas);\n        }\n\n        return render;\n    };\n\n    /**\n     * Continuously updates the render canvas on the `requestAnimationFrame` event.\n     * @method run\n     * @param {render} render\n     */\n    Render.run = function(render) {\n        (function loop(time){\n            render.frameRequestId = _requestAnimationFrame(loop);\n            \n            _updateTiming(render, time);\n\n            Render.world(render, time);\n\n            render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n\n            if (render.options.showStats || render.options.showDebug) {\n                Render.stats(render, render.context, time);\n            }\n\n            if (render.options.showPerformance || render.options.showDebug) {\n                Render.performance(render, render.context, time);\n            }\n\n            render.context.setTransform(1, 0, 0, 1, 0, 0);\n        })();\n    };\n\n    /**\n     * Ends execution of `Render.run` on the given `render`, by canceling the animation frame request event loop.\n     * @method stop\n     * @param {render} render\n     */\n    Render.stop = function(render) {\n        _cancelAnimationFrame(render.frameRequestId);\n    };\n\n    /**\n     * Sets the pixel ratio of the renderer and updates the canvas.\n     * To automatically detect the correct ratio, pass the string `'auto'` for `pixelRatio`.\n     * @method setPixelRatio\n     * @param {render} render\n     * @param {number} pixelRatio\n     */\n    Render.setPixelRatio = function(render, pixelRatio) {\n        var options = render.options,\n            canvas = render.canvas;\n\n        if (pixelRatio === 'auto') {\n            pixelRatio = _getPixelRatio(canvas);\n        }\n\n        options.pixelRatio = pixelRatio;\n        canvas.setAttribute('data-pixel-ratio', pixelRatio);\n        canvas.width = options.width * pixelRatio;\n        canvas.height = options.height * pixelRatio;\n        canvas.style.width = options.width + 'px';\n        canvas.style.height = options.height + 'px';\n    };\n\n    /**\n     * Sets the render `width` and `height`.\n     * \n     * Updates the canvas accounting for `render.options.pixelRatio`.  \n     * \n     * Updates the bottom right render bound `render.bounds.max` relative to the provided `width` and `height`.\n     * The top left render bound `render.bounds.min` isn't changed.\n     * \n     * Follow this call with `Render.lookAt` if you need to change the render bounds.\n     * \n     * See also `Render.setPixelRatio`.\n     * @method setSize\n     * @param {render} render\n     * @param {number} width The width (in CSS pixels)\n     * @param {number} height The height (in CSS pixels)\n     */\n    Render.setSize = function(render, width, height) {\n        render.options.width = width;\n        render.options.height = height;\n        render.bounds.max.x = render.bounds.min.x + width;\n        render.bounds.max.y = render.bounds.min.y + height;\n\n        if (render.options.pixelRatio !== 1) {\n            Render.setPixelRatio(render, render.options.pixelRatio);\n        } else {\n            render.canvas.width = width;\n            render.canvas.height = height;\n        }\n    };\n\n    /**\n     * Positions and sizes the viewport around the given object bounds.\n     * Objects must have at least one of the following properties:\n     * - `object.bounds`\n     * - `object.position`\n     * - `object.min` and `object.max`\n     * - `object.x` and `object.y`\n     * @method lookAt\n     * @param {render} render\n     * @param {object[]} objects\n     * @param {vector} [padding]\n     * @param {bool} [center=true]\n     */\n    Render.lookAt = function(render, objects, padding, center) {\n        center = typeof center !== 'undefined' ? center : true;\n        objects = Common.isArray(objects) ? objects : [objects];\n        padding = padding || {\n            x: 0,\n            y: 0\n        };\n\n        // find bounds of all objects\n        var bounds = {\n            min: { x: Infinity, y: Infinity },\n            max: { x: -Infinity, y: -Infinity }\n        };\n\n        for (var i = 0; i < objects.length; i += 1) {\n            var object = objects[i],\n                min = object.bounds ? object.bounds.min : (object.min || object.position || object),\n                max = object.bounds ? object.bounds.max : (object.max || object.position || object);\n\n            if (min && max) {\n                if (min.x < bounds.min.x)\n                    bounds.min.x = min.x;\n\n                if (max.x > bounds.max.x)\n                    bounds.max.x = max.x;\n\n                if (min.y < bounds.min.y)\n                    bounds.min.y = min.y;\n\n                if (max.y > bounds.max.y)\n                    bounds.max.y = max.y;\n            }\n        }\n\n        // find ratios\n        var width = (bounds.max.x - bounds.min.x) + 2 * padding.x,\n            height = (bounds.max.y - bounds.min.y) + 2 * padding.y,\n            viewHeight = render.canvas.height,\n            viewWidth = render.canvas.width,\n            outerRatio = viewWidth / viewHeight,\n            innerRatio = width / height,\n            scaleX = 1,\n            scaleY = 1;\n\n        // find scale factor\n        if (innerRatio > outerRatio) {\n            scaleY = innerRatio / outerRatio;\n        } else {\n            scaleX = outerRatio / innerRatio;\n        }\n\n        // enable bounds\n        render.options.hasBounds = true;\n\n        // position and size\n        render.bounds.min.x = bounds.min.x;\n        render.bounds.max.x = bounds.min.x + width * scaleX;\n        render.bounds.min.y = bounds.min.y;\n        render.bounds.max.y = bounds.min.y + height * scaleY;\n\n        // center\n        if (center) {\n            render.bounds.min.x += width * 0.5 - (width * scaleX) * 0.5;\n            render.bounds.max.x += width * 0.5 - (width * scaleX) * 0.5;\n            render.bounds.min.y += height * 0.5 - (height * scaleY) * 0.5;\n            render.bounds.max.y += height * 0.5 - (height * scaleY) * 0.5;\n        }\n\n        // padding\n        render.bounds.min.x -= padding.x;\n        render.bounds.max.x -= padding.x;\n        render.bounds.min.y -= padding.y;\n        render.bounds.max.y -= padding.y;\n\n        // update mouse\n        if (render.mouse) {\n            Mouse.setScale(render.mouse, {\n                x: (render.bounds.max.x - render.bounds.min.x) / render.canvas.width,\n                y: (render.bounds.max.y - render.bounds.min.y) / render.canvas.height\n            });\n\n            Mouse.setOffset(render.mouse, render.bounds.min);\n        }\n    };\n\n    /**\n     * Applies viewport transforms based on `render.bounds` to a render context.\n     * @method startViewTransform\n     * @param {render} render\n     */\n    Render.startViewTransform = function(render) {\n        var boundsWidth = render.bounds.max.x - render.bounds.min.x,\n            boundsHeight = render.bounds.max.y - render.bounds.min.y,\n            boundsScaleX = boundsWidth / render.options.width,\n            boundsScaleY = boundsHeight / render.options.height;\n\n        render.context.setTransform(\n            render.options.pixelRatio / boundsScaleX, 0, 0, \n            render.options.pixelRatio / boundsScaleY, 0, 0\n        );\n        \n        render.context.translate(-render.bounds.min.x, -render.bounds.min.y);\n    };\n\n    /**\n     * Resets all transforms on the render context.\n     * @method endViewTransform\n     * @param {render} render\n     */\n    Render.endViewTransform = function(render) {\n        render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n    };\n\n    /**\n     * Renders the given `engine`'s `Matter.World` object.\n     * This is the entry point for all rendering and should be called every time the scene changes.\n     * @method world\n     * @param {render} render\n     */\n    Render.world = function(render, time) {\n        var startTime = Common.now(),\n            engine = render.engine,\n            world = engine.world,\n            canvas = render.canvas,\n            context = render.context,\n            options = render.options,\n            timing = render.timing;\n\n        var allBodies = Composite.allBodies(world),\n            allConstraints = Composite.allConstraints(world),\n            background = options.wireframes ? options.wireframeBackground : options.background,\n            bodies = [],\n            constraints = [],\n            i;\n\n        var event = {\n            timestamp: engine.timing.timestamp\n        };\n\n        Events.trigger(render, 'beforeRender', event);\n\n        // apply background if it has changed\n        if (render.currentBackground !== background)\n            _applyBackground(render, background);\n\n        // clear the canvas with a transparent fill, to allow the canvas background to show\n        context.globalCompositeOperation = 'source-in';\n        context.fillStyle = \"transparent\";\n        context.fillRect(0, 0, canvas.width, canvas.height);\n        context.globalCompositeOperation = 'source-over';\n\n        // handle bounds\n        if (options.hasBounds) {\n            // filter out bodies that are not in view\n            for (i = 0; i < allBodies.length; i++) {\n                var body = allBodies[i];\n                if (Bounds.overlaps(body.bounds, render.bounds))\n                    bodies.push(body);\n            }\n\n            // filter out constraints that are not in view\n            for (i = 0; i < allConstraints.length; i++) {\n                var constraint = allConstraints[i],\n                    bodyA = constraint.bodyA,\n                    bodyB = constraint.bodyB,\n                    pointAWorld = constraint.pointA,\n                    pointBWorld = constraint.pointB;\n\n                if (bodyA) pointAWorld = Vector.add(bodyA.position, constraint.pointA);\n                if (bodyB) pointBWorld = Vector.add(bodyB.position, constraint.pointB);\n\n                if (!pointAWorld || !pointBWorld)\n                    continue;\n\n                if (Bounds.contains(render.bounds, pointAWorld) || Bounds.contains(render.bounds, pointBWorld))\n                    constraints.push(constraint);\n            }\n\n            // transform the view\n            Render.startViewTransform(render);\n\n            // update mouse\n            if (render.mouse) {\n                Mouse.setScale(render.mouse, {\n                    x: (render.bounds.max.x - render.bounds.min.x) / render.options.width,\n                    y: (render.bounds.max.y - render.bounds.min.y) / render.options.height\n                });\n\n                Mouse.setOffset(render.mouse, render.bounds.min);\n            }\n        } else {\n            constraints = allConstraints;\n            bodies = allBodies;\n\n            if (render.options.pixelRatio !== 1) {\n                render.context.setTransform(render.options.pixelRatio, 0, 0, render.options.pixelRatio, 0, 0);\n            }\n        }\n\n        if (!options.wireframes || (engine.enableSleeping && options.showSleeping)) {\n            // fully featured rendering of bodies\n            Render.bodies(render, bodies, context);\n        } else {\n            if (options.showConvexHulls)\n                Render.bodyConvexHulls(render, bodies, context);\n\n            // optimised method for wireframes only\n            Render.bodyWireframes(render, bodies, context);\n        }\n\n        if (options.showBounds)\n            Render.bodyBounds(render, bodies, context);\n\n        if (options.showAxes || options.showAngleIndicator)\n            Render.bodyAxes(render, bodies, context);\n\n        if (options.showPositions)\n            Render.bodyPositions(render, bodies, context);\n\n        if (options.showVelocity)\n            Render.bodyVelocity(render, bodies, context);\n\n        if (options.showIds)\n            Render.bodyIds(render, bodies, context);\n\n        if (options.showSeparations)\n            Render.separations(render, engine.pairs.list, context);\n\n        if (options.showCollisions)\n            Render.collisions(render, engine.pairs.list, context);\n\n        if (options.showVertexNumbers)\n            Render.vertexNumbers(render, bodies, context);\n\n        if (options.showMousePosition)\n            Render.mousePosition(render, render.mouse, context);\n\n        Render.constraints(constraints, context);\n\n        if (options.hasBounds) {\n            // revert view transforms\n            Render.endViewTransform(render);\n        }\n\n        Events.trigger(render, 'afterRender', event);\n\n        // log the time elapsed computing this update\n        timing.lastElapsed = Common.now() - startTime;\n    };\n\n    /**\n     * Renders statistics about the engine and world useful for debugging.\n     * @private\n     * @method stats\n     * @param {render} render\n     * @param {RenderingContext} context\n     * @param {Number} time\n     */\n    Render.stats = function(render, context, time) {\n        var engine = render.engine,\n            world = engine.world,\n            bodies = Composite.allBodies(world),\n            parts = 0,\n            width = 55,\n            height = 44,\n            x = 0,\n            y = 0;\n        \n        // count parts\n        for (var i = 0; i < bodies.length; i += 1) {\n            parts += bodies[i].parts.length;\n        }\n\n        // sections\n        var sections = {\n            'Part': parts,\n            'Body': bodies.length,\n            'Cons': Composite.allConstraints(world).length,\n            'Comp': Composite.allComposites(world).length,\n            'Pair': engine.pairs.list.length\n        };\n\n        // background\n        context.fillStyle = '#0e0f19';\n        context.fillRect(x, y, width * 5.5, height);\n\n        context.font = '12px Arial';\n        context.textBaseline = 'top';\n        context.textAlign = 'right';\n\n        // sections\n        for (var key in sections) {\n            var section = sections[key];\n            // label\n            context.fillStyle = '#aaa';\n            context.fillText(key, x + width, y + 8);\n\n            // value\n            context.fillStyle = '#eee';\n            context.fillText(section, x + width, y + 26);\n\n            x += width;\n        }\n    };\n\n    /**\n     * Renders engine and render performance information.\n     * @private\n     * @method performance\n     * @param {render} render\n     * @param {RenderingContext} context\n     */\n    Render.performance = function(render, context) {\n        var engine = render.engine,\n            timing = render.timing,\n            deltaHistory = timing.deltaHistory,\n            elapsedHistory = timing.elapsedHistory,\n            timestampElapsedHistory = timing.timestampElapsedHistory,\n            engineDeltaHistory = timing.engineDeltaHistory,\n            engineUpdatesHistory = timing.engineUpdatesHistory,\n            engineElapsedHistory = timing.engineElapsedHistory,\n            lastEngineUpdatesPerFrame = engine.timing.lastUpdatesPerFrame,\n            lastEngineDelta = engine.timing.lastDelta;\n        \n        var deltaMean = _mean(deltaHistory),\n            elapsedMean = _mean(elapsedHistory),\n            engineDeltaMean = _mean(engineDeltaHistory),\n            engineUpdatesMean = _mean(engineUpdatesHistory),\n            engineElapsedMean = _mean(engineElapsedHistory),\n            timestampElapsedMean = _mean(timestampElapsedHistory),\n            rateMean = (timestampElapsedMean / deltaMean) || 0,\n            neededUpdatesPerFrame = Math.round(deltaMean / lastEngineDelta),\n            fps = (1000 / deltaMean) || 0;\n\n        var graphHeight = 4,\n            gap = 12,\n            width = 60,\n            height = 34,\n            x = 10,\n            y = 69;\n\n        // background\n        context.fillStyle = '#0e0f19';\n        context.fillRect(0, 50, gap * 5 + width * 6 + 22, height);\n\n        // show FPS\n        Render.status(\n            context, x, y, width, graphHeight, deltaHistory.length, \n            Math.round(fps) + ' fps', \n            fps / Render._goodFps,\n            function(i) { return (deltaHistory[i] / deltaMean) - 1; }\n        );\n\n        // show engine delta\n        Render.status(\n            context, x + gap + width, y, width, graphHeight, engineDeltaHistory.length,\n            lastEngineDelta.toFixed(2) + ' dt', \n            Render._goodDelta / lastEngineDelta,\n            function(i) { return (engineDeltaHistory[i] / engineDeltaMean) - 1; }\n        );\n\n        // show engine updates per frame\n        Render.status(\n            context, x + (gap + width) * 2, y, width, graphHeight, engineUpdatesHistory.length,\n            lastEngineUpdatesPerFrame + ' upf', \n            Math.pow(Common.clamp((engineUpdatesMean / neededUpdatesPerFrame) || 1, 0, 1), 4),\n            function(i) { return (engineUpdatesHistory[i] / engineUpdatesMean) - 1; }\n        );\n\n        // show engine update time\n        Render.status(\n            context, x + (gap + width) * 3, y, width, graphHeight, engineElapsedHistory.length,\n            engineElapsedMean.toFixed(2) + ' ut', \n            1 - (lastEngineUpdatesPerFrame * engineElapsedMean / Render._goodFps),\n            function(i) { return (engineElapsedHistory[i] / engineElapsedMean) - 1; }\n        );\n\n        // show render time\n        Render.status(\n            context, x + (gap + width) * 4, y, width, graphHeight, elapsedHistory.length,\n            elapsedMean.toFixed(2) + ' rt', \n            1 - (elapsedMean / Render._goodFps),\n            function(i) { return (elapsedHistory[i] / elapsedMean) - 1; }\n        );\n\n        // show effective speed\n        Render.status(\n            context, x + (gap + width) * 5, y, width, graphHeight, timestampElapsedHistory.length, \n            rateMean.toFixed(2) + ' x', \n            rateMean * rateMean * rateMean,\n            function(i) { return (((timestampElapsedHistory[i] / deltaHistory[i]) / rateMean) || 0) - 1; }\n        );\n    };\n\n    /**\n     * Renders a label, indicator and a chart.\n     * @private\n     * @method status\n     * @param {RenderingContext} context\n     * @param {number} x\n     * @param {number} y\n     * @param {number} width\n     * @param {number} height\n     * @param {number} count\n     * @param {string} label\n     * @param {string} indicator\n     * @param {function} plotY\n     */\n    Render.status = function(context, x, y, width, height, count, label, indicator, plotY) {\n        // background\n        context.strokeStyle = '#888';\n        context.fillStyle = '#444';\n        context.lineWidth = 1;\n        context.fillRect(x, y + 7, width, 1);\n\n        // chart\n        context.beginPath();\n        context.moveTo(x, y + 7 - height * Common.clamp(0.4 * plotY(0), -2, 2));\n        for (var i = 0; i < width; i += 1) {\n            context.lineTo(x + i, y + 7 - (i < count ? height * Common.clamp(0.4 * plotY(i), -2, 2) : 0));\n        }\n        context.stroke();\n\n        // indicator\n        context.fillStyle = 'hsl(' + Common.clamp(25 + 95 * indicator, 0, 120) + ',100%,60%)';\n        context.fillRect(x, y - 7, 4, 4);\n\n        // label\n        context.font = '12px Arial';\n        context.textBaseline = 'middle';\n        context.textAlign = 'right';\n        context.fillStyle = '#eee';\n        context.fillText(label, x + width, y - 5);\n    };\n\n    /**\n     * Description\n     * @private\n     * @method constraints\n     * @param {constraint[]} constraints\n     * @param {RenderingContext} context\n     */\n    Render.constraints = function(constraints, context) {\n        var c = context;\n\n        for (var i = 0; i < constraints.length; i++) {\n            var constraint = constraints[i];\n\n            if (!constraint.render.visible || !constraint.pointA || !constraint.pointB)\n                continue;\n\n            var bodyA = constraint.bodyA,\n                bodyB = constraint.bodyB,\n                start,\n                end;\n\n            if (bodyA) {\n                start = Vector.add(bodyA.position, constraint.pointA);\n            } else {\n                start = constraint.pointA;\n            }\n\n            if (constraint.render.type === 'pin') {\n                c.beginPath();\n                c.arc(start.x, start.y, 3, 0, 2 * Math.PI);\n                c.closePath();\n            } else {\n                if (bodyB) {\n                    end = Vector.add(bodyB.position, constraint.pointB);\n                } else {\n                    end = constraint.pointB;\n                }\n\n                c.beginPath();\n                c.moveTo(start.x, start.y);\n\n                if (constraint.render.type === 'spring') {\n                    var delta = Vector.sub(end, start),\n                        normal = Vector.perp(Vector.normalise(delta)),\n                        coils = Math.ceil(Common.clamp(constraint.length / 5, 12, 20)),\n                        offset;\n\n                    for (var j = 1; j < coils; j += 1) {\n                        offset = j % 2 === 0 ? 1 : -1;\n\n                        c.lineTo(\n                            start.x + delta.x * (j / coils) + normal.x * offset * 4,\n                            start.y + delta.y * (j / coils) + normal.y * offset * 4\n                        );\n                    }\n                }\n\n                c.lineTo(end.x, end.y);\n            }\n\n            if (constraint.render.lineWidth) {\n                c.lineWidth = constraint.render.lineWidth;\n                c.strokeStyle = constraint.render.strokeStyle;\n                c.stroke();\n            }\n\n            if (constraint.render.anchors) {\n                c.fillStyle = constraint.render.strokeStyle;\n                c.beginPath();\n                c.arc(start.x, start.y, 3, 0, 2 * Math.PI);\n                c.arc(end.x, end.y, 3, 0, 2 * Math.PI);\n                c.closePath();\n                c.fill();\n            }\n        }\n    };\n\n    /**\n     * Description\n     * @private\n     * @method bodies\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodies = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            showInternalEdges = options.showInternalEdges || !options.wireframes,\n            body,\n            part,\n            i,\n            k;\n\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n\n                if (!part.render.visible)\n                    continue;\n\n                if (options.showSleeping && body.isSleeping) {\n                    c.globalAlpha = 0.5 * part.render.opacity;\n                } else if (part.render.opacity !== 1) {\n                    c.globalAlpha = part.render.opacity;\n                }\n\n                if (part.render.sprite && part.render.sprite.texture && !options.wireframes) {\n                    // part sprite\n                    var sprite = part.render.sprite,\n                        texture = _getTexture(render, sprite.texture);\n\n                    c.translate(part.position.x, part.position.y);\n                    c.rotate(part.angle);\n\n                    c.drawImage(\n                        texture,\n                        texture.width * -sprite.xOffset * sprite.xScale,\n                        texture.height * -sprite.yOffset * sprite.yScale,\n                        texture.width * sprite.xScale,\n                        texture.height * sprite.yScale\n                    );\n\n                    // revert translation, hopefully faster than save / restore\n                    c.rotate(-part.angle);\n                    c.translate(-part.position.x, -part.position.y);\n                } else {\n                    // part polygon\n                    if (part.circleRadius) {\n                        c.beginPath();\n                        c.arc(part.position.x, part.position.y, part.circleRadius, 0, 2 * Math.PI);\n                    } else {\n                        c.beginPath();\n                        c.moveTo(part.vertices[0].x, part.vertices[0].y);\n\n                        for (var j = 1; j < part.vertices.length; j++) {\n                            if (!part.vertices[j - 1].isInternal || showInternalEdges) {\n                                c.lineTo(part.vertices[j].x, part.vertices[j].y);\n                            } else {\n                                c.moveTo(part.vertices[j].x, part.vertices[j].y);\n                            }\n\n                            if (part.vertices[j].isInternal && !showInternalEdges) {\n                                c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);\n                            }\n                        }\n\n                        c.lineTo(part.vertices[0].x, part.vertices[0].y);\n                        c.closePath();\n                    }\n\n                    if (!options.wireframes) {\n                        c.fillStyle = part.render.fillStyle;\n\n                        if (part.render.lineWidth) {\n                            c.lineWidth = part.render.lineWidth;\n                            c.strokeStyle = part.render.strokeStyle;\n                            c.stroke();\n                        }\n\n                        c.fill();\n                    } else {\n                        c.lineWidth = 1;\n                        c.strokeStyle = render.options.wireframeStrokeStyle;\n                        c.stroke();\n                    }\n                }\n\n                c.globalAlpha = 1;\n            }\n        }\n    };\n\n    /**\n     * Optimised method for drawing body wireframes in one pass\n     * @private\n     * @method bodyWireframes\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyWireframes = function(render, bodies, context) {\n        var c = context,\n            showInternalEdges = render.options.showInternalEdges,\n            body,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        // render all bodies\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = body.parts.length > 1 ? 1 : 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n\n                c.moveTo(part.vertices[0].x, part.vertices[0].y);\n\n                for (j = 1; j < part.vertices.length; j++) {\n                    if (!part.vertices[j - 1].isInternal || showInternalEdges) {\n                        c.lineTo(part.vertices[j].x, part.vertices[j].y);\n                    } else {\n                        c.moveTo(part.vertices[j].x, part.vertices[j].y);\n                    }\n\n                    if (part.vertices[j].isInternal && !showInternalEdges) {\n                        c.moveTo(part.vertices[(j + 1) % part.vertices.length].x, part.vertices[(j + 1) % part.vertices.length].y);\n                    }\n                }\n\n                c.lineTo(part.vertices[0].x, part.vertices[0].y);\n            }\n        }\n\n        c.lineWidth = 1;\n        c.strokeStyle = render.options.wireframeStrokeStyle;\n        c.stroke();\n    };\n\n    /**\n     * Optimised method for drawing body convex hull wireframes in one pass\n     * @private\n     * @method bodyConvexHulls\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyConvexHulls = function(render, bodies, context) {\n        var c = context,\n            body,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        // render convex hulls\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible || body.parts.length === 1)\n                continue;\n\n            c.moveTo(body.vertices[0].x, body.vertices[0].y);\n\n            for (j = 1; j < body.vertices.length; j++) {\n                c.lineTo(body.vertices[j].x, body.vertices[j].y);\n            }\n\n            c.lineTo(body.vertices[0].x, body.vertices[0].y);\n        }\n\n        c.lineWidth = 1;\n        c.strokeStyle = 'rgba(255,255,255,0.2)';\n        c.stroke();\n    };\n\n    /**\n     * Renders body vertex numbers.\n     * @private\n     * @method vertexNumbers\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.vertexNumbers = function(render, bodies, context) {\n        var c = context,\n            i,\n            j,\n            k;\n\n        for (i = 0; i < bodies.length; i++) {\n            var parts = bodies[i].parts;\n            for (k = parts.length > 1 ? 1 : 0; k < parts.length; k++) {\n                var part = parts[k];\n                for (j = 0; j < part.vertices.length; j++) {\n                    c.fillStyle = 'rgba(255,255,255,0.2)';\n                    c.fillText(i + '_' + j, part.position.x + (part.vertices[j].x - part.position.x) * 0.8, part.position.y + (part.vertices[j].y - part.position.y) * 0.8);\n                }\n            }\n        }\n    };\n\n    /**\n     * Renders mouse position.\n     * @private\n     * @method mousePosition\n     * @param {render} render\n     * @param {mouse} mouse\n     * @param {RenderingContext} context\n     */\n    Render.mousePosition = function(render, mouse, context) {\n        var c = context;\n        c.fillStyle = 'rgba(255,255,255,0.8)';\n        c.fillText(mouse.position.x + '  ' + mouse.position.y, mouse.position.x + 5, mouse.position.y - 5);\n    };\n\n    /**\n     * Draws body bounds\n     * @private\n     * @method bodyBounds\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyBounds = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options;\n\n        c.beginPath();\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (body.render.visible) {\n                var parts = bodies[i].parts;\n                for (var j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    var part = parts[j];\n                    c.rect(part.bounds.min.x, part.bounds.min.y, part.bounds.max.x - part.bounds.min.x, part.bounds.max.y - part.bounds.min.y);\n                }\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,255,255,0.08)';\n        } else {\n            c.strokeStyle = 'rgba(0,0,0,0.1)';\n        }\n\n        c.lineWidth = 1;\n        c.stroke();\n    };\n\n    /**\n     * Draws body angle indicators and axes\n     * @private\n     * @method bodyAxes\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyAxes = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            part,\n            i,\n            j,\n            k;\n\n        c.beginPath();\n\n        for (i = 0; i < bodies.length; i++) {\n            var body = bodies[i],\n                parts = body.parts;\n\n            if (!body.render.visible)\n                continue;\n\n            if (options.showAxes) {\n                // render all axes\n                for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    part = parts[j];\n                    for (k = 0; k < part.axes.length; k++) {\n                        var axis = part.axes[k];\n                        c.moveTo(part.position.x, part.position.y);\n                        c.lineTo(part.position.x + axis.x * 20, part.position.y + axis.y * 20);\n                    }\n                }\n            } else {\n                for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                    part = parts[j];\n                    for (k = 0; k < part.axes.length; k++) {\n                        // render a single axis indicator\n                        c.moveTo(part.position.x, part.position.y);\n                        c.lineTo((part.vertices[0].x + part.vertices[part.vertices.length-1].x) / 2,\n                            (part.vertices[0].y + part.vertices[part.vertices.length-1].y) / 2);\n                    }\n                }\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'indianred';\n            c.lineWidth = 1;\n        } else {\n            c.strokeStyle = 'rgba(255, 255, 255, 0.4)';\n            c.globalCompositeOperation = 'overlay';\n            c.lineWidth = 2;\n        }\n\n        c.stroke();\n        c.globalCompositeOperation = 'source-over';\n    };\n\n    /**\n     * Draws body positions\n     * @private\n     * @method bodyPositions\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyPositions = function(render, bodies, context) {\n        var c = context,\n            engine = render.engine,\n            options = render.options,\n            body,\n            part,\n            i,\n            k;\n\n        c.beginPath();\n\n        // render current positions\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            // handle compound parts\n            for (k = 0; k < body.parts.length; k++) {\n                part = body.parts[k];\n                c.arc(part.position.x, part.position.y, 3, 0, 2 * Math.PI, false);\n                c.closePath();\n            }\n        }\n\n        if (options.wireframes) {\n            c.fillStyle = 'indianred';\n        } else {\n            c.fillStyle = 'rgba(0,0,0,0.5)';\n        }\n        c.fill();\n\n        c.beginPath();\n\n        // render previous positions\n        for (i = 0; i < bodies.length; i++) {\n            body = bodies[i];\n            if (body.render.visible) {\n                c.arc(body.positionPrev.x, body.positionPrev.y, 2, 0, 2 * Math.PI, false);\n                c.closePath();\n            }\n        }\n\n        c.fillStyle = 'rgba(255,165,0,0.8)';\n        c.fill();\n    };\n\n    /**\n     * Draws body velocity\n     * @private\n     * @method bodyVelocity\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyVelocity = function(render, bodies, context) {\n        var c = context;\n\n        c.beginPath();\n\n        for (var i = 0; i < bodies.length; i++) {\n            var body = bodies[i];\n\n            if (!body.render.visible)\n                continue;\n\n            var velocity = Body.getVelocity(body);\n\n            c.moveTo(body.position.x, body.position.y);\n            c.lineTo(body.position.x + velocity.x, body.position.y + velocity.y);\n        }\n\n        c.lineWidth = 3;\n        c.strokeStyle = 'cornflowerblue';\n        c.stroke();\n    };\n\n    /**\n     * Draws body ids\n     * @private\n     * @method bodyIds\n     * @param {render} render\n     * @param {body[]} bodies\n     * @param {RenderingContext} context\n     */\n    Render.bodyIds = function(render, bodies, context) {\n        var c = context,\n            i,\n            j;\n\n        for (i = 0; i < bodies.length; i++) {\n            if (!bodies[i].render.visible)\n                continue;\n\n            var parts = bodies[i].parts;\n            for (j = parts.length > 1 ? 1 : 0; j < parts.length; j++) {\n                var part = parts[j];\n                c.font = \"12px Arial\";\n                c.fillStyle = 'rgba(255,255,255,0.5)';\n                c.fillText(part.id, part.position.x + 10, part.position.y - 10);\n            }\n        }\n    };\n\n    /**\n     * Description\n     * @private\n     * @method collisions\n     * @param {render} render\n     * @param {pair[]} pairs\n     * @param {RenderingContext} context\n     */\n    Render.collisions = function(render, pairs, context) {\n        var c = context,\n            options = render.options,\n            pair,\n            collision,\n            corrected,\n            bodyA,\n            bodyB,\n            i,\n            j;\n\n        c.beginPath();\n\n        // render collision positions\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n            for (j = 0; j < pair.contactCount; j++) {\n                var contact = pair.contacts[j],\n                    vertex = contact.vertex;\n                c.rect(vertex.x - 1.5, vertex.y - 1.5, 3.5, 3.5);\n            }\n        }\n\n        if (options.wireframes) {\n            c.fillStyle = 'rgba(255,255,255,0.7)';\n        } else {\n            c.fillStyle = 'orange';\n        }\n        c.fill();\n\n        c.beginPath();\n\n        // render collision normals\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n\n            if (pair.contactCount > 0) {\n                var normalPosX = pair.contacts[0].vertex.x,\n                    normalPosY = pair.contacts[0].vertex.y;\n\n                if (pair.contactCount === 2) {\n                    normalPosX = (pair.contacts[0].vertex.x + pair.contacts[1].vertex.x) / 2;\n                    normalPosY = (pair.contacts[0].vertex.y + pair.contacts[1].vertex.y) / 2;\n                }\n\n                if (collision.bodyB === collision.supports[0].body || collision.bodyA.isStatic === true) {\n                    c.moveTo(normalPosX - collision.normal.x * 8, normalPosY - collision.normal.y * 8);\n                } else {\n                    c.moveTo(normalPosX + collision.normal.x * 8, normalPosY + collision.normal.y * 8);\n                }\n\n                c.lineTo(normalPosX, normalPosY);\n            }\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,165,0,0.7)';\n        } else {\n            c.strokeStyle = 'orange';\n        }\n\n        c.lineWidth = 1;\n        c.stroke();\n    };\n\n    /**\n     * Description\n     * @private\n     * @method separations\n     * @param {render} render\n     * @param {pair[]} pairs\n     * @param {RenderingContext} context\n     */\n    Render.separations = function(render, pairs, context) {\n        var c = context,\n            options = render.options,\n            pair,\n            collision,\n            corrected,\n            bodyA,\n            bodyB,\n            i,\n            j;\n\n        c.beginPath();\n\n        // render separations\n        for (i = 0; i < pairs.length; i++) {\n            pair = pairs[i];\n\n            if (!pair.isActive)\n                continue;\n\n            collision = pair.collision;\n            bodyA = collision.bodyA;\n            bodyB = collision.bodyB;\n\n            var k = 1;\n\n            if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;\n            if (bodyB.isStatic) k = 0;\n\n            c.moveTo(bodyB.position.x, bodyB.position.y);\n            c.lineTo(bodyB.position.x - collision.penetration.x * k, bodyB.position.y - collision.penetration.y * k);\n\n            k = 1;\n\n            if (!bodyB.isStatic && !bodyA.isStatic) k = 0.5;\n            if (bodyA.isStatic) k = 0;\n\n            c.moveTo(bodyA.position.x, bodyA.position.y);\n            c.lineTo(bodyA.position.x + collision.penetration.x * k, bodyA.position.y + collision.penetration.y * k);\n        }\n\n        if (options.wireframes) {\n            c.strokeStyle = 'rgba(255,165,0,0.5)';\n        } else {\n            c.strokeStyle = 'orange';\n        }\n        c.stroke();\n    };\n\n    /**\n     * Description\n     * @private\n     * @method inspector\n     * @param {inspector} inspector\n     * @param {RenderingContext} context\n     */\n    Render.inspector = function(inspector, context) {\n        var engine = inspector.engine,\n            selected = inspector.selected,\n            render = inspector.render,\n            options = render.options,\n            bounds;\n\n        if (options.hasBounds) {\n            var boundsWidth = render.bounds.max.x - render.bounds.min.x,\n                boundsHeight = render.bounds.max.y - render.bounds.min.y,\n                boundsScaleX = boundsWidth / render.options.width,\n                boundsScaleY = boundsHeight / render.options.height;\n\n            context.scale(1 / boundsScaleX, 1 / boundsScaleY);\n            context.translate(-render.bounds.min.x, -render.bounds.min.y);\n        }\n\n        for (var i = 0; i < selected.length; i++) {\n            var item = selected[i].data;\n\n            context.translate(0.5, 0.5);\n            context.lineWidth = 1;\n            context.strokeStyle = 'rgba(255,165,0,0.9)';\n            context.setLineDash([1,2]);\n\n            switch (item.type) {\n\n            case 'body':\n\n                // render body selections\n                bounds = item.bounds;\n                context.beginPath();\n                context.rect(Math.floor(bounds.min.x - 3), Math.floor(bounds.min.y - 3),\n                    Math.floor(bounds.max.x - bounds.min.x + 6), Math.floor(bounds.max.y - bounds.min.y + 6));\n                context.closePath();\n                context.stroke();\n\n                break;\n\n            case 'constraint':\n\n                // render constraint selections\n                var point = item.pointA;\n                if (item.bodyA)\n                    point = item.pointB;\n                context.beginPath();\n                context.arc(point.x, point.y, 10, 0, 2 * Math.PI);\n                context.closePath();\n                context.stroke();\n\n                break;\n\n            }\n\n            context.setLineDash([]);\n            context.translate(-0.5, -0.5);\n        }\n\n        // render selection region\n        if (inspector.selectStart !== null) {\n            context.translate(0.5, 0.5);\n            context.lineWidth = 1;\n            context.strokeStyle = 'rgba(255,165,0,0.6)';\n            context.fillStyle = 'rgba(255,165,0,0.1)';\n            bounds = inspector.selectBounds;\n            context.beginPath();\n            context.rect(Math.floor(bounds.min.x), Math.floor(bounds.min.y),\n                Math.floor(bounds.max.x - bounds.min.x), Math.floor(bounds.max.y - bounds.min.y));\n            context.closePath();\n            context.stroke();\n            context.fill();\n            context.translate(-0.5, -0.5);\n        }\n\n        if (options.hasBounds)\n            context.setTransform(1, 0, 0, 1, 0, 0);\n    };\n\n    /**\n     * Updates render timing.\n     * @method _updateTiming\n     * @private\n     * @param {render} render\n     * @param {number} time\n     */\n    var _updateTiming = function(render, time) {\n        var engine = render.engine,\n            timing = render.timing,\n            historySize = timing.historySize,\n            timestamp = engine.timing.timestamp;\n\n        timing.delta = time - timing.lastTime || Render._goodDelta;\n        timing.lastTime = time;\n\n        timing.timestampElapsed = timestamp - timing.lastTimestamp || 0;\n        timing.lastTimestamp = timestamp;\n\n        timing.deltaHistory.unshift(timing.delta);\n        timing.deltaHistory.length = Math.min(timing.deltaHistory.length, historySize);\n\n        timing.engineDeltaHistory.unshift(engine.timing.lastDelta);\n        timing.engineDeltaHistory.length = Math.min(timing.engineDeltaHistory.length, historySize);\n\n        timing.timestampElapsedHistory.unshift(timing.timestampElapsed);\n        timing.timestampElapsedHistory.length = Math.min(timing.timestampElapsedHistory.length, historySize);\n\n        timing.engineUpdatesHistory.unshift(engine.timing.lastUpdatesPerFrame);\n        timing.engineUpdatesHistory.length = Math.min(timing.engineUpdatesHistory.length, historySize);\n\n        timing.engineElapsedHistory.unshift(engine.timing.lastElapsed);\n        timing.engineElapsedHistory.length = Math.min(timing.engineElapsedHistory.length, historySize);\n\n        timing.elapsedHistory.unshift(timing.lastElapsed);\n        timing.elapsedHistory.length = Math.min(timing.elapsedHistory.length, historySize);\n    };\n\n    /**\n     * Returns the mean value of the given numbers.\n     * @method _mean\n     * @private\n     * @param {Number[]} values\n     * @return {Number} the mean of given values\n     */\n    var _mean = function(values) {\n        var result = 0;\n        for (var i = 0; i < values.length; i += 1) {\n            result += values[i];\n        }\n        return (result / values.length) || 0;\n    };\n\n    /**\n     * @method _createCanvas\n     * @private\n     * @param {} width\n     * @param {} height\n     * @return canvas\n     */\n    var _createCanvas = function(width, height) {\n        var canvas = document.createElement('canvas');\n        canvas.width = width;\n        canvas.height = height;\n        canvas.oncontextmenu = function() { return false; };\n        canvas.onselectstart = function() { return false; };\n        return canvas;\n    };\n\n    /**\n     * Gets the pixel ratio of the canvas.\n     * @method _getPixelRatio\n     * @private\n     * @param {HTMLElement} canvas\n     * @return {Number} pixel ratio\n     */\n    var _getPixelRatio = function(canvas) {\n        var context = canvas.getContext('2d'),\n            devicePixelRatio = window.devicePixelRatio || 1,\n            backingStorePixelRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio\n                                      || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio\n                                      || context.backingStorePixelRatio || 1;\n\n        return devicePixelRatio / backingStorePixelRatio;\n    };\n\n    /**\n     * Gets the requested texture (an Image) via its path\n     * @method _getTexture\n     * @private\n     * @param {render} render\n     * @param {string} imagePath\n     * @return {Image} texture\n     */\n    var _getTexture = function(render, imagePath) {\n        var image = render.textures[imagePath];\n\n        if (image)\n            return image;\n\n        image = render.textures[imagePath] = new Image();\n        image.src = imagePath;\n\n        return image;\n    };\n\n    /**\n     * Applies the background to the canvas using CSS.\n     * @method applyBackground\n     * @private\n     * @param {render} render\n     * @param {string} background\n     */\n    var _applyBackground = function(render, background) {\n        var cssBackground = background;\n\n        if (/(jpg|gif|png)$/.test(background))\n            cssBackground = 'url(' + background + ')';\n\n        render.canvas.style.background = cssBackground;\n        render.canvas.style.backgroundSize = \"contain\";\n        render.currentBackground = background;\n    };\n\n    /*\n    *\n    *  Events Documentation\n    *\n    */\n\n    /**\n    * Fired before rendering\n    *\n    * @event beforeRender\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /**\n    * Fired after rendering\n    *\n    * @event afterRender\n    * @param {} event An event object\n    * @param {number} event.timestamp The engine.timing.timestamp of the event\n    * @param {} event.source The source object of the event\n    * @param {} event.name The name of the event\n    */\n\n    /*\n    *\n    *  Properties Documentation\n    *\n    */\n\n    /**\n     * A back-reference to the `Matter.Render` module.\n     *\n     * @deprecated\n     * @property controller\n     * @type render\n     */\n\n    /**\n     * A reference to the `Matter.Engine` instance to be used.\n     *\n     * @property engine\n     * @type engine\n     */\n\n    /**\n     * A reference to the element where the canvas is to be inserted (if `render.canvas` has not been specified)\n     *\n     * @property element\n     * @type HTMLElement\n     * @default null\n     */\n\n    /**\n     * The canvas element to render to. If not specified, one will be created if `render.element` has been specified.\n     *\n     * @property canvas\n     * @type HTMLCanvasElement\n     * @default null\n     */\n\n    /**\n     * A `Bounds` object that specifies the drawing view region.\n     * Rendering will be automatically transformed and scaled to fit within the canvas size (`render.options.width` and `render.options.height`).\n     * This allows for creating views that can pan or zoom around the scene.\n     * You must also set `render.options.hasBounds` to `true` to enable bounded rendering.\n     *\n     * @property bounds\n     * @type bounds\n     */\n\n    /**\n     * The 2d rendering context from the `render.canvas` element.\n     *\n     * @property context\n     * @type CanvasRenderingContext2D\n     */\n\n    /**\n     * The sprite texture cache.\n     *\n     * @property textures\n     * @type {}\n     */\n\n    /**\n     * The mouse to render if `render.options.showMousePosition` is enabled.\n     *\n     * @property mouse\n     * @type mouse\n     * @default null\n     */\n\n    /**\n     * The configuration options of the renderer.\n     *\n     * @property options\n     * @type {}\n     */\n\n    /**\n     * The target width in pixels of the `render.canvas` to be created.\n     * See also the `options.pixelRatio` property to change render quality.\n     *\n     * @property options.width\n     * @type number\n     * @default 800\n     */\n\n    /**\n     * The target height in pixels of the `render.canvas` to be created.\n     * See also the `options.pixelRatio` property to change render quality.\n     *\n     * @property options.height\n     * @type number\n     * @default 600\n     */\n\n    /**\n     * The [pixel ratio](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) to use when rendering.\n     *\n     * @property options.pixelRatio\n     * @type number\n     * @default 1\n     */\n\n    /**\n     * A CSS background color string to use when `render.options.wireframes` is disabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.background\n     * @type string\n     * @default '#14151f'\n     */\n\n    /**\n     * A CSS color string to use for background when `render.options.wireframes` is enabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.wireframeBackground\n     * @type string\n     * @default '#14151f'\n     */\n\n    /**\n     * A CSS color string to use for stroke when `render.options.wireframes` is enabled.\n     * This may be also set to `'transparent'` or equivalent.\n     *\n     * @property options.wireframeStrokeStyle\n     * @type string\n     * @default '#bbb'\n     */\n\n    /**\n     * A flag that specifies if `render.bounds` should be used when rendering.\n     *\n     * @property options.hasBounds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable all debug information overlays together.  \n     * This includes and has priority over the values of:\n     *\n     * - `render.options.showStats`\n     * - `render.options.showPerformance`\n     *\n     * @property options.showDebug\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the engine stats info overlay.  \n     * From left to right, the values shown are:\n     *\n     * - body parts total\n     * - body total\n     * - constraints total\n     * - composites total\n     * - collision pairs total\n     *\n     * @property options.showStats\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable performance charts.  \n     * From left to right, the values shown are:\n     *\n     * - average render frequency (e.g. 60 fps)\n     * - exact engine delta time used for last update (e.g. 16.66ms)\n     * - average updates per frame (e.g. 1)\n     * - average engine execution duration (e.g. 5.00ms)\n     * - average render execution duration (e.g. 0.40ms)\n     * - average effective play speed (e.g. '1.00x' is 'real-time')\n     *\n     * Each value is recorded over a fixed sample of past frames (60 frames).\n     *\n     * A chart shown below each value indicates the variance from the average over the sample.\n     * The more stable or fixed the value is the flatter the chart will appear.\n     *\n     * @property options.showPerformance\n     * @type boolean\n     * @default false\n     */\n    \n    /**\n     * A flag to enable or disable rendering entirely.\n     *\n     * @property options.enabled\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to toggle wireframe rendering otherwise solid fill rendering is used.\n     *\n     * @property options.wireframes\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A flag to enable or disable sleeping bodies indicators.\n     *\n     * @property options.showSleeping\n     * @type boolean\n     * @default true\n     */\n\n    /**\n     * A flag to enable or disable the debug information overlay.\n     *\n     * @property options.showDebug\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the collision broadphase debug overlay.\n     *\n     * @deprecated no longer implemented\n     * @property options.showBroadphase\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body bounds debug overlay.\n     *\n     * @property options.showBounds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body velocity debug overlay.\n     *\n     * @property options.showVelocity\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body collisions debug overlay.\n     *\n     * @property options.showCollisions\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the collision resolver separations debug overlay.\n     *\n     * @property options.showSeparations\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body axes debug overlay.\n     *\n     * @property options.showAxes\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body positions debug overlay.\n     *\n     * @property options.showPositions\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body angle debug overlay.\n     *\n     * @property options.showAngleIndicator\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body and part ids debug overlay.\n     *\n     * @property options.showIds\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body vertex numbers debug overlay.\n     *\n     * @property options.showVertexNumbers\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body convex hulls debug overlay.\n     *\n     * @property options.showConvexHulls\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the body internal edges debug overlay.\n     *\n     * @property options.showInternalEdges\n     * @type boolean\n     * @default false\n     */\n\n    /**\n     * A flag to enable or disable the mouse position debug overlay.\n     *\n     * @property options.showMousePosition\n     * @type boolean\n     * @default false\n     */\n\n})();\n"
  },
  {
    "path": "test/Browser.spec.js",
    "content": "/* eslint-env es6 */\n\"use strict\";\n\njest.setTimeout(120 * 1000);\n\nconst puppeteer = require('puppeteer-core');\nconst Example = require('../examples/index');\nconst fs = require('fs'); \n\nconst examples = Object.keys(Example);\n\nconst browserPath = '/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome';\nconst demoPagePath = 'http://localhost:8000/';\nconst totalUpdates = 5;\n\nif (!fs.existsSync(browserPath)) {\n  // Skip if browser is missing \n  console.warn('Could not find browser. Browser tests skipped.');\n  describe.skip('Browser integration tests');\n} else {\n  describe('Browser integration tests', () => {\n    let results;\n\n    // Set up the environment and run examples\n    beforeAll(async () => results = await runExamplesBrowser(totalUpdates));\n\n    it('all examples run without throwing error or warning', () => {\n      if (results.error) {\n        console.error(results.error);\n        expect(Boolean(results.error)).toBe(false);\n      }\n      if (results.warns) {\n        console.error(results.warns);\n        expect(results.warns.size).toBe(0);\n      }\n      if (!results.error && !results.warns) {\n        for (const example of examples) {\n          expect(results[example].id).toBe(example);\n          expect(results[example].timestamp).toBeGreaterThan(0);\n        }\n      }\n    });\n  });\n}\n\nconst runExamplesBrowser = async updates => {\n  // Set up browser environment\n  const browser = await puppeteer.launch({ executablePath: browserPath });\n  const page = await browser.newPage();\n  const results = {};\n  let example;\n\n  // Load local demo page and catch errors\n  let pageError;\n  let pageWarns;\n\n  const onPageError = error => pageError = error;\n  const onPageConsole = async message => {\n    const type = message.type();\n    if (example && type === 'error' || type === 'warning') {\n      const log = `[${example}] ${message.type()} ${message.text()}`;\n      pageWarns = pageWarns || new Set();\n      pageWarns.add(log);\n    }\n  }\n\n  page.addListener('pageerror', onPageError);\n  page.addListener('console', onPageConsole);\n\n  await page.goto(demoPagePath).catch(onPageError);\n\n  // For every example\n  for (example of examples) {\n    // Bail on error\n    if (pageError) {\n      break;\n    }\n\n    // In the demo page context\n    results[example] = await page.evaluate(async (example, updates) => {\n      const demo = window.MatterDemoInstance;\n\n      // Set the current example\n      MatterTools.Demo.setExampleById(demo, example);\n      const instance = demo.example.instance;\n      let ticks = 0;\n\n      // Wait while running\n      await new Promise((resolve) => {\n        Matter.Events.on(instance.runner, 'tick', () => {\n          // Stop after enough updates\n          if (ticks >= updates) {\n            Matter.Runner.stop(instance.runner);\n            resolve();\n          }\n          ticks += 1;\n        });\n      });\n\n      // Return results\n      return {\n        id: demo.example.id,\n        timestamp: instance.engine.timing.timestamp\n      };\n    }, example, updates);\n  }\n\n  // Tear down\n  await browser.close();\n\n  results.error = pageError;\n  results.warns = pageWarns;\n  return results;\n};\n"
  },
  {
    "path": "test/ExampleWorker.js",
    "content": "/* eslint-env es6 */\n/* eslint no-global-assign: 0 */\n\"use strict\";\n\nconst mock = require('mock-require');\nconst { requireUncached, serialize, smoothExp } = require('./TestTools');\nconst consoleOriginal = global.console;\nconst DateOriginal = global.Date;\n\nconst runExample = options => {\n  const { \n    Matter,\n    logs,\n    frameCallbacks\n  } = prepareEnvironment(options);\n\n  let memoryDeltaAverage = 0;\n  let timeDeltaAverage = 0;\n  let overlapTotal = 0;\n  let overlapCount = 0;\n  let i;\n  let j;\n\n  try {\n    let runner;\n    let engine;\n    let render;\n    let extrinsicCapture;\n\n    const pairOverlap = (pair) => {\n      const collision = Matter.Collision.collides(pair.bodyA, pair.bodyB);\n      return collision ? Math.max(collision.depth - pair.slop, 0) : -1;\n    };\n\n    for (i = 0; i < options.repeats; i += 1) {\n      if (global.gc) {\n        global.gc();\n      }\n\n      const Examples = requireUncached('../examples/index');\n      const example = Examples[options.name]();\n\n      runner = example.runner;\n      engine = example.engine;\n      render = example.render;\n\n      for (j = 0; j < options.updates; j += 1) {\n        const time = j * runner.delta;\n        const callbackCount = frameCallbacks.length;\n\n        global.timeNow = time;\n\n        for (let p = 0; p < callbackCount; p += 1) {\n          const frameCallback = frameCallbacks.shift();\n          const memoryBefore = process.memoryUsage().heapUsed;\n          const timeBefore = process.hrtime();\n\n          frameCallback(time);\n\n          const timeDuration = process.hrtime(timeBefore);\n          const timeDelta = timeDuration[0] * 1e9 + timeDuration[1];\n          const memoryAfter = process.memoryUsage().heapUsed;\n          const memoryDelta = Math.max(memoryAfter - memoryBefore, 0);\n\n          memoryDeltaAverage = smoothExp(memoryDeltaAverage, memoryDelta);\n          timeDeltaAverage = smoothExp(timeDeltaAverage, timeDelta);\n        }\n\n        let overlapTotalUpdate = 0;\n        let overlapCountUpdate = 0;\n\n        const pairsList = engine.pairs.list;\n        const pairsListLength = engine.pairs.list.length;\n\n        for (let p = 0; p < pairsListLength; p += 1) {\n          const pair = pairsList[p];\n\n          if (pair.isActive && !pair.isSensor){\n            const overlap = pairOverlap(pair);\n\n            if (overlap >= 0) {\n              overlapTotalUpdate += overlap;\n              overlapCountUpdate += 1;\n            }\n          }\n        }\n\n        if (overlapCountUpdate > 0) {\n          overlapTotal += overlapTotalUpdate / overlapCountUpdate;\n          overlapCount += 1;\n        }\n\n        if (!extrinsicCapture && engine.timing.timestamp >= 1000) {\n          extrinsicCapture = captureExtrinsics(engine, Matter);\n          extrinsicCapture.updates = j;\n        }\n      }\n    }\n\n    resetEnvironment();\n\n    return {\n      name: options.name,\n      duration: timeDeltaAverage,\n      memory: memoryDeltaAverage,\n      overlap: overlapTotal / (overlapCount || 1),\n      extrinsic: extrinsicCapture,\n      intrinsic: captureIntrinsics(engine, Matter),\n      state: captureState(engine, runner, render),\n      logs\n    };\n\n  } catch (err) {\n    err.message = `On example '${options.name}' update ${j}:\\n\\n  ${err.message}`;\n    throw err;\n  }\n};\n\nconst prepareMatter = (options) => {\n  const Matter = requireUncached(options.useDev ? '../build/matter.dev' : '../build/matter');\n\n  if (Matter.Common._nextId !== 0) {\n    throw 'Matter instance has already been used.';\n  }\n\n  Matter.Common.info = Matter.Common.warn = Matter.Common.log;\n\n  if (options.stableSort) {\n    if (Matter.Collision) {\n      const MatterCollisionCollides = Matter.Collision.collides;\n      Matter.Collision.collides = function(bodyA, bodyB, pairs) {\n        const _bodyA = bodyA.id < bodyB.id ? bodyA : bodyB;\n        const _bodyB = bodyA.id < bodyB.id ? bodyB : bodyA;\n        return MatterCollisionCollides(_bodyA, _bodyB, pairs);\n      };\n    } else {\n      const MatterSATCollides = Matter.SAT.collides;\n      Matter.SAT.collides = function(bodyA, bodyB, previousCollision, pairActive) {\n        const _bodyA = bodyA.id < bodyB.id ? bodyA : bodyB;\n        const _bodyB = bodyA.id < bodyB.id ? bodyB : bodyA;\n        return MatterSATCollides(_bodyA, _bodyB, previousCollision, pairActive);\n      };\n    }\n\n    Matter.after('Detector.collisions', function() { this.sort(collisionCompareId); });\n    Matter.after('Composite.allBodies', function() { sortById(this); });\n    Matter.after('Composite.allConstraints', function() { sortById(this); });\n    Matter.after('Composite.allComposites', function() { sortById(this); });\n\n    Matter.before('Pairs.update', function(pairs) {\n      pairs.list.sort((pairA, pairB) => collisionCompareId(pairA.collision, pairB.collision));\n    });\n\n    Matter.after('Pairs.update', function(pairs) {\n      pairs.list.sort((pairA, pairB) => collisionCompareId(pairA.collision, pairB.collision));\n    });\n  }\n\n  if (options.jitter) {\n    Matter.after('Body.create', function() {\n      Matter.Body.applyForce(this, this.position, { \n        x: Math.cos(this.id * this.id) * options.jitter * this.mass, \n        y: Math.sin(this.id * this.id) * options.jitter * this.mass\n      });\n    });\n  }\n  \n  return Matter;\n};\n\nconst prepareEnvironment = options => {\n  const logs = [];\n  const frameCallbacks = [];\n\n  global.document = global.window = {\n    performance: {},\n    addEventListener: () => {},\n    requestAnimationFrame: callback => {\n      frameCallbacks.push(callback);\n      return frameCallbacks.length;\n    },\n    createElement: () => ({\n      parentNode: {},\n      width: 800,\n      height: 600,\n      style: {},\n      addEventListener: () => {},\n      setAttribute: () => {},\n      getAttribute: name => ({\n        'data-pixel-ratio': '1'\n      }[name]),\n      getContext: () => new Proxy({}, {\n        get() { return () => {}; }\n      })\n    })\n  };\n\n  global.document.body = global.document.createElement();\n\n  global.Image = function Image() { };\n\n  global.console = { \n    log: (...args) => {\n      logs.push(args.join(' '));\n    }\n  };\n\n  global.Math.random = () => {\n    throw new Error(\"Math.random was called during tests, output can not be compared.\");\n  };\n\n  global.timeNow = 0;\n\n  global.window.performance.now = () => global.timeNow;\n\n  global.Date = function() {\n    this.toString = () => global.timeNow.toString();\n    this.valueOf = () => global.timeNow;\n  };\n\n  global.Date.now = () => global.timeNow;\n\n  const Matter = prepareMatter(options);\n  mock('matter-js', Matter);\n  global.Matter = Matter;\n\n  return {\n    Matter,\n    logs,\n    frameCallbacks\n  };\n};\n\nconst resetEnvironment = () => {\n  global.console = consoleOriginal;\n  global.Date = DateOriginal;\n  global.window = undefined;\n  global.document = undefined;\n  global.Matter = undefined;\n  mock.stopAll();\n};\n\nconst captureExtrinsics = ({ world }, Matter) => ({\n  bodies: Matter.Composite.allBodies(world).reduce((bodies, body) => {\n      bodies[body.id] = {\n        position: { x: body.position.x, y: body.position.y },\n        vertices: body.vertices.map(vertex => ({ x: vertex.x, y: vertex.y }))\n      };\n\n      return bodies;\n  }, {})\n});\n\nconst captureIntrinsics = ({ world, timing }, Matter) => serialize({\n  engine: {\n    timing: {\n      timeScale: timing.timeScale,\n      timestamp: timing.timestamp\n    }\n  },\n  bodies: Matter.Composite.allBodies(world).reduce((bodies, body) => {\n      bodies[body.id] = body;\n      return bodies;\n  }, {}),\n  constraints: Matter.Composite.allConstraints(world).reduce((constraints, constraint) => {\n      constraints[constraint.id] = constraint;\n      return constraints;\n  }, {}),\n  composites: Matter.Composite.allComposites(world).reduce((composites, composite) => {\n      composites[composite.id] = {\n          bodies: Matter.Composite.allBodies(composite).map(body => body.id), \n          constraints: Matter.Composite.allConstraints(composite).map(constraint => constraint.id), \n          composites: Matter.Composite.allComposites(composite).map(composite => composite.id)\n      };\n      return composites;\n  }, {})\n}, (key) => !Number.isInteger(parseInt(key)) && !intrinsicProperties.includes(key));\n\nconst captureState = (engine, runner, render, excludeKeys=excludeStateProperties) => (\n  serialize({ engine, runner, render }, (key) => excludeKeys.includes(key))\n);\n\nconst intrinsicProperties = [\n  // Composite\n  'bodies', 'constraints', 'composites',\n\n  // Common\n  'id', 'label', \n\n  // Constraint\n  'angularStiffness', 'bodyA', 'bodyB', 'damping', 'length', 'stiffness',\n\n  // Body\n  'area', 'collisionFilter', 'category', 'mask', 'group', 'density', 'friction', \n  'frictionAir', 'frictionStatic', 'inertia', 'inverseInertia', 'inverseMass', \n  'isSensor', 'isSleeping', 'isStatic', 'mass', 'parent', 'parts', 'restitution', \n  'sleepThreshold', 'slop', 'timeScale',\n\n  // Composite\n  'bodies', 'constraints', 'composites'\n];\n\nconst extrinsicProperties = [\n  'axes',\n  'vertices',\n  'bounds',\n  'angle',\n  'anglePrev',\n  'angularVelocity',\n  'angularSpeed',\n  'speed',\n  'velocity',\n  'position',\n  'positionPrev',\n  'motion',\n  'sleepCounter',\n  'positionImpulse'\n];\n\nconst excludeStateProperties = [\n  'cache',\n  'grid',\n  'context',\n  'broadphase',\n  'metrics',\n  'controller',\n  'detector',\n  'pairs',\n  'lastElapsed',\n  'deltaHistory',\n  'elapsedHistory',\n  'engineDeltaHistory',\n  'engineElapsedHistory',\n  'timestampElapsedHistory',\n].concat(extrinsicProperties);\n\nconst collisionId = (collision) => \n  Math.min(collision.bodyA.id, collision.bodyB.id) + Math.max(collision.bodyA.id, collision.bodyB.id) * 10000;\n\nconst collisionCompareId = (collisionA, collisionB) => collisionId(collisionA) - collisionId(collisionB);\n\nconst sortById = (objs) => objs.sort((objA, objB) => objA.id - objB.id);\n\nmodule.exports = { runExample };\n"
  },
  {
    "path": "test/Examples.spec.js",
    "content": "/* eslint-env es6 */\n\"use strict\";\n\njest.setTimeout(2 * 60 * 1000);\n\nconst fs = require('fs');\n\nconst {\n    requireUncached,\n    comparisonReport, \n    logReport, \n    toMatchExtrinsics, \n    toMatchIntrinsics,\n    getArg\n} = require('./TestTools');\n\nconst Example = requireUncached('../examples/index');\nconst MatterBuild = requireUncached('../build/matter');\nconst { versionSatisfies } = requireUncached('../src/core/Plugin');\nconst Worker = require('jest-worker').Worker;\n\nconst testComparison = getArg('compare', null) === 'true';\nconst saveComparison = getArg('save', null) === 'true';\nconst specificExamples = getArg('examples', null, (val) => val.split(','));\nconst repeats = getArg('repeats', 1, parseFloat);\nconst updates = getArg('updates', 150, parseFloat);\nconst benchmark = getArg('benchmark', null) === 'true';\n\nconst excludeExamples = ['svg', 'terrain'];\nconst excludeJitter = ['stack', 'circleStack', 'restitution', 'staticFriction', 'friction', 'newtonsCradle', 'catapult'];\n\nconst examples = (specificExamples || Object.keys(Example)).filter(key => {\n    const excluded = excludeExamples.includes(key);\n    const buildVersion = MatterBuild.version;\n    const exampleFor = Example[key].for;\n    const supported = versionSatisfies(buildVersion, exampleFor);\n    return !excluded && supported;\n});\n\nconst captureExamples = async useDev => {\n    const worker = new Worker(require.resolve('./ExampleWorker'), {\n        enableWorkerThreads: true,\n        numWorkers: benchmark ? 1 : undefined\n    });\n\n    const completeRuns = await Promise.all(examples.map(name => worker.runExample({\n        name,\n        useDev,\n        updates: updates,\n        repeats: benchmark ? Math.max(repeats, 3) : repeats,\n        stableSort: false,\n        jitter: excludeJitter.includes(name) ? 0 : 1e-10\n    })));\n\n    await worker.end();\n\n    const capture = {};\n\n    for (const completeRun of completeRuns) {\n        capture[completeRun.name] = completeRun;\n    }\n\n    return capture;\n};\n\nconst capturesDev = captureExamples(true);\nconst capturesBuild = captureExamples(false);\n\nafterAll(async () => {\n    // Report experimental capture comparison.\n    const dev = await capturesDev;\n    const build = await capturesBuild;\n\n    const buildSize = fs.statSync('./build/matter.min.js').size;\n    const devSize = fs.statSync('./build/matter.dev.min.js').size;\n\n    console.log(\n        'Examples ran against previous release and current build\\n\\n'\n        + logReport(build, `release`) + '\\n'\n        + logReport(dev, `current`) + '\\n'\n        + comparisonReport(dev, build, devSize, buildSize, MatterBuild.version, saveComparison, benchmark)\n    );\n});\n\ndescribe(`Integration checks (${examples.length})`, () => {\n    test(`Examples run without throwing`, async () => {\n        const dev = await capturesDev;\n        const build = await capturesBuild;\n        expect(Object.keys(dev)).toEqual(examples);\n        expect(Object.keys(build)).toEqual(examples);\n    });\n});\n\n// Experimental regression comparison checks.\nif (testComparison) {\n    describe(`Regression checks (${examples.length})`, () => {\n        expect.extend(toMatchExtrinsics);\n        expect.extend(toMatchIntrinsics);\n\n        test(`Examples match intrinsic properties with release build`, async () => {\n            const dev = await capturesDev;\n            const build = await capturesBuild;\n            // compare mass, inertia, friction etc.\n            expect(dev).toMatchIntrinsics(build);\n        });\n\n        test(`Examples match extrinsic positions and velocities with release build`, async () => {\n            const dev = await capturesDev;\n            const build = await capturesBuild;\n            // compare position, linear and angular velocity\n            expect(dev).toMatchExtrinsics(build);\n        });\n    });\n}"
  },
  {
    "path": "test/TestTools.js",
    "content": "/* eslint-env es6 */\n\"use strict\";\n\nconst fs = require('fs');\nconst compactStringify = require('json-stringify-pretty-compact');\n\nconst comparePath = './test/__compare__';\nconst compareCommand = 'open http://localhost:8000/?compare';\nconst diffSaveCommand = 'npm run test-save';\nconst diffCommand = 'code -n -d test/__compare__/examples-build.json test/__compare__/examples-dev.json';\nconst equalityThreshold = 1;\nconst colors = { Red: 31, Green: 32, Yellow: 33, White: 37, BrightWhite: 90, BrightCyan: 36 };\n\nconst comparisonReport = (capturesDev, capturesBuild, devSize, buildSize, buildVersion, save, benchmark) => {\n    const {\n        durationChange,\n        memoryChange,\n        overlapChange\n    } = captureBenchmark(capturesDev, capturesBuild);\n\n    const filesizeChange = (devSize / buildSize) - 1;\n\n    const firstCapture = Object.entries(capturesDev)[0][1];\n    const updates = firstCapture.extrinsic.updates;\n\n    const similaritys = extrinsicSimilarity(capturesDev, capturesBuild);\n    const similarityAverage = extrinsicSimilarityAverage(similaritys);\n    const similarityAveragePerUpdate = Math.pow(1, -1 / updates) * Math.pow(similarityAverage, 1 / updates);\n    const similarityEntries = Object.entries(similaritys);\n    similarityEntries.sort((a, b) => a[1] - b[1]);\n\n    const devIntrinsicsChanged = {};\n    const buildIntrinsicsChanged = {};\n    let intrinsicChangeCount = 0;\n\n    const captureSummary = Object.entries(capturesDev)\n        .map(([name]) => {\n            const changedIntrinsics = !equals(capturesDev[name].intrinsic, capturesBuild[name].intrinsic);\n\n            if (changedIntrinsics) {\n                capturesDev[name].changedIntrinsics = true;\n                if (intrinsicChangeCount < 1) {\n                    devIntrinsicsChanged[name] = capturesDev[name].state;\n                    buildIntrinsicsChanged[name] = capturesBuild[name].state;\n                    intrinsicChangeCount += 1;\n                }\n            }\n            \n            return { name };\n        })\n        .sort((a, b) => a.name.localeCompare(b.name));\n\n    const report = (breakEvery, format) => [\n        [`Output sample comparison estimates of ${similarityEntries.length} examples`,\n         `against previous release ${format('matter-js@' + buildVersion, colors.Yellow)}:`\n        ].join(' '),\n\n        `\\n\\n${format(`Similarity`, colors.White)}  `,\n        `${format(formatPercent(similarityAveragePerUpdate, false, true), formatColor(similarityAveragePerUpdate === 1))}% `,\n\n        ` ${format('Overlap', colors.White)}`,\n        ` ${format(formatPercent(overlapChange), formatColor(overlapChange <= 0))}%`,\n\n        ` ${format('Filesize', colors.White)}`,\n        `${format(formatPercent(filesizeChange), formatColor(filesizeChange <= 0))}%`,\n        `${format(`${(devSize / 1024).toPrecision(4)} KB`, colors.White)}`,\n\n        ...(benchmark ? [\n            `\\n${format('Performance', colors.White)}`,\n            ` ${format(formatPercent(durationChange), formatColor(durationChange >= 0))}%`,\n    \n            `  ${format('Memory', colors.White)} `,\n            ` ${format(formatPercent(memoryChange), formatColor(memoryChange <= 0))}%`,\n        ] : []),\n\n        captureSummary.reduce((output, p, i) => {\n            output += `${p.name} `;\n            output += `${similarityRatings(similaritys[p.name])} `;\n            output += `${changeRatings(capturesDev[p.name].changedIntrinsics)} `;\n            if (i > 0 && i < captureSummary.length && breakEvery > 0 && i % breakEvery === 0) {\n                output += '\\n';\n            }\n            return output;\n        }, '\\n\\n'),\n\n        `\\n\\nwhere for the sample  · no change detected  ● extrinsics changed  ◆ intrinsics changed\\n`,\n\n        similarityAverage < 1 ? `\\n${format('▶', colors.White)} ${format(compareCommand + '=' + 150 + '#' + similarityEntries[0][0], colors.BrightCyan)}` : '',\n        intrinsicChangeCount > 0 ? `\\n${format('▶', colors.White)} ${format((save ? diffCommand : diffSaveCommand), colors.BrightCyan)}` : ''\n    ].join('  ');\n\n    if (save) {\n        writeResult('examples-dev', devIntrinsicsChanged);\n        writeResult('examples-build', buildIntrinsicsChanged);\n        writeResult('examples-report', report(5, s => s));\n    }\n\n    return report(5, color);\n};\n\nconst similarityRatings = similarity => similarity < equalityThreshold ? color('●', colors.Yellow) : '·';\n\nconst changeRatings = isChanged => isChanged ? color('◆', colors.White) : '·';\n\nconst color = (text, number) => number ? `\\x1b[${number}m${text}\\x1b[0m` : text;\n\nconst formatColor = isGreen => isGreen ? colors.Green : colors.Yellow;\n\nconst formatPercent = (val, showSign=true, showFractional=false, padStart=6) => {\n    let fractionalSign = '';\n\n    if (showFractional && val > 0.9999 && val < 1) {\n        val = 0.9999;\n        fractionalSign = '>';\n    } else if (showFractional && val > 0 && val < 0.0001) {\n        val = 0.0001;\n        fractionalSign = '<';\n    }\n\n    const percentFixed = Math.abs(100 * val).toFixed(2);\n    const sign = parseFloat((100 * val).toFixed(2)) >= 0 ? '+' : '-';\n    return ((showFractional ? fractionalSign : '') + (showSign ? sign : '') + percentFixed).padStart(padStart, ' ');\n};\n\nconst noiseThreshold = (val, threshold) => {\n    const sign = val < 0 ? -1 : 1;\n    const magnitude = Math.abs(val);\n    return sign * Math.max(0, magnitude - threshold) / (1 - threshold);\n};\n\nconst median = (values, lower, upper) => {\n    const valuesSorted = values.slice(0).sort();\n\n    return mean(valuesSorted.slice(\n        Math.floor(valuesSorted.length * lower), \n        Math.floor(valuesSorted.length * upper)\n    ));\n};\n\nconst mean = (values) => {\n    const valuesLength = values.length;\n    let result = 0;\n\n    for (let i = 0; i < valuesLength; i += 1) {\n        result += values[i];\n    }\n\n    return (result / valuesLength) || 0;\n};\n\nconst smoothExp = (last, current) => {\n    const delta = current - last;\n    const sign = delta < 0 ? -1 : 1;\n    const magnitude = Math.abs(delta);\n\n    if (magnitude < 1) {\n        return last + 0.01 * delta;\n    }\n\n    return last + Math.sqrt(magnitude) * sign;\n};\n\nconst equals = (a, b) => {\n    try {\n        expect(a).toEqual(b);\n    } catch (e) {\n        return false;\n    }\n    return true;\n};\n\nconst captureBenchmark = (capturesDev, capturesBuild) => {\n    const overlapChanges = [];\n\n    let durationDev = 0;\n    let durationBuild = 0;\n    let memoryDev = 0;\n    let memoryBuild = 0;\n\n    for (const name in capturesDev) {\n        durationDev += capturesDev[name].duration;\n        durationBuild += capturesBuild[name].duration;\n\n        memoryDev += capturesDev[name].memory;\n        memoryBuild += capturesBuild[name].memory;\n\n        if (capturesBuild[name].overlap > 0.1 && capturesDev[name].overlap > 0.1){\n            overlapChanges.push(capturesDev[name].overlap / capturesBuild[name].overlap);\n        }\n    };\n\n    const durationChange = 1 - noiseThreshold(durationDev / durationBuild, 0.02);\n    const memoryChange = noiseThreshold(memoryDev / memoryBuild, 0.02) - 1;\n    const overlapChange = noiseThreshold(median(overlapChanges, 0.45, 0.55), 0.001) - 1;\n\n    return {\n        durationChange, \n        memoryChange, \n        overlapChange\n    };\n};\n\nconst extrinsicSimilarity = (currentCaptures, referenceCaptures, key='extrinsic') => {\n    const result = {};\n    const zeroVector = { x: 0, y: 0 };\n\n    for (const name in currentCaptures) {\n        const currentExtrinsic = currentCaptures[name][key];\n        const referenceExtrinsic = referenceCaptures[name][key];\n\n        let totalCount = 0;\n        let totalSimilarity = 0;\n\n        for (const objectType in currentExtrinsic) {\n            for (const objectId in currentExtrinsic[objectType]) {\n                const currentObject = currentExtrinsic[objectType][objectId];\n                const referenceObject = referenceExtrinsic[objectType][objectId];\n\n                for (let i = 0; i < currentObject.vertices.length; i += 1) {\n                    const currentPosition = currentObject.position;\n                    const currentVertex = currentObject.vertices[i];\n                    const referenceVertex = referenceObject.vertices[i] ? referenceObject.vertices[i] : zeroVector;\n\n                    const radius = Math.sqrt(\n                        Math.pow(currentVertex.x - currentPosition.x, 2)\n                        + Math.pow(currentVertex.y - currentPosition.y, 2)\n                    );\n\n                    const distance = Math.sqrt(\n                        Math.pow(currentVertex.x - referenceVertex.x, 2)\n                        + Math.pow(currentVertex.y - referenceVertex.y, 2)\n                    );\n\n                    totalSimilarity += Math.min(1, distance / (2 * radius)) / currentObject.vertices.length;\n                }\n\n                totalCount += 1;\n            }\n        }\n\n        result[name] = 1 - (totalSimilarity / (totalCount || 1));\n    }\n\n    return result;\n};\n\nconst extrinsicSimilarityAverage = (similaritys) => {\n    const entries = Object.entries(similaritys);\n    let average = 0;\n\n    entries.forEach(([_, similarity]) => average += similarity);\n\n    return average /= entries.length;\n};\n\nconst serialize = (obj, exclude=()=>false, precision=4, path='$', visited=[], paths=[]) => {\n    if (typeof obj === 'number') {\n        return parseFloat(obj.toPrecision(precision));\n    } else if (typeof obj === 'string' || typeof obj === 'boolean') {\n        return obj;\n    } else if (obj === null) {\n        return 'null';\n    } else if (typeof obj === 'undefined') {\n        return 'undefined';\n    } else if (obj === Infinity) {\n        return 'Infinity';\n    } else if (obj === -Infinity) {\n        return '-Infinity';\n    } else if (typeof obj === 'function') {\n        return 'function';\n    } else if (Array.isArray(obj)) {\n        return obj.map(\n            (item, index) => serialize(item, exclude, precision, path + '.' + index, visited, paths)\n        );\n    }\n  \n    const visitedIndex = visited.indexOf(obj);\n  \n    if (visitedIndex !== -1) {\n      return paths[visitedIndex];\n    }\n  \n    visited.push(obj);\n    paths.push(path);\n  \n    const result = {};\n  \n    for (const key of Object.keys(obj).sort()) {\n      if (!exclude(key, obj[key], path + '.' + key)) {\n        result[key] = serialize(obj[key], exclude, precision, path + '.' + key, visited, paths);\n      }\n    }\n  \n    return result;\n};\n\nconst writeResult = (name, obj) => {\n    try {\n        fs.mkdirSync(comparePath, { recursive: true });\n    } catch (err) {\n        if (err.code !== 'EEXIST') throw err;\n    }\n\n    if (typeof obj === 'string') {\n        fs.writeFileSync(`${comparePath}/${name}.md`, obj, 'utf8');\n    } else {\n        fs.writeFileSync(`${comparePath}/${name}.json`, compactStringify(obj, { maxLength: 100 }), 'utf8');\n    }\n};\n\nconst logReport = (captures, version) => {\n    let report = '';\n\n    for (const capture of Object.values(captures)) {\n        if (!capture.logs.length) {\n            continue;\n        }\n\n        report += `  ${capture.name}\\n`;\n\n        for (const log of capture.logs) {\n            report += `    ${log}\\n`;\n        }\n    }\n\n    return `Output logs from ${color(version, colors.Yellow)} build on last run\\n\\n` \n        + (report ? report : '  None\\n');\n};\n\nconst requireUncached = path => {\n    delete require.cache[require.resolve(path)];\n    const module = require(path);\n    delete require.cache[require.resolve(path)];\n    return module;\n};\n\nconst getArg = (name, defaultValue=null, parser=(v) => v) => {\n    const value = process.argv.find(arg => arg.startsWith(`--${name}=`));\n    return value ? parser(value.split('=')[1]) : defaultValue;\n};\n\nconst toMatchExtrinsics = {\n    toMatchExtrinsics(received, value) {\n        const similaritys = extrinsicSimilarity(received, value, 'extrinsic');\n        const pass = Object.values(similaritys).every(similarity => similarity >= equalityThreshold);\n\n        return {\n            message: () => 'Expected positions and velocities to match between builds.',\n            pass\n        };\n    }\n};\n\nconst toMatchIntrinsics = {\n    toMatchIntrinsics(currentCaptures, referenceCaptures) {\n        const entries = Object.entries(currentCaptures);\n        let changed = false;\n\n        entries.forEach(([name, current]) => {\n            const reference = referenceCaptures[name];\n            if (!this.equals(current.intrinsic, reference.intrinsic)) {\n                changed = true;\n            }\n        });\n\n        return {\n            message: () => 'Expected intrinsic properties to match between builds.',\n            pass: !changed\n        };\n    }\n};\n\nmodule.exports = {\n    requireUncached, comparisonReport, logReport, getArg, smoothExp,\n    serialize, toMatchExtrinsics, toMatchIntrinsics\n};"
  },
  {
    "path": "webpack.config.js",
    "content": "/* eslint-env es6 */\n\"use strict\";\n\nconst webpack = require('webpack');\nconst path = require('path');\nconst pkg = require('./package.json');\nconst fs = require('fs');\nconst execSync = require('child_process').execSync;\n\nmodule.exports = (env = {}) => {\n    const minimize = env.MINIMIZE || false;\n    const kind = env.KIND || null;\n    const sizeThreshold = minimize ? 100 * 1024 : 512 * 1024;\n\n    const commitHash = execSync('git rev-parse --short HEAD').toString().trim();\n    const version = !kind ? pkg.version : `${pkg.version}-${kind}+${commitHash}`;\n    const license = fs.readFileSync('LICENSE', 'utf8');\n    const resolve = relativePath => path.resolve(__dirname, relativePath);\n    \n    const banner = \n`${pkg.name} ${version} by @liabru\n${kind ? 'Experimental pre-release build.\\n  ' : ''}${pkg.homepage}\nLicense ${pkg.license}${!minimize ? '\\n\\n' + license : ''}`;\n\n    return {\n        entry: { 'matter': './src/module/main.js' },\n        node: false,\n        output: {\n            library: 'Matter',\n            libraryTarget: 'umd',\n            umdNamedDefine: true,\n            globalObject: 'this',\n            path: resolve('./build'),\n            filename: `[name]${kind ? '.' + kind : ''}${minimize ? '.min' : ''}.js`\n        },\n        optimization: { minimize },\n        performance: {\n            maxEntrypointSize: sizeThreshold,\n            maxAssetSize: sizeThreshold\n        },\n        plugins: [\n            new webpack.BannerPlugin(banner),\n            new webpack.DefinePlugin({\n                __MATTER_VERSION__: JSON.stringify(version),\n            })\n        ],\n        externals: {\n            'poly-decomp': {\n                commonjs: 'poly-decomp',\n                commonjs2: 'poly-decomp',\n                amd: 'poly-decomp',\n                root: 'decomp'\n            },\n            'matter-wrap': {\n                commonjs: 'matter-wrap',\n                commonjs2: 'matter-wrap',\n                amd: 'matter-wrap',\n                root: 'MatterWrap'\n            }\n        }\n    };\n};\n"
  },
  {
    "path": "webpack.demo.config.js",
    "content": "/* eslint-env es6 */\n\"use strict\";\n\nconst webpack = require('webpack');\nconst path = require('path');\nconst pkg = require('./package.json');\nconst BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\nconst TerserPlugin = require('terser-webpack-plugin');\n\nmodule.exports = (env = {}) => {\n    const version = pkg.version;\n    const analyze = env.ANALYZE || false;\n    const devServer = Boolean(process.env.WEBPACK_DEV_SERVER);\n    const minimize = !devServer;\n    const sizeThreshold = 600 * 1024;\n\n    const publicPath = devServer ? '/' : './js';\n    const devPath = './src/module/main.js';\n    const buildPath = './build/matter.js';\n    const resolve = relativePath => path.resolve(__dirname, relativePath);\n    \n    const name = 'matter-demo';\n    const banner = \n`${name} bundle ${version} by @liabru\n${pkg.homepage}\nLicense ${pkg.license}`;\n\n    return {\n        entry: { [name]: './demo/src/index.js' },\n        node: false,\n        devtool: devServer ? false : 'none',\n        output: {\n            library: 'MatterDemo',\n            libraryTarget: 'umd',\n            umdNamedDefine: true,\n            globalObject: 'this',\n            publicPath,\n            path: resolve('./demo/js'),\n            filename: `[name].[contenthash:6]${minimize ? '.min' : ''}.js`\n        },\n        resolve: {\n            alias:{\n                'matter-js': resolve(devPath),\n                'MatterDev': resolve(devPath),\n                'MatterBuild': resolve(\n                    devServer ? buildPath : devPath\n                )\n            }\n        },\n        optimization: {\n            minimize,\n            minimizer: [new TerserPlugin({ extractComments: false })],\n            moduleIds: 'hashed',\n            runtimeChunk: { name: `${name}.main` },\n            splitChunks: {\n                automaticNameDelimiter: '.',\n                cacheGroups: {\n                    default: false,\n                    vendors: false,\n                    vendor: {\n                        chunks: 'all',\n                        enforce: true,\n                        test: /[\\\\/]node_modules[\\\\/]/,\n                        name: module => {\n                            if (devServer) {\n                                return `${name}.vendor`;\n                            }\n                            const parser = /[\\\\/]node_modules[\\\\/](.*?)([\\\\/]|$)/;\n                            const moduleName = module.context.match(parser)[1];\n                            return `${name}.${moduleName.replace('@', '')}`;\n                        }\n                    },\n                },\n            },\n        },\n        performance: {\n            maxEntrypointSize: sizeThreshold,\n            maxAssetSize: sizeThreshold\n        },\n        plugins: [\n            new webpack.BannerPlugin(banner),\n            new webpack.DefinePlugin({\n                __MATTER_VERSION__: JSON.stringify('*'),\n                __MATTER_IS_DEV__: devServer\n            }),\n            new HtmlWebpackPlugin({\n                template: resolve('./demo/src/index.ejs'),\n                filename: devServer ? 'index.html' \n                    : resolve('./demo/index.html'),\n                inject: false,\n                minify: false,\n                publicPath\n            })\n        ].concat(analyze ? [new BundleAnalyzerPlugin({\n            openAnalyzer: true\n        })] : []),\n        devServer: {\n            contentBase: [resolve('./demo')],\n            watchContentBase: true,\n            hot: false,\n            compress: true,\n            overlay: true,\n            port: 8000\n        }\n    };\n};\n"
  },
  {
    "path": "yuidoc.json",
    "content": "{\n  \"name\": \"Matter.js Physics Engine API Docs\",\n  \"description\": \"a 2D rigid body physics engine for the web\",\n  \"url\": \"http://brm.io/matter-js/\",\n  \"options\": {\n      \"linkNatives\": true,\n      \"outdir\": \"docs\",\n      \"themedir\": \"matter-doc-theme\",\n      \"paths\": \"src\"\n  }\n}"
  }
]