diff --git a/activities.json b/activities.json index 98d5c0244b..9cd7fc751e 100644 --- a/activities.json +++ b/activities.json @@ -1,4 +1,5 @@ [ + {"id": "org.sugarlabs.3DVolume", "name": "3D Volume", "version": 1, "directory": "activities/3DVolume.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null}, {"id": "org.olpcfrance.XmasLights", "name": "Xmas Lights", "version": 1, "directory": "activities/XmasLights.activity", "icon": "activity/activity-icon.svg", "favorite": false, "activityId": null}, {"id": "org.olpcfrance.DollarStreet", "name": "Dollar Street", "version": 1, "directory": "activities/DollarStreet.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null}, {"id": "org.sugarlabs.Tangram", "name": "Tangram", "version": 1, "directory": "activities/Tangram.activity", "icon": "activity/activity-icon.svg", "favorite": true, "activityId": null}, diff --git a/activities/3DVolume.activity/LICENSE b/activities/3DVolume.activity/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/activities/3DVolume.activity/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/activities/3DVolume.activity/NOTICE b/activities/3DVolume.activity/NOTICE new file mode 100644 index 0000000000..004c62e1b1 --- /dev/null +++ b/activities/3DVolume.activity/NOTICE @@ -0,0 +1,13 @@ +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/activities/3DVolume.activity/activity/activity-icon.svg b/activities/3DVolume.activity/activity/activity-icon.svg new file mode 100644 index 0000000000..3338761866 --- /dev/null +++ b/activities/3DVolume.activity/activity/activity-icon.svg @@ -0,0 +1,75 @@ + + + +]> + + + + + + + diff --git a/activities/3DVolume.activity/activity/activity.info b/activities/3DVolume.activity/activity/activity.info new file mode 100644 index 0000000000..19af2d93b6 --- /dev/null +++ b/activities/3DVolume.activity/activity/activity.info @@ -0,0 +1,6 @@ +[Activity] +name = 3D Volume +activity_version = 1 +bundle_id = org.sugarlabs.3DVolume +exec = sugar-activity-web +icon = activity-icon \ No newline at end of file diff --git a/activities/3DVolume.activity/css/activity.css b/activities/3DVolume.activity/css/activity.css new file mode 100644 index 0000000000..c00ae1ab72 --- /dev/null +++ b/activities/3DVolume.activity/css/activity.css @@ -0,0 +1,613 @@ +#main-toolbar #activity-button { + background-image: url(../activity/activity-icon.svg); +} +#main-toolbar #network-button { + background-image: url(../lib/sugar-web/graphics/icons/actions/zoom-home.svg); +} +.toolbar hr { + vertical-align: bottom; + margin-bottom: 10px; + height: 45px; +} +.toolbar { + display: flex; + justify-content: space-between; +} +.left-container { + display: flex; +} + +#private-button { + background-image: url(../lib/sugar-web/graphics/icons/actions/zoom-home.svg); + width: 47px; + height: 47px; + margin: 4px 2px; + color: white; + color: transparent; + background-color: transparent; + background-position: center; + background-repeat: no-repeat; + background-size: contain; + border: 0; + border-radius: 5.5px; +} + +#shared-button { + background-image: url(../lib/sugar-web/graphics/icons/actions/zoom-neighborhood.svg); + width: 47px; + height: 47px; + margin: 4px 2px; + color: white; + color: transparent; + background-color: transparent; + background-position: center; + background-repeat: no-repeat; + background-size: contain; + border: 0; + border-radius: 5.5px; +} + +body { + height: 100vh; +} +#main-toolbar #bg-button { + background-image: url(../icons/insert-picture.svg); + outline: none; +} +#volume-button { + background-image: url(../icons/default_volume.svg); + outline: none; + +} +#main-toolbar #clear-button { + background-image: url(../icons/minus.svg); + outline: none; +} +#clear-button.active { + background-color: #d3d3d3; +} + +#main-toolbar #solid-button { + background-image: url(../icons/cube_solid.svg); + height: 100px; + width: 65px; + background-size: cover; + background-repeat: no-repeat; + outline: none; +} +#number-button { + height: 65px; + width: 65px; + background-size: cover; + background-repeat: no-repeat; + background-image: url(../icons/number_volume.svg); + border-radius: 5px; +} +#fullscreen-button { + background-image: url(../icons/view-fullscreen.svg); +} + +#unfullscreen-button { + background-image: url(../icons/view-return.svg); + border: 0; + border-radius: 0px; + margin: 1px; + width: 45px; + height: 45px; + top: 10px; + right: 15px; + position: absolute; + visibility: hidden; +} + +#zoom-button { + height: 45px; + width: 45xpx; + background-size: cover; + background-repeat: no-repeat; + background-image: url(../icons/glass.svg); + outline: none; + +} +#throw-button { + height: 45px; + width: 45xpx; + background-size: cover; + background-repeat: no-repeat; + background-image: url(../icons/throw.svg); + outline: none; +} +#sensor-button { + height: 45px; + width: 45xpx; + background-size: cover; + background-repeat: no-repeat; + background-image: url(../icons/sensor.svg); + outline: none; +} +#transparent-button { + margin: 0; + padding: 0; + height: 65px; + width: 65px; + background-size: contain; + background-repeat: no-repeat; + background-image: url(../icons/transparent_volume.svg); + border-radius: 5px; +} + +#default-button { + margin: 0; + padding: 0; + height: 65px; + width: 65px; + background-size: contain; + background-repeat: no-repeat; + background-image: url(../icons/default_volume.svg); + outline: none; + border-radius: 5px; +} + +#colors-button-fill { + display: none; +} +.button-background { + background-color: #000; +} +#cube-button { + background-image: url(../icons/cube.svg); + outline: none; + background-repeat: no-repeat; + background-position: center; + background-size: calc(100% - 5px) calc(100% - 5px); /* Adjust the values as needed */ +} +#tetra-button { + background-image: url(../icons/tetra.svg); + outline: none; + background-repeat: no-repeat; + background-size: cover; + background-size: calc(100% - 10px) calc(100% - 10px); /* Adjust the values as needed */ + +} +#octa-button { + background-image: url(../icons/octa.svg); + outline: none; + background-repeat: no-repeat; + background-size: cover; + background-size: calc(100% - 10px) calc(100% - 10px); /* Adjust the values as needed */ + +} +#dodeca-button { + background-image: url(../icons/dodeca.svg); + outline: none; + background-repeat: no-repeat; + background-size: cover; + background-size: calc(100% - 10px) calc(100% - 10px); /* Adjust the values as needed */ + +} +#deca-button { + background-image: url(../icons/deca.svg); + outline: none; + background-repeat: no-repeat; + background-size: cover; + background-size: calc(100% - 5px) calc(100% - 5px); /* Adjust the values as needed */ + +} +#icosa-button { + background-image: url(../icons/icosa.svg); + outline: none; + margin-left: 10px; + background-repeat: no-repeat; + background-size: cover; + background-size: calc(100% - 10px) calc(100% - 10px); /* Adjust the values as needed */ + +} +.active { + background-color: #656565 !important; +} + +#main-toolbar #help-button { + background-image: url(../icons/help.svg); +} +/* #main-toolbar { + visibility: hidden; +} */ +.vertical-line { + width: 5px; + height: 55px; + background-color: white; + transform: translateX(-50%); + margin-left: 5px; + margin-right: 5px; +} + +.selector { + display: flex; +} +.bg-select { + /* padding: 10px; */ + width: fit-content; + text-align: center; + background-color: black; +} +.bg-select button { + border: none; + border-radius: 0; +} +.bg-select-item { + display: flex; + align-items: center; + justify-content: center; + margin: 0 auto; + background: transparent; + width: 90%; +} +.bg-select-item img { + width: 40px; + margin: 10px; +} +.bg-select-item div { + margin: 0 10px; +} +#main-toolbar #reset-button { + background-image: url(../icons/restart.svg); +} +#main-toolbar #image-button { + background-image: url(../icons/image.svg); +} +body { + margin: 0; + color: var(--color-text); + background-color: var(--color-bg); + font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +body { + margin: 0; + overflow: hidden; + height: 100vh; +} + +.gray-rectangle { + width: 50px; /* Adjust the width as needed */ + height: 25px; /* Adjust the height as needed */ + background-color: #9C9C9C; + margin-bottom: 5px; /* Adjust the spacing between the rectangle and the text as needed */ +} + +#wood img { + margin-right: 25px; +} + +#game-container { + position: absolute; +} + +/* #throw-button { + position: absolute; + top: 20px; + left: 20px; + padding: 10px; + font-size: 16px; + cursor: pointer; + background-color: #3498db; + color: #fff; + border: none; + border-radius: 5px; + outline: none; +} */ + +#score-container { + position: absolute; + height: 70vh; + width: 70vh; + top: 70px; + left: 20px; + font-size: 16px; + color: #fff; + border: none; + outline: none; +} + +#sum-display { + position: absolute; + top: 20px; + right: 20px; + font-size: 18px; +} + +#last-roll { + position: fixed; + bottom: 100px; + right: 100px; + font-size: 1.5rem; +} +#roll { + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; /* Non-prefixed version, currently supported by most browsers */ + +} + +.color-palette { + display: flex; + width: 370px; /* ugly hack */ + background-color: #000000; + border: #808080 2px solid; +} + +#color-grid-fill { + display: grid; + grid-template-columns: repeat(3, 50px); + grid-gap: 10px; + margin-left: 5px; + margin-bottom: 5px; + margin-top: 5px; + margin-right: 5px; +} +#color-grid-text { + display: grid; + grid-template-columns: repeat(3, 50px); + grid-gap: 10px; + margin-left: 5px; + margin-bottom: 5px; + margin-top: 5px; + margin-right: 5px; +} + +.slider-container { + display: flex; + margin-top: 10px; + margin-bottom: 10px; +} + +#zoom-in-button { + background-image: url(../icons/zoom-in.svg); + width: 50px; + height: 50px; + background-color: #000000; + background-size: cover; + background-repeat: no-repeat; +} + +#zoom-out-button { + background-image: url(../icons/zoom-out.svg); + width: 50px; + height: 50px; + background-color: #000000; + background-size: cover; + background-repeat: no-repeat; +} + +#zoom-equal-button { + background-image: url(../icons/zoom-original.svg); + width: 50px; + height: 50px; + background-color: #000000; + background-size: cover; + background-repeat: no-repeat; +} + +#zoom-to-button { + background-image: url(../icons/zoom-to-width.svg); + width: 50px; + height: 50px; + background-color: #000000; + background-size: cover; + background-repeat: no-repeat; +} + +#right-button { + background-image: url(../icons/go-right.svg); +} +#up-button { + background-image: url(../icons/go-right.svg); + transform: rotate(-90deg); +} +#down-button { + background-image: url(../icons/go-left.svg); + transform: rotate(-90deg); +} + +#left-button { + background-image: url(../icons/go-left.svg); +} +#increase-button { + background-image: url(../icons/go-left.svg); +} +#try-button { + background-image: url(../icons/go-left.svg); + transform: rotate(-90deg); +} + +.arrow-container { + width: 50%; + display: flex; + flex-direction: column; + align-items: center; + /* background-color:white; */ +} + +.arrow-button { + width: 50px; + height: 50px; + border: none; + background-size: contain; + background-repeat: no-repeat; + margin: 5px 0; +} + +.left-right-buttons { + display: flex; + justify-content: space-between; + /* background-color:pink; */ + width: 80%; +} + +.left-right-buttons .arrow-button { + margin: 0 5px; +} + +.color-fill { + width: 45px; /* Decreased circle size */ + height: 45px; /* Decreased circle size */ + border-radius: 50%; + cursor: pointer; + border: white solid 2px; +} + +.color-text { + width: 45px; /* Decreased circle size */ + height: 45px; /* Decreased circle size */ + border-radius: 50%; + cursor: pointer; + border: white solid 2px; +} + +/* UI styling for introJs-tutorial */ + +.introjs-overlay { + background-color: #000 !important; + opacity: .8 !important; +} + +.introjs-tooltip { + font-family: "Helvetica Neue",Helvetica,Arial,sans-serif!important; + border-radius: 6px !important; + padding: 2px 1px !important; + font-size: 14px !important; +} + +.introjs-helperLayer{ + background: inherit !important; + opacity: 0.6 !important; +} + +.customTooltip .introjs-tooltip-header { + font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; + color : #ffffff; + text-shadow: none; + background-color: #808080; + margin: 0; + padding: 0px 10px; + border-bottom: 1px solid #ebebeb; + border-radius: 5px 5px 0 0; +} + +.customTooltip .introjs-tooltip-title { + font-size: 14px; + padding: 0px 8px; + font-weight: 800; +} + +.customTooltip .introjs-tooltiptext { + color: #000000; + line-height: 1.42857143; +} + +.customTooltip .introjs-skipbutton { + float: right; + cursor: pointer; + background-image: url(../icons/dialog-cancel.svg); + width: 25px; + height: 25px; + background-size: 25px 25px; + margin-top: 2px; + padding: 0px; + white-space: nowrap; + color: transparent; + line-height: 27px; +} + +.customTooltip .introjs-nextbutton::before { + content: ""; + margin-right: 6px; + background-image: url(../icons/go-right.svg); + width: 20px; + height: 20px; + background-size: 20px 20px; +} + +.customTooltip .introjs-prevbutton::before { + content: ""; + margin-right: 6px; + background-image: url(../icons/go-left.svg); + width: 20px; + height: 20px; + background-size: 20px 20px; +} + +.customTooltip .introjs-tooltipbuttons { + display: flex; + flex-wrap:wrap; + justify-content: center; + align-items: center; + cursor: pointer; + border-top: 0px; + padding: 0px; + text-align: center; + white-space: normal; +} + +.customTooltip .introjs-button { + text-shadow: none; + border-radius: 22px; + margin: 5px 8px 8px 8px; + width: fit-content; + background-color: #808080 !important; + display: flex !important; + align-items: center !important; + color: white !important; + padding: 6px 20px 6px 10px; + border: 0px; +} + +.customTooltip .introjs-button:focus { + -webkit-box-shadow: 0 0 0 0rem rgba(158, 158, 158, .5); + box-shadow: 0 0 0 0rem rgba(158, 158, 158, .5); + border: 0px; + background-color: #808080 !important; +} + +.customTooltip .introjs-disabled { + color: black !important; + border: 0px; + opacity: .65; +} + +.customTooltip .introjs-disabled:focus { + -webkit-box-shadow: 0 0 0 0rem rgba(158, 158, 158, .5); + box-shadow: 0 0 0 0rem rgba(158, 158, 158, .5); + border: 0px; +} + +@media (max-width: 1120px) { + #color-button-text, + #bg-button, + #zoom-button { + display: none; + } + + /* Adjust remaining buttons to fit within the toolbar */ + .toolbutton { + margin: 2px; + width: 40px; + height: 40px; + } +} + +@media (max-width: 800px) { + #volume-button, #color-button-fill, #remove-first { + display: none; + } +} + +@media (max-width: 690px) { + #sensor-button, #throw-button { + display: none; + } +} diff --git a/activities/3DVolume.activity/css/introjs.css b/activities/3DVolume.activity/css/introjs.css new file mode 100644 index 0000000000..d9d8459844 --- /dev/null +++ b/activities/3DVolume.activity/css/introjs.css @@ -0,0 +1,543 @@ +.introjs-overlay { + position: absolute; + -webkit-box-sizing: content-box; + box-sizing: content-box; + z-index: 999999; + opacity: 0; + -webkit-transition: all .3s ease-out; + -o-transition: all .3s ease-out; + transition: all .3s ease-out +} + +.introjs-showElement { + z-index: 9999999 !important +} + +tr.introjs-showElement>td { + z-index: 9999999 !important; + position: relative +} + +tr.introjs-showElement>th { + z-index: 9999999 !important; + position: relative +} + +.introjs-disableInteraction { + z-index: 99999999 !important; + position: absolute; + background-color: #fff; + opacity: 0 +} + +.introjs-relativePosition { + position: relative +} + +.introjs-helperLayer { + -webkit-box-sizing: content-box; + box-sizing: content-box; + position: absolute; + z-index: 9999998; + border-radius: 4px; + -webkit-transition: all .3s ease-out; + -o-transition: all .3s ease-out; + transition: all .3s ease-out +} + +.introjs-helperLayer * { + -webkit-box-sizing: content-box; + box-sizing: content-box +} + +.introjs-helperLayer :before { + -webkit-box-sizing: content-box; + box-sizing: content-box +} + +.introjs-helperLayer :after { + -webkit-box-sizing: content-box; + box-sizing: content-box +} + +.introjs-tooltipReferenceLayer { + font-family: "Helvetica Neue", Inter, ui-sans-serif, "Apple Color Emoji", Helvetica, Arial, sans-serif; + -webkit-box-sizing: content-box; + box-sizing: content-box; + position: absolute; + visibility: hidden; + z-index: 100000000; + background-color: transparent; + -webkit-transition: all .3s ease-out; + -o-transition: all .3s ease-out; + transition: all .3s ease-out +} + +.introjs-tooltipReferenceLayer * { + font-family: "Helvetica Neue", Inter, ui-sans-serif, "Apple Color Emoji", Helvetica, Arial, sans-serif +} + +.introjs-helperNumberLayer { + font-family: "Helvetica Neue", Inter, ui-sans-serif, "Apple Color Emoji", Helvetica, Arial, sans-serif; + color: #9e9e9e; + text-align: center; + padding-top: 10px; + padding-bottom: 10px +} + +.introjs-arrow { + border: 5px solid transparent; + content: ""; + position: absolute +} + +.introjs-arrow.top { + top: -10px; + left: 10px; + border-bottom-color: #fff +} + +.introjs-arrow.top-right { + top: -10px; + right: 10px; + border-bottom-color: #fff +} + +.introjs-arrow.top-middle { + top: -10px; + left: 50%; + margin-left: -5px; + border-bottom-color: #fff +} + +.introjs-arrow.right { + right: -10px; + top: 10px; + border-left-color: #fff +} + +.introjs-arrow.right-bottom { + bottom: 10px; + right: -10px; + border-left-color: #fff +} + +.introjs-arrow.bottom { + bottom: -10px; + left: 10px; + border-top-color: #fff +} + +.introjs-arrow.bottom-right { + bottom: -10px; + right: 10px; + border-top-color: #fff +} + +.introjs-arrow.bottom-middle { + bottom: -10px; + left: 50%; + margin-left: -5px; + border-top-color: #fff +} + +.introjs-arrow.left { + left: -10px; + top: 10px; + border-right-color: #fff +} + +.introjs-arrow.left-bottom { + left: -10px; + bottom: 10px; + border-right-color: #fff +} + +.introjs-tooltip { + -webkit-box-sizing: content-box; + box-sizing: content-box; + position: absolute; + visibility: visible; + background-color: #fff; + min-width: 250px; + max-width: 300px; + border-radius: 5px; + -webkit-box-shadow: 0 3px 30px rgba(33, 33, 33, .3); + box-shadow: 0 3px 30px rgba(33, 33, 33, .3); + -webkit-transition: opacity .1s ease-out; + -o-transition: opacity .1s ease-out; + transition: opacity .1s ease-out +} + +.introjs-tooltiptext { + padding: 20px +} + +.introjs-dontShowAgain { + padding-left: 20px; + padding-right: 20px +} + +.introjs-dontShowAgain input { + padding: 0; + margin: 0; + margin-bottom: 2px; + display: inline; + width: 10px; + height: 10px +} + +.introjs-dontShowAgain label { + font-size: 14px; + display: inline-block; + font-weight: 400; + display: inline-block; + margin: 0 0 0 5px; + padding: 0; + background-color: #fff; + color: #616161; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none +} + +.introjs-tooltip-title { + font-size: 18px; + margin: 0; + padding: 0; + font-weight: 700; + float: left; + line-height: 32px +} + +.introjs-tooltip-header { + padding-left: 20px; + padding-right: 20px; + padding-top: 10px +} + +.introjs-tooltip-header:after { + content: "."; + visibility: hidden; + display: block; + height: 0; + clear: both +} + +.introjs-tooltipbuttons { + border-top: 1px solid #e0e0e0; + padding: 10px; + text-align: right; + white-space: nowrap +} + +.introjs-tooltipbuttons:after { + content: ""; + visibility: hidden; + display: block; + height: 0; + clear: both +} + +.introjs-button { + -webkit-box-sizing: content-box; + box-sizing: content-box; + position: relative; + overflow: visible; + display: inline-block; + padding: .5rem 1rem; + border: 1px solid #bdbdbd; + text-decoration: none; + text-shadow: 1px 1px 0 #fff; + font-size: 14px; + color: #424242; + white-space: nowrap; + cursor: pointer; + outline: 0; + background-color: #f4f4f4; + border-radius: .2em; + zoom: 1; + display: inline +} + +.introjs-button:hover { + outline: 0; + text-decoration: none; + border-color: #9e9e9e; + background-color: #e0e0e0; + color: #212121 +} + +.introjs-button:focus { + outline: 0; + text-decoration: none; + background-color: #eee; + -webkit-box-shadow: 0 0 0 .2rem rgba(158, 158, 158, .5); + box-shadow: 0 0 0 .2rem rgba(158, 158, 158, .5); + border: 1px solid #616161; + color: #212121 +} + +.introjs-button:active { + outline: 0; + text-decoration: none; + background-color: #e0e0e0; + border-color: #9e9e9e; + color: #212121 +} + +.introjs-button::-moz-focus-inner { + padding: 0; + border: 0 +} + +.introjs-skipbutton { + -webkit-box-sizing: content-box; + box-sizing: content-box; + color: #616161; + float: right; + font-size: 20px; + cursor: pointer; + font-weight: 700; + line-height: 1; + text-align: center; + padding: 7px 10px +} + +.introjs-skipbutton:focus, +.introjs-skipbutton:hover { + color: #212121; + outline: 0; + text-decoration: none +} + +.introjs-prevbutton { + float: left +} + +.introjs-nextbutton { + float: right +} + +.introjs-disabled { + color: #9e9e9e; + border-color: #bdbdbd; + -webkit-box-shadow: none; + box-shadow: none; + cursor: default; + background-color: #f4f4f4; + background-image: none; + text-decoration: none +} + +.introjs-disabled:focus, +.introjs-disabled:hover { + color: #9e9e9e; + border-color: #bdbdbd; + -webkit-box-shadow: none; + box-shadow: none; + cursor: default; + background-color: #f4f4f4; + background-image: none; + text-decoration: none +} + +.introjs-hidden { + display: none +} + +.introjs-bullets { + text-align: center; + padding-top: 10px; + padding-bottom: 10px +} + +.introjs-bullets ul { + -webkit-box-sizing: content-box; + box-sizing: content-box; + clear: both; + margin: 0 auto 0; + padding: 0; + display: inline-block +} + +.introjs-bullets ul li { + -webkit-box-sizing: content-box; + box-sizing: content-box; + list-style: none; + float: left; + margin: 0 2px +} + +.introjs-bullets ul li a { + -webkit-transition: width .1s ease-in; + -o-transition: width .1s ease-in; + transition: width .1s ease-in; + -webkit-box-sizing: content-box; + box-sizing: content-box; + display: block; + width: 6px; + height: 6px; + background: #ccc; + border-radius: 10px; + text-decoration: none; + cursor: pointer +} + +.introjs-bullets ul li a:focus, +.introjs-bullets ul li a:hover { + width: 15px; + background: #999; + text-decoration: none; + outline: 0 +} + +.introjs-bullets ul li a.active { + width: 15px; + background: #999 +} + +.introjs-progress { + -webkit-box-sizing: content-box; + box-sizing: content-box; + overflow: hidden; + height: 10px; + margin: 10px; + border-radius: 4px; + background-color: #e0e0e0 +} + +.introjs-progressbar { + -webkit-box-sizing: content-box; + box-sizing: content-box; + float: left; + width: 0%; + height: 100%; + font-size: 10px; + line-height: 10px; + text-align: center; + background-color: #08c +} + +.introjsFloatingElement { + position: absolute; + height: 0; + width: 0; + left: 50%; + top: 50% +} + +.introjs-fixedTooltip { + position: fixed +} + +.introjs-hint { + -webkit-box-sizing: content-box; + box-sizing: content-box; + position: absolute; + background: 0 0; + width: 20px; + height: 15px; + cursor: pointer +} + +.introjs-hint:focus { + border: 0; + outline: 0 +} + +.introjs-hint:hover>.introjs-hint-pulse { + background-color: rgba(60, 60, 60, .57) +} + +.introjs-hidehint { + display: none +} + +.introjs-fixedhint { + position: fixed +} + +@-webkit-keyframes introjspulse { + 0% { + -webkit-transform: scale(.95); + transform: scale(.95); + -webkit-box-shadow: 0 0 0 0 rgba(0, 0, 0, .7); + box-shadow: 0 0 0 0 rgba(0, 0, 0, .7) + } + + 70% { + -webkit-transform: scale(1); + transform: scale(1); + -webkit-box-shadow: 0 0 0 10px transparent; + box-shadow: 0 0 0 10px transparent + } + + 100% { + -webkit-transform: scale(.95); + transform: scale(.95); + -webkit-box-shadow: 0 0 0 0 transparent; + box-shadow: 0 0 0 0 transparent + } +} + +@keyframes introjspulse { + 0% { + -webkit-transform: scale(.95); + transform: scale(.95); + -webkit-box-shadow: 0 0 0 0 rgba(0, 0, 0, .7); + box-shadow: 0 0 0 0 rgba(0, 0, 0, .7) + } + + 70% { + -webkit-transform: scale(1); + transform: scale(1); + -webkit-box-shadow: 0 0 0 10px transparent; + box-shadow: 0 0 0 10px transparent + } + + 100% { + -webkit-transform: scale(.95); + transform: scale(.95); + -webkit-box-shadow: 0 0 0 0 transparent; + box-shadow: 0 0 0 0 transparent + } +} + +.introjs-hint-pulse { + -webkit-box-sizing: content-box; + box-sizing: content-box; + width: 15px; + height: 15px; + border-radius: 30px; + background-color: rgba(136, 136, 136, .24); + z-index: 10; + position: absolute; + -webkit-transition: all .2s ease-out; + -o-transition: all .2s ease-out; + transition: all .2s ease-out; + -webkit-animation: introjspulse 2s infinite; + animation: introjspulse 2s infinite +} + +.introjs-hint-no-anim .introjs-hint-pulse { + -webkit-animation: none; + animation: none +} + +.introjs-hint-dot { + -webkit-box-sizing: content-box; + box-sizing: content-box; + background: 0 0; + border-radius: 60px; + height: 50px; + width: 50px; + position: absolute; + top: -18px; + left: -18px; + z-index: 1; + opacity: 0 +} + +/*# sourceMappingURL=introjs.css.map */ \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/add.svg b/activities/3DVolume.activity/icons/add.svg new file mode 100644 index 0000000000..2aad05f62e --- /dev/null +++ b/activities/3DVolume.activity/icons/add.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/clear.svg b/activities/3DVolume.activity/icons/clear.svg new file mode 100644 index 0000000000..bf2a7ac7d0 --- /dev/null +++ b/activities/3DVolume.activity/icons/clear.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/cube.svg b/activities/3DVolume.activity/icons/cube.svg new file mode 100644 index 0000000000..0aceb06d79 --- /dev/null +++ b/activities/3DVolume.activity/icons/cube.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/cube_solid.svg b/activities/3DVolume.activity/icons/cube_solid.svg new file mode 100644 index 0000000000..5081def15e --- /dev/null +++ b/activities/3DVolume.activity/icons/cube_solid.svg @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/deca.svg b/activities/3DVolume.activity/icons/deca.svg new file mode 100644 index 0000000000..78d80c4d50 --- /dev/null +++ b/activities/3DVolume.activity/icons/deca.svg @@ -0,0 +1,95 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + diff --git a/activities/3DVolume.activity/icons/default_volume.svg b/activities/3DVolume.activity/icons/default_volume.svg new file mode 100644 index 0000000000..d2b004bfaf --- /dev/null +++ b/activities/3DVolume.activity/icons/default_volume.svg @@ -0,0 +1,66 @@ + + + + + + image/svg+xml + + + + + + + + + diff --git a/activities/3DVolume.activity/icons/dialog-cancel.svg b/activities/3DVolume.activity/icons/dialog-cancel.svg new file mode 100644 index 0000000000..dab4ae2d99 --- /dev/null +++ b/activities/3DVolume.activity/icons/dialog-cancel.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/dialog-ok.svg b/activities/3DVolume.activity/icons/dialog-ok.svg new file mode 100644 index 0000000000..69e5a2a13c --- /dev/null +++ b/activities/3DVolume.activity/icons/dialog-ok.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/dodeca.svg b/activities/3DVolume.activity/icons/dodeca.svg new file mode 100644 index 0000000000..780771ccc6 --- /dev/null +++ b/activities/3DVolume.activity/icons/dodeca.svg @@ -0,0 +1,26 @@ + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/down-arrow.svg b/activities/3DVolume.activity/icons/down-arrow.svg new file mode 100644 index 0000000000..49b67a6d39 --- /dev/null +++ b/activities/3DVolume.activity/icons/down-arrow.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/glass.svg b/activities/3DVolume.activity/icons/glass.svg new file mode 100644 index 0000000000..242a16a704 --- /dev/null +++ b/activities/3DVolume.activity/icons/glass.svg @@ -0,0 +1,60 @@ + +image/svg+xml + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/go-left.svg b/activities/3DVolume.activity/icons/go-left.svg new file mode 100644 index 0000000000..a66530b8e2 --- /dev/null +++ b/activities/3DVolume.activity/icons/go-left.svg @@ -0,0 +1,8 @@ + + +]> + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/go-right.svg b/activities/3DVolume.activity/icons/go-right.svg new file mode 100644 index 0000000000..90a2d98d3f --- /dev/null +++ b/activities/3DVolume.activity/icons/go-right.svg @@ -0,0 +1,36 @@ + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/help.svg b/activities/3DVolume.activity/icons/help.svg new file mode 100644 index 0000000000..3ebda0a2a2 --- /dev/null +++ b/activities/3DVolume.activity/icons/help.svg @@ -0,0 +1,9 @@ + + +]> + + + + + diff --git a/activities/3DVolume.activity/icons/icosa.svg b/activities/3DVolume.activity/icons/icosa.svg new file mode 100644 index 0000000000..cb4f855510 --- /dev/null +++ b/activities/3DVolume.activity/icons/icosa.svg @@ -0,0 +1,25 @@ + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/image.svg b/activities/3DVolume.activity/icons/image.svg new file mode 100644 index 0000000000..3137f71647 --- /dev/null +++ b/activities/3DVolume.activity/icons/image.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/insert-picture.svg b/activities/3DVolume.activity/icons/insert-picture.svg new file mode 100644 index 0000000000..b8d4cf42f3 --- /dev/null +++ b/activities/3DVolume.activity/icons/insert-picture.svg @@ -0,0 +1,40 @@ + + + +]> + + + + + + + + + + + + + + + + + + + diff --git a/activities/3DVolume.activity/icons/left-arrow.svg b/activities/3DVolume.activity/icons/left-arrow.svg new file mode 100644 index 0000000000..4752e2a0cb --- /dev/null +++ b/activities/3DVolume.activity/icons/left-arrow.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/minus.svg b/activities/3DVolume.activity/icons/minus.svg new file mode 100644 index 0000000000..2964a64837 --- /dev/null +++ b/activities/3DVolume.activity/icons/minus.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/number_off.svg b/activities/3DVolume.activity/icons/number_off.svg new file mode 100644 index 0000000000..1e98ce9e88 --- /dev/null +++ b/activities/3DVolume.activity/icons/number_off.svg @@ -0,0 +1,18 @@ + + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/number_on.svg b/activities/3DVolume.activity/icons/number_on.svg new file mode 100644 index 0000000000..7db4931b23 --- /dev/null +++ b/activities/3DVolume.activity/icons/number_on.svg @@ -0,0 +1,18 @@ + + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/number_volume.svg b/activities/3DVolume.activity/icons/number_volume.svg new file mode 100644 index 0000000000..311a9111c4 --- /dev/null +++ b/activities/3DVolume.activity/icons/number_volume.svg @@ -0,0 +1,175 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + 1 + + + diff --git a/activities/3DVolume.activity/icons/octa.svg b/activities/3DVolume.activity/icons/octa.svg new file mode 100644 index 0000000000..ce3f913df2 --- /dev/null +++ b/activities/3DVolume.activity/icons/octa.svg @@ -0,0 +1,21 @@ + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/restart.svg b/activities/3DVolume.activity/icons/restart.svg new file mode 100644 index 0000000000..1fba0ec6e9 --- /dev/null +++ b/activities/3DVolume.activity/icons/restart.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/right-arrow.svg b/activities/3DVolume.activity/icons/right-arrow.svg new file mode 100644 index 0000000000..517724c35c --- /dev/null +++ b/activities/3DVolume.activity/icons/right-arrow.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/sensor.svg b/activities/3DVolume.activity/icons/sensor.svg new file mode 100644 index 0000000000..4f71f85332 --- /dev/null +++ b/activities/3DVolume.activity/icons/sensor.svg @@ -0,0 +1,70 @@ + +image/svg+xml \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/tess.png b/activities/3DVolume.activity/icons/tess.png new file mode 100644 index 0000000000..9977b91516 Binary files /dev/null and b/activities/3DVolume.activity/icons/tess.png differ diff --git a/activities/3DVolume.activity/icons/tetra.svg b/activities/3DVolume.activity/icons/tetra.svg new file mode 100644 index 0000000000..65deceae10 --- /dev/null +++ b/activities/3DVolume.activity/icons/tetra.svg @@ -0,0 +1,16 @@ + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/throw.svg b/activities/3DVolume.activity/icons/throw.svg new file mode 100644 index 0000000000..673fb179ad --- /dev/null +++ b/activities/3DVolume.activity/icons/throw.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/transparent_volume.svg b/activities/3DVolume.activity/icons/transparent_volume.svg new file mode 100644 index 0000000000..8c612e1a39 --- /dev/null +++ b/activities/3DVolume.activity/icons/transparent_volume.svg @@ -0,0 +1,62 @@ + + + + + + image/svg+xml + + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/type.svg b/activities/3DVolume.activity/icons/type.svg new file mode 100644 index 0000000000..121012365d --- /dev/null +++ b/activities/3DVolume.activity/icons/type.svg @@ -0,0 +1,12 @@ + + + + spatial + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/up-arrow.svg b/activities/3DVolume.activity/icons/up-arrow.svg new file mode 100644 index 0000000000..acaa8de38d --- /dev/null +++ b/activities/3DVolume.activity/icons/up-arrow.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/view-fullscreen.svg b/activities/3DVolume.activity/icons/view-fullscreen.svg new file mode 100644 index 0000000000..f71058c69c --- /dev/null +++ b/activities/3DVolume.activity/icons/view-fullscreen.svg @@ -0,0 +1,6 @@ + + +]> + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/view-return.svg b/activities/3DVolume.activity/icons/view-return.svg new file mode 100644 index 0000000000..dade2d2081 --- /dev/null +++ b/activities/3DVolume.activity/icons/view-return.svg @@ -0,0 +1,74 @@ + +image/svg+xml \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/zoom-in.svg b/activities/3DVolume.activity/icons/zoom-in.svg new file mode 100644 index 0000000000..803190341b --- /dev/null +++ b/activities/3DVolume.activity/icons/zoom-in.svg @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/zoom-original.svg b/activities/3DVolume.activity/icons/zoom-original.svg new file mode 100644 index 0000000000..2ccb5c512f --- /dev/null +++ b/activities/3DVolume.activity/icons/zoom-original.svg @@ -0,0 +1,11 @@ + + +]> + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/zoom-out.svg b/activities/3DVolume.activity/icons/zoom-out.svg new file mode 100644 index 0000000000..1e6a68113a --- /dev/null +++ b/activities/3DVolume.activity/icons/zoom-out.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/activities/3DVolume.activity/icons/zoom-to-width.svg b/activities/3DVolume.activity/icons/zoom-to-width.svg new file mode 100644 index 0000000000..f7ca59074b --- /dev/null +++ b/activities/3DVolume.activity/icons/zoom-to-width.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/activities/3DVolume.activity/images/default.png b/activities/3DVolume.activity/images/default.png new file mode 100644 index 0000000000..27e4b2f77d Binary files /dev/null and b/activities/3DVolume.activity/images/default.png differ diff --git a/activities/3DVolume.activity/images/grass_background.png b/activities/3DVolume.activity/images/grass_background.png new file mode 100644 index 0000000000..27bffb0a72 Binary files /dev/null and b/activities/3DVolume.activity/images/grass_background.png differ diff --git a/activities/3DVolume.activity/images/green-board.jpeg b/activities/3DVolume.activity/images/green-board.jpeg new file mode 100644 index 0000000000..281ef1dce7 Binary files /dev/null and b/activities/3DVolume.activity/images/green-board.jpeg differ diff --git a/activities/3DVolume.activity/images/wood.png b/activities/3DVolume.activity/images/wood.png new file mode 100644 index 0000000000..adaec39e7d Binary files /dev/null and b/activities/3DVolume.activity/images/wood.png differ diff --git a/activities/3DVolume.activity/index.html b/activities/3DVolume.activity/index.html new file mode 100644 index 0000000000..2084f3ccd9 --- /dev/null +++ b/activities/3DVolume.activity/index.html @@ -0,0 +1,239 @@ + + + + + 3D Volume Activity + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + +
+ + + + + + + +
+ + + +
+ + + + + + + + + + + +
+ + + + + + +
+ + + + + + + +
+ + + +
+
+
+ +
+ +
+ +
+ + +
+ +
+
+

+
+ + + + diff --git a/activities/3DVolume.activity/js/Cube.js b/activities/3DVolume.activity/js/Cube.js new file mode 100644 index 0000000000..9bba8fc635 --- /dev/null +++ b/activities/3DVolume.activity/js/Cube.js @@ -0,0 +1,230 @@ +function createCube( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let boxMesh; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + // let tempImage = ifImage == null ? showImage : ifImage; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + + if (tempShowNumbers) { + let tileDimension = new THREE.Vector2(4, 2); + let tileSize = 512; + let g = new THREE.BoxGeometry(2, 2, 2); + + let c = document.createElement("canvas"); + c.width = tileSize * tileDimension.x; + c.height = tileSize * tileDimension.y; + let ctx = c.getContext("2d"); + ctx.fillStyle = tempFillColor; + ctx.fillRect(0, 0, c.width, c.height); + + let baseUVs = [ + [0, 1], + [1, 1], + [0, 0], + [1, 0], + ].map((p) => { + return new THREE.Vector2(...p); + }); + let uvs = []; + let vTemp = new THREE.Vector2(); + let vCenter = new THREE.Vector2(0.5, 0.5); + for (let i = 0; i < 6; i++) { + let u = i % tileDimension.x; + let v = Math.floor(i / tileDimension.x); + baseUVs.forEach((buv) => { + uvs.push( + (buv.x + u) / tileDimension.x, + (buv.y + v) / tileDimension.y + ); + }); + + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = `bold 300px Arial`; + ctx.fillStyle = tempTextColor; + ctx.fillText( + i + 1, + (u + 0.5) * tileSize, + c.height - (v + 0.5) * tileSize + ); + } + g.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + + let tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + + let m = new THREE.MeshPhongMaterial({ + map: tex, + }); + + boxMesh = new THREE.Mesh(g, m); + } else if (tempTransparent) { + const boxTransparentGeometry = new THREE.BoxGeometry(2, 2, 2); + const wireframe = new THREE.WireframeGeometry(boxTransparentGeometry); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + boxMesh = line; + } else { + const boxGeo = new THREE.BoxGeometry(2, 2, 2); + const boxMat = new THREE.MeshPhongMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + boxMesh = new THREE.Mesh(boxGeo, boxMat); + } + boxMesh.castShadow = true; + scene.add(boxMesh); + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 10 : yCoordinateShared; + + let vertices = [ + [-1, -1, -1], + [1, -1, -1], + [1, 1, -1], + [-1, 1, -1], + [-1, -1, 1], + [1, -1, 1], + [1, 1, 1], + [-1, 1, 1], + ]; + + let faces = [ + [0, 3, 2, 1, 1], + [1, 2, 6, 5, 2], + [0, 1, 5, 4, 3], + [3, 7, 6, 2, 4], + [0, 4, 7, 3, 5], + [4, 5, 6, 7, 6], + ]; + + const boxBody = new CANNON.Body({ + mass: 1, + shape: createCubeShape(vertices, faces, 1), + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 5, + }); + + world.addBody(boxBody); + let angVel1 = + sharedAngVel1 == null ? Math.random() * (4 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (4 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (4 - 0.1) + 0.1 : sharedAngVel3; + + boxBody.angularVelocity.set(angVel1, angVel2, angVel3); + boxBody.angularDamping = 0.1; // This will help in reducing rotation over time + boxBody.applyImpulse(ctx.offset, ctx.rollingForce); + + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + boxBody.material, + { friction: ctx.friction } + ); + + world.addContactMaterial(contactMat); + if (quaternionShared != null && quaternionShared != undefined) { + boxMesh.quaternion.copy(quaternionShared); + boxBody.quaternion.copy(quaternionShared); + } + diceArray.push([ + boxMesh, + boxBody, + "cube", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat, + ]); +} + +function getCubeScore(scoresObject, body, ifRemove) { + const faceVectors = [ + { + vector: new THREE.Vector3(1, 0, 0), + face: 1, + }, + { + vector: new THREE.Vector3(-1, 0, 0), + face: 2, + }, + { + vector: new THREE.Vector3(0, 1, 0), + face: 3, + }, + { + vector: new THREE.Vector3(0, -1, 0), + face: 4, + }, + { + vector: new THREE.Vector3(0, 0, 1), + face: 5, + }, + { + vector: new THREE.Vector3(0, 0, -1), + face: 6, + }, + ]; + for (const faceVector of faceVectors) { + faceVector.vector.applyEuler(body.rotation); + if (Math.round(faceVector.vector.y) == 1) { + if (!ifRemove) { + scoresObject.lastRoll += faceVector.face + " + "; + scoresObject.presentScore += faceVector.face; + } + return faceVector.face; + } + } +} + +function createCubeShape(vertices, faces, radius) { + let cv = new Array(vertices.length), + cf = new Array(faces.length); + + // Convert vertices to CANNON.Vec3 + for (let i = 0; i < vertices.length; ++i) { + let v = vertices[i]; + cv[i] = new CANNON.Vec3(v[0] * radius, v[1] * radius, v[2] * radius); + } + + // Extract vertex indices from faces, ignoring the last number + for (let i = 0; i < faces.length; ++i) { + cf[i] = faces[i].slice(0, faces[i].length - 1); + } + + return new CANNON.ConvexPolyhedron({ vertices: cv, faces: cf }); +} diff --git a/activities/3DVolume.activity/js/Deca.js b/activities/3DVolume.activity/js/Deca.js new file mode 100644 index 0000000000..94687bc575 --- /dev/null +++ b/activities/3DVolume.activity/js/Deca.js @@ -0,0 +1,499 @@ +let vertices = []; +let faces = [ + [5, 7, 11, 0], + [4, 2, 10, 1], + [1, 3, 11, 2], + [0, 8, 10, 3], + [7, 9, 11, 4], + [8, 6, 10, 5], + [9, 1, 11, 6], + [2, 0, 10, 7], + [3, 5, 11, 8], + [6, 4, 10, 9], + [1, 0, 2, -1], + [1, 2, 3, -1], + [3, 2, 4, -1], + [3, 4, 5, -1], + [5, 4, 6, -1], + [5, 6, 7, -1], + [7, 6, 8, -1], + [7, 8, 9, -1], + [9, 8, 0, -1], + [9, 0, 1, -1], +]; + +for (let i = 0, b = 0; i < 10; ++i, b += (Math.PI * 2) / 10) { + vertices.push([Math.cos(b), Math.sin(b), 0.105 * (i % 2 ? 1 : -1)]); +} +vertices.push([0, 0, -1]); +vertices.push([0, 0, 1]); +let scaleFactor = 1.5; +let values = 10; +let faceTexts = [ + " ", + "10", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "20", +]; +let textMargin = 1; +let chamfer = 0.945; +let af = (Math.PI * 6) / 5; +let tab = 0; +let backColor; +let color; +function createDecahedron( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let decahedron; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + backColor = tempFillColor; + color = tempTextColor; + + // let diceMesh = new THREE.Mesh(getGeometry(), getMaterials()); + // diceMesh.reveiceShadow = true; + // diceMesh.castShadow = true; + // diceMesh.diceObject = this; + + if (tempShowNumbers) { + decahedron = new THREE.Mesh(getGeometry(), getMaterials()); + } else if (tempTransparent) { + const decahedronTransaprentGeometry = getGeometry(); + const wireframe = new THREE.WireframeGeometry( + decahedronTransaprentGeometry + ); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + decahedron = line; + } else { + const decahedronGeometry = getGeometry(); + + const decaMaterial = new THREE.MeshStandardMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + + decahedron = new THREE.Mesh(decahedronGeometry, decaMaterial); + } + + decahedron.rotation.set(Math.PI / 4, Math.PI / 4, 0); // Rotates 90 degrees on X, 45 degrees on Y + decahedron.castShadow = true; + // decahedron = diceMesh; + scene.add(decahedron); + + // Create vertices for the decahedron + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 10 : 1; + + const sides = 10; + const scalingFactor = 1.5; + + const verticesGeo = [ + [0, 0, scalingFactor * 1], // Top vertex + [0, 0, scalingFactor * -1], // Bottom vertex + ]; + + for (let i = 0; i < sides; ++i) { + const b = (i * Math.PI * 2) / sides; + verticesGeo.push([ + scalingFactor * Math.cos(b), + scalingFactor * Math.sin(b), + scalingFactor * 0.105 * (i % 2 ? 1 : -1), + ]); + } + + // Convert vertices to CANNON.Vec3 format + let verticesCannon2 = verticesGeo.map( + (v) => new CANNON.Vec3(v[0], v[1], v[2]) + ); + + // Define faces + const facesGeo = [ + [0, 2, 3], + [0, 3, 4], + [0, 4, 5], + [0, 5, 6], + [0, 6, 7], + [0, 7, 8], + [0, 8, 9], + [0, 9, 10], + [0, 10, 11], + [0, 11, 2], + [1, 3, 2], + [1, 4, 3], + [1, 5, 4], + [1, 6, 5], + [1, 7, 6], + [1, 8, 7], + [1, 9, 8], + [1, 10, 9], + [1, 11, 10], + [1, 2, 11], + ]; + + // Corrected face definition + let correctedFacesGeo = facesGeo.map((face) => { + return [face[0], face[1], face[2]]; + }); + + // Create the ConvexPolyhedron shape + const decahedronShape2 = new CANNON.ConvexPolyhedron({ + vertices: verticesCannon2, + faces: correctedFacesGeo, + }); + let decahedronBody = new CANNON.Body({ + mass: 2, // Set mass + shape: decahedronShape2, + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 0.3, + }); + world.addBody(decahedronBody); + if (xCoordinateShared != null) { + decahedronBody.sleep() + } + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + decahedronBody.material, + { friction: ctx.friction } + ); + + world.addContactMaterial(contactMat); + + decahedronBody.sleepSpeedLimit = 4; + decahedronBody.sleepTimeLimit = 10; + + + let angVel1 = + sharedAngVel1 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel3; + + decahedronBody.angularVelocity.set(angVel1, angVel2, angVel3); + decahedronBody.angularDamping = 0.1; // This will help in reducing rotation over time + decahedronBody.applyImpulse(ctx.offset, ctx.rollingForce); + decahedron.position.copy(decahedronBody.position); // this merges the physics body to threejs mesh + decahedron.quaternion.copy(decahedronBody.quaternion); + + if (quaternionShared != null && quaternionShared != undefined) { + decahedron.quaternion.copy(quaternionShared); + decahedronBody.quaternion.copy(quaternionShared); + } + + diceArray.push([ + decahedron, + decahedronBody, + "deca", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat, + ]); +} + +function getGeometry() { + let radius = 1 * scaleFactor; + + let vectors = new Array(vertices.length); + for (let i = 0; i < vertices.length; ++i) { + vectors[i] = new THREE.Vector3().fromArray(vertices[i]).normalize(); + } + + let chamferGeometry = getChamferGeometry(vectors); + let geometry = makeGeometry( + chamferGeometry.vectors, + chamferGeometry.faces, + radius, + tab, + af + ); + geometry.cannon_shape = createShape(vectors, faces, radius); + + return geometry; +} + +function getChamferGeometry(vectors) { + let chamfer_vectors = [], + chamfer_faces = [], + corner_faces = new Array(vectors.length); + for (let i = 0; i < vectors.length; ++i) corner_faces[i] = []; + for (let i = 0; i < faces.length; ++i) { + let ii = faces[i], + fl = ii.length - 1; + let center_point = new THREE.Vector3(); + let face = new Array(fl); + for (let j = 0; j < fl; ++j) { + let vv = vectors[ii[j]].clone(); + center_point.add(vv); + corner_faces[ii[j]].push((face[j] = chamfer_vectors.push(vv) - 1)); + } + center_point.divideScalar(fl); + for (let j = 0; j < fl; ++j) { + let vv = chamfer_vectors[face[j]]; + vv.subVectors(vv, center_point) + .multiplyScalar(chamfer) + .addVectors(vv, center_point); + } + face.push(ii[fl]); + chamfer_faces.push(face); + } + for (let i = 0; i < faces.length - 1; ++i) { + for (let j = i + 1; j < faces.length; ++j) { + let pairs = [], + lastm = -1; + for (let m = 0; m < faces[i].length - 1; ++m) { + let n = faces[j].indexOf(faces[i][m]); + if (n >= 0 && n < faces[j].length - 1) { + if (lastm >= 0 && m !== lastm + 1) + pairs.unshift([i, m], [j, n]); + else pairs.push([i, m], [j, n]); + lastm = m; + } + } + if (pairs.length !== 4) continue; + chamfer_faces.push([ + chamfer_faces[pairs[0][0]][pairs[0][1]], + chamfer_faces[pairs[1][0]][pairs[1][1]], + chamfer_faces[pairs[3][0]][pairs[3][1]], + chamfer_faces[pairs[2][0]][pairs[2][1]], + -1, + ]); + } + } + for (let i = 0; i < corner_faces.length; ++i) { + let cf = corner_faces[i], + face = [cf[0]], + count = cf.length - 1; + while (count) { + for (let m = faces.length; m < chamfer_faces.length; ++m) { + let index = chamfer_faces[m].indexOf(face[face.length - 1]); + if (index >= 0 && index < 4) { + if (--index === -1) index = 3; + let next_vertex = chamfer_faces[m][index]; + if (cf.indexOf(next_vertex) >= 0) { + face.push(next_vertex); + break; + } + } + } + --count; + } + face.push(-1); + chamfer_faces.push(face); + } + return { vectors: chamfer_vectors, faces: chamfer_faces }; +} + +function makeGeometry(vertices, faces, radius) { + let geom = new THREE.BufferGeometry(); + + for (let i = 0; i < vertices.length; ++i) { + vertices[i] = vertices[i].multiplyScalar(radius); + } + + let positions = []; + const normals = []; + const uvs = []; + + const cb = new THREE.Vector3(); + const ab = new THREE.Vector3(); + let materialIndex; + let faceFirstVertexIndex = 0; + + for (let i = 0; i < faces.length; ++i) { + let ii = faces[i], + fl = ii.length - 1; + let aa = (Math.PI * 2) / fl; + materialIndex = ii[fl] + 1; + for (let j = 0; j < fl - 2; ++j) { + //Vertices + positions.push(...vertices[ii[0]].toArray()); + positions.push(...vertices[ii[j + 1]].toArray()); + positions.push(...vertices[ii[j + 2]].toArray()); + + // Flat face normals + cb.subVectors(vertices[ii[j + 2]], vertices[ii[j + 1]]); + ab.subVectors(vertices[ii[0]], vertices[ii[j + 1]]); + cb.cross(ab); + cb.normalize(); + + // Vertex Normals + normals.push(...cb.toArray()); + normals.push(...cb.toArray()); + normals.push(...cb.toArray()); + + //UVs + uvs.push( + (Math.cos(af) + 1 + tab) / 2 / (1 + tab), + (Math.sin(af) + 1 + tab) / 2 / (1 + tab) + ); + uvs.push( + (Math.cos(aa * (j + 1) + af) + 1 + tab) / 2 / (1 + tab), + (Math.sin(aa * (j + 1) + af) + 1 + tab) / 2 / (1 + tab) + ); + uvs.push( + (Math.cos(aa * (j + 2) + af) + 1 + tab) / 2 / (1 + tab), + (Math.sin(aa * (j + 2) + af) + 1 + tab) / 2 / (1 + tab) + ); + } + + //Set Group for face materials. + let numOfVertices = (fl - 2) * 3; + for (let i = 0; i < numOfVertices / 3; i++) { + geom.addGroup(faceFirstVertexIndex, 3, materialIndex); + faceFirstVertexIndex += 3; + } + } + + geom.setAttribute( + "position", + new THREE.Float32BufferAttribute(positions, 3) + ); + geom.setAttribute("normal", new THREE.Float32BufferAttribute(normals, 3)); + geom.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + geom.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius); + return geom; +} + +function createShape(vertices, faces, radius) { + let cv = new Array(vertices.length), + cf = new Array(faces.length); + for (let i = 0; i < vertices.length; ++i) { + let v = vertices[i]; + cv[i] = new CANNON.Vec3(v.x * radius, v.y * radius, v.z * radius); + } + for (let i = 0; i < faces.length; ++i) { + cf[i] = faces[i].slice(0, faces[i].length - 1); + } + console.log(faces); + return new CANNON.ConvexPolyhedron(cv, cf); +} + +function getMaterials() { + let materials = []; + for (let i = 0; i < faceTexts.length; ++i) { + let texture = null; + texture = createTextTexture(faceTexts[i]); + + materials.push( + new THREE.MeshPhongMaterial(Object.assign({}, { map: texture })) + ); + } + return materials; +} + +function createTextTexture(text) { + let canvas = document.createElement("canvas"); + let context = canvas.getContext("2d"); + let ts = calculateTextureSize(1 / 2 + 1 * textMargin) * 2; + canvas.width = canvas.height = ts; + context.font = ts / (1 + 2 * textMargin) + "pt Arial"; + context.fillStyle = backColor; + context.fillRect(0, 0, canvas.width, canvas.height); + context.textAlign = "center"; + context.textBaseline = "middle"; + context.fillStyle = color; + context.fillText(text, canvas.width / 2, canvas.height / 2); + let texture = new THREE.Texture(canvas); + texture.needsUpdate = true; + return texture; +} + +function calculateTextureSize(approx) { + return Math.max( + 128, + Math.pow(2, Math.floor(Math.log(approx) / Math.log(2))) + ); +} + +function getDecaScore(scoresObject, body, ifRemove) { + let vector = new THREE.Vector3(0, 1); + let closest_face; + let closest_angle = Math.PI * 2; + + let normals = body.geometry.getAttribute("normal").array; + for (let i = 0; i < body.geometry.groups.length; ++i) { + let face = body.geometry.groups[i]; + if (face.materialIndex === 0) continue; + + //Each group consists in 3 vertices of 3 elements (x, y, z) so the offset between faces in the Float32BufferAttribute is 9 + let startVertex = i * 9; + let normal = new THREE.Vector3( + normals[startVertex], + normals[startVertex + 1], + normals[startVertex + 2] + ); + let angle = normal + .clone() + .applyQuaternion(body.quaternion) + .angleTo(vector); + if (angle < closest_angle) { + closest_angle = angle; + closest_face = face; + } + } + let scoreToShow; + if (closest_face.materialIndex - 1 == 0) { + scoreToShow = 10; + } else { + scoreToShow = closest_face.materialIndex - 1; + } + if (!ifRemove) { + scoresObject.lastRoll += scoreToShow + " + "; + scoresObject.presentScore += scoreToShow; + } else { + return scoreToShow; + } +} diff --git a/activities/3DVolume.activity/js/Dodeca.js b/activities/3DVolume.activity/js/Dodeca.js new file mode 100644 index 0000000000..5d83b277e8 --- /dev/null +++ b/activities/3DVolume.activity/js/Dodeca.js @@ -0,0 +1,514 @@ +let p = (1 + Math.sqrt(5)) / 2; +let q = 1 / p; +let vertices2 = [ + [0, q, p], + [0, q, -p], + [0, -q, p], + [0, -q, -p], + [p, 0, q], + [p, 0, -q], + [-p, 0, q], + [-p, 0, -q], + [q, p, 0], + [q, -p, 0], + [-q, p, 0], + [-q, -p, 0], + [1, 1, 1], + [1, 1, -1], + [1, -1, 1], + [1, -1, -1], + [-1, 1, 1], + [-1, 1, -1], + [-1, -1, 1], + [-1, -1, -1], +]; +let faces2 = [ + [2, 14, 4, 12, 0, 1], + [15, 9, 11, 19, 3, 2], + [16, 10, 17, 7, 6, 3], + [6, 7, 19, 11, 18, 4], + [6, 18, 2, 0, 16, 5], + [18, 11, 9, 14, 2, 6], + [1, 17, 10, 8, 13, 7], + [1, 13, 5, 15, 3, 8], + [13, 8, 12, 4, 5, 9], + [5, 4, 14, 9, 15, 10], + [0, 12, 8, 10, 16, 11], + [3, 19, 7, 17, 1, 12], +]; + +let scaleFactor2 = 1.5; +let values2 = 12; +let faceTexts2 = [ + " ", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "10", + "11", + "12", + "13", + "14", + "15", + "16", + "17", + "18", + "19", + "20", +]; +let textMargin2 = 1.0; +let chamfer2 = 0.968; +let af2 = -Math.PI / 4 / 2; +let tab2 = 0.2; +let backColor2; +let color2; +function createDodecahedron( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let dodecahedron; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + backColor2 = tempFillColor; + color2 = tempTextColor; + + if (tempShowNumbers) { + dodecahedron = new THREE.Mesh(getGeometry2(), getMaterials2()); + } else if (tempTransparent) { + const dodecahedronTransparentGeometry = getGeometry2(); + const wireframe = new THREE.WireframeGeometry( + dodecahedronTransparentGeometry + ); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + dodecahedron = line; + } else { + const dodecahedronGeometry = getGeometry2(); + const dodecaMaterial = new THREE.MeshStandardMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + dodecahedron = new THREE.Mesh(dodecahedronGeometry, dodecaMaterial); + } + + dodecahedron.rotation.set(Math.PI / 4, Math.PI / 4, 0); // Rotates 90 degrees on X, 45 degrees on Y + dodecahedron.castShadow = true; + scene.add(dodecahedron); + + const t = 1.618; + const r = 0.618; + let scaleFactorCannon = 0.83; + + const vertices3 = [ + new CANNON.Vec3(-1, -1, -1).scale(scaleFactorCannon), + new CANNON.Vec3(-1, -1, 1).scale(scaleFactorCannon), + new CANNON.Vec3(-1, 1, -1).scale(scaleFactorCannon), + new CANNON.Vec3(-1, 1, 1).scale(scaleFactorCannon), + new CANNON.Vec3(1, -1, -1).scale(scaleFactorCannon), + new CANNON.Vec3(1, -1, 1).scale(scaleFactorCannon), + new CANNON.Vec3(1, 1, -1).scale(scaleFactorCannon), + new CANNON.Vec3(1, 1, 1).scale(scaleFactorCannon), + new CANNON.Vec3(0, -r, -t).scale(scaleFactorCannon), + new CANNON.Vec3(0, -r, t).scale(scaleFactorCannon), + new CANNON.Vec3(0, r, -t).scale(scaleFactorCannon), + new CANNON.Vec3(0, r, t).scale(scaleFactorCannon), + new CANNON.Vec3(-r, -t, 0).scale(scaleFactorCannon), + new CANNON.Vec3(-r, t, 0).scale(scaleFactorCannon), + new CANNON.Vec3(r, -t, 0).scale(scaleFactorCannon), + new CANNON.Vec3(r, t, 0).scale(scaleFactorCannon), + new CANNON.Vec3(-t, 0, -r).scale(scaleFactorCannon), + new CANNON.Vec3(t, 0, -r).scale(scaleFactorCannon), + new CANNON.Vec3(-t, 0, r).scale(scaleFactorCannon), + new CANNON.Vec3(t, 0, r).scale(scaleFactorCannon), + ]; + + const indices = [ + [3, 11, 7], + [3, 7, 15], + [3, 15, 13], + [7, 19, 17], + [7, 17, 6], + [7, 6, 15], + [17, 4, 8], + [17, 8, 10], + [17, 10, 6], + [8, 0, 16], + [8, 16, 2], + [8, 2, 10], + [0, 12, 1], + [0, 1, 18], + [0, 18, 16], + [6, 10, 2], + [6, 2, 13], + [6, 13, 15], + [2, 16, 18], + [2, 18, 3], + [2, 3, 13], + [18, 1, 9], + [18, 9, 11], + [18, 11, 3], + [4, 14, 12], + [4, 12, 0], + [4, 0, 8], + [11, 9, 5], + [11, 5, 19], + [11, 19, 7], + [19, 5, 14], + [19, 14, 4], + [19, 4, 17], + [1, 12, 14], + [1, 14, 5], + [1, 5, 9], + ]; + + const dodecahedronShape = new CANNON.ConvexPolyhedron({ + vertices: vertices3, + faces: indices, + }); + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 4 : 1; // Ensure initial y is above the plane + const dodecahedronBody = new CANNON.Body({ + mass: 2, // Set mass + shape: myShape, + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 0.3, // Lower the restitution value + }); + dodecahedronBody.sleepSpeedLimit = 0.2; + dodecahedronBody.sleepTimeLimit = 3; + dodecahedronBody.linearDamping = 0.1; // Apply linear damping + dodecahedronBody.angularDamping = 0.1; // Apply angular damping + + world.addBody(dodecahedronBody); + + if (xCoordinateShared != null) { + dodecahedronBody.sleep() + } + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + dodecahedronBody.material, + { friction: ctx.friction } + ); + world.addContactMaterial(contactMat); + + let angVel1 = + sharedAngVel1 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel3; + + dodecahedronBody.angularVelocity.set(angVel1, angVel2, angVel3); + + dodecahedronBody.applyImpulse(ctx.offset, ctx.rollingForce); + dodecahedron.position.copy(dodecahedronBody.position); // Sync positions + dodecahedron.quaternion.copy(dodecahedronBody.quaternion); // Sync orientations + if (quaternionShared != null) { + dodecahedron.quaternion.copy(quaternionShared); + dodecahedronBody.quaternion.copy(quaternionShared); + } + + diceArray.push([ + dodecahedron, + dodecahedronBody, + "dodeca", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat, + ]); + +} + +function getGeometry2() { + let radius = 1 * scaleFactor2; + + let vectors = new Array(vertices2.length); + for (let i = 0; i < vertices2.length; ++i) { + vectors[i] = new THREE.Vector3().fromArray(vertices2[i]).normalize(); + } + + let chamferGeometry = getChamferGeometry2(vectors); + let geometry = makeGeometry2( + chamferGeometry.vectors, + chamferGeometry.faces2, + radius, + tab2, + af2 + ); + myShape = createShape(vectors, faces2, radius); + + return geometry; +} + +function getChamferGeometry2(vectors) { + let chamfer_vectors = [], + chamfer_faces = [], + corner_faces = new Array(vectors.length); + for (let i = 0; i < vectors.length; ++i) corner_faces[i] = []; + for (let i = 0; i < faces2.length; ++i) { + let ii = faces2[i], + fl = ii.length - 1; + let center_point = new THREE.Vector3(); + let face = new Array(fl); + for (let j = 0; j < fl; ++j) { + let vv = vectors[ii[j]].clone(); + center_point.add(vv); + corner_faces[ii[j]].push((face[j] = chamfer_vectors.push(vv) - 1)); + } + center_point.divideScalar(fl); + for (let j = 0; j < fl; ++j) { + let vv = chamfer_vectors[face[j]]; + vv.subVectors(vv, center_point) + .multiplyScalar(chamfer2) + .addVectors(vv, center_point); + } + face.push(ii[fl]); + chamfer_faces.push(face); + } + for (let i = 0; i < faces2.length - 1; ++i) { + for (let j = i + 1; j < faces2.length; ++j) { + let pairs = [], + lastm = -1; + for (let m = 0; m < faces2[i].length - 1; ++m) { + let n = faces2[j].indexOf(faces2[i][m]); + if (n >= 0 && n < faces2[j].length - 1) { + if (lastm >= 0 && m !== lastm + 1) + pairs.unshift([i, m], [j, n]); + else pairs.push([i, m], [j, n]); + lastm = m; + } + } + if (pairs.length !== 4) continue; + chamfer_faces.push([ + chamfer_faces[pairs[0][0]][pairs[0][1]], + chamfer_faces[pairs[1][0]][pairs[1][1]], + chamfer_faces[pairs[3][0]][pairs[3][1]], + chamfer_faces[pairs[2][0]][pairs[2][1]], + -1, + ]); + } + } + for (let i = 0; i < corner_faces.length; ++i) { + let cf = corner_faces[i], + face = [cf[0]], + count = cf.length - 1; + while (count) { + for (let m = faces2.length; m < chamfer_faces.length; ++m) { + let index = chamfer_faces[m].indexOf(face[face.length - 1]); + if (index >= 0 && index < 4) { + if (--index === -1) index = 3; + let next_vertex = chamfer_faces[m][index]; + if (cf.indexOf(next_vertex) >= 0) { + face.push(next_vertex); + break; + } + } + } + --count; + } + face.push(-1); + chamfer_faces.push(face); + } + return { vectors: chamfer_vectors, faces2: chamfer_faces }; +} + +function makeGeometry2(vertices2, faces2, radius) { + let geom = new THREE.BufferGeometry(); + + for (let i = 0; i < vertices2.length; ++i) { + vertices2[i] = vertices2[i].multiplyScalar(radius); + } + + let positions = []; + const normals = []; + const uvs = []; + + const cb = new THREE.Vector3(); + const ab = new THREE.Vector3(); + let materialIndex; + let faceFirstVertexIndex = 0; + + for (let i = 0; i < faces2.length; ++i) { + let ii = faces2[i], + fl = ii.length - 1; + let aa = (Math.PI * 2) / fl; + materialIndex = ii[fl] + 1; + for (let j = 0; j < fl - 2; ++j) { + //Vertices + positions.push(...vertices2[ii[0]].toArray()); + positions.push(...vertices2[ii[j + 1]].toArray()); + positions.push(...vertices2[ii[j + 2]].toArray()); + + // Flat face normals + cb.subVectors(vertices2[ii[j + 2]], vertices2[ii[j + 1]]); + ab.subVectors(vertices2[ii[0]], vertices2[ii[j + 1]]); + cb.cross(ab); + cb.normalize(); + + // Vertex Normals + normals.push(...cb.toArray()); + normals.push(...cb.toArray()); + normals.push(...cb.toArray()); + + //UVs + uvs.push( + (Math.cos(af2) + 1 + tab2) / 2 / (1 + tab2), + (Math.sin(af2) + 1 + tab2) / 2 / (1 + tab2) + ); + uvs.push( + (Math.cos(aa * (j + 1) + af2) + 1 + tab2) / 2 / (1 + tab2), + (Math.sin(aa * (j + 1) + af2) + 1 + tab2) / 2 / (1 + tab2) + ); + uvs.push( + (Math.cos(aa * (j + 2) + af2) + 1 + tab2) / 2 / (1 + tab2), + (Math.sin(aa * (j + 2) + af2) + 1 + tab2) / 2 / (1 + tab2) + ); + } + + //Set Group for face materials. + let numOfVertices = (fl - 2) * 3; + for (let i = 0; i < numOfVertices / 3; i++) { + geom.addGroup(faceFirstVertexIndex, 3, materialIndex); + faceFirstVertexIndex += 3; + } + } + + geom.setAttribute( + "position", + new THREE.Float32BufferAttribute(positions, 3) + ); + geom.setAttribute("normal", new THREE.Float32BufferAttribute(normals, 3)); + geom.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + geom.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius); + return geom; +} + +function createShape(vertices2, faces2, radius) { + let cv = new Array(vertices2.length), + cf = new Array(faces2.length); + for (let i = 0; i < vertices2.length; ++i) { + let v = vertices2[i]; + cv[i] = new CANNON.Vec3(v.x * radius, v.y * radius, v.z * radius); + } + for (let i = 0; i < faces2.length; ++i) { + cf[i] = faces2[i].slice(0, faces2[i].length - 1); + } + + return new CANNON.ConvexPolyhedron({ vertices: cv, faces: cf }); +} +let myShape = null; + +function getMaterials2() { + let materials = []; + for (let i = 0; i < faceTexts2.length; ++i) { + let texture = null; + texture = createTextTexture2(faceTexts2[i]); + + materials.push( + new THREE.MeshPhongMaterial(Object.assign({}, { map: texture })) + ); + } + return materials; +} + +function createTextTexture2(text) { + let canvas = document.createElement("canvas"); + let context = canvas.getContext("2d"); + let ts = calculateTextureSize(1 / 2 + 1 * textMargin2) * 2; + canvas.width = canvas.height = ts; + context.font = ts / (1 + 2 * textMargin2) + "pt Arial"; + context.fillStyle = backColor2; + context.fillRect(0, 0, canvas.width, canvas.height); + context.textAlign = "center"; + context.textBaseline = "middle"; + context.fillStyle = color2; + context.fillText(text, canvas.width / 2, canvas.height / 2); + let texture = new THREE.Texture(canvas); + texture.needsUpdate = true; + return texture; +} + +function calculateTextureSize(approx) { + return Math.max( + 128, + Math.pow(2, Math.floor(Math.log(approx) / Math.log(2))) + ); +} +function getDodecaScore(scoresObject, body, ifRemove) { + let vector = new THREE.Vector3(0, 1); + let closest_face; + let closest_angle = Math.PI * 2; + + let normals = body.geometry.getAttribute("normal").array; + for (let i = 0; i < body.geometry.groups.length; ++i) { + let face = body.geometry.groups[i]; + if (face.materialIndex === 0) continue; + + //Each group consists in 3 vertices of 3 elements (x, y, z) so the offset between faces in the Float32BufferAttribute is 9 + let startVertex = i * 9; + let normal = new THREE.Vector3( + normals[startVertex], + normals[startVertex + 1], + normals[startVertex + 2] + ); + let angle = normal + .clone() + .applyQuaternion(body.quaternion) + .angleTo(vector); + if (angle < closest_angle) { + closest_angle = angle; + closest_face = face; + } + } + let scoreToShow; + if (closest_face.materialIndex - 1 == 0) { + scoreToShow = 10; + } else { + scoreToShow = closest_face.materialIndex - 1; + } + if (!ifRemove) { + scoresObject.lastRoll += scoreToShow + " + "; + scoresObject.presentScore += scoreToShow; + } else { + return scoreToShow; + } +} diff --git a/activities/3DVolume.activity/js/Icosa.js b/activities/3DVolume.activity/js/Icosa.js new file mode 100644 index 0000000000..512891f3ed --- /dev/null +++ b/activities/3DVolume.activity/js/Icosa.js @@ -0,0 +1,263 @@ +function createIcosahedron( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let icosahedron; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + // let tempImage = ifImage == null ? showImage : ifImage; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + + if (tempShowNumbers) { + let tileDimension = new THREE.Vector2(4, 5); + let tileSize = 512; + let g = new THREE.IcosahedronGeometry(1.5); + + let c = document.createElement("canvas"); + c.width = tileSize * tileDimension.x; + c.height = tileSize * tileDimension.y; + let ctx = c.getContext("2d"); + ctx.fillStyle = tempFillColor; + ctx.fillRect(0, 0, c.width, c.height); + + let uvs = []; + + let baseUVs = [ + [0.067, 0.25], + [0.933, 0.25], + [0.5, 1], + ].map((p) => { + return new THREE.Vector2(...p); + }); + for (let i = 0; i < 20; i++) { + let u = i % tileDimension.x; + let v = Math.floor(i / tileDimension.x); + uvs.push( + (baseUVs[0].x + u) / tileDimension.x, + (baseUVs[0].y + v) / tileDimension.y, + (baseUVs[1].x + u) / tileDimension.x, + (baseUVs[1].y + v) / tileDimension.y, + (baseUVs[2].x + u) / tileDimension.x, + (baseUVs[2].y + v) / tileDimension.y + ); + + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = `bold 175px Arial`; + ctx.fillStyle = tempTextColor; + let text = i + 1; + if (i == 5) { + text + "."; + } + ctx.fillText( + i + 1, + (u + 0.5) * tileSize, + c.height - (v + 0.5) * tileSize + ); + } + g.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + + let tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + + let m = new THREE.MeshPhongMaterial({ + map: tex, + }); + + icosahedron = new THREE.Mesh(g, m); + } else if (tempTransparent) { + const icosahedronTransparentGeometry = new THREE.IcosahedronGeometry( + 1.5 + ); // Size of the Icosahedron + const wireframe = new THREE.WireframeGeometry( + icosahedronTransparentGeometry + ); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + icosahedron = line; + } else { + const icosahedronGeometry = new THREE.IcosahedronGeometry(1.5); // Size of the icosahedron + + const icosaMaterial = new THREE.MeshStandardMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + + icosahedron = new THREE.Mesh(icosahedronGeometry, icosaMaterial); + } + icosahedron.rotation.set(Math.PI / 4, Math.PI / 4, 0); // Rotates 90 degrees on X, 45 degrees on Y + icosahedron.castShadow = true; + scene.add(icosahedron); + + // Vertices + // Vertices + const t = (1 + Math.sqrt(5)) / 2; + const scaleFactor = 0.8; + const verticesIcosa = [ + new CANNON.Vec3(-1, t, 0).scale(scaleFactor), + new CANNON.Vec3(1, t, 0).scale(scaleFactor), + new CANNON.Vec3(-1, -t, 0).scale(scaleFactor), + new CANNON.Vec3(1, -t, 0).scale(scaleFactor), + new CANNON.Vec3(0, -1, t).scale(scaleFactor), + new CANNON.Vec3(0, 1, t).scale(scaleFactor), + new CANNON.Vec3(0, -1, -t).scale(scaleFactor), + new CANNON.Vec3(0, 1, -t).scale(scaleFactor), + new CANNON.Vec3(t, 0, -1).scale(scaleFactor), + new CANNON.Vec3(t, 0, 1).scale(scaleFactor), + new CANNON.Vec3(-t, 0, -1).scale(scaleFactor), + new CANNON.Vec3(-t, 0, 1).scale(scaleFactor), + ]; + + // Faces + const facesIcosa = [ + [0, 11, 5], + [0, 5, 1], + [0, 1, 7], + [0, 7, 10], + [0, 10, 11], + [1, 5, 9], + [5, 11, 4], + [11, 10, 2], + [10, 7, 6], + [7, 1, 8], + [3, 9, 4], + [3, 4, 2], + [3, 2, 6], + [3, 6, 8], + [3, 8, 9], + [4, 9, 5], + [2, 4, 11], + [6, 2, 10], + [8, 6, 7], + [9, 8, 1], + ]; + + // Create a ConvexPolyhedron shape from the vertices and faces + const icosahedronShape = new CANNON.ConvexPolyhedron({ + vertices: verticesIcosa, + faces: facesIcosa, + }); + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 4 : 1; + + const icosahedronBody = new CANNON.Body({ + mass: 2, // Set mass + shape: icosahedronShape, + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 0.3, + }); + icosahedronBody.sleepSpeedLimit = 0.5; + icosahedronBody.sleepTimeLimit = 3; + + if (xCoordinateShared != null) { + icosahedronBody.sleep() + } + + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + icosahedronBody.material, + { friction: ctx.friction } + ); + + world.addContactMaterial(contactMat); + + // if (tempShowNumbers) { + // icosahedronBody.addEventListener("sleep", () => { + // console.log("icosa going to sleeep"); + // sleepCounter++; + // getIcosaScore(icosahedron); + // }); + // } + world.addBody(icosahedronBody); + let angVel1 = + sharedAngVel1 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel3; + + icosahedronBody.angularVelocity.set(angVel1, angVel2, angVel3); + icosahedronBody.angularDamping = 0.1; // This will help in reducing rotation over time + + icosahedronBody.applyImpulse(ctx.offset, ctx.rollingForce); + icosahedron.position.copy(icosahedronBody.position); // this merges the physics body to threejs mesh + icosahedron.quaternion.copy(icosahedronBody.quaternion); + + if (quaternionShared != null && quaternionShared != undefined) { + icosahedron.quaternion.copy(quaternionShared); + icosahedronBody.quaternion.copy(quaternionShared); + } + + diceArray.push([ + icosahedron, + icosahedronBody, + "icosa", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat, + ]); +} + +function getIcosaScore(scoresObject, body, ifRemove) { + let vector = new THREE.Vector3(0, 1); + let closest_face; + let closest_angle = Math.PI * 2; + + let normals = body.geometry.getAttribute("normal").array; + for (let i = 0; i < 20; ++i) { + let face = i + 1; + + let startVertex = i * 9; + let normal = new THREE.Vector3( + normals[startVertex], + normals[startVertex + 1], + normals[startVertex + 2] + ); + let angle = normal + .clone() + .applyQuaternion(body.quaternion) + .angleTo(vector); + if (angle < closest_angle) { + closest_angle = angle; + closest_face = face; + } + } + if (!ifRemove) { + scoresObject.lastRoll += closest_face + " + "; + scoresObject.presentScore += closest_face; + } + + return closest_face; +} diff --git a/activities/3DVolume.activity/js/Octa.js b/activities/3DVolume.activity/js/Octa.js new file mode 100644 index 0000000000..f75df80de2 --- /dev/null +++ b/activities/3DVolume.activity/js/Octa.js @@ -0,0 +1,277 @@ +function createOctahedron( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let octahedron; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + // let tempImage = ifImage == null ? showImage : ifImage; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + + if (tempShowNumbers) { + let tileDimension = new THREE.Vector2(4, 5); + let tileSize = 512; + let g = new THREE.OctahedronGeometry(1.6); + + let c = document.createElement("canvas"); + c.width = tileSize * tileDimension.x; + c.height = tileSize * tileDimension.y; + let ctx = c.getContext("2d"); + ctx.fillStyle = tempFillColor; + ctx.fillRect(0, 0, c.width, c.height); + + let uvs = []; + + let baseUVs = [ + [0.067, 0.25], + [0.933, 0.25], + [0.5, 1], + ].map((p) => { + return new THREE.Vector2(...p); + }); + + for (let i = 0; i < 9; i++) { + let u = i % tileDimension.x; + let v = Math.floor(i / tileDimension.x); + uvs.push( + (baseUVs[0].x + u) / tileDimension.x, + (baseUVs[0].y + v) / tileDimension.y, + (baseUVs[1].x + u) / tileDimension.x, + (baseUVs[1].y + v) / tileDimension.y, + (baseUVs[2].x + u) / tileDimension.x, + (baseUVs[2].y + v) / tileDimension.y + ); + + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = `bold 200px Arial`; + ctx.fillStyle = tempTextColor; + ctx.fillText( + i + 1 + (i == 5 || i == 8 ? "" : ""), + (u + 0.5) * tileSize, + c.height - (v + 0.5) * tileSize + ); + } + g.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + + let tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + + let m = new THREE.MeshPhongMaterial({ + map: tex, + }); + + octahedron = new THREE.Mesh(g, m); + } else if (tempTransparent) { + const octahedronTransparentGeometry = new THREE.OctahedronGeometry(1.6); // Size of the octahedron + const wireframe = new THREE.WireframeGeometry( + octahedronTransparentGeometry + ); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + octahedron = line; + } else { + const octahedronGeometry = new THREE.OctahedronGeometry(1.6); // Size of the octahedron + + const octaMaterial = new THREE.MeshPhongMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + octahedron = new THREE.Mesh(octahedronGeometry, octaMaterial); + } + octahedron.castShadow = true; + scene.add(octahedron); + + const scaleFactor = 0.8; // Change this value to scale the shape + + const verticesOcta = [ + new CANNON.Vec3(2 * scaleFactor, 0, 0), // Vertex 1 (right) + new CANNON.Vec3(-2 * scaleFactor, 0, 0), // Vertex 2 (left) + new CANNON.Vec3(0, 2 * scaleFactor, 0), // Vertex 3 (top) + new CANNON.Vec3(0, -2 * scaleFactor, 0), // Vertex 4 (bottom) + new CANNON.Vec3(0, 0, 2 * scaleFactor), // Vertex 5 (front) + new CANNON.Vec3(0, 0, -2 * scaleFactor), // Vertex 6 (back) + ]; + + // Define the faces of the octahedron (counter-clockwise order) + const facesOcta = [ + [0, 2, 4], // Triangle 1 (right, top, front) + [0, 4, 3], // Triangle 2 (right, front, bottom) + [0, 3, 5], // Triangle 3 (right, bottom, back) + [0, 5, 2], // Triangle 4 (right, back, top) + [1, 2, 5], // Triangle 5 (left, top, back) + [1, 5, 3], // Triangle 6 (left, back, bottom) + [1, 3, 4], // Triangle 7 (left, bottom, front) + [1, 4, 2], // Triangle 8 (left, front, top) + ]; + + const octahedronShape = new CANNON.ConvexPolyhedron({ + vertices: verticesOcta, + faces: facesOcta, + }); + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 10 : 1; + + const octahedronBody = new CANNON.Body({ + mass: 2, // Set mass + shape: octahedronShape, + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 0.3, + }); + + world.addBody(octahedronBody); + + if (xCoordinateShared != null) { + octahedronBody.sleep() + } + + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + octahedronBody.material, + { friction: ctx.friction } + ); + + world.addContactMaterial(contactMat); + + + let angVel1 = + sharedAngVel1 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel3; + + octahedronBody.angularVelocity.set(angVel1, angVel2, angVel3); + octahedronBody.angularDamping = 0.1; // This will help in reducing rotation over time + + octahedronBody.applyImpulse(ctx.offset, ctx.rollingForce); + octahedron.position.copy(octahedronBody.position); // this merges the physics body to threejs mesh + octahedron.quaternion.copy(octahedronBody.quaternion); + if (quaternionShared != null && quaternionShared != undefined) { + octahedron.quaternion.copy(quaternionShared); + octahedronBody.quaternion.copy(quaternionShared); + } + diceArray.push([ + octahedron, + octahedronBody, + "octa", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat + ]); +} + +function getOctaScore(scoresObject, body, ifRemove) { + const faceVectors = [ + { + vector: new THREE.Vector3(1, 0, 0), // Along the positive x-axis + face: 4, + }, + { + vector: new THREE.Vector3(-1, 0, 0), // Along the negative x-axis + face: 6, + }, + { + vector: new THREE.Vector3(0, 1, 0), // Along the positive y-axis + face: 5, + }, + { + vector: new THREE.Vector3(0, -1, 0), // Along the negative y-axis + face: 3, + }, + { + vector: new THREE.Vector3(1, 1, 1).normalize(), // Towards a corner (positive x, y, z) + face: 1, + }, + { + vector: new THREE.Vector3(-1, 1, 1).normalize(), // Towards a corner (negative x, positive y, z) + face: 8, + }, + { + vector: new THREE.Vector3(1, -1, 1).normalize(), // Towards a corner (positive x, negative y, z) + face: 2, + }, + { + vector: new THREE.Vector3(-1, -1, 1).normalize(), // Towards a corner (negative x, negative y, z) + face: 7, + }, + ]; + + let minValue = 1000000; + let minInd; + for (let i = 0; i < faceVectors.length; i++) { + let faceVector = faceVectors[i]; + faceVector.vector.applyEuler(body.rotation); + if (minValue > Math.abs(1 - faceVector.vector.y)) { + minValue = Math.abs(1 - faceVector.vector.y); + minInd = i; + } + } + if (!ifRemove) { + scoresObject.lastRoll += faceVectors[minInd].face + " + "; + scoresObject.presentScore += faceVectors[minInd].face; + } + return faceVectors[minInd].face; + + // let vector = new THREE.Vector3(0, 1); + // let closest_face; + // let closest_angle = Math.PI * 2; + + // let normals = body.geometry.getAttribute("normal").array; + // for (let i = 0; i < 8; ++i) { + // let face = i + 1; + + // //Each group consists in 3 vertices of 3 elements (x, y, z) so the offset between faces in the Float32BufferAttribute is 9 + // let startVertex = i * 9; + // let normal = new THREE.Vector3( + // normals[startVertex], + // normals[startVertex + 1], + // normals[startVertex + 2] + // ); + // let angle = normal + // .clone() + // .applyQuaternion(body.quaternion) + // .angleTo(vector); + // if (angle < closest_angle) { + // closest_angle = angle; + // closest_face = face; + // } + // } + // scoresObject.lastRoll += closest_face + " + "; + // scoresObject.presentScore += closest_face; + // updateElements(); + + // return closest_face; +} diff --git a/activities/3DVolume.activity/js/Tetra.js b/activities/3DVolume.activity/js/Tetra.js new file mode 100644 index 0000000000..64434462f6 --- /dev/null +++ b/activities/3DVolume.activity/js/Tetra.js @@ -0,0 +1,237 @@ +function createTetrahedron( + sharedColor, + ifNumbers, + ifTransparent, + xCoordinateShared, + zCoordinateShared, + ifImage, + sharedImageData, + yCoordinateShared, + quaternionShared, + sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + sharedAngVel1, + sharedAngVel2, + sharedAngVel3 +) { + let tetrahedron; + let tempShowNumbers = ifNumbers == null ? ctx.showNumbers : ifNumbers; + let tempTransparent = + ifTransparent == null ? ctx.toggleTransparent : ifTransparent; + // let tempImage = ifImage == null ? showImage : ifImage; + let tempFillColor = sharedColor != null ? sharedColor : ctx.presentColor; + let tempTextColor = + sharedTextColor != null ? sharedTextColor : ctx.textColor; + if (tempShowNumbers) { + let tileDimension = new THREE.Vector2(4, 5); + let tileSize = 512; + let g = new THREE.TetrahedronGeometry(1.7); + + let c = document.createElement("canvas"); + let div = document.createElement("div"); + c.width = tileSize * tileDimension.x; + c.height = tileSize * tileDimension.y; + let ctx = c.getContext("2d"); + ctx.fillStyle = tempFillColor; + ctx.fillRect(0, 0, c.width, c.height); + + let uvs = []; + + let baseUVs = [ + [0.067, 0.25], + [0.933, 0.25], + [0.5, 1], + ].map((p) => { + return new THREE.Vector2(...p); + }); + let arrOfNums = [ + [2, 1, 3], + [1, 2, 4], + [3, 1, 4], + [2, 3, 4], + ]; + for (let i = 0; i < 4; i++) { + let u = i % tileDimension.x; + let v = Math.floor(i / tileDimension.x); + uvs.push( + (baseUVs[0].x + u) / tileDimension.x, + (baseUVs[0].y + v) / tileDimension.y, + (baseUVs[1].x + u) / tileDimension.x, + (baseUVs[1].y + v) / tileDimension.y, + (baseUVs[2].x + u) / tileDimension.x, + (baseUVs[2].y + v) / tileDimension.y + ); + + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = `bold 150px Arial`; + ctx.fillStyle = tempTextColor; + // ctx.fillText( + // i + 1, + // (u + 0.5) * tileSize, + // c.height - (v + 0.5) * tileSize + // ); + let aStep = (Math.PI * 2) / 3; + let yAlign = Math.PI * 0.5; + let tileQuarter = tileSize * 0.25; + for (let j = 0; j < 3; j++) { + ctx.save(); + ctx.translate( + (u + 0.5) * tileSize + + Math.cos(j * aStep - yAlign) * tileQuarter, + c.height - + (v + 0.5) * tileSize + + Math.sin(j * aStep - yAlign) * tileQuarter + ); + ctx.rotate((j * Math.PI * 2) / 3); + ctx.fillText(arrOfNums[i][j], 0, 0); + ctx.restore(); + } + } + g.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2)); + + let tex = new THREE.CanvasTexture(c); + tex.colorSpace = THREE.SRGBColorSpace; + + let m = new THREE.MeshPhongMaterial({ + map: tex, + }); + + tetrahedron = new THREE.Mesh(g, m); + } else if (tempTransparent) { + const tetrahedronTransparentGeometry = new THREE.TetrahedronGeometry( + 1.7 + ); // Size of the tetrahedron + const wireframe = new THREE.WireframeGeometry( + tetrahedronTransparentGeometry + ); + const lineMaterial = new THREE.LineBasicMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + depthTest: true, + opacity: 1, + transparent: false, + }); + const line = new THREE.LineSegments(wireframe, lineMaterial); + tetrahedron = line; + } else { + const tetrahedronGeometry = new THREE.TetrahedronGeometry(1.7); // Size of the tetrahedron + + const tetraMaterial = new THREE.MeshStandardMaterial({ + color: sharedColor != null ? sharedColor : ctx.presentColor, + wireframe: false, + }); + + tetrahedron = new THREE.Mesh(tetrahedronGeometry, tetraMaterial); + } + + tetrahedron.rotation.set(Math.PI / 4, Math.PI / 4, 0); + tetrahedron.castShadow = true; + scene.add(tetrahedron); + + const verticesTetra = [ + new CANNON.Vec3(1, 1, 1), // Vertex 1 (right) + new CANNON.Vec3(-1, -1, 1), // Vertex 2 (top) + new CANNON.Vec3(-1, 1, -1), // Vertex 3 (left) + new CANNON.Vec3(1, -1, -1), // Vertex 4 (front) + ]; + const facesTetra = [ + [2, 1, 0], + [0, 3, 2], + [1, 3, 0], + [2, 3, 1], + ]; + // Create a ConvexPolyhedron shape from the vertices and faces + const tetrahedronShape = new CANNON.ConvexPolyhedron({ + vertices: verticesTetra, + faces: facesTetra, + }); + + let x = xCoordinateShared == null ? xCoordinate : xCoordinateShared; + let z = zCoordinateShared == null ? zCoordinate : zCoordinateShared; + let y = yCoordinateShared == null ? 4 : yCoordinateShared; + + const tetrahedronBody = new CANNON.Body({ + mass: 2, // Set mass + shape: tetrahedronShape, + position: new CANNON.Vec3(x, y, z), + material: new CANNON.Material(), + restitution: 5, + }); + world.addBody(tetrahedronBody); + + let angVel1 = + sharedAngVel1 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel1; + let angVel2 = + sharedAngVel2 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel2; + let angVel3 = + sharedAngVel3 == null ? Math.random() * (1 - 0.1) + 0.1 : sharedAngVel3; + + const contactMat = new CANNON.ContactMaterial( + groundPhysMat, + tetrahedronBody.material, + { friction: ctx.friction } + ); + + world.addContactMaterial(contactMat); + + tetrahedronBody.angularVelocity.set(angVel1, angVel2, angVel3); + tetrahedronBody.angularDamping = 0.1; // This will help in reducing rotation over time + + tetrahedronBody.applyImpulse(ctx.offset, ctx.rollingForce); + tetrahedron.position.copy(tetrahedronBody.position); // this merges the physics body to threejs mesh + tetrahedron.quaternion.copy(tetrahedronBody.quaternion); + if (quaternionShared != null && quaternionShared != undefined) { + tetrahedron.quaternion.copy(quaternionShared); + tetrahedronBody.quaternion.copy(quaternionShared); + } + diceArray.push([ + tetrahedron, + tetrahedronBody, + "tetra", + tempShowNumbers, + tempTransparent, + tempFillColor, + tempTextColor, + angVel1, + angVel2, + angVel3, + contactMat + ]); +} + +function getTetraScore(scoresObject, body, ifRemove) { + const faceVectors = [ + { + vector: new THREE.Vector3(1, 1, 1).normalize(), // Towards a corner (positive x, y, z) + face: 1, + }, + { + vector: new THREE.Vector3(-1, -1, 1).normalize(), // Towards a corner (negative x, negative y, z) + face: 3, + }, + { + vector: new THREE.Vector3(-1, 1, -1).normalize(), // Towards a corner (negative x, positive y, negative z) + face: 2, + }, + { + vector: new THREE.Vector3(1, -1, -1).normalize(), // Towards a corner (positive x, negative y, negative z) + face: 4, + }, + ]; + + for (const faceVector of faceVectors) { + faceVector.vector.applyEuler(body.rotation); + if (Math.round(faceVector.vector.y) == 1) { + if (!ifRemove) { + scoresObject.lastRoll += faceVector.face + " + "; + scoresObject.presentScore += faceVector.face; + break; + } + return faceVector.face; + } + } +} diff --git a/activities/3DVolume.activity/js/activity.js b/activities/3DVolume.activity/js/activity.js new file mode 100644 index 0000000000..2e756e21ec --- /dev/null +++ b/activities/3DVolume.activity/js/activity.js @@ -0,0 +1,1744 @@ +define([ + "sugar-web/activity/activity", + "sugar-web/env", + "activity/palettes/bgpalette", + "activity/palettes/volumepalette", + "activity/palettes/colorpalettefill", + "activity/palettes/colorpalettetext", + "activity/palettes/zoompalette", + "sugar-web/graphics/presencepalette", + "tutorial", + "sugar-web/graphics/journalchooser", + "sugar-web/datastore", + "l10n", +], function ( + activity, + env, + bgpalette, + volumepalette, + colorpaletteFill, + colorpaletteText, + zoompalette, + presencepalette, + tutorial, + journalchooser, + datastore, + l10n +) { + // Function to change the background color based on the provided string + requirejs(["domReady!"], function (doc) { + activity.setup(); + // Link presence palette + var paletteBg = new bgpalette.BgPalette( + document.getElementById("bg-button"), + undefined + ); + paletteBg.setBackgroundChangeCallback(changeBoardBackgroundHelper); + function changeBoardBackgroundHelper(selectedBoard) { + console.log("changing background from base func"); + if (presence) { + presence.sendMessage(presence.getSharedInfo().id, { + user: presence.getUserInfo(), + action: "changeBg", + content: selectedBoard, + }); + } + changeBoardBackground(selectedBoard); + } + var paletteVolume = new volumepalette.VolumePalette( + document.getElementById("volume-button"), + undefined + ); + var paletteZoom = new zoompalette.ZoomPalette( + document.getElementById("zoom-button"), + undefined + ); + + // Full screen + document + .getElementById("fullscreen-button") + .addEventListener("click", function () { + document.getElementById("main-toolbar").style.visibility = + "hidden"; + document.getElementById("game-container").style.top = "0px"; + document.getElementById( + "unfullscreen-button" + ).style.visibility = "visible"; + }); + document + .getElementById("unfullscreen-button") + .addEventListener("click", function () { + document.getElementById("main-toolbar").style.visibility = + "visible"; + document.getElementById("game-container").style.top = "55px"; + document.getElementById( + "unfullscreen-button" + ).style.visibility = "hidden"; + }); + + const randomDirection = new CANNON.Vec3(0.3, 0.05, 0.3); + randomDirection.normalize(); // Normalize to unit vector + + let ctx = { + showNumbers: false, + presentColor: null, + textColor: "#ffffff", + toggleTransparent: false, + offset: new CANNON.Vec3(0, 0, 0), + rollingForce: randomDirection, + friction: 0.1, + }; + let presentBackground = null; + let scoresObject = { + lastRoll: "", + presentScore: 0, + }; + let diceArray = []; + let journalDiceArray = []; + let showImage = false; + let imageData; + var currentenv; + let removeVolume = false; + let transparent = false; + let defaultVolume = true; + let isInit = false; + + let xCoordinate, zCoordinate; + + var defaultButton = document.getElementById("default-button"); + defaultButton.classList.toggle("active"); + + // Setting user preferences through the env + env.getEnvironment(function (err, environment) { + currentenv = environment; + + // Set current language to Sugarizer + var defaultLanguage = + typeof chrome != "undefined" && chrome.app && chrome.app.runtime + ? chrome.i18n.getUILanguage() + : navigator.language; + var language = environment.user + ? environment.user.language + : defaultLanguage; + l10n.init(language); + window.addEventListener( + "localized", + function () { + l10n.updateDocument(); + }, + false + ); + + ctx.presentColor = + currentenv.user.colorvalue.fill != null + ? currentenv.user.colorvalue.fill + : ctx.presentColor; + + scene.background = new THREE.Color("#ffffff"); + console.log(ctx.presentColor); + + ctx.textColor = + currentenv.user.colorvalue.stroke != null + ? currentenv.user.colorvalue.stroke + : ctx.textColor; + + document.getElementById("color-button-fill").style.backgroundColor = + ctx.presentColor; + document.getElementById("color-button-text").style.backgroundColor = + ctx.textColor; + + if (environment.sharedId) { + console.log(environment.sharedId) + console.log("Shared instance"); + presence = activity.getPresenceObject(function ( + error, + network + ) { + network.onDataReceived(onNetworkDataReceived); + }); + } + }); + + var paletteColorFill = new colorpaletteFill.ColorPalette( + document.getElementById("color-button-fill"), + undefined, + ctx + ); + + var paletteColorText = new colorpaletteText.ColorPalette( + document.getElementById("color-button-text"), + undefined, + ctx + ); + + var onNetworkDataReceived = function (msg) { + console.log("received data"); + console.log(msg); + console.log(msg.action); + if (presence.getUserInfo().networkId === msg.user.networkId) { + return; + } + // If user already has some volumes on the board + if (msg.action == "init") { + if (isInit) { + return; + } + isInit = true; + + changeBoardBackground(msg.content[1]); + data = msg.content[0]; + for (let i = 0; i < data.length; i++) { + let createFunction = null; + switch (data[i][0]) { + case "cube": + createFunction = createCube; + break; + case "octa": + createFunction = createOctahedron; + break; + case "tetra": + createFunction = createTetrahedron; + break; + case "deca": + createFunction = createDecahedron; + break; + case "dodeca": + createFunction = createDodecahedron; + break; + case "icosa": + createFunction = createIcosahedron; + break; + default: + console.log(`Unexpected shape: ${data[i][0]}`); + continue; + } + // Add those volumes to the board. + if (createFunction) { + const fillColorStored = data[i][3]; + const textColorStored = data[i][4]; + createFunction( + fillColorStored, + data[i][5], + data[i][6], + data[i][1].x, + data[i][1].z, + false, + null, + data[i][1].y, + data[i][2], + textColorStored, + ctx, + diceArray, + world, + scene, + groundPhysMat, + data[i][7], + data[i][8], + data[i][9] + ); + } + } + } + + if (msg.action == "positions") { + console.log("received positonns"); + copyPositions(msg.content); + } + // if (msg.action == "throw") { + // copyPosition(); + // throwDice(msg.content[0], msg.content[1]); + // } + if (msg.action == "changeBg") { + changeBoardBackground(msg.content); + } + if (msg.action == "remove") { + // This starts a ray from the top of the scene and that ray intersects objects. + raycaster.setFromCamera(msg.content[0], camera); + var intersects = raycaster.intersectObjects(scene.children); + + // The object that is intersected first is the object that needs to be removed. + var intersectedObject = intersects[0]?.object; + + // If the first object is the board do not let it be removed + if (intersectedObject?.geometry.type == "PlaneGeometry") { + if (msg.content[1] != null) { + remove(null, msg.content[1]); + } + return; + } + remove(intersectedObject); + } else { + let createFunction = null; + + switch (msg.content.shape) { + case "cube": + createFunction = createCube; + break; + case "octa": + createFunction = createOctahedron; + break; + case "tetra": + createFunction = createTetrahedron; + break; + case "dodeca": + createFunction = createDodecahedron; + switch (msg.content.shape) { + case "cube": + createFunction = createCube; + break; + case "octa": + createFunction = createOctahedron; + break; + case "tetra": + createFunction = createTetrahedron; + break; + case "dodeca": + createFunction = createDodecahedron; + break; + case "deca": + createFunction = createDecahedron; + break; + case "icosa": + createFunction = createIcosahedron; + break; + } + break; + case "deca": + createFunction = createDecahedron; + break; + case "icosa": + createFunction = createIcosahedron; + break; + } + + if (createFunction) { + createFunction( + msg.content.color, + msg.content.ifNumbers, + msg.content.ifTransparent, + msg.content.xCoordinateShared, + msg.content.zCoordinateShared, + msg.content.ifImage, + msg.content.sharedImageData, + msg.content.yCoordinateShared, + msg.content.quaternionShared, + msg.content.sharedTextColor, + ctx, + diceArray, + world, + scene, + groundPhysMat, + msg.content.sharedAngVel1, + msg.content.sharedAngVel2, + msg.content.sharedAngVel3 + ); + } + } + }; + + // Handling the journal addition. + + document + .getElementById("stop-button") + .addEventListener("click", function (event) { + // We must add to the journal all the features of the added volume along with its exact position and quaternion + journalDiceArray.push(presentBackground); + for (let i = 0; i < diceArray.length; i++) { + journalDiceArray.push([ + diceArray[i][2], + diceArray[i][1].position, + diceArray[i][1].quaternion, + diceArray[i][5], + diceArray[i][6], + diceArray[i][3], + diceArray[i][4], + diceArray[i][7], + diceArray[i][8], + diceArray[i][9], + ]); + } + console.log("writing..."); + var jsonData = JSON.stringify(journalDiceArray); + console.log(jsonData); + activity.getDatastoreObject().setDataAsText(jsonData); + activity.getDatastoreObject().save(function (error) { + if (error === null) { + console.log("write done."); + } else { + console.log("write failed."); + } + }); + }); + + // Loading the journal data. + + env.getEnvironment(function (err, environment) { + currentenv = environment; + + // Load from datastore + if (!environment.objectId) { + console.log("New instance"); + } else { + activity + .getDatastoreObject() + .loadAsText(function (error, metadata, data) { + if (error == null && data != null) { + data = JSON.parse(data); + if (data.length > 1) { + for (let i = 1; i < data.length; i++) { + let fillColorStored = data[i][3]; + let textColorStored = data[i][4]; + switch (data[i][0]) { + case "cube": + createFunction = createCube; + break; + case "octa": + createFunction = createOctahedron; + break; + case "tetra": + createFunction = createTetrahedron; + break; + case "deca": + createFunction = createDecahedron; + break; + case "dodeca": + createFunction = createDodecahedron; + break; + case "icosa": + createFunction = createIcosahedron; + break; + default: + console.log( + `Unexpected shape: ${data[i][0]}` + ); + break; + } + + // Create the volumes + + if (createFunction) { + createFunction( + fillColorStored, + data[i][5], + data[i][6], + data[i][1].x, + data[i][1].z, + false, + null, + data[i][1].y, + data[i][2], + textColorStored, + ctx, + diceArray, + world, + scene, + groundPhysMat, + data[i][7], + data[i][8], + data[i][9] + ); + } + } + } + changeBoardBackground(data[0]); + } + }); + } + }); + + // Launch tutorial + document + .getElementById("help-button") + .addEventListener("click", function (e) { + // Set the adding flag to false so that new volumes are not added to the board when the tutorial is running. + ifAdding.adding = false; + tutorial.start(ifAdding); + }); + + // Handle the color sliders for the volume fill color. + const redSliderFill = document.getElementById("red-slider-fill"); + const greenSliderFill = document.getElementById("green-slider-fill"); + const blueSliderFill = document.getElementById("blue-slider-fill"); + + let sliderColorFill = { r: 0, g: 0, b: 0 }; + + function rgbToHex(r, g, b) { + return ( + "#" + + ((1 << 24) + (r << 16) + (g << 8) + b) + .toString(16) + .slice(1) + .toUpperCase() + ); + } + + function hexToRgb(hex) { + let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result + ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16), + } + : null; + } + + function updateColorDisplayFill() { + const hexColor = rgbToHex( + sliderColorFill.r, + sliderColorFill.g, + sliderColorFill.b + ); + ctx.presentColor = hexColor; + document.getElementById("color-button-fill").style.backgroundColor = + ctx.presentColor; + } + + function updateSlidersFill(color) { + const rgb = color.match(/\d+/g).map((num) => parseInt(num, 10)); + redSliderFill.value = rgb[0]; + greenSliderFill.value = rgb[1]; + blueSliderFill.value = rgb[2]; + } + + function handleSliderChangeFill() { + sliderColorFill = { + r: parseInt(redSliderFill.value), + g: parseInt(greenSliderFill.value), + b: parseInt(blueSliderFill.value), + }; + updateColorDisplayFill(); + } + redSliderFill.addEventListener("input", handleSliderChangeFill); + greenSliderFill.addEventListener("input", handleSliderChangeFill); + blueSliderFill.addEventListener("input", handleSliderChangeFill); + + document.addEventListener("color-selected-fill", function (event) { + const selectedColorFill = event.detail.color; + ctx.presentColor = selectedColorFill; + document.getElementById("color-button-fill").style.backgroundColor = + ctx.presentColor; + updateSlidersFill(selectedColorFill); + }); + + // Handle the color sliders for the volume text color. + const redSliderText = document.getElementById("red-slider-text"); + const greenSliderText = document.getElementById("green-slider-text"); + const blueSliderText = document.getElementById("blue-slider-text"); + + let sliderColorText = { r: 0, g: 0, b: 0 }; + + function updateColorDisplayText() { + const hexColor = rgbToHex( + sliderColorText.r, + sliderColorText.g, + sliderColorText.b + ); + ctx.textColor = hexColor; + document.getElementById("color-button-text").style.backgroundColor = + ctx.textColor; + } + + function updateSlidersText(color) { + const rgb = color.match(/\d+/g).map((num) => parseInt(num, 10)); + redSliderText.value = rgb[0]; + greenSliderText.value = rgb[1]; + blueSliderText.value = rgb[2]; + } + + function handleSliderChangeText() { + sliderColorText = { + r: parseInt(redSliderText.value), + g: parseInt(greenSliderText.value), + b: parseInt(blueSliderText.value), + }; + updateColorDisplayText(); + } + + redSliderText.addEventListener("input", handleSliderChangeText); + greenSliderText.addEventListener("input", handleSliderChangeText); + blueSliderText.addEventListener("input", handleSliderChangeText); + + document.addEventListener("color-selected-text", function (event) { + const selectedColorText = event.detail.color; + ctx.textColor = selectedColorText; + document.getElementById("color-button-text").style.backgroundColor = + ctx.textColor; + updateSlidersText(selectedColorText); + }); + + // Handle the tossing of the volumes. + document + .querySelector("#throw-button") + .addEventListener("click", () => { + throwDice(); + if (presence) { + presence.sendMessage(presence.getSharedInfo().id, { + user: presence.getUserInfo(), + action: "throw", + content: [ctx.offset, ctx.rollingForce], + }); + } + }); + + // Toggles showing numbers on the volumes. + + document + .querySelector("#number-button") + .addEventListener("click", () => { + var numberButton = document.getElementById("number-button"); + if (ctx.showNumbers) { + return; + } + numberButton.classList.toggle("active"); + document.getElementById("volume-button").style.backgroundImage = + "url(icons/number_volume.svg)"; + if (defaultVolume) { + var defaultButton = + document.getElementById("default-button"); + defaultButton.classList.toggle("active"); + defaultVolume = !defaultVolume; + } + if (ctx.toggleTransparent) { + var transparentButton = + document.getElementById("transparent-button"); + transparentButton.classList.toggle("active"); + ctx.toggleTransparent = !ctx.toggleTransparent; + } + ctx.showNumbers = !ctx.showNumbers; + // toggleNumbers(); + }); + + // Handles the transparent volume type button. + document + .querySelector("#transparent-button") + .addEventListener("click", () => { + if (ctx.toggleTransparent) { + return; + } + var transparentButton = + document.getElementById("transparent-button"); + // Toggle the 'active' class on the clear button + transparentButton.classList.toggle("active"); + document.getElementById("volume-button").style.backgroundImage = + "url(icons/transparent_volume.svg)"; + + if (defaultVolume) { + var defaultButton = + document.getElementById("default-button"); + defaultButton.classList.toggle("active"); + defaultVolume = !defaultVolume; + } + + if (ctx.showNumbers) { + var numberButton = document.getElementById("number-button"); + numberButton.classList.toggle("active"); + ctx.showNumbers = !ctx.showNumbers; + } + ctx.toggleTransparent = !ctx.toggleTransparent; + }); + + // Handles the default (solid volume, without numbers nor transparent) volume type button. + document + .querySelector("#default-button") + .addEventListener("click", (event) => { + if (defaultVolume) { + return; + } + var defaultButton = document.getElementById("default-button"); + // Toggle the 'active' class on the clear button + defaultButton.classList.toggle("active"); + document.getElementById("volume-button").style.backgroundImage = + "url(icons/default_volume.svg)"; + + if (ctx.toggleTransparent) { + var transparentButton = + document.getElementById("transparent-button"); + transparentButton.classList.toggle("active"); + ctx.toggleTransparent = !ctx.toggleTransparent; + } + + if (ctx.showNumbers) { + var numberButton = document.getElementById("number-button"); + numberButton.classList.toggle("active"); + ctx.showNumbers = !ctx.showNumbers; + } + defaultVolume = !defaultVolume; + }); + + let addShape = { + cube: true, + tetra: false, + octa: false, + dodeca: false, + deca: false, + icosa: false, + }; + document.getElementById("cube-button").classList.toggle("active"); + + const buttons = ["cube", "tetra", "octa", "dodeca", "deca", "icosa"]; + const removeButton = document.querySelector("#clear-button"); + const solidButton = document.querySelector("#solid-button"); + + const toggleShape = (shape) => { + buttons.forEach((btn) => { + addShape[btn] = btn === shape; + document + .getElementById(`${btn}-button`) + .classList.toggle("active", btn === shape); + }); + removeVolume = false; + removeButton.classList.remove("active"); + }; + // Handles the remove button. + removeButton.addEventListener("click", () => { + if (!removeButton.classList.contains("active")) { + buttons.forEach((btn) => { + addShape[btn] = false; + document + .getElementById(`${btn}-button`) + .classList.remove("active"); + }); + removeVolume = true; + removeButton.classList.add("active"); + } + }); + + buttons.forEach((shape) => { + document + .getElementById(`${shape}-button`) + .addEventListener("click", () => { + if ( + !document + .getElementById(`${shape}-button`) + .classList.contains("active") + ) { + toggleShape(shape); + } + }); + }); + + const lastRollElement = document.getElementById("roll"); + + // Adds all the numbers on top for the numbered volumes. + function updateElements() { + lastRollElement.textContent = + scoresObject.lastRoll.substring( + 0, + scoresObject.lastRoll.length - 2 + ) + + "= " + + scoresObject.presentScore; + } + + const renderer = new THREE.WebGLRenderer({ + antialias: true, + alpha: true, + }); + renderer.shadowMap.enabled = true; + + const raycaster = new THREE.Raycaster(); + const mouse = new THREE.Vector2(); + document.querySelector("body").addEventListener("click", onRemoveClick); + document + .querySelector("#game-container") + .addEventListener("click", onAddClick); + + let ifAdding = { + adding: true, + }; + + function onAddClick(event) { + throwingDice = true; + // This will be false only when tutorial is running. + if (!ifAdding.adding) { + return; + } + // This is so that volumes are not added to the board when the board is being rotated. + if (window.isRotating) { + window.isRotating = false; + return; + } + if (!removeVolume) { + // Calculates the exact point where the user clicks and wants to add the volume to. + var rect = renderer.domElement.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + + // Update the picking ray with the camera and mouse position + raycaster.setFromCamera(mouse, camera); + + // Calculate objects intersecting the picking ray + var intersects = raycaster.intersectObjects(scene.children); + + for (let i = 0; i < intersects.length; i++) { + var intersectedObject = intersects[i]?.object; + // The volume must be added to the board only when the board is clicked. + if (intersectedObject.geometry.type == "PlaneGeometry") { + xCoordinate = intersects[i].point.x; + zCoordinate = intersects[i].point.z; + + let createFunction = null; + let shapeType = null; + + if (addShape["cube"]) { + createFunction = createCube; + shapeType = "cube"; + } else if (addShape["tetra"]) { + createFunction = createTetrahedron; + shapeType = "tetra"; + } else if (addShape["deca"]) { + createFunction = createDecahedron; + shapeType = "deca"; + } else if (addShape["dodeca"]) { + createFunction = createDodecahedron; + shapeType = "dodeca"; + } else if (addShape["icosa"]) { + createFunction = createIcosahedron; + shapeType = "icosa"; + } else if (addShape["octa"]) { + createFunction = createOctahedron; + shapeType = "octa"; + } + + if (createFunction) { + let angVel1 = Math.random() * (3 - 0.1) + 0.1; + let angVel2 = Math.random() * (3 - 0.1) + 0.1; + let angVel3 = Math.random() * (3 - 0.1) + 0.1; + createFunction( + null, + null, + null, + xCoordinate, + zCoordinate, + null, + null, + null, + null, + null, + ctx, + diceArray, + world, + scene, + groundPhysMat, + angVel1, + angVel2, + angVel3 + ); + // Create the volume for the connected users as well. + if (presence) { + presence.sendMessage( + presence.getSharedInfo().id, + { + user: presence.getUserInfo(), + content: { + shape: shapeType, + color: ctx.presentColor, + ifTransparent: + ctx.toggleTransparent, + ifNumbers: ctx.showNumbers, + xCoordinateShared: xCoordinate, + zCoordinateShared: zCoordinate, + ifImage: showImage, + sharedImageData: imageData, + yCoordinateShared: null, + quaternionShared: null, + sharedTextColor: ctx.textColor, + sharedAngVel1: angVel1, + sharedAngVel2: angVel2, + sharedAngVel3: angVel3, + }, + } + ); + } + } + } + } + } + } + + function onRemoveClick(event) { + if (removeVolume) { + // Calculate mouse position in normalized device coordinates + var rect = renderer.domElement.getBoundingClientRect(); + mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; + mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; + + // Update the picking ray with the camera and mouse position + raycaster.setFromCamera(mouse, camera); + + // Calculate objects intersecting the picking ray + var intersects = raycaster.intersectObjects(scene.children); + + // Gets the first object intersected by the ray, which is the volume the user is clicking on. + var intersectedObject = intersects[0]?.object; + if (intersectedObject?.geometry.type == "PlaneGeometry") { + return; + } + let index = null; + for (let i = 0; i < diceArray.length; i++) { + if (intersectedObject == diceArray[i][0]) { + index = i; + break; + } + } + + // Removing the volume for other users as well. + if (presence) { + presence.sendMessage(presence.getSharedInfo().id, { + user: presence.getUserInfo(), + action: "remove", + content: [mouse, index], // Send the point which the user is clicking on. + }); + } + + remove(intersectedObject); + } + } + function remove(intersectedObject, index) { + let num = 0; + for (let i = 0; i < diceArray.length; i++) { + if (diceArray[i][3]) { + num++; + } + } + // Find the volume being clicked within the diceArray to remove it. + if (intersectedObject == null) { + if (index < diceArray.length && diceArray[index][3]) { + // If the volume being removed is a numbered volume then get the number on top of the volume and remove it from the score. + let score; + switch (diceArray[index][2]) { + case "cube": + score = getCubeScore( + scoresObject, + diceArray[index][0], + true + ); + break; + case "icosa": + score = getIcosaScore( + scoresObject, + diceArray[index][0], + true + ); + break; + case "deca": + score = getDecaScore( + scoresObject, + diceArray[index][0], + true + ); + break; + case "dodeca": + score = getDodecaScore( + scoresObject, + diceArray[index][0], + true + ); + break; + case "octa": + score = getOctaScore( + scoresObject, + diceArray[index][0], + true + ); + break; + case "tetra": + score = getTetraScore( + scoresObject, + diceArray[index][0], + true + ); + break; + default: + console.log(`Unknown type: ${diceArray[index][3]}`); + } + + scoresObject.presentScore = + scoresObject.presentScore - score; + + let scoresArray = scoresObject.lastRoll.split(" + "); + + // Find the index of the first occurrence of the score to remove + let indexToRemove = scoresArray.indexOf(score.toString()); + + // If the score is found, remove it + if (indexToRemove !== -1) { + scoresArray.splice(indexToRemove, 1); + } + + // Join the remaining scores back into a string + scoresObject.lastRoll = scoresArray.join(" + "); + updateElements(); + num--; + } + world.removeBody(diceArray[index][1]); + scene.remove(diceArray[index][0]); + diceArray.splice(index, 1); + } else { + for (let i = 0; i < diceArray.length; i++) { + if (diceArray[i][0] == intersectedObject) { + if (diceArray[i][3]) { + // If the volume being removed is a numbered volume then get the number on top of the volume and remove it from the score. + let score; + switch (diceArray[i][2]) { + case "cube": + score = getCubeScore( + scoresObject, + diceArray[i][0], + true + ); + break; + case "icosa": + score = getIcosaScore( + scoresObject, + diceArray[i][0], + true + ); + break; + case "deca": + score = getDecaScore( + scoresObject, + diceArray[i][0], + true + ); + break; + case "dodeca": + score = getDodecaScore( + scoresObject, + diceArray[i][0], + true + ); + break; + case "octa": + score = getOctaScore( + scoresObject, + diceArray[i][0], + true + ); + break; + case "tetra": + score = getTetraScore( + scoresObject, + diceArray[i][0], + true + ); + break; + default: + console.log( + `Unknown type: ${diceArray[i][3]}` + ); + continue; + } + + scoresObject.presentScore = + scoresObject.presentScore - score; + console.log(scoresObject.presentScore); + + let scoresArray = + scoresObject.lastRoll.split(" + "); + + // Find the index of the first occurrence of the score to remove + let indexToRemove = scoresArray.indexOf( + score.toString() + ); + + // If the score is found, remove it + if (indexToRemove !== -1) { + scoresArray.splice(indexToRemove, 1); + } + + // Join the remaining scores back into a string + scoresObject.lastRoll = scoresArray.join(" + "); + updateElements(); + console.log(scoresObject.lastRoll); + console.log(scoresObject.presentScore); + num--; + } + world.removeBody(diceArray[i][1]); + scene.remove(diceArray[i][0]); + diceArray.splice(i, 1); + } + } + } + if (num == 0) { + lastRollElement.textContent = ""; + scoresObject.lastRoll = ""; + scoresObject.presentScore = 0; + } + } + + var presence = null; + var palette = new presencepalette.PresencePalette( + document.getElementById("network-button"), + undefined + ); + var isHost = false; + palette.addEventListener("shared", function () { + palette.popDown(); + console.log("Want to share"); + presence = activity.getPresenceObject(function (error, network) { + if (error) { + console.log("Sharing error"); + return; + } + network.createSharedActivity( + "org.sugarlabs.3DVolume", + function (groupId) { + console.log("Activity shared"); + isHost = true; + console.log(groupId) + } + ); + network.onDataReceived(onNetworkDataReceived); + network.onSharedActivityUserChanged(onNetworkUserChanged); + }); + }); + + var onNetworkUserChanged = function (msg) { + if (isHost) { + let presenceDiceArray = []; + for (let i = 0; i < diceArray.length; i++) { + // Handles the situation when the user already has some volume on the board before the connected user joins. + presenceDiceArray.push([ + diceArray[i][2], + diceArray[i][1].position, + diceArray[i][1].quaternion, + diceArray[i][5], + diceArray[i][6], + diceArray[i][3], + diceArray[i][4], + diceArray[i][7], + diceArray[i][8], + diceArray[i][9], + ]); + } + if (isHost) { + presence.sendMessage(presence.getSharedInfo().id, { + user: presence.getUserInfo(), + action: "init", + content: [presenceDiceArray, presentBackground], // sends the diceArray and the present background of the user to the users which are joining + }); + } + setTimeout(sendPositions, 4500); + } + }; + + renderer.setSize(window.innerWidth, window.innerHeight); + const canvas = document.getElementById("game-container"); + document + .getElementById("game-container") + .appendChild(renderer.domElement); + // Create the scene and add lighting to it. + const scene = new THREE.Scene(); + scene.background = new THREE.Color("#ffffff"); + const light = new THREE.DirectionalLight(0xffffff, 0.4); + light.castShadow = true; + const leftLight = new THREE.DirectionalLight(0xffffff, 0.25); + leftLight.castShadow = true; + const rightLight = new THREE.DirectionalLight(0xffffff, 0.1); + rightLight.castShadow = true; + const backLight = new THREE.DirectionalLight(0xffffff, 0.1); + const bottomLight = new THREE.DirectionalLight(0xffffff, 0.1); + const topLight = new THREE.DirectionalLight(0xffffff, 0.2); + topLight.castShadow = true; + leftLight.position.set(-30, 20, -30); + rightLight.position.set(30, 20, -30); + backLight.position.set(0, 20, 30); + light.position.set(0, 20, -30); + bottomLight.position.set(0, -20, -30); + topLight.position.set(0, 10, 0); + scene.add(backLight); + scene.add(rightLight); + scene.add(leftLight); + scene.add(light); + scene.add(bottomLight); + scene.add(topLight); + + const ambientLight = new THREE.AmbientLight(0x222222); // Soft ambient lighting + scene.add(ambientLight); + + const camera = new THREE.PerspectiveCamera( + 45, + window.innerWidth / window.innerHeight, + 0.1, + 1000 + ); + // Create the cannon physics worls. + const world = new CANNON.World({ + gravity: new CANNON.Vec3(0, -9.81, 0), + }); + world.allowSleep = true; + + var sensorButton = document.getElementById("sensor-button"); + var sensorMode = false; + + // Handles the accelerometer + if (navigator.accelerometer != null) { + // If the accelerometer is available then keep the accelerometer on by default. + sensorMode = true; + sensorButton.classList.add("active"); + watchId = navigator.accelerometer.watchAcceleration( + accelerationChanged, + null, + { frequency: 500 } + ); + } + + sensorButton.addEventListener("click", function () { + if (navigator.accelerometer == null) { + return; + } + sensorMode = !sensorMode; + if (sensorMode) { + sensorButton.classList.add("active"); + watchId = navigator.accelerometer.watchAcceleration( + accelerationChanged, + null, + { frequency: 500 } + ); + } else { + sensorButton.classList.remove("active"); + world.gravity.set(0, -9.81, 0); + wakeAll(); + } + }); + + function accelerationChanged(acceleration) { + if (!sensorMode) return; + if (window.orientation == -90) { + // If its in reverse. + if (acceleration.y > 0) { + if (acceleration.y < -2.8) { + world.gravity.set(3, -9.81, 0); // Gravity towards the left + wakeAll(); + } else { + world.gravity.set(9.81, -9.81, 0); // Gravity towards the left + wakeAll(); + } + // left + } else { + if (acceleration.z > 0) { + if (acceleration.y > -1 && acceleration.y < 1) { + if (acceleration.z > 6) { + // front + world.gravity.set(0, -9.81, -9.81); // Gravity towards the front + wakeAll(); + } else { + // straight + world.gravity.set(0, -9.81, 0); + wakeAll(); + } + } else { + if (acceleration.y < -2.7) { + world.gravity.set(-3, -9.81, 0); // Gravity towards the right + wakeAll(); + } else { + world.gravity.set(-9.81, -9.81, 0); // Gravity towards the right + wakeAll(); + } + // right + } + } else { + // back + world.gravity.set(0, -9.81, 9.81); // Gravity towards the back + wakeAll(); + } + } + } else { + if (acceleration.y > 0) { + if (acceleration.y < -2.7) { + world.gravity.set(-3, -9.81, 0); // Gravity towards the right + wakeAll(); + } else { + world.gravity.set(-9.81, -9.81, 0); // Gravity towards the right + wakeAll(); + } + // right + } else { + if (acceleration.z > 0) { + if (acceleration.y > -1 && acceleration.y < 1) { + if (acceleration.z > 6) { + // back + world.gravity.set(0, -9.81, 9.81); // Gravity towards the back + wakeAll(); + } else { + // straight + world.gravity.set(0, -9.81, 0); + wakeAll(); + } + } else { + if (acceleration.y < -2.8) { + world.gravity.set(3, -9.81, 0); // Gravity towards the left + wakeAll(); + } else { + world.gravity.set(9.81, -9.81, 0); // Gravity towards the left + wakeAll(); + } + // left + } + } else { + // front + world.gravity.set(0, -9.81, -9.81); // Gravity towards the front + wakeAll(); + } + } + } + + // lastRollElement.textContent = + // "x- " + + // acceleration.x + + // ", " + + // "y- " + + // acceleration.y + + // ", " + + // "z- " + + // acceleration.x + + // " "; + } + + // Wakes all the volumes so that they move towards the gravity. + function wakeAll() { + for (let i = 0; i < diceArray.length; i++) { + diceArray[i][1].wakeUp(); + } + } + + // Create the threejs mesh of the board. + const groundGeo = new THREE.PlaneGeometry(30, 30); + const groundMat = new THREE.MeshPhongMaterial({ + side: THREE.DoubleSide, + wireframe: false, + }); + groundMat.needsUpdate = true; + const groundMesh = new THREE.Mesh(groundGeo, groundMat); + groundMesh.receiveShadow = true; + + groundMesh.material.color.setHex(0xc9c9c9); + + scene.add(groundMesh); + const groundPhysMat = new CANNON.Material(); + const groundWidth = 0; // Desired width of the ground + const groundDepth = 0; // Desired depth of the ground + const boxWidth = groundWidth / 2; + const boxDepth = groundDepth / 2; + const boxHeight = 10; // Adjust this for desired box height + + const boxShape = new CANNON.Box( + new CANNON.Vec3(boxWidth, boxHeight / 2, boxDepth) + ); + + // Create the physical cannon-es ground. + const groundBody = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(15, 15, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + }); + groundBody.material.friction = 0; + groundBody.material.contactEquationStiffness = 1e8; + groundBody.material.contactEquationRelaxation = 3; + groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0); + world.addBody(groundBody); + + // We will add invisible walls to all sides of the board so that the volumes do not fly off the board. + + const topWall = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(15, 15, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + }); + topWall.quaternion.setFromEuler(-Math.PI / 2, 0, 0); + topWall.position.set(0, 15, 0); + + world.addBody(topWall); + + const leftWallBody = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(15, 100, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + friction: -10, + restitution: 10, + }); + world.addBody(leftWallBody); + leftWallBody.position.set(15, 0, 0); + leftWallBody.quaternion.setFromEuler(0, -Math.PI / 2, 0); + + const rightWallBody = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(15, 100, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + friction: -10, + restitution: 10, + }); + world.addBody(rightWallBody); + rightWallBody.position.set(-15, 0, 0); + rightWallBody.quaternion.setFromEuler(0, -Math.PI / 2, 0); + + const backWallBody = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(100, 15, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + friction: -10, + restitution: 10, + }); + world.addBody(backWallBody); + backWallBody.position.set(0, 0, 15); + backWallBody.quaternion.setFromEuler(0, 0, -Math.PI / 2); + + const frontWallBody = new CANNON.Body({ + shape: new CANNON.Box(new CANNON.Vec3(100, 15, 0.1)), + type: CANNON.Body.STATIC, + material: groundPhysMat, + friction: -10, + restitution: 10, + }); + world.addBody(frontWallBody); + frontWallBody.position.set(0, 0, -15); + frontWallBody.quaternion.setFromEuler(0, 0, -Math.PI / 2); + + // Use OrbitControls to add orbital controls :) + const orbit = new OrbitControls.OrbitControls( + camera, + renderer.domElement + ); + camera.position.set(0, 25, -30); + orbit.update(); + orbit.listenToKeyEvents(document.querySelector("body")); + + const goRightButton = document.querySelector("#right-button"); + const goLeftButton = document.querySelector("#left-button"); + const goUpButton = document.querySelector("#up-button"); + const goDownButton = document.querySelector("#down-button"); + + // Handles the rotation of the board through the arrow buttons + goRightButton.addEventListener("click", function (event) { + orbit.rotateRight(); + event.stopPropagation(); + }); + + goLeftButton.addEventListener("click", function (event) { + orbit.rotateLeft(); + event.stopPropagation(); + }); + goUpButton.addEventListener("click", function (event) { + orbit.rotateUp(); + event.stopPropagation(); + }); + goDownButton.addEventListener("click", function (event) { + orbit.rotateDown(); + event.stopPropagation(); + }); + // Zoom code + const evt = new Event("wheel", { bubbles: true, cancelable: true }); + + const zoomInButton = document.getElementById("zoom-in-button"); + const zoomOutButton = document.getElementById("zoom-out-button"); + const zoomEqualButton = document.getElementById("zoom-equal-button"); + const zoomToButton = document.getElementById("zoom-to-button"); + + // Zoom code is self explanatory + const zoomInFunction = (e) => { + const fov = getFov(); + camera.fov = clickZoom(fov, "zoomIn"); + camera.updateProjectionMatrix(); + e.stopPropagation(); + }; + + const zoomOutFunction = (e) => { + const fov = getFov(); + camera.fov = clickZoom(fov, "zoomOut"); + camera.updateProjectionMatrix(); + e.stopPropagation(); + }; + + const zoomEqualFunction = (e) => { + const fov = getFov(); + camera.fov = 29; + camera.updateProjectionMatrix(); + e.stopPropagation(); + }; + + const zoomToFunction = (e) => { + const fov = getFov(); + camera.fov = 35; + camera.updateProjectionMatrix(); + e.stopPropagation(); + }; + + const clickZoom = (value, zoomType) => { + if (value >= 20 && zoomType === "zoomIn") { + return value - 5; + } else if (value <= 75 && zoomType === "zoomOut") { + return value + 5; + } else { + return value; + } + }; + + const getFov = () => { + return Math.floor( + (2 * + Math.atan( + camera.getFilmHeight() / 2 / camera.getFocalLength() + ) * + 180) / + Math.PI + ); + }; + + const fov = getFov(); + camera.fov = 29; + camera.updateProjectionMatrix(); + + zoomInButton.addEventListener("click", zoomInFunction); + zoomOutButton.addEventListener("click", zoomOutFunction); + zoomEqualButton.addEventListener("click", zoomEqualFunction); + zoomToButton.addEventListener("click", zoomToFunction); + + // This function handles the tossing of the volumes. + + // function throwDice(sharedOffset, sharedRolling) { + // for (let i = 0; i < diceArray.length; i++) { + // scene.remove(diceArray[i][0]); + // world.removeBody(diceArray[i][1]); + // } + // if (diceArray.length > 0) { + // scoresObject.lastRoll = ""; + // scoresObject.presentScore = 0; + // for (let i = 0; i < diceArray.length; i++) { + // diceArray[i][1].angularVelocity.set( + // diceArray[i][7], + // diceArray[i][8], + // diceArray[i][9] + // ); + // diceArray[i][1].applyImpulse(ctx.offset, ctx.rollingForce); + // diceArray[i][1].position.set(0, 10, 0); + // } + // for (let i = 0; i < diceArray.length; i++) { + // scene.add(diceArray[i][0]); + // world.addBody(diceArray[i][1]); + // } + // } + // console.log(diceArray); + // } + function throwDice(sharedOffset, sharedRolling) { + throwingDice = true; + for (let i = 0; i < diceArray.length; i++) { + scene.remove(diceArray[i][0]); + world.removeBody(diceArray[i][1]); + } + if (diceArray.length > 0) { + scoresObject.lastRoll = ""; + scoresObject.presentScore = 0; + for (let i = 0; i < diceArray.length; i++) { + diceArray[i][1].angularVelocity.set( + diceArray[i][7], + diceArray[i][8], + diceArray[i][9] + ); + diceArray[i][1].applyImpulse(ctx.offset, ctx.rollingForce); + diceArray[i][1].position.set(0, 10, 0); + } + for (let i = 0; i < diceArray.length; i++) { + scene.add(diceArray[i][0]); + world.addBody(diceArray[i][1]); + } + } + console.log(diceArray); + } + + // Functions to get the scores of the dice. + + function changeBoardBackground(selectedBoard) { + presentBackground = selectedBoard; + let textureLoader = new THREE.TextureLoader(); + switch (selectedBoard) { + case "green-board": + textureLoader.load( + "images/grass_background.png", + function (groundTexture) { + groundMesh.material.wireframe = false; + groundMesh.material.map = groundTexture; + groundMesh.material.needsUpdate = true; + groundBody.material.friction = 100; + } + ); + ctx.friction = 100; + break; + case "wood": + textureLoader.load( + "images/wood.png", + function (groundTexture) { + groundMesh.material.wireframe = false; + groundMesh.material.color.setHex(0xf0c592); + groundMesh.material.map = groundTexture; + groundMesh.material.needsUpdate = true; + // groundBody.material.friction = 60; + } + ); + ctx.friction = 0; + break; + case "default": + groundMesh.material.needsUpdate = true; + groundMesh.material.color.setHex(0xc9c9c9); + groundMesh.material.wireframe = false; + groundMesh.material.map = null; + groundBody.material.friction = 1; + ctx.friction = 1; + + break; + } + for (let i = 0; i < diceArray.length; i++) { + world.removeContactMaterial(diceArray[i][10]); + let newContactMaterial = new CANNON.ContactMaterial( + groundPhysMat, + diceArray[i][1].material, + { friction: ctx.friction } + ); + world.addContactMaterial(newContactMaterial); + } + } + // This function calls the getScore functions for all the volumes and displays them. + function getScores() { + console.log("getting scores now"); + scoresObject.presentScore = 0; + scoresObject.lastRoll = ""; + lastRollElement.textContent = ""; + + for (let i = 0; i < diceArray.length; i++) { + if (diceArray[i][3]) { + switch (diceArray[i][2]) { + case "cube": + score = getCubeScore(scoresObject, diceArray[i][0]); + break; + case "icosa": + score = getIcosaScore( + scoresObject, + diceArray[i][0] + ); + break; + case "deca": + score = getDecaScore(scoresObject, diceArray[i][0]); + break; + case "dodeca": + score = getDodecaScore( + scoresObject, + diceArray[i][0] + ); + break; + case "octa": + score = getOctaScore(scoresObject, diceArray[i][0]); + break; + case "tetra": + score = getTetraScore( + scoresObject, + diceArray[i][0] + ); + break; + default: + console.log(`Unknown type: ${diceArray[i][3]}`); + continue; + } + updateElements(); + } + } + } + + function sendPositions() { + console.log("sending positions now"); + let dicePositions = []; + for (let i = 0; i < diceArray.length; i++) { + dicePositions.push([ + diceArray[i][1].position, + diceArray[i][1].quaternion, + ]); + } + presence.sendMessage(presence.getSharedInfo().id, { + user: presence.getUserInfo(), + action: "positions", + content: dicePositions, + }); + } + + function copyPositions(positions) { + console.log("copying positions now"); + console.log(diceArray); + for (let i = 0; i < diceArray.length; i++) { + scene.remove(diceArray[i][0]); + world.removeBody(diceArray[i][1]); + } + for (let i = 0; i < diceArray.length; i++) { + diceArray[i][0].position.copy(positions[i][0]); + diceArray[i][1].position.copy(positions[i][0]); + diceArray[i][1].quaternion.copy(positions[i][1]); + diceArray[i][1].quaternion.copy(positions[i][1]); + } + for (let i = 0; i < diceArray.length; i++) { + scene.add(diceArray[i][0]); + world.addBody(diceArray[i][1]); + } + awake = true; + } + + // Leaving this here so that in the future contributors find it easier to debug the cannon-es physical world. Go to the animate function and uncomment the cannonDebugger line to view the physical world. + + const cannonDebugger = new CannonDebugger(scene, world, { + color: 0xadd8e6, + }); + + let awake = false; + let throwingDice = false; + + animate(); + + function animate(time) { + // world.step(timeStep); + // Uncomment the next line to view how the physical world actually looks like. + // cannonDebugger.update(); + + groundMesh.position.copy(groundBody.position); + groundMesh.quaternion.copy(groundBody.quaternion); + + // Loop to merge the cannon bodies to the threejs meshes + for (let i = 0; i < diceArray.length; i++) { + diceArray[i][0]?.position?.copy(diceArray[i][1].position); + diceArray[i][0]?.quaternion?.copy(diceArray[i][1].quaternion); + } + // console.log(world.hasActiveBodies); + // console.log(world.hasActiveBodies + "," + awake) + if (world.hasActiveBodies == false && awake == true) { + awake = false; + console.log("the world is going to sleep now bye bye"); + getScores(); + if (throwingDice) { + throwingDice = false; + if (presence) { + sendPositions(); + } + } + } + if (world.hasActiveBodies == true) { + awake = true; + } + + renderer.render(scene, camera); + } + + renderer.setAnimationLoop(animate); + + const fixedTimeStep = 1 / 40; + const maxSubSteps = 3; + + function updatePhysics() { + world.step(fixedTimeStep, fixedTimeStep * maxSubSteps); + } + + setInterval(updatePhysics, 1000 * fixedTimeStep); + + window.addEventListener("resize", function () { + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + renderer.setSize(window.innerWidth, window.innerHeight); + }); + }); +}); diff --git a/activities/3DVolume.activity/js/loader.js b/activities/3DVolume.activity/js/loader.js new file mode 100644 index 0000000000..01021e981d --- /dev/null +++ b/activities/3DVolume.activity/js/loader.js @@ -0,0 +1,8 @@ +requirejs.config({ + baseUrl: "lib", + paths: { + activity: "../js" + } +}); + +requirejs(["activity/activity"]); diff --git a/activities/3DVolume.activity/js/palettes/bgpalette.html b/activities/3DVolume.activity/js/palettes/bgpalette.html new file mode 100644 index 0000000000..05a203f5ce --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/bgpalette.html @@ -0,0 +1,21 @@ +
+

Select Background

+
+
+ + + + +
+
diff --git a/activities/3DVolume.activity/js/palettes/bgpalette.js b/activities/3DVolume.activity/js/palettes/bgpalette.js new file mode 100644 index 0000000000..963af7651c --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/bgpalette.js @@ -0,0 +1,78 @@ +define([ + "sugar-web/graphics/palette", + "text!activity/palettes/bgpalette.html", + "sugar-web/graphics/presencepalette", +], function (palette, template, presencepalette) { + var bgpalette = {}; + bgpalette.BgPalette = function (invoker, primaryText) { + palette.Palette.call(this, invoker, primaryText); + this.getPalette().id = "bg-palette"; + + var containerElem = document.createElement("div"); + containerElem.innerHTML = template; + + this.setContent([containerElem]); + + this.bgSelectedEvent = document.createEvent("CustomEvent"); + this.bgSelectedEvent.initCustomEvent("bg-selected", true, true, { + bg: "", + }); + + let that = this; + let backgroundChangeCallback = null; + + this.setBackgroundChangeCallback = function (callback) { + backgroundChangeCallback = callback; + }; + + document + .getElementById("green-board") + .addEventListener("click", onClick); + document.getElementById("default").addEventListener("click", onClick); + document.getElementById("wood").addEventListener("click", onClick); + + function onClick(event) { + that.bgSelectedEvent.bg = event.currentTarget.id; + if ( + document + .querySelector("#green-board") + .classList.contains("active") + ) { + document + .querySelector("#green-board") + .classList.remove("active"); + } + if (document.querySelector("#wood").classList.contains("active")) { + document.querySelector("#wood").classList.remove("active"); + } + if ( + document.querySelector("#default").classList.contains("active") + ) { + document.querySelector("#default").classList.remove("active"); + } + event.currentTarget.classList.add("active"); + + if (backgroundChangeCallback) { + backgroundChangeCallback(that.bgSelectedEvent.bg); + } + + that.popDown(); + } + }; + + var addEventListener = function (type, listener, useCapture) { + console.log("adding event listener"); + return this.getPalette().addEventListener(type, listener, useCapture); + }; + + bgpalette.BgPalette.prototype = Object.create(palette.Palette.prototype, { + addEventListener: { + value: addEventListener, + enumerable: true, + configurable: true, + writable: true, + }, + }); + + return bgpalette; +}); diff --git a/activities/3DVolume.activity/js/palettes/colorpalettefill.html b/activities/3DVolume.activity/js/palettes/colorpalettefill.html new file mode 100644 index 0000000000..476ca35200 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/colorpalettefill.html @@ -0,0 +1,27 @@ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
diff --git a/activities/3DVolume.activity/js/palettes/colorpalettefill.js b/activities/3DVolume.activity/js/palettes/colorpalettefill.js new file mode 100644 index 0000000000..52a2a51144 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/colorpalettefill.js @@ -0,0 +1,64 @@ +define([ + "sugar-web/graphics/palette", + "text!activity/palettes/colorpalettefill.html", + "sugar-web/env", +], function (palette, template, env) { + var colorpalette = {}; + colorpalette.ColorPalette = function (invoker, primaryText) { + palette.Palette.call(this, invoker, primaryText); + this.getPalette().id = "color-palette"; + + var containerElem = document.createElement("div"); + + containerElem.innerHTML = template; + + this.setContent([containerElem]); + + let that = this; + // that.getPalette().childNodes[0].style.backgroundColor = ctx.presentColor + env.getEnvironment(function (err, environment) { + currentenv = environment; + that.getPalette().childNodes[0].style.backgroundColor = currentenv.user.colorvalue.fill + }); + + + const colors = document.querySelectorAll(".color-fill"); + colors.forEach((color) => { + color.addEventListener("click", function () { + const selectedColor = this.style.backgroundColor; + that.getPalette().childNodes[0].style.backgroundColor = this.style.backgroundColor; + const colorChangeEvent = new CustomEvent( + "color-selected-fill", + { + detail: { color: selectedColor }, + } + ); + document.dispatchEvent(colorChangeEvent); + that.popDown(); + }); + }); + }; + + function myFunc123() { + console.log("HI FROM PAINT") + } + + var addEventListener = function (type, listener, useCapture) { + console.log("adding event listener"); + return this.getPalette().addEventListener(type, listener, useCapture); + }; + + colorpalette.ColorPalette.prototype = Object.create( + palette.Palette.prototype, + { + addEventListener: { + value: addEventListener, + enumerable: true, + configurable: true, + writable: true, + }, + } + ); + + return colorpalette; +}); diff --git a/activities/3DVolume.activity/js/palettes/colorpalettetext.html b/activities/3DVolume.activity/js/palettes/colorpalettetext.html new file mode 100644 index 0000000000..2e10a60601 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/colorpalettetext.html @@ -0,0 +1,28 @@ +
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+
diff --git a/activities/3DVolume.activity/js/palettes/colorpalettetext.js b/activities/3DVolume.activity/js/palettes/colorpalettetext.js new file mode 100644 index 0000000000..08bca2c327 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/colorpalettetext.js @@ -0,0 +1,60 @@ +define([ + "sugar-web/graphics/palette", + "text!activity/palettes/colorpalettetext.html", + "sugar-web/env", +], function (palette, template,env) { + var colorpalette = {}; + colorpalette.ColorPalette = function (invoker, primaryText) { + palette.Palette.call(this, invoker, primaryText); + this.getPalette().id = "color-palette"; + + var containerElem = document.createElement("div"); + containerElem.innerHTML = template; + + this.setContent([containerElem]); + + let that = this; + // that.getPalette().childNodes[0].style.backgroundColor = ctx.textColor + env.getEnvironment(function (err, environment) { + currentenv = environment; + that.getPalette().childNodes[0].style.backgroundColor = currentenv.user.colorvalue.stroke + }); + + + + const colors = document.querySelectorAll(".color-text"); + colors.forEach((color) => { + color.addEventListener("click", function () { + const selectedColor = this.style.backgroundColor; + that.getPalette().childNodes[0].style.backgroundColor = this.style.backgroundColor; + const colorChangeEvent = new CustomEvent( + "color-selected-text", + { + detail: { color: selectedColor }, + } + ); + document.dispatchEvent(colorChangeEvent); + that.popDown(); + }); + }); + }; + + var addEventListener = function (type, listener, useCapture) { + console.log("adding event listener"); + return this.getPalette().addEventListener(type, listener, useCapture); + }; + + colorpalette.ColorPalette.prototype = Object.create( + palette.Palette.prototype, + { + addEventListener: { + value: addEventListener, + enumerable: true, + configurable: true, + writable: true, + }, + } + ); + + return colorpalette; +}); diff --git a/activities/3DVolume.activity/js/palettes/volumepalette.html b/activities/3DVolume.activity/js/palettes/volumepalette.html new file mode 100644 index 0000000000..134bed1954 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/volumepalette.html @@ -0,0 +1,20 @@ +
+ + + +
diff --git a/activities/3DVolume.activity/js/palettes/volumepalette.js b/activities/3DVolume.activity/js/palettes/volumepalette.js new file mode 100644 index 0000000000..754cc528a7 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/volumepalette.js @@ -0,0 +1,43 @@ +define([ + "sugar-web/graphics/palette", + "text!activity/palettes/volumepalette.html", +], function (palette, template) { + var volumepalette = {}; + volumepalette.VolumePalette = function (invoker, primaryText) { + palette.Palette.call(this, invoker, primaryText); + this.getPalette().id = "volume-palette"; + + var containerElem = document.createElement("div"); + containerElem.innerHTML = template; + + this.setContent([containerElem]); + + var that = this; + + document + .getElementById("volume-palette") + .addEventListener("click", () => { + that.getPalette().childNodes[0].style.backgroundImage = + invoker.style.backgroundImage; + this.popDown(); + }); + }; + + var addEventListener = function (type, listener, useCapture) { + return this.getPalette().addEventListener(type, listener, useCapture); + }; + + volumepalette.VolumePalette.prototype = Object.create( + palette.Palette.prototype, + { + addEventListener: { + value: addEventListener, + enumerable: true, + configurable: true, + writable: true, + }, + } + ); + + return volumepalette; +}); diff --git a/activities/3DVolume.activity/js/palettes/zoompalette.html b/activities/3DVolume.activity/js/palettes/zoompalette.html new file mode 100644 index 0000000000..f277e9710d --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/zoompalette.html @@ -0,0 +1,29 @@ +
+ + + + +
diff --git a/activities/3DVolume.activity/js/palettes/zoompalette.js b/activities/3DVolume.activity/js/palettes/zoompalette.js new file mode 100644 index 0000000000..6191e29684 --- /dev/null +++ b/activities/3DVolume.activity/js/palettes/zoompalette.js @@ -0,0 +1,33 @@ +define([ + "sugar-web/graphics/palette", + "text!activity/palettes/zoompalette.html", +], function (palette, template) { + var zoompalette = {}; + zoompalette.ZoomPalette = function (invoker, primaryText) { + palette.Palette.call(this, invoker, primaryText); + this.getPalette().id = "zoom-palette"; + + var containerElem = document.createElement("div"); + containerElem.innerHTML = template; + + this.setContent([containerElem]); + }; + + var addEventListener = function (type, listener, useCapture) { + return this.getPalette().addEventListener(type, listener, useCapture); + }; + + zoompalette.ZoomPalette.prototype = Object.create( + palette.Palette.prototype, + { + addEventListener: { + value: addEventListener, + enumerable: true, + configurable: true, + writable: true, + }, + } + ); + + return zoompalette; +}); diff --git a/activities/3DVolume.activity/lib/axios.min.js b/activities/3DVolume.activity/lib/axios.min.js new file mode 100644 index 0000000000..fc6c8b6187 --- /dev/null +++ b/activities/3DVolume.activity/lib/axios.min.js @@ -0,0 +1,3 @@ +/* axios v0.21.1 | (c) 2020 by Matt Zabriskie */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new i(e),n=s(i.prototype.request,t);return o.extend(n,i.prototype,t),o.extend(n,t),n}var o=n(2),s=n(3),i=n(4),a=n(22),u=n(10),c=r(u);c.Axios=i,c.create=function(e){return r(a(c.defaults,e))},c.Cancel=n(23),c.CancelToken=n(24),c.isCancel=n(9),c.all=function(e){return Promise.all(e)},c.spread=n(25),c.isAxiosError=n(26),e.exports=c,e.exports.default=c},function(e,t,n){"use strict";function r(e){return"[object Array]"===R.call(e)}function o(e){return"undefined"==typeof e}function s(e){return null!==e&&!o(e)&&null!==e.constructor&&!o(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function i(e){return"[object ArrayBuffer]"===R.call(e)}function a(e){return"undefined"!=typeof FormData&&e instanceof FormData}function u(e){var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function c(e){return"string"==typeof e}function f(e){return"number"==typeof e}function p(e){return null!==e&&"object"==typeof e}function d(e){if("[object Object]"!==R.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function l(e){return"[object Date]"===R.call(e)}function h(e){return"[object File]"===R.call(e)}function m(e){return"[object Blob]"===R.call(e)}function y(e){return"[object Function]"===R.call(e)}function g(e){return p(e)&&y(e.pipe)}function v(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function x(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function w(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function b(e,t){if(null!==e&&"undefined"!=typeof e)if("object"!=typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;n=200&&e<300}};u.headers={common:{Accept:"application/json, text/plain, */*"}},s.forEach(["delete","get","head"],function(e){u.headers[e]={}}),s.forEach(["post","put","patch"],function(e){u.headers[e]=s.merge(a)}),e.exports=u},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(13),s=n(16),i=n(5),a=n(17),u=n(20),c=n(21),f=n(14);e.exports=function(e){return new Promise(function(t,n){var p=e.data,d=e.headers;r.isFormData(p)&&delete d["Content-Type"];var l=new XMLHttpRequest;if(e.auth){var h=e.auth.username||"",m=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";d.Authorization="Basic "+btoa(h+":"+m)}var y=a(e.baseURL,e.url);if(l.open(e.method.toUpperCase(),i(y,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,l.onreadystatechange=function(){if(l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))){var r="getAllResponseHeaders"in l?u(l.getAllResponseHeaders()):null,s=e.responseType&&"text"!==e.responseType?l.response:l.responseText,i={data:s,status:l.status,statusText:l.statusText,headers:r,config:e,request:l};o(t,n,i),l=null}},l.onabort=function(){l&&(n(f("Request aborted",e,"ECONNABORTED",l)),l=null)},l.onerror=function(){n(f("Network Error",e,null,l)),l=null},l.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),n(f(t,e,"ECONNABORTED",l)),l=null},r.isStandardBrowserEnv()){var g=(e.withCredentials||c(y))&&e.xsrfCookieName?s.read(e.xsrfCookieName):void 0;g&&(d[e.xsrfHeaderName]=g)}if("setRequestHeader"in l&&r.forEach(d,function(e,t){"undefined"==typeof p&&"content-type"===t.toLowerCase()?delete d[t]:l.setRequestHeader(t,e)}),r.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),e.responseType)try{l.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){l&&(l.abort(),n(e),l=null)}),p||(p=null),l.send(p)})}},function(e,t,n){"use strict";var r=n(14);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(15);e.exports=function(e,t,n,o,s){var i=new Error(e);return r(i,t,n,o,s)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,s,i){var a=[];a.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(o)&&a.push("path="+o),r.isString(s)&&a.push("domain="+s),i===!0&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";var r=n(18),o=n(19);e.exports=function(e,t){return e&&!r(t)?o(e,t):t}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t,n){"use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,s,i={};return e?(r.forEach(e.split("\n"),function(e){if(s=e.indexOf(":"),t=r.trim(e.substr(0,s)).toLowerCase(),n=r.trim(e.substr(s+1)),t){if(i[t]&&o.indexOf(t)>=0)return;"set-cookie"===t?i[t]=(i[t]?i[t]:[]).concat([n]):i[t]=i[t]?i[t]+", "+n:n}}),i):i}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return function(){return!0}}()},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){function n(e,t){return r.isPlainObject(e)&&r.isPlainObject(t)?r.merge(e,t):r.isPlainObject(t)?r.merge({},t):r.isArray(t)?t.slice():t}function o(o){r.isUndefined(t[o])?r.isUndefined(e[o])||(s[o]=n(void 0,e[o])):s[o]=n(e[o],t[o])}t=t||{};var s={},i=["url","method","data"],a=["headers","auth","proxy","params"],u=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],c=["validateStatus"];r.forEach(i,function(e){r.isUndefined(t[e])||(s[e]=n(void 0,t[e]))}),r.forEach(a,o),r.forEach(u,function(o){r.isUndefined(t[o])?r.isUndefined(e[o])||(s[o]=n(void 0,e[o])):s[o]=n(void 0,t[o])}),r.forEach(c,function(r){r in t?s[r]=n(e[r],t[r]):r in e&&(s[r]=n(void 0,e[r]))});var f=i.concat(a).concat(u).concat(c),p=Object.keys(e).concat(Object.keys(t)).filter(function(e){return f.indexOf(e)===-1});return r.forEach(p,o),s}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(23);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t){"use strict";e.exports=function(e){return"object"==typeof e&&e.isAxiosError===!0}}])}); +//# sourceMappingURL=axios.min.map \ No newline at end of file diff --git a/activities/3DVolume.activity/lib/buffer.js b/activities/3DVolume.activity/lib/buffer.js new file mode 100644 index 0000000000..98c39975c2 --- /dev/null +++ b/activities/3DVolume.activity/lib/buffer.js @@ -0,0 +1,934 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) : + typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BufferGeometryUtils = {}, global.THREE)); +})(this, (function (exports, three) { 'use strict'; + + function computeTangents( geometry ) { + + geometry.computeTangents(); + console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use BufferGeometry.computeTangents() instead.' ); + + } + + /** + * @param {Array} geometries + * @param {Boolean} useGroups + * @return {BufferGeometry} + */ + function mergeBufferGeometries( geometries, useGroups = false ) { + + const isIndexed = geometries[ 0 ].index !== null; + + const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) ); + const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) ); + + const attributes = {}; + const morphAttributes = {}; + + const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative; + + const mergedGeometry = new THREE.BufferGeometry(); + + let offset = 0; + + for ( let i = 0; i < geometries.length; ++ i ) { + + const geometry = geometries[ i ]; + let attributesCount = 0; + + // ensure that all geometries are indexed, or none + + if ( isIndexed !== ( geometry.index !== null ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' ); + return null; + + } + + // gather attributes, exit early if they're different + + for ( const name in geometry.attributes ) { + + if ( ! attributesUsed.has( name ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' ); + return null; + + } + + if ( attributes[ name ] === undefined ) attributes[ name ] = []; + + attributes[ name ].push( geometry.attributes[ name ] ); + + attributesCount ++; + + } + + // ensure geometries have the same number of attributes + + if ( attributesCount !== attributesUsed.size ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' ); + return null; + + } + + // gather morph attributes, exit early if they're different + + if ( morphTargetsRelative !== geometry.morphTargetsRelative ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' ); + return null; + + } + + for ( const name in geometry.morphAttributes ) { + + if ( ! morphAttributesUsed.has( name ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' ); + return null; + + } + + if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = []; + + morphAttributes[ name ].push( geometry.morphAttributes[ name ] ); + + } + + // gather .userData + + mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || []; + mergedGeometry.userData.mergedUserData.push( geometry.userData ); + + if ( useGroups ) { + + let count; + + if ( isIndexed ) { + + count = geometry.index.count; + + } else if ( geometry.attributes.position !== undefined ) { + + count = geometry.attributes.position.count; + + } else { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' ); + return null; + + } + + mergedGeometry.addGroup( offset, count, i ); + + offset += count; + + } + + } + + // merge indices + + if ( isIndexed ) { + + let indexOffset = 0; + const mergedIndex = []; + + for ( let i = 0; i < geometries.length; ++ i ) { + + const index = geometries[ i ].index; + + for ( let j = 0; j < index.count; ++ j ) { + + mergedIndex.push( index.getX( j ) + indexOffset ); + + } + + indexOffset += geometries[ i ].attributes.position.count; + + } + + mergedGeometry.setIndex( mergedIndex ); + + } + + // merge attributes + + for ( const name in attributes ) { + + const mergedAttribute = mergeBufferAttributes( attributes[ name ] ); + + if ( ! mergedAttribute ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' ); + return null; + + } + + mergedGeometry.setAttribute( name, mergedAttribute ); + + } + + // merge morph attributes + + for ( const name in morphAttributes ) { + + const numMorphTargets = morphAttributes[ name ][ 0 ].length; + + if ( numMorphTargets === 0 ) break; + + mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; + mergedGeometry.morphAttributes[ name ] = []; + + for ( let i = 0; i < numMorphTargets; ++ i ) { + + const morphAttributesToMerge = []; + + for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) { + + morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] ); + + } + + const mergedMorphAttribute = mergeBufferAttributes( morphAttributesToMerge ); + + if ( ! mergedMorphAttribute ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' ); + return null; + + } + + mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute ); + + } + + } + + return mergedGeometry; + + } + + /** + * @param {Array} attributes + * @return {BufferAttribute} + */ + function mergeBufferAttributes( attributes ) { + + let TypedArray; + let itemSize; + let normalized; + let arrayLength = 0; + + for ( let i = 0; i < attributes.length; ++ i ) { + + const attribute = attributes[ i ]; + + if ( attribute.isInterleavedBufferAttribute ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' ); + return null; + + } + + if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; + if ( TypedArray !== attribute.array.constructor ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' ); + return null; + + } + + if ( itemSize === undefined ) itemSize = attribute.itemSize; + if ( itemSize !== attribute.itemSize ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' ); + return null; + + } + + if ( normalized === undefined ) normalized = attribute.normalized; + if ( normalized !== attribute.normalized ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' ); + return null; + + } + + arrayLength += attribute.array.length; + + } + + const array = new TypedArray( arrayLength ); + let offset = 0; + + for ( let i = 0; i < attributes.length; ++ i ) { + + array.set( attributes[ i ].array, offset ); + + offset += attributes[ i ].array.length; + + } + + return new THREE.BufferAttribute( array, itemSize, normalized ); + + } + + /** + * @param {Array} attributes + * @return {Array} + */ + function interleaveAttributes( attributes ) { + + // Interleaves the provided attributes into an InterleavedBuffer and returns + // a set of InterleavedBufferAttributes for each attribute + let TypedArray; + let arrayLength = 0; + let stride = 0; + + // calculate the the length and type of the interleavedBuffer + for ( let i = 0, l = attributes.length; i < l; ++ i ) { + + const attribute = attributes[ i ]; + + if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; + if ( TypedArray !== attribute.array.constructor ) { + + console.error( 'AttributeBuffers of different types cannot be interleaved' ); + return null; + + } + + arrayLength += attribute.array.length; + stride += attribute.itemSize; + + } + + // Create the set of buffer attributes + const interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride ); + let offset = 0; + const res = []; + const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; + const setters = [ 'setX', 'setY', 'setZ', 'setW' ]; + + for ( let j = 0, l = attributes.length; j < l; j ++ ) { + + const attribute = attributes[ j ]; + const itemSize = attribute.itemSize; + const count = attribute.count; + const iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized ); + res.push( iba ); + + offset += itemSize; + + // Move the data for each attribute into the new interleavedBuffer + // at the appropriate offset + for ( let c = 0; c < count; c ++ ) { + + for ( let k = 0; k < itemSize; k ++ ) { + + iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) ); + + } + + } + + } + + return res; + + } + + /** + * @param {Array} geometry + * @return {number} + */ + function estimateBytesUsed( geometry ) { + + // Return the estimated memory used by this geometry in bytes + // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account + // for InterleavedBufferAttributes. + let mem = 0; + for ( const name in geometry.attributes ) { + + const attr = geometry.getAttribute( name ); + mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT; + + } + + const indices = geometry.getIndex(); + mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0; + return mem; + + } + + /** + * @param {BufferGeometry} geometry + * @param {number} tolerance + * @return {BufferGeometry>} + */ + function mergeVertices( geometry, tolerance = 1e-4 ) { + + tolerance = Math.max( tolerance, Number.EPSILON ); + + // Generate an index buffer if the geometry doesn't have one, or optimize it + // if it's already available. + const hashToIndex = {}; + const indices = geometry.getIndex(); + const positions = geometry.getAttribute( 'position' ); + const vertexCount = indices ? indices.count : positions.count; + + // next value for triangle indices + let nextIndex = 0; + + // attributes and new attribute arrays + const attributeNames = Object.keys( geometry.attributes ); + const attrArrays = {}; + const morphAttrsArrays = {}; + const newIndices = []; + const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; + + // initialize the arrays + for ( let i = 0, l = attributeNames.length; i < l; i ++ ) { + + const name = attributeNames[ i ]; + + attrArrays[ name ] = []; + + const morphAttr = geometry.morphAttributes[ name ]; + if ( morphAttr ) { + + morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] ); + + } + + } + + // convert the error tolerance to an amount of decimal places to truncate to + const decimalShift = Math.log10( 1 / tolerance ); + const shiftMultiplier = Math.pow( 10, decimalShift ); + for ( let i = 0; i < vertexCount; i ++ ) { + + const index = indices ? indices.getX( i ) : i; + + // Generate a hash for the vertex attributes at the current index 'i' + let hash = ''; + for ( let j = 0, l = attributeNames.length; j < l; j ++ ) { + + const name = attributeNames[ j ]; + const attribute = geometry.getAttribute( name ); + const itemSize = attribute.itemSize; + + for ( let k = 0; k < itemSize; k ++ ) { + + // double tilde truncates the decimal value + hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`; + + } + + } + + // Add another reference to the vertex if it's already + // used by another index + if ( hash in hashToIndex ) { + + newIndices.push( hashToIndex[ hash ] ); + + } else { + + // copy data to the new index in the attribute arrays + for ( let j = 0, l = attributeNames.length; j < l; j ++ ) { + + const name = attributeNames[ j ]; + const attribute = geometry.getAttribute( name ); + const morphAttr = geometry.morphAttributes[ name ]; + const itemSize = attribute.itemSize; + const newarray = attrArrays[ name ]; + const newMorphArrays = morphAttrsArrays[ name ]; + + for ( let k = 0; k < itemSize; k ++ ) { + + const getterFunc = getters[ k ]; + newarray.push( attribute[ getterFunc ]( index ) ); + + if ( morphAttr ) { + + for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) { + + newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) ); + + } + + } + + } + + } + + hashToIndex[ hash ] = nextIndex; + newIndices.push( nextIndex ); + nextIndex ++; + + } + + } + + // Generate typed arrays from new attribute arrays and update + // the attributeBuffers + const result = geometry.clone(); + for ( let i = 0, l = attributeNames.length; i < l; i ++ ) { + + const name = attributeNames[ i ]; + const oldAttribute = geometry.getAttribute( name ); + + const buffer = new oldAttribute.array.constructor( attrArrays[ name ] ); + const attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized ); + + result.setAttribute( name, attribute ); + + // Update the attribute arrays + if ( name in morphAttrsArrays ) { + + for ( let j = 0; j < morphAttrsArrays[ name ].length; j ++ ) { + + const oldMorphAttribute = geometry.morphAttributes[ name ][ j ]; + + const buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] ); + const morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized ); + result.morphAttributes[ name ][ j ] = morphAttribute; + + } + + } + + } + + // indices + + result.setIndex( newIndices ); + + return result; + + } + + /** + * @param {BufferGeometry} geometry + * @param {number} drawMode + * @return {BufferGeometry>} + */ + function toTrianglesDrawMode( geometry, drawMode ) { + + if ( drawMode === THREE.TrianglesDrawMode ) { + + console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' ); + return geometry; + + } + + if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) { + + let index = geometry.getIndex(); + + // generate index if not present + + if ( index === null ) { + + const indices = []; + + const position = geometry.getAttribute( 'position' ); + + if ( position !== undefined ) { + + for ( let i = 0; i < position.count; i ++ ) { + + indices.push( i ); + + } + + geometry.setIndex( indices ); + index = geometry.getIndex(); + + } else { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); + return geometry; + + } + + } + + // + + const numberOfTriangles = index.count - 2; + const newIndices = []; + + if ( drawMode === THREE.TriangleFanDrawMode ) { + + // gl.TRIANGLE_FAN + + for ( let i = 1; i <= numberOfTriangles; i ++ ) { + + newIndices.push( index.getX( 0 ) ); + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + + } + + } else { + + // gl.TRIANGLE_STRIP + + for ( let i = 0; i < numberOfTriangles; i ++ ) { + + if ( i % 2 === 0 ) { + + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i + 2 ) ); + + } else { + + newIndices.push( index.getX( i + 2 ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i ) ); + + } + + } + + } + + if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); + + } + + // build final geometry + + const newGeometry = geometry.clone(); + newGeometry.setIndex( newIndices ); + newGeometry.clearGroups(); + + return newGeometry; + + } else { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode ); + return geometry; + + } + + } + + /** + * Calculates the morphed attributes of a morphed/skinned BufferGeometry. + * Helpful for Raytracing or Decals. + * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points. + * @return {Object} An Object with original position/normal attributes and morphed ones. + */ + function computeMorphedAttributes( object ) { + + if ( object.geometry.isBufferGeometry !== true ) { + + console.error( 'THREE.BufferGeometryUtils: Geometry is not of type BufferGeometry.' ); + return null; + + } + + const _vA = new THREE.Vector3(); + const _vB = new THREE.Vector3(); + const _vC = new THREE.Vector3(); + + const _tempA = new THREE.Vector3(); + const _tempB = new THREE.Vector3(); + const _tempC = new THREE.Vector3(); + + const _morphA = new THREE.Vector3(); + const _morphB = new THREE.Vector3(); + const _morphC = new THREE.Vector3(); + + function _calculateMorphedAttributeData( + object, + material, + attribute, + morphAttribute, + morphTargetsRelative, + a, + b, + c, + modifiedAttributeArray + ) { + + _vA.fromBufferAttribute( attribute, a ); + _vB.fromBufferAttribute( attribute, b ); + _vC.fromBufferAttribute( attribute, c ); + + const morphInfluences = object.morphTargetInfluences; + + if ( material.morphTargets && morphAttribute && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + _morphB.set( 0, 0, 0 ); + _morphC.set( 0, 0, 0 ); + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morph = morphAttribute[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morph, a ); + _tempB.fromBufferAttribute( morph, b ); + _tempC.fromBufferAttribute( morph, c ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + _morphB.addScaledVector( _tempB, influence ); + _morphC.addScaledVector( _tempC, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( _vA ), influence ); + _morphB.addScaledVector( _tempB.sub( _vB ), influence ); + _morphC.addScaledVector( _tempC.sub( _vC ), influence ); + + } + + } + + _vA.add( _morphA ); + _vB.add( _morphB ); + _vC.add( _morphC ); + + } + + if ( object.isSkinnedMesh ) { + + object.boneTransform( a, _vA ); + object.boneTransform( b, _vB ); + object.boneTransform( c, _vC ); + + } + + modifiedAttributeArray[ a * 3 + 0 ] = _vA.x; + modifiedAttributeArray[ a * 3 + 1 ] = _vA.y; + modifiedAttributeArray[ a * 3 + 2 ] = _vA.z; + modifiedAttributeArray[ b * 3 + 0 ] = _vB.x; + modifiedAttributeArray[ b * 3 + 1 ] = _vB.y; + modifiedAttributeArray[ b * 3 + 2 ] = _vB.z; + modifiedAttributeArray[ c * 3 + 0 ] = _vC.x; + modifiedAttributeArray[ c * 3 + 1 ] = _vC.y; + modifiedAttributeArray[ c * 3 + 2 ] = _vC.z; + + } + + const geometry = object.geometry; + const material = object.material; + + let a, b, c; + const index = geometry.index; + const positionAttribute = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const normalAttribute = geometry.attributes.normal; + const morphNormal = geometry.morphAttributes.position; + + const groups = geometry.groups; + const drawRange = geometry.drawRange; + let i, j, il, jl; + let group, groupMaterial; + let start, end; + + const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize ); + const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize ); + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( i = 0, il = groups.length; i < il; i ++ ) { + + group = groups[ i ]; + groupMaterial = material[ group.materialIndex ]; + + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + + for ( j = start, jl = end; j < jl; j += 3 ) { + + a = index.getX( j ); + b = index.getX( j + 1 ); + c = index.getX( j + 2 ); + + _calculateMorphedAttributeData( + object, + groupMaterial, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + groupMaterial, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + start = Math.max( 0, drawRange.start ); + end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( i = start, il = end; i < il; i += 3 ) { + + a = index.getX( i ); + b = index.getX( i + 1 ); + c = index.getX( i + 2 ); + + _calculateMorphedAttributeData( + object, + material, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + material, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( i = 0, il = groups.length; i < il; i ++ ) { + + group = groups[ i ]; + groupMaterial = material[ group.materialIndex ]; + + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + + for ( j = start, jl = end; j < jl; j += 3 ) { + + a = j; + b = j + 1; + c = j + 2; + + _calculateMorphedAttributeData( + object, + groupMaterial, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + groupMaterial, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + start = Math.max( 0, drawRange.start ); + end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( i = start, il = end; i < il; i += 3 ) { + + a = i; + b = i + 1; + c = i + 2; + + _calculateMorphedAttributeData( + object, + material, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + material, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } + + const morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 ); + const morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 ); + + return { + + positionAttribute: positionAttribute, + normalAttribute: normalAttribute, + morphedPositionAttribute: morphedPositionAttribute, + morphedNormalAttribute: morphedNormalAttribute + + }; + + } + + exports.computeMorphedAttributes = computeMorphedAttributes; + exports.computeTangents = computeTangents; + exports.estimateBytesUsed = estimateBytesUsed; + exports.interleaveAttributes = interleaveAttributes; + exports.mergeBufferAttributes = mergeBufferAttributes; + exports.mergeBufferGeometries = mergeBufferGeometries; + exports.mergeVertices = mergeVertices; + exports.toTrianglesDrawMode = toTrianglesDrawMode; + +})); diff --git a/activities/3DVolume.activity/lib/cannon.js b/activities/3DVolume.activity/lib/cannon.js new file mode 100644 index 0000000000..224e09eac7 --- /dev/null +++ b/activities/3DVolume.activity/lib/cannon.js @@ -0,0 +1,13850 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('perf_hooks')) : + typeof define === 'function' && define.amd ? define(['exports', 'perf_hooks'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CANNON = {}, global.require$$0)); +})(this, (function (exports, require$$0) { 'use strict'; + + var cannon = {}; + + + /** + * Records what objects are colliding with each other + */ + class ObjectCollisionMatrix { + /** + * The matrix storage. + */ + + /** + * @todo Remove useless constructor + */ + constructor() { + this.matrix = {}; + } + /** + * get + */ + + get(bi, bj) { + let { id: i } = bi; + let { id: j } = bj; + + if (j > i) { + const temp = j; + j = i; + i = temp; + } + + return `${i}-${j}` in this.matrix; + } + /** + * set + */ + + set(bi, bj, value) { + let { id: i } = bi; + let { id: j } = bj; + + if (j > i) { + const temp = j; + j = i; + i = temp; + } + + if (value) { + this.matrix[`${i}-${j}`] = true; + } else { + delete this.matrix[`${i}-${j}`]; + } + } + /** + * Empty the matrix + */ + + reset() { + this.matrix = {}; + } + /** + * Set max number of objects + */ + + setNumObjects(n) {} + } + + /** + * A 3x3 matrix. + * Authored by {@link http://github.com/schteppe/ schteppe} + */ + class Mat3 { + /** + * A vector of length 9, containing all matrix elements. + */ + + /** + * @param elements A vector of length 9, containing all matrix elements. + */ + constructor(elements) { + if (elements === void 0) { + elements = [0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + + this.elements = elements; + } + /** + * Sets the matrix to identity + * @todo Should perhaps be renamed to `setIdentity()` to be more clear. + * @todo Create another function that immediately creates an identity matrix eg. `eye()` + */ + + identity() { + const e = this.elements; + e[0] = 1; + e[1] = 0; + e[2] = 0; + e[3] = 0; + e[4] = 1; + e[5] = 0; + e[6] = 0; + e[7] = 0; + e[8] = 1; + } + /** + * Set all elements to zero + */ + + setZero() { + const e = this.elements; + e[0] = 0; + e[1] = 0; + e[2] = 0; + e[3] = 0; + e[4] = 0; + e[5] = 0; + e[6] = 0; + e[7] = 0; + e[8] = 0; + } + /** + * Sets the matrix diagonal elements from a Vec3 + */ + + setTrace(vector) { + const e = this.elements; + e[0] = vector.x; + e[4] = vector.y; + e[8] = vector.z; + } + /** + * Gets the matrix diagonal elements + */ + + getTrace(target) { + if (target === void 0) { + target = new Vec3(); + } + + const e = this.elements; + target.x = e[0]; + target.y = e[4]; + target.z = e[8]; + return target; + } + /** + * Matrix-Vector multiplication + * @param v The vector to multiply with + * @param target Optional, target to save the result in. + */ + + vmult(v, target) { + if (target === void 0) { + target = new Vec3(); + } + + const e = this.elements; + const x = v.x; + const y = v.y; + const z = v.z; + target.x = e[0] * x + e[1] * y + e[2] * z; + target.y = e[3] * x + e[4] * y + e[5] * z; + target.z = e[6] * x + e[7] * y + e[8] * z; + return target; + } + /** + * Matrix-scalar multiplication + */ + + smult(s) { + for (let i = 0; i < this.elements.length; i++) { + this.elements[i] *= s; + } + } + /** + * Matrix multiplication + * @param matrix Matrix to multiply with from left side. + */ + + mmult(matrix, target) { + if (target === void 0) { + target = new Mat3(); + } + + const A = this.elements; + const B = matrix.elements; + const T = target.elements; + const a11 = A[0], + a12 = A[1], + a13 = A[2], + a21 = A[3], + a22 = A[4], + a23 = A[5], + a31 = A[6], + a32 = A[7], + a33 = A[8]; + const b11 = B[0], + b12 = B[1], + b13 = B[2], + b21 = B[3], + b22 = B[4], + b23 = B[5], + b31 = B[6], + b32 = B[7], + b33 = B[8]; + T[0] = a11 * b11 + a12 * b21 + a13 * b31; + T[1] = a11 * b12 + a12 * b22 + a13 * b32; + T[2] = a11 * b13 + a12 * b23 + a13 * b33; + T[3] = a21 * b11 + a22 * b21 + a23 * b31; + T[4] = a21 * b12 + a22 * b22 + a23 * b32; + T[5] = a21 * b13 + a22 * b23 + a23 * b33; + T[6] = a31 * b11 + a32 * b21 + a33 * b31; + T[7] = a31 * b12 + a32 * b22 + a33 * b32; + T[8] = a31 * b13 + a32 * b23 + a33 * b33; + return target; + } + /** + * Scale each column of the matrix + */ + + scale(vector, target) { + if (target === void 0) { + target = new Mat3(); + } + + const e = this.elements; + const t = target.elements; + + for (let i = 0; i !== 3; i++) { + t[3 * i + 0] = vector.x * e[3 * i + 0]; + t[3 * i + 1] = vector.y * e[3 * i + 1]; + t[3 * i + 2] = vector.z * e[3 * i + 2]; + } + + return target; + } + /** + * Solve Ax=b + * @param b The right hand side + * @param target Optional. Target vector to save in. + * @return The solution x + * @todo should reuse arrays + */ + + solve(b, target) { + if (target === void 0) { + target = new Vec3(); + } + + // Construct equations + const nr = 3; // num rows + + const nc = 4; // num cols + + const eqns = []; + let i; + let j; + + for (i = 0; i < nr * nc; i++) { + eqns.push(0); + } + + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + eqns[i + nc * j] = this.elements[i + 3 * j]; + } + } + + eqns[3 + 4 * 0] = b.x; + eqns[3 + 4 * 1] = b.y; + eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination + + let n = 3; + const k = n; + let np; + const kp = 4; // num rows + + let p; + + do { + i = k - n; + + if (eqns[i + nc * i] === 0) { + // the pivot is null, swap lines + for (j = i + 1; j < k; j++) { + if (eqns[i + nc * j] !== 0) { + np = kp; + + do { + // do ligne( i ) = ligne( i ) + ligne( k ) + p = kp - np; + eqns[p + nc * i] += eqns[p + nc * j]; + } while (--np); + + break; + } + } + } + + if (eqns[i + nc * i] !== 0) { + for (j = i + 1; j < k; j++) { + const multiplier = eqns[i + nc * j] / eqns[i + nc * i]; + np = kp; + + do { + // do ligne( k ) = ligne( k ) - multiplier * ligne( i ) + p = kp - np; + eqns[p + nc * j] = + p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier; + } while (--np); + } + } + } while (--n); // Get the solution + + target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2]; + target.y = + (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1]; + target.x = + (eqns[0 * nc + 3] - + eqns[0 * nc + 2] * target.z - + eqns[0 * nc + 1] * target.y) / + eqns[0 * nc + 0]; + + if ( + isNaN(target.x) || + isNaN(target.y) || + isNaN(target.z) || + target.x === Infinity || + target.y === Infinity || + target.z === Infinity + ) { + throw `Could not solve equation! Got x=[${target.toString()}], b=[${b.toString()}], A=[${this.toString()}]`; + } + + return target; + } + /** + * Get an element in the matrix by index. Index starts at 0, not 1!!! + * @param value If provided, the matrix element will be set to this value. + */ + + e(row, column, value) { + if (value === undefined) { + return this.elements[column + 3 * row]; + } else { + // Set value + this.elements[column + 3 * row] = value; + } + } + /** + * Copy another matrix into this matrix object. + */ + + copy(matrix) { + for (let i = 0; i < matrix.elements.length; i++) { + this.elements[i] = matrix.elements[i]; + } + + return this; + } + /** + * Returns a string representation of the matrix. + */ + + toString() { + let r = ""; + const sep = ","; + + for (let i = 0; i < 9; i++) { + r += this.elements[i] + sep; + } + + return r; + } + /** + * reverse the matrix + * @param target Target matrix to save in. + * @return The solution x + */ + + reverse(target) { + if (target === void 0) { + target = new Mat3(); + } + + // Construct equations + const nr = 3; // num rows + + const nc = 6; // num cols + + const eqns = reverse_eqns; + let i; + let j; + + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + eqns[i + nc * j] = this.elements[i + 3 * j]; + } + } + + eqns[3 + 6 * 0] = 1; + eqns[3 + 6 * 1] = 0; + eqns[3 + 6 * 2] = 0; + eqns[4 + 6 * 0] = 0; + eqns[4 + 6 * 1] = 1; + eqns[4 + 6 * 2] = 0; + eqns[5 + 6 * 0] = 0; + eqns[5 + 6 * 1] = 0; + eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination + + let n = 3; + const k = n; + let np; + const kp = nc; // num rows + + let p; + + do { + i = k - n; + + if (eqns[i + nc * i] === 0) { + // the pivot is null, swap lines + for (j = i + 1; j < k; j++) { + if (eqns[i + nc * j] !== 0) { + np = kp; + + do { + // do line( i ) = line( i ) + line( k ) + p = kp - np; + eqns[p + nc * i] += eqns[p + nc * j]; + } while (--np); + + break; + } + } + } + + if (eqns[i + nc * i] !== 0) { + for (j = i + 1; j < k; j++) { + const multiplier = eqns[i + nc * j] / eqns[i + nc * i]; + np = kp; + + do { + // do line( k ) = line( k ) - multiplier * line( i ) + p = kp - np; + eqns[p + nc * j] = + p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier; + } while (--np); + } + } + } while (--n); // eliminate the upper left triangle of the matrix + + i = 2; + + do { + j = i - 1; + + do { + const multiplier = eqns[i + nc * j] / eqns[i + nc * i]; + np = nc; + + do { + p = nc - np; + eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier; + } while (--np); + } while (j--); + } while (--i); // operations on the diagonal + + i = 2; + + do { + const multiplier = 1 / eqns[i + nc * i]; + np = nc; + + do { + p = nc - np; + eqns[p + nc * i] = eqns[p + nc * i] * multiplier; + } while (--np); + } while (i--); + + i = 2; + + do { + j = 2; + + do { + p = eqns[nr + j + nc * i]; + + if (isNaN(p) || p === Infinity) { + throw `Could not reverse! A=[${this.toString()}]`; + } + + target.e(i, j, p); + } while (j--); + } while (i--); + + return target; + } + /** + * Set the matrix from a quaterion + */ + + setRotationFromQuaternion(q) { + const x = q.x; + const y = q.y; + const z = q.z; + const w = q.w; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + const xx = x * x2; + const xy = x * y2; + const xz = x * z2; + const yy = y * y2; + const yz = y * z2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + const e = this.elements; + e[3 * 0 + 0] = 1 - (yy + zz); + e[3 * 0 + 1] = xy - wz; + e[3 * 0 + 2] = xz + wy; + e[3 * 1 + 0] = xy + wz; + e[3 * 1 + 1] = 1 - (xx + zz); + e[3 * 1 + 2] = yz - wx; + e[3 * 2 + 0] = xz - wy; + e[3 * 2 + 1] = yz + wx; + e[3 * 2 + 2] = 1 - (xx + yy); + return this; + } + /** + * Transpose the matrix + * @param target Optional. Where to store the result. + * @return The target Mat3, or a new Mat3 if target was omitted. + */ + + transpose(target) { + if (target === void 0) { + target = new Mat3(); + } + + const M = this.elements; + const T = target.elements; + let tmp; //Set diagonals + + T[0] = M[0]; + T[4] = M[4]; + T[8] = M[8]; + tmp = M[1]; + T[1] = M[3]; + T[3] = tmp; + tmp = M[2]; + T[2] = M[6]; + T[6] = tmp; + tmp = M[5]; + T[5] = M[7]; + T[7] = tmp; + return target; + } + } + const reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + + /** + * 3-dimensional vector + * @example + * const v = new Vec3(1, 2, 3) + * console.log('x=' + v.x) // x=1 + */ + + class Vec3 { + constructor(x, y, z) { + if (x === void 0) { + x = 0.0; + } + + if (y === void 0) { + y = 0.0; + } + + if (z === void 0) { + z = 0.0; + } + + this.x = x; + this.y = y; + this.z = z; + } + /** + * Vector cross product + * @param target Optional target to save in. + */ + + cross(vector, target) { + if (target === void 0) { + target = new Vec3(); + } + + const vx = vector.x; + const vy = vector.y; + const vz = vector.z; + const x = this.x; + const y = this.y; + const z = this.z; + target.x = y * vz - z * vy; + target.y = z * vx - x * vz; + target.z = x * vy - y * vx; + return target; + } + /** + * Set the vectors' 3 elements + */ + + set(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + /** + * Set all components of the vector to zero. + */ + + setZero() { + this.x = this.y = this.z = 0; + } + /** + * Vector addition + */ + + vadd(vector, target) { + if (target) { + target.x = vector.x + this.x; + target.y = vector.y + this.y; + target.z = vector.z + this.z; + } else { + return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z); + } + } + /** + * Vector subtraction + * @param target Optional target to save in. + */ + + vsub(vector, target) { + if (target) { + target.x = this.x - vector.x; + target.y = this.y - vector.y; + target.z = this.z - vector.z; + } else { + return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z); + } + } + /** + * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c + * + * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture} + */ + + crossmat() { + return new Mat3([ + 0, + -this.z, + this.y, + this.z, + 0, + -this.x, + -this.y, + this.x, + 0, + ]); + } + /** + * Normalize the vector. Note that this changes the values in the vector. + * @return Returns the norm of the vector + */ + + normalize() { + const x = this.x; + const y = this.y; + const z = this.z; + const n = Math.sqrt(x * x + y * y + z * z); + + if (n > 0.0) { + const invN = 1 / n; + this.x *= invN; + this.y *= invN; + this.z *= invN; + } else { + // Make something up + this.x = 0; + this.y = 0; + this.z = 0; + } + + return n; + } + /** + * Get the version of this vector that is of length 1. + * @param target Optional target to save in + * @return Returns the unit vector + */ + + unit(target) { + if (target === void 0) { + target = new Vec3(); + } + + const x = this.x; + const y = this.y; + const z = this.z; + let ninv = Math.sqrt(x * x + y * y + z * z); + + if (ninv > 0.0) { + ninv = 1.0 / ninv; + target.x = x * ninv; + target.y = y * ninv; + target.z = z * ninv; + } else { + target.x = 1; + target.y = 0; + target.z = 0; + } + + return target; + } + /** + * Get the length of the vector + */ + + length() { + const x = this.x; + const y = this.y; + const z = this.z; + return Math.sqrt(x * x + y * y + z * z); + } + /** + * Get the squared length of the vector. + */ + + lengthSquared() { + return this.dot(this); + } + /** + * Get distance from this point to another point + */ + + distanceTo(p) { + const x = this.x; + const y = this.y; + const z = this.z; + const px = p.x; + const py = p.y; + const pz = p.z; + return Math.sqrt( + (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z) + ); + } + /** + * Get squared distance from this point to another point + */ + + distanceSquared(p) { + const x = this.x; + const y = this.y; + const z = this.z; + const px = p.x; + const py = p.y; + const pz = p.z; + return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z); + } + /** + * Multiply all the components of the vector with a scalar. + * @param target The vector to save the result in. + */ + + scale(scalar, target) { + if (target === void 0) { + target = new Vec3(); + } + + const x = this.x; + const y = this.y; + const z = this.z; + target.x = scalar * x; + target.y = scalar * y; + target.z = scalar * z; + return target; + } + /** + * Multiply the vector with an other vector, component-wise. + * @param target The vector to save the result in. + */ + + vmul(vector, target) { + if (target === void 0) { + target = new Vec3(); + } + + target.x = vector.x * this.x; + target.y = vector.y * this.y; + target.z = vector.z * this.z; + return target; + } + /** + * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar) + * @param target The vector to save the result in. + */ + + addScaledVector(scalar, vector, target) { + if (target === void 0) { + target = new Vec3(); + } + + target.x = this.x + scalar * vector.x; + target.y = this.y + scalar * vector.y; + target.z = this.z + scalar * vector.z; + return target; + } + /** + * Calculate dot product + * @param vector + */ + + dot(vector) { + return this.x * vector.x + this.y * vector.y + this.z * vector.z; + } + + isZero() { + return this.x === 0 && this.y === 0 && this.z === 0; + } + /** + * Make the vector point in the opposite direction. + * @param target Optional target to save in + */ + + negate(target) { + if (target === void 0) { + target = new Vec3(); + } + + target.x = -this.x; + target.y = -this.y; + target.z = -this.z; + return target; + } + /** + * Compute two artificial tangents to the vector + * @param t1 Vector object to save the first tangent in + * @param t2 Vector object to save the second tangent in + */ + + tangents(t1, t2) { + const norm = this.length(); + + if (norm > 0.0) { + const n = Vec3_tangents_n; + const inorm = 1 / norm; + n.set(this.x * inorm, this.y * inorm, this.z * inorm); + const randVec = Vec3_tangents_randVec; + + if (Math.abs(n.x) < 0.9) { + randVec.set(1, 0, 0); + n.cross(randVec, t1); + } else { + randVec.set(0, 1, 0); + n.cross(randVec, t1); + } + + n.cross(t1, t2); + } else { + // The normal length is zero, make something up + t1.set(1, 0, 0); + t2.set(0, 1, 0); + } + } + /** + * Converts to a more readable format + */ + + toString() { + return `${this.x},${this.y},${this.z}`; + } + /** + * Converts to an array + */ + + toArray() { + return [this.x, this.y, this.z]; + } + /** + * Copies value of source to this vector. + */ + + copy(vector) { + this.x = vector.x; + this.y = vector.y; + this.z = vector.z; + return this; + } + /** + * Do a linear interpolation between two vectors + * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them. + */ + + lerp(vector, t, target) { + const x = this.x; + const y = this.y; + const z = this.z; + target.x = x + (vector.x - x) * t; + target.y = y + (vector.y - y) * t; + target.z = z + (vector.z - z) * t; + } + /** + * Check if a vector equals is almost equal to another one. + */ + + almostEquals(vector, precision) { + if (precision === void 0) { + precision = 1e-6; + } + + if ( + Math.abs(this.x - vector.x) > precision || + Math.abs(this.y - vector.y) > precision || + Math.abs(this.z - vector.z) > precision + ) { + return false; + } + + return true; + } + /** + * Check if a vector is almost zero + */ + + almostZero(precision) { + if (precision === void 0) { + precision = 1e-6; + } + + if ( + Math.abs(this.x) > precision || + Math.abs(this.y) > precision || + Math.abs(this.z) > precision + ) { + return false; + } + + return true; + } + /** + * Check if the vector is anti-parallel to another vector. + * @param precision Set to zero for exact comparisons + */ + + isAntiparallelTo(vector, precision) { + this.negate(antip_neg); + return antip_neg.almostEquals(vector, precision); + } + /** + * Clone the vector + */ + + clone() { + return new Vec3(this.x, this.y, this.z); + } + } + Vec3.ZERO = new Vec3(0, 0, 0); + Vec3.UNIT_X = new Vec3(1, 0, 0); + Vec3.UNIT_Y = new Vec3(0, 1, 0); + Vec3.UNIT_Z = new Vec3(0, 0, 1); + const Vec3_tangents_n = new Vec3(); + const Vec3_tangents_randVec = new Vec3(); + const antip_neg = new Vec3(); + + /** + * Axis aligned bounding box class. + */ + class AABB { + /** + * The lower bound of the bounding box + */ + + /** + * The upper bound of the bounding box + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + this.lowerBound = new Vec3(); + this.upperBound = new Vec3(); + + if (options.lowerBound) { + this.lowerBound.copy(options.lowerBound); + } + + if (options.upperBound) { + this.upperBound.copy(options.upperBound); + } + } + /** + * Set the AABB bounds from a set of points. + * @param points An array of Vec3's. + * @return The self object + */ + + setFromPoints(points, position, quaternion, skinSize) { + const l = this.lowerBound; + const u = this.upperBound; + const q = quaternion; // Set to the first point + + l.copy(points[0]); + + if (q) { + q.vmult(l, l); + } + + u.copy(l); + + for (let i = 1; i < points.length; i++) { + let p = points[i]; + + if (q) { + q.vmult(p, tmp$1); + p = tmp$1; + } + + if (p.x > u.x) { + u.x = p.x; + } + + if (p.x < l.x) { + l.x = p.x; + } + + if (p.y > u.y) { + u.y = p.y; + } + + if (p.y < l.y) { + l.y = p.y; + } + + if (p.z > u.z) { + u.z = p.z; + } + + if (p.z < l.z) { + l.z = p.z; + } + } // Add offset + + if (position) { + position.vadd(l, l); + position.vadd(u, u); + } + + if (skinSize) { + l.x -= skinSize; + l.y -= skinSize; + l.z -= skinSize; + u.x += skinSize; + u.y += skinSize; + u.z += skinSize; + } + + return this; + } + /** + * Copy bounds from an AABB to this AABB + * @param aabb Source to copy from + * @return The this object, for chainability + */ + + copy(aabb) { + this.lowerBound.copy(aabb.lowerBound); + this.upperBound.copy(aabb.upperBound); + return this; + } + /** + * Clone an AABB + */ + + clone() { + return new AABB().copy(this); + } + /** + * Extend this AABB so that it covers the given AABB too. + */ + + extend(aabb) { + this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x); + this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x); + this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y); + this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y); + this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z); + this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z); + } + /** + * Returns true if the given AABB overlaps this AABB. + */ + + overlaps(aabb) { + const l1 = this.lowerBound; + const u1 = this.upperBound; + const l2 = aabb.lowerBound; + const u2 = aabb.upperBound; // l2 u2 + // |---------| + // |--------| + // l1 u1 + + const overlapsX = + (l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x); + const overlapsY = + (l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y); + const overlapsZ = + (l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z); + return overlapsX && overlapsY && overlapsZ; + } // Mostly for debugging + + volume() { + const l = this.lowerBound; + const u = this.upperBound; + return (u.x - l.x) * (u.y - l.y) * (u.z - l.z); + } + /** + * Returns true if the given AABB is fully contained in this AABB. + */ + + contains(aabb) { + const l1 = this.lowerBound; + const u1 = this.upperBound; + const l2 = aabb.lowerBound; + const u2 = aabb.upperBound; // l2 u2 + // |---------| + // |---------------| + // l1 u1 + + return ( + l1.x <= l2.x && + u1.x >= u2.x && + l1.y <= l2.y && + u1.y >= u2.y && + l1.z <= l2.z && + u1.z >= u2.z + ); + } + + getCorners(a, b, c, d, e, f, g, h) { + const l = this.lowerBound; + const u = this.upperBound; + a.copy(l); + b.set(u.x, l.y, l.z); + c.set(u.x, u.y, l.z); + d.set(l.x, u.y, u.z); + e.set(u.x, l.y, u.z); + f.set(l.x, u.y, l.z); + g.set(l.x, l.y, u.z); + h.copy(u); + } + /** + * Get the representation of an AABB in another frame. + * @return The "target" AABB object. + */ + + toLocalFrame(frame, target) { + const corners = transformIntoFrame_corners; + const a = corners[0]; + const b = corners[1]; + const c = corners[2]; + const d = corners[3]; + const e = corners[4]; + const f = corners[5]; + const g = corners[6]; + const h = corners[7]; // Get corners in current frame + + this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame + + for (let i = 0; i !== 8; i++) { + const corner = corners[i]; + frame.pointToLocal(corner, corner); + } + + return target.setFromPoints(corners); + } + /** + * Get the representation of an AABB in the global frame. + * @return The "target" AABB object. + */ + + toWorldFrame(frame, target) { + const corners = transformIntoFrame_corners; + const a = corners[0]; + const b = corners[1]; + const c = corners[2]; + const d = corners[3]; + const e = corners[4]; + const f = corners[5]; + const g = corners[6]; + const h = corners[7]; // Get corners in current frame + + this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame + + for (let i = 0; i !== 8; i++) { + const corner = corners[i]; + frame.pointToWorld(corner, corner); + } + + return target.setFromPoints(corners); + } + /** + * Check if the AABB is hit by a ray. + */ + + overlapsRay(ray) { + const { direction, from } = ray; // const t = 0 + // ray.direction is unit direction vector of ray + + const dirFracX = 1 / direction.x; + const dirFracY = 1 / direction.y; + const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner + + const t1 = (this.lowerBound.x - from.x) * dirFracX; + const t2 = (this.upperBound.x - from.x) * dirFracX; + const t3 = (this.lowerBound.y - from.y) * dirFracY; + const t4 = (this.upperBound.y - from.y) * dirFracY; + const t5 = (this.lowerBound.z - from.z) * dirFracZ; + const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4))); + // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4))); + + const tmin = Math.max( + Math.max(Math.min(t1, t2), Math.min(t3, t4)), + Math.min(t5, t6) + ); + const tmax = Math.min( + Math.min(Math.max(t1, t2), Math.max(t3, t4)), + Math.max(t5, t6) + ); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us + + if (tmax < 0) { + //t = tmax; + return false; + } // if tmin > tmax, ray doesn't intersect AABB + + if (tmin > tmax) { + //t = tmax; + return false; + } + + return true; + } + } + const tmp$1 = new Vec3(); + const transformIntoFrame_corners = [ + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + ]; + + /** + * Collision "matrix". + * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step + */ + class ArrayCollisionMatrix { + /** + * The matrix storage. + */ + constructor() { + this.matrix = []; + } + /** + * Get an element + */ + + get(bi, bj) { + let { index: i } = bi; + let { index: j } = bj; + + if (j > i) { + const temp = j; + j = i; + i = temp; + } + + return this.matrix[((i * (i + 1)) >> 1) + j - 1]; + } + /** + * Set an element + */ + + set(bi, bj, value) { + let { index: i } = bi; + let { index: j } = bj; + + if (j > i) { + const temp = j; + j = i; + i = temp; + } + + this.matrix[((i * (i + 1)) >> 1) + j - 1] = value ? 1 : 0; + } + /** + * Sets all elements to zero + */ + + reset() { + for (let i = 0, l = this.matrix.length; i !== l; i++) { + this.matrix[i] = 0; + } + } + /** + * Sets the max number of objects + */ + + setNumObjects(n) { + this.matrix.length = (n * (n - 1)) >> 1; + } + } + + /** + * Base class for objects that dispatches events. + */ + class EventTarget { + /** + * Add an event listener + * @return The self object, for chainability. + */ + addEventListener(type, listener) { + if (this._listeners === undefined) { + this._listeners = {}; + } + + const listeners = this._listeners; + + if (listeners[type] === undefined) { + listeners[type] = []; + } + + if (!listeners[type].includes(listener)) { + listeners[type].push(listener); + } + + return this; + } + /** + * Check if an event listener is added + */ + + hasEventListener(type, listener) { + if (this._listeners === undefined) { + return false; + } + + const listeners = this._listeners; + + if (listeners[type] !== undefined && listeners[type].includes(listener)) { + return true; + } + + return false; + } + /** + * Check if any event listener of the given type is added + */ + + hasAnyEventListener(type) { + if (this._listeners === undefined) { + return false; + } + + const listeners = this._listeners; + return listeners[type] !== undefined; + } + /** + * Remove an event listener + * @return The self object, for chainability. + */ + + removeEventListener(type, listener) { + if (this._listeners === undefined) { + return this; + } + + const listeners = this._listeners; + + if (listeners[type] === undefined) { + return this; + } + + const index = listeners[type].indexOf(listener); + + if (index !== -1) { + listeners[type].splice(index, 1); + } + + return this; + } + /** + * Emit an event. + * @return The self object, for chainability. + */ + + dispatchEvent(event) { + if (this._listeners === undefined) { + return this; + } + + const listeners = this._listeners; + const listenerArray = listeners[event.type]; + + if (listenerArray !== undefined) { + event.target = this; + + for (let i = 0, l = listenerArray.length; i < l; i++) { + listenerArray[i].call(this, event); + } + } + + return this; + } + } + + /** + * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation. + * @param x Multiplier of the imaginary basis vector i. + * @param y Multiplier of the imaginary basis vector j. + * @param z Multiplier of the imaginary basis vector k. + * @param w Multiplier of the real part. + * @see http://en.wikipedia.org/wiki/Quaternion + */ + + class Quaternion { + constructor(x, y, z, w) { + if (x === void 0) { + x = 0; + } + + if (y === void 0) { + y = 0; + } + + if (z === void 0) { + z = 0; + } + + if (w === void 0) { + w = 1; + } + + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + /** + * Set the value of the quaternion. + */ + + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + /** + * Convert to a readable format + * @return "x,y,z,w" + */ + + toString() { + return `${this.x},${this.y},${this.z},${this.w}`; + } + /** + * Convert to an Array + * @return [x, y, z, w] + */ + + toArray() { + return [this.x, this.y, this.z, this.w]; + } + /** + * Set the quaternion components given an axis and an angle in radians. + */ + + setFromAxisAngle(vector, angle) { + const s = Math.sin(angle * 0.5); + this.x = vector.x * s; + this.y = vector.y * s; + this.z = vector.z * s; + this.w = Math.cos(angle * 0.5); + return this; + } + /** + * Converts the quaternion to [ axis, angle ] representation. + * @param targetAxis A vector object to reuse for storing the axis. + * @return An array, first element is the axis and the second is the angle in radians. + */ + + toAxisAngle(targetAxis) { + if (targetAxis === void 0) { + targetAxis = new Vec3(); + } + + this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised + + const angle = 2 * Math.acos(this.w); + const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive. + + if (s < 0.001) { + // test to avoid divide by zero, s is always positive due to sqrt + // if s close to zero then direction of axis not important + targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0; + + targetAxis.y = this.y; + targetAxis.z = this.z; + } else { + targetAxis.x = this.x / s; // normalise axis + + targetAxis.y = this.y / s; + targetAxis.z = this.z / s; + } + + return [targetAxis, angle]; + } + /** + * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v. + */ + + setFromVectors(u, v) { + if (u.isAntiparallelTo(v)) { + const t1 = sfv_t1; + const t2 = sfv_t2; + u.tangents(t1, t2); + this.setFromAxisAngle(t1, Math.PI); + } else { + const a = u.cross(v); + this.x = a.x; + this.y = a.y; + this.z = a.z; + this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v); + this.normalize(); + } + + return this; + } + /** + * Multiply the quaternion with an other quaternion. + */ + + mult(quat, target) { + if (target === void 0) { + target = new Quaternion(); + } + + const ax = this.x; + const ay = this.y; + const az = this.z; + const aw = this.w; + const bx = quat.x; + const by = quat.y; + const bz = quat.z; + const bw = quat.w; + target.x = ax * bw + aw * bx + ay * bz - az * by; + target.y = ay * bw + aw * by + az * bx - ax * bz; + target.z = az * bw + aw * bz + ax * by - ay * bx; + target.w = aw * bw - ax * bx - ay * by - az * bz; + return target; + } + /** + * Get the inverse quaternion rotation. + */ + + inverse(target) { + if (target === void 0) { + target = new Quaternion(); + } + + const x = this.x; + const y = this.y; + const z = this.z; + const w = this.w; + this.conjugate(target); + const inorm2 = 1 / (x * x + y * y + z * z + w * w); + target.x *= inorm2; + target.y *= inorm2; + target.z *= inorm2; + target.w *= inorm2; + return target; + } + /** + * Get the quaternion conjugate + */ + + conjugate(target) { + if (target === void 0) { + target = new Quaternion(); + } + + target.x = -this.x; + target.y = -this.y; + target.z = -this.z; + target.w = this.w; + return target; + } + /** + * Normalize the quaternion. Note that this changes the values of the quaternion. + */ + + normalize() { + let l = Math.sqrt( + this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w + ); + + if (l === 0) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + } else { + l = 1 / l; + this.x *= l; + this.y *= l; + this.z *= l; + this.w *= l; + } + + return this; + } + /** + * Approximation of quaternion normalization. Works best when quat is already almost-normalized. + * @author unphased, https://github.com/unphased + */ + + normalizeFast() { + const f = + (3.0 - + (this.x * this.x + + this.y * this.y + + this.z * this.z + + this.w * this.w)) / + 2.0; + + if (f === 0) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + } else { + this.x *= f; + this.y *= f; + this.z *= f; + this.w *= f; + } + + return this; + } + /** + * Multiply the quaternion by a vector + */ + + vmult(v, target) { + if (target === void 0) { + target = new Vec3(); + } + + const x = v.x; + const y = v.y; + const z = v.z; + const qx = this.x; + const qy = this.y; + const qz = this.z; + const qw = this.w; // q*v + + const ix = qw * x + qy * z - qz * y; + const iy = qw * y + qz * x - qx * z; + const iz = qw * z + qx * y - qy * x; + const iw = -qx * x - qy * y - qz * z; + target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return target; + } + /** + * Copies value of source to this quaternion. + * @return this + */ + + copy(quat) { + this.x = quat.x; + this.y = quat.y; + this.z = quat.z; + this.w = quat.w; + return this; + } + /** + * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm + * @param order Three-character string, defaults to "YZX" + */ + + toEuler(target, order) { + if (order === void 0) { + order = "YZX"; + } + + let heading; + let attitude; + let bank; + const x = this.x; + const y = this.y; + const z = this.z; + const w = this.w; + + switch (order) { + case "YZX": + const test = x * y + z * w; + + if (test > 0.499) { + // singularity at north pole + heading = 2 * Math.atan2(x, w); + attitude = Math.PI / 2; + bank = 0; + } + + if (test < -0.499) { + // singularity at south pole + heading = -2 * Math.atan2(x, w); + attitude = -Math.PI / 2; + bank = 0; + } + + if (heading === undefined) { + const sqx = x * x; + const sqy = y * y; + const sqz = z * z; + heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading + + attitude = Math.asin(2 * test); // attitude + + bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank + } + + break; + + default: + throw new Error(`Euler order ${order} not supported yet.`); + } + + target.y = heading; + target.z = attitude; + target.x = bank; + } + /** + * Set the quaternion components given Euler angle representation. + * + * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination. + * + * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference + */ + + setFromEuler(x, y, z, order) { + if (order === void 0) { + order = "XYZ"; + } + + const c1 = Math.cos(x / 2); + const c2 = Math.cos(y / 2); + const c3 = Math.cos(z / 2); + const s1 = Math.sin(x / 2); + const s2 = Math.sin(y / 2); + const s3 = Math.sin(z / 2); + + if (order === "XYZ") { + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + } else if (order === "YXZ") { + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + } else if (order === "ZXY") { + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + } else if (order === "ZYX") { + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + } else if (order === "YZX") { + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + } else if (order === "XZY") { + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + } + + return this; + } + + clone() { + return new Quaternion(this.x, this.y, this.z, this.w); + } + /** + * Performs a spherical linear interpolation between two quat + * + * @param toQuat second operand + * @param t interpolation amount between the self quaternion and toQuat + * @param target A quaternion to store the result in. If not provided, a new one will be created. + * @returns {Quaternion} The "target" object + */ + + slerp(toQuat, t, target) { + if (target === void 0) { + target = new Quaternion(); + } + + const ax = this.x; + const ay = this.y; + const az = this.z; + const aw = this.w; + let bx = toQuat.x; + let by = toQuat.y; + let bz = toQuat.z; + let bw = toQuat.w; + let omega; + let cosom; + let sinom; + let scale0; + let scale1; // calc cosine + + cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary) + + if (cosom < 0.0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } // calculate coefficients + + if (1.0 - cosom > 0.000001) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } // calculate final values + + target.x = scale0 * ax + scale1 * bx; + target.y = scale0 * ay + scale1 * by; + target.z = scale0 * az + scale1 * bz; + target.w = scale0 * aw + scale1 * bw; + return target; + } + /** + * Rotate an absolute orientation quaternion given an angular velocity and a time step. + */ + + integrate(angularVelocity, dt, angularFactor, target) { + if (target === void 0) { + target = new Quaternion(); + } + + const ax = angularVelocity.x * angularFactor.x, + ay = angularVelocity.y * angularFactor.y, + az = angularVelocity.z * angularFactor.z, + bx = this.x, + by = this.y, + bz = this.z, + bw = this.w; + const half_dt = dt * 0.5; + target.x += half_dt * (ax * bw + ay * bz - az * by); + target.y += half_dt * (ay * bw + az * bx - ax * bz); + target.z += half_dt * (az * bw + ax * by - ay * bx); + target.w += half_dt * (-ax * bx - ay * by - az * bz); + return target; + } + } + const sfv_t1 = new Vec3(); + const sfv_t2 = new Vec3(); + + /** + * The available shape types. + */ + const SHAPE_TYPES = { + /** SPHERE */ + SPHERE: 1, + + /** PLANE */ + PLANE: 2, + + /** BOX */ + BOX: 4, + + /** COMPOUND */ + COMPOUND: 8, + + /** CONVEXPOLYHEDRON */ + CONVEXPOLYHEDRON: 16, + + /** HEIGHTFIELD */ + HEIGHTFIELD: 32, + + /** PARTICLE */ + PARTICLE: 64, + + /** CYLINDER */ + CYLINDER: 128, + + /** TRIMESH */ + TRIMESH: 256, + }; + /** + * ShapeType + */ + + /** + * Base class for shapes + */ + class Shape { + /** + * Identifier of the Shape. + */ + + /** + * The type of this shape. Must be set to an int > 0 by subclasses. + */ + + /** + * The local bounding sphere radius of this shape. + */ + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. + * @default true + */ + + /** + * @default 1 + */ + + /** + * @default -1 + */ + + /** + * Optional material of the shape that regulates contact properties. + */ + + /** + * The body to which the shape is added to. + */ + + /** + * All the Shape types. + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + this.id = Shape.idCounter++; + this.type = options.type || 0; + this.boundingSphereRadius = 0; + this.collisionResponse = options.collisionResponse + ? options.collisionResponse + : true; + this.collisionFilterGroup = + options.collisionFilterGroup !== undefined + ? options.collisionFilterGroup + : 1; + this.collisionFilterMask = + options.collisionFilterMask !== undefined + ? options.collisionFilterMask + : -1; + this.material = options.material ? options.material : null; + this.body = null; + } + /** + * Computes the bounding sphere radius. + * The result is stored in the property `.boundingSphereRadius` + */ + + updateBoundingSphereRadius() { + throw `computeBoundingSphereRadius() not implemented for shape type ${this.type}`; + } + /** + * Get the volume of this shape + */ + + volume() { + throw `volume() not implemented for shape type ${this.type}`; + } + /** + * Calculates the inertia in the local frame for this shape. + * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia + */ + + calculateLocalInertia(mass, target) { + throw `calculateLocalInertia() not implemented for shape type ${this.type}`; + } + /** + * @todo use abstract for these kind of methods + */ + + calculateWorldAABB(pos, quat, min, max) { + throw `calculateWorldAABB() not implemented for shape type ${this.type}`; + } + } + Shape.idCounter = 0; + Shape.types = SHAPE_TYPES; + + /** + * Transformation utilities. + */ + class Transform { + /** + * position + */ + + /** + * quaternion + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + this.position = new Vec3(); + this.quaternion = new Quaternion(); + + if (options.position) { + this.position.copy(options.position); + } + + if (options.quaternion) { + this.quaternion.copy(options.quaternion); + } + } + /** + * Get a global point in local transform coordinates. + */ + + pointToLocal(worldPoint, result) { + return Transform.pointToLocalFrame( + this.position, + this.quaternion, + worldPoint, + result + ); + } + /** + * Get a local point in global transform coordinates. + */ + + pointToWorld(localPoint, result) { + return Transform.pointToWorldFrame( + this.position, + this.quaternion, + localPoint, + result + ); + } + /** + * vectorToWorldFrame + */ + + vectorToWorldFrame(localVector, result) { + if (result === void 0) { + result = new Vec3(); + } + + this.quaternion.vmult(localVector, result); + return result; + } + /** + * pointToLocalFrame + */ + + static pointToLocalFrame(position, quaternion, worldPoint, result) { + if (result === void 0) { + result = new Vec3(); + } + + worldPoint.vsub(position, result); + quaternion.conjugate(tmpQuat$1); + tmpQuat$1.vmult(result, result); + return result; + } + /** + * pointToWorldFrame + */ + + static pointToWorldFrame(position, quaternion, localPoint, result) { + if (result === void 0) { + result = new Vec3(); + } + + quaternion.vmult(localPoint, result); + result.vadd(position, result); + return result; + } + /** + * vectorToWorldFrame + */ + + static vectorToWorldFrame(quaternion, localVector, result) { + if (result === void 0) { + result = new Vec3(); + } + + quaternion.vmult(localVector, result); + return result; + } + /** + * vectorToLocalFrame + */ + + static vectorToLocalFrame(position, quaternion, worldVector, result) { + if (result === void 0) { + result = new Vec3(); + } + + quaternion.w *= -1; + quaternion.vmult(worldVector, result); + quaternion.w *= -1; + return result; + } + } + const tmpQuat$1 = new Quaternion(); + + /** + * A set of polygons describing a convex shape. + * + * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained + * in the same 3D plane), instead these should be merged into one polygon. + * + * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f) + * @author schteppe / https://github.com/schteppe + * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/ + * + * @todo Move the clipping functions to ContactGenerator? + * @todo Automatically merge coplanar polygons in constructor. + * @example + * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces }) + * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape }) + * world.addBody(convexBody) + */ + class ConvexPolyhedron extends Shape { + /** vertices */ + + /** + * Array of integer arrays, indicating which vertices each face consists of + */ + + /** faceNormals */ + + /** worldVertices */ + + /** worldVerticesNeedsUpdate */ + + /** worldFaceNormals */ + + /** worldFaceNormalsNeedsUpdate */ + + /** + * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check. + */ + + /** uniqueEdges */ + + /** + * @param vertices An array of Vec3's + * @param faces Array of integer arrays, describing which vertices that is included in each face. + */ + constructor(props) { + if (props === void 0) { + props = {}; + } + + const { + vertices = [], + faces = [], + normals = [], + axes, + boundingSphereRadius, + } = props; + super({ + type: Shape.types.CONVEXPOLYHEDRON, + }); + this.vertices = vertices; + this.faces = faces; + this.faceNormals = normals; + + if (this.faceNormals.length === 0) { + this.computeNormals(); + } + + if (!boundingSphereRadius) { + this.updateBoundingSphereRadius(); + } else { + this.boundingSphereRadius = boundingSphereRadius; + } + + this.worldVertices = []; // World transformed version of .vertices + + this.worldVerticesNeedsUpdate = true; + this.worldFaceNormals = []; // World transformed version of .faceNormals + + this.worldFaceNormalsNeedsUpdate = true; + this.uniqueAxes = axes ? axes.slice() : null; + this.uniqueEdges = []; + this.computeEdges(); + } + /** + * Computes uniqueEdges + */ + + computeEdges() { + const faces = this.faces; + const vertices = this.vertices; + const edges = this.uniqueEdges; + edges.length = 0; + const edge = new Vec3(); + + for (let i = 0; i !== faces.length; i++) { + const face = faces[i]; + const numVertices = face.length; + + for (let j = 0; j !== numVertices; j++) { + const k = (j + 1) % numVertices; + vertices[face[j]].vsub(vertices[face[k]], edge); + edge.normalize(); + let found = false; + + for (let p = 0; p !== edges.length; p++) { + if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) { + found = true; + break; + } + } + + if (!found) { + edges.push(edge.clone()); + } + } + } + } + /** + * Compute the normals of the faces. + * Will reuse existing Vec3 objects in the `faceNormals` array if they exist. + */ + + computeNormals() { + this.faceNormals.length = this.faces.length; // Generate normals + + for (let i = 0; i < this.faces.length; i++) { + // Check so all vertices exists for this face + for (let j = 0; j < this.faces[i].length; j++) { + if (!this.vertices[this.faces[i][j]]) { + throw new Error(`Vertex ${this.faces[i][j]} not found!`); + } + } + + const n = this.faceNormals[i] || new Vec3(); + this.getFaceNormal(i, n); + n.negate(n); + this.faceNormals[i] = n; + const vertex = this.vertices[this.faces[i][0]]; + + if (n.dot(vertex) < 0) { + console.error( + `.faceNormals[${i}] = Vec3(${n.toString()}) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.` + ); + + for (let j = 0; j < this.faces[i].length; j++) { + console.warn( + `.vertices[${this.faces[i][j]}] = Vec3(${this.vertices[ + this.faces[i][j] + ].toString()})` + ); + } + } + } + } + /** + * Compute the normal of a face from its vertices + */ + + getFaceNormal(i, target) { + const f = this.faces[i]; + const va = this.vertices[f[0]]; + const vb = this.vertices[f[1]]; + const vc = this.vertices[f[2]]; + ConvexPolyhedron.computeNormal(va, vb, vc, target); + } + /** + * Get face normal given 3 vertices + */ + + static computeNormal(va, vb, vc, target) { + const cb = new Vec3(); + const ab = new Vec3(); + vb.vsub(va, ab); + vc.vsub(vb, cb); + cb.cross(ab, target); + + if (!target.isZero()) { + target.normalize(); + } + } + /** + * @param minDist Clamp distance + * @param result The an array of contact point objects, see clipFaceAgainstHull + */ + + clipAgainstHull( + posA, + quatA, + hullB, + posB, + quatB, + separatingNormal, + minDist, + maxDist, + result + ) { + const WorldNormal = new Vec3(); + let closestFaceB = -1; + let dmax = -Number.MAX_VALUE; + + for (let face = 0; face < hullB.faces.length; face++) { + WorldNormal.copy(hullB.faceNormals[face]); + quatB.vmult(WorldNormal, WorldNormal); + const d = WorldNormal.dot(separatingNormal); + + if (d > dmax) { + dmax = d; + closestFaceB = face; + } + } + + const worldVertsB1 = []; + + for (let i = 0; i < hullB.faces[closestFaceB].length; i++) { + const b = hullB.vertices[hullB.faces[closestFaceB][i]]; + const worldb = new Vec3(); + worldb.copy(b); + quatB.vmult(worldb, worldb); + posB.vadd(worldb, worldb); + worldVertsB1.push(worldb); + } + + if (closestFaceB >= 0) { + this.clipFaceAgainstHull( + separatingNormal, + posA, + quatA, + worldVertsB1, + minDist, + maxDist, + result + ); + } + } + /** + * Find the separating axis between this hull and another + * @param target The target vector to save the axis in + * @return Returns false if a separation is found, else true + */ + + findSeparatingAxis( + hullB, + posA, + quatA, + posB, + quatB, + target, + faceListA, + faceListB + ) { + const faceANormalWS3 = new Vec3(); + const Worldnormal1 = new Vec3(); + const deltaC = new Vec3(); + const worldEdge0 = new Vec3(); + const worldEdge1 = new Vec3(); + const Cross = new Vec3(); + let dmin = Number.MAX_VALUE; + const hullA = this; + + if (!hullA.uniqueAxes) { + const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA + + for (let i = 0; i < numFacesA; i++) { + const fi = faceListA ? faceListA[i] : i; // Get world face normal + + faceANormalWS3.copy(hullA.faceNormals[fi]); + quatA.vmult(faceANormalWS3, faceANormalWS3); + const d = hullA.testSepAxis( + faceANormalWS3, + hullB, + posA, + quatA, + posB, + quatB + ); + + if (d === false) { + return false; + } + + if (d < dmin) { + dmin = d; + target.copy(faceANormalWS3); + } + } + } else { + // Test unique axes + for (let i = 0; i !== hullA.uniqueAxes.length; i++) { + // Get world axis + quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3); + const d = hullA.testSepAxis( + faceANormalWS3, + hullB, + posA, + quatA, + posB, + quatB + ); + + if (d === false) { + return false; + } + + if (d < dmin) { + dmin = d; + target.copy(faceANormalWS3); + } + } + } + + if (!hullB.uniqueAxes) { + // Test face normals from hullB + const numFacesB = faceListB ? faceListB.length : hullB.faces.length; + + for (let i = 0; i < numFacesB; i++) { + const fi = faceListB ? faceListB[i] : i; + Worldnormal1.copy(hullB.faceNormals[fi]); + quatB.vmult(Worldnormal1, Worldnormal1); + const d = hullA.testSepAxis( + Worldnormal1, + hullB, + posA, + quatA, + posB, + quatB + ); + + if (d === false) { + return false; + } + + if (d < dmin) { + dmin = d; + target.copy(Worldnormal1); + } + } + } else { + // Test unique axes in B + for (let i = 0; i !== hullB.uniqueAxes.length; i++) { + quatB.vmult(hullB.uniqueAxes[i], Worldnormal1); + const d = hullA.testSepAxis( + Worldnormal1, + hullB, + posA, + quatA, + posB, + quatB + ); + + if (d === false) { + return false; + } + + if (d < dmin) { + dmin = d; + target.copy(Worldnormal1); + } + } + } // Test edges + + for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) { + // Get world edge + quatA.vmult(hullA.uniqueEdges[e0], worldEdge0); + + for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) { + // Get world edge 2 + quatB.vmult(hullB.uniqueEdges[e1], worldEdge1); + worldEdge0.cross(worldEdge1, Cross); + + if (!Cross.almostZero()) { + Cross.normalize(); + const dist = hullA.testSepAxis( + Cross, + hullB, + posA, + quatA, + posB, + quatB + ); + + if (dist === false) { + return false; + } + + if (dist < dmin) { + dmin = dist; + target.copy(Cross); + } + } + } + } + + posB.vsub(posA, deltaC); + + if (deltaC.dot(target) > 0.0) { + target.negate(target); + } + + return true; + } + /** + * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one. + * @return The overlap depth, or FALSE if no penetration. + */ + + testSepAxis(axis, hullB, posA, quatA, posB, quatB) { + const hullA = this; + ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA); + ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB); + const maxA = maxminA[0]; + const minA = maxminA[1]; + const maxB = maxminB[0]; + const minB = maxminB[1]; + + if (maxA < minB || maxB < minA) { + return false; // Separated + } + + const d0 = maxA - minB; + const d1 = maxB - minA; + const depth = d0 < d1 ? d0 : d1; + return depth; + } + /** + * calculateLocalInertia + */ + + calculateLocalInertia(mass, target) { + // Approximate with box inertia + // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it + const aabbmax = new Vec3(); + const aabbmin = new Vec3(); + this.computeLocalAABB(aabbmin, aabbmax); + const x = aabbmax.x - aabbmin.x; + const y = aabbmax.y - aabbmin.y; + const z = aabbmax.z - aabbmin.z; + target.x = (1.0 / 12.0) * mass * (2 * y * 2 * y + 2 * z * 2 * z); + target.y = (1.0 / 12.0) * mass * (2 * x * 2 * x + 2 * z * 2 * z); + target.z = (1.0 / 12.0) * mass * (2 * y * 2 * y + 2 * x * 2 * x); + } + /** + * @param face_i Index of the face + */ + + getPlaneConstantOfFace(face_i) { + const f = this.faces[face_i]; + const n = this.faceNormals[face_i]; + const v = this.vertices[f[0]]; + const c = -n.dot(v); + return c; + } + /** + * Clip a face against a hull. + * @param worldVertsB1 An array of Vec3 with vertices in the world frame. + * @param minDist Distance clamping + * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates. + */ + + clipFaceAgainstHull( + separatingNormal, + posA, + quatA, + worldVertsB1, + minDist, + maxDist, + result + ) { + const faceANormalWS = new Vec3(); + const edge0 = new Vec3(); + const WorldEdge0 = new Vec3(); + const worldPlaneAnormal1 = new Vec3(); + const planeNormalWS1 = new Vec3(); + const worldA1 = new Vec3(); + const localPlaneNormal = new Vec3(); + const planeNormalWS = new Vec3(); + const hullA = this; + const worldVertsB2 = []; + const pVtxIn = worldVertsB1; + const pVtxOut = worldVertsB2; + let closestFaceA = -1; + let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis + + for (let face = 0; face < hullA.faces.length; face++) { + faceANormalWS.copy(hullA.faceNormals[face]); + quatA.vmult(faceANormalWS, faceANormalWS); + const d = faceANormalWS.dot(separatingNormal); + + if (d < dmin) { + dmin = d; + closestFaceA = face; + } + } + + if (closestFaceA < 0) { + return; + } // Get the face and construct connected faces + + const polyA = hullA.faces[closestFaceA]; + polyA.connectedFaces = []; + + for (let i = 0; i < hullA.faces.length; i++) { + for (let j = 0; j < hullA.faces[i].length; j++) { + if ( + /* Sharing a vertex*/ + polyA.indexOf(hullA.faces[i][j]) !== -1 && + /* Not the one we are looking for connections from */ + i !== closestFaceA && + /* Not already added */ + polyA.connectedFaces.indexOf(i) === -1 + ) { + polyA.connectedFaces.push(i); + } + } + } // Clip the polygon to the back of the planes of all faces of hull A, + // that are adjacent to the witness face + + const numVerticesA = polyA.length; + + for (let i = 0; i < numVerticesA; i++) { + const a = hullA.vertices[polyA[i]]; + const b = hullA.vertices[polyA[(i + 1) % numVerticesA]]; + a.vsub(b, edge0); + WorldEdge0.copy(edge0); + quatA.vmult(WorldEdge0, WorldEdge0); + posA.vadd(WorldEdge0, WorldEdge0); + worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]); + quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1); + posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1); + WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1); + planeNormalWS1.negate(planeNormalWS1); + worldA1.copy(a); + quatA.vmult(worldA1, worldA1); + posA.vadd(worldA1, worldA1); + const otherFace = polyA.connectedFaces[i]; + localPlaneNormal.copy(this.faceNormals[otherFace]); + const localPlaneEq = this.getPlaneConstantOfFace(otherFace); + planeNormalWS.copy(localPlaneNormal); + quatA.vmult(planeNormalWS, planeNormalWS); + const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane + + this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip + + while (pVtxIn.length) { + pVtxIn.shift(); + } + + while (pVtxOut.length) { + pVtxIn.push(pVtxOut.shift()); + } + } // only keep contact points that are behind the witness face + + localPlaneNormal.copy(this.faceNormals[closestFaceA]); + const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA); + planeNormalWS.copy(localPlaneNormal); + quatA.vmult(planeNormalWS, planeNormalWS); + const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); + + for (let i = 0; i < pVtxIn.length; i++) { + let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ??? + + if (depth <= minDist) { + console.log(`clamped: depth=${depth} to minDist=${minDist}`); + depth = minDist; + } + + if (depth <= maxDist) { + const point = pVtxIn[i]; + + if (depth <= 1e-6) { + const p = { + point, + normal: planeNormalWS, + depth, + }; + result.push(p); + } + } + } + } + /** + * Clip a face in a hull against the back of a plane. + * @param planeConstant The constant in the mathematical plane equation + */ + + clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) { + let n_dot_first; + let n_dot_last; + const numVerts = inVertices.length; + + if (numVerts < 2) { + return outVertices; + } + + let firstVertex = inVertices[inVertices.length - 1]; + let lastVertex = inVertices[0]; + n_dot_first = planeNormal.dot(firstVertex) + planeConstant; + + for (let vi = 0; vi < numVerts; vi++) { + lastVertex = inVertices[vi]; + n_dot_last = planeNormal.dot(lastVertex) + planeConstant; + + if (n_dot_first < 0) { + if (n_dot_last < 0) { + // Start < 0, end < 0, so output lastVertex + const newv = new Vec3(); + newv.copy(lastVertex); + outVertices.push(newv); + } else { + // Start < 0, end >= 0, so output intersection + const newv = new Vec3(); + firstVertex.lerp( + lastVertex, + n_dot_first / (n_dot_first - n_dot_last), + newv + ); + outVertices.push(newv); + } + } else { + if (n_dot_last < 0) { + // Start >= 0, end < 0 so output intersection and end + const newv = new Vec3(); + firstVertex.lerp( + lastVertex, + n_dot_first / (n_dot_first - n_dot_last), + newv + ); + outVertices.push(newv); + outVertices.push(lastVertex); + } + } + + firstVertex = lastVertex; + n_dot_first = n_dot_last; + } + + return outVertices; + } + /** + * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false. + */ + + computeWorldVertices(position, quat) { + while (this.worldVertices.length < this.vertices.length) { + this.worldVertices.push(new Vec3()); + } + + const verts = this.vertices; + const worldVerts = this.worldVertices; + + for (let i = 0; i !== this.vertices.length; i++) { + quat.vmult(verts[i], worldVerts[i]); + position.vadd(worldVerts[i], worldVerts[i]); + } + + this.worldVerticesNeedsUpdate = false; + } + + computeLocalAABB(aabbmin, aabbmax) { + const vertices = this.vertices; + aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + + for (let i = 0; i < this.vertices.length; i++) { + const v = vertices[i]; + + if (v.x < aabbmin.x) { + aabbmin.x = v.x; + } else if (v.x > aabbmax.x) { + aabbmax.x = v.x; + } + + if (v.y < aabbmin.y) { + aabbmin.y = v.y; + } else if (v.y > aabbmax.y) { + aabbmax.y = v.y; + } + + if (v.z < aabbmin.z) { + aabbmin.z = v.z; + } else if (v.z > aabbmax.z) { + aabbmax.z = v.z; + } + } + } + /** + * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false. + */ + + computeWorldFaceNormals(quat) { + const N = this.faceNormals.length; + + while (this.worldFaceNormals.length < N) { + this.worldFaceNormals.push(new Vec3()); + } + + const normals = this.faceNormals; + const worldNormals = this.worldFaceNormals; + + for (let i = 0; i !== N; i++) { + quat.vmult(normals[i], worldNormals[i]); + } + + this.worldFaceNormalsNeedsUpdate = false; + } + /** + * updateBoundingSphereRadius + */ + + updateBoundingSphereRadius() { + // Assume points are distributed with local (0,0,0) as center + let max2 = 0; + const verts = this.vertices; + + for (let i = 0; i !== verts.length; i++) { + const norm2 = verts[i].lengthSquared(); + + if (norm2 > max2) { + max2 = norm2; + } + } + + this.boundingSphereRadius = Math.sqrt(max2); + } + /** + * calculateWorldAABB + */ + + calculateWorldAABB(pos, quat, min, max) { + const verts = this.vertices; + let minx; + let miny; + let minz; + let maxx; + let maxy; + let maxz; + let tempWorldVertex = new Vec3(); + + for (let i = 0; i < verts.length; i++) { + tempWorldVertex.copy(verts[i]); + quat.vmult(tempWorldVertex, tempWorldVertex); + pos.vadd(tempWorldVertex, tempWorldVertex); + const v = tempWorldVertex; + + if (minx === undefined || v.x < minx) { + minx = v.x; + } + + if (maxx === undefined || v.x > maxx) { + maxx = v.x; + } + + if (miny === undefined || v.y < miny) { + miny = v.y; + } + + if (maxy === undefined || v.y > maxy) { + maxy = v.y; + } + + if (minz === undefined || v.z < minz) { + minz = v.z; + } + + if (maxz === undefined || v.z > maxz) { + maxz = v.z; + } + } + + min.set(minx, miny, minz); + max.set(maxx, maxy, maxz); + } + /** + * Get approximate convex volume + */ + + volume() { + return (4.0 * Math.PI * this.boundingSphereRadius) / 3.0; + } + /** + * Get an average of all the vertices positions + */ + + getAveragePointLocal(target) { + if (target === void 0) { + target = new Vec3(); + } + + const verts = this.vertices; + + for (let i = 0; i < verts.length; i++) { + target.vadd(verts[i], target); + } + + target.scale(1 / verts.length, target); + return target; + } + /** + * Transform all local points. Will change the .vertices + */ + + transformAllPoints(offset, quat) { + const n = this.vertices.length; + const verts = this.vertices; // Apply rotation + + if (quat) { + // Rotate vertices + for (let i = 0; i < n; i++) { + const v = verts[i]; + quat.vmult(v, v); + } // Rotate face normals + + for (let i = 0; i < this.faceNormals.length; i++) { + const v = this.faceNormals[i]; + quat.vmult(v, v); + } + /* + // Rotate edges + for(let i=0; i 0) || (r1 > 0 && r2 < 0)) { + return false; // Encountered some other sign. Exit. + } + } // If we got here, all dot products were of the same sign. + + return positiveResult ? 1 : -1; + } + /** + * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis. + * Results are saved in the array maxmin. + * @param result result[0] and result[1] will be set to maximum and minimum, respectively. + */ + + static project(shape, axis, pos, quat, result) { + const n = shape.vertices.length; + const localAxis = project_localAxis; + let max = 0; + let min = 0; + const localOrigin = project_localOrigin; + const vs = shape.vertices; + localOrigin.setZero(); // Transform the axis to local + + Transform.vectorToLocalFrame(pos, quat, axis, localAxis); + Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin); + const add = localOrigin.dot(localAxis); + min = max = vs[0].dot(localAxis); + + for (let i = 1; i < n; i++) { + const val = vs[i].dot(localAxis); + + if (val > max) { + max = val; + } + + if (val < min) { + min = val; + } + } + + min -= add; + max -= add; + + if (min > max) { + // Inconsistent - swap + const temp = min; + min = max; + max = temp; + } // Output + + result[0] = max; + result[1] = min; + } + } + const maxminA = []; + const maxminB = []; + new Vec3(); + const project_localAxis = new Vec3(); + const project_localOrigin = new Vec3(); + + /** + * A 3d box shape. + * @example + * const size = 1 + * const halfExtents = new CANNON.Vec3(size, size, size) + * const boxShape = new CANNON.Box(halfExtents) + * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape }) + * world.addBody(boxBody) + */ + class Box extends Shape { + /** + * The half extents of the box. + */ + + /** + * Used by the contact generator to make contacts with other convex polyhedra for example. + */ + constructor(halfExtents) { + super({ + type: Shape.types.BOX, + }); + this.halfExtents = halfExtents; + this.convexPolyhedronRepresentation = null; + this.updateConvexPolyhedronRepresentation(); + this.updateBoundingSphereRadius(); + } + /** + * Updates the local convex polyhedron representation used for some collisions. + */ + + updateConvexPolyhedronRepresentation() { + const sx = this.halfExtents.x; + const sy = this.halfExtents.y; + const sz = this.halfExtents.z; + const V = Vec3; + const vertices = [ + new V(-sx, -sy, -sz), + new V(sx, -sy, -sz), + new V(sx, sy, -sz), + new V(-sx, sy, -sz), + new V(-sx, -sy, sz), + new V(sx, -sy, sz), + new V(sx, sy, sz), + new V(-sx, sy, sz), + ]; + const faces = [ + [3, 2, 1, 0], // -z + [4, 5, 6, 7], // +z + [5, 4, 0, 1], // -y + [2, 3, 7, 6], // +y + [0, 4, 7, 3], // -x + [1, 2, 6, 5], // +x + ]; + const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)]; + const h = new ConvexPolyhedron({ + vertices, + faces, + axes, + }); + this.convexPolyhedronRepresentation = h; + h.material = this.material; + } + /** + * Calculate the inertia of the box. + */ + + calculateLocalInertia(mass, target) { + if (target === void 0) { + target = new Vec3(); + } + + Box.calculateInertia(this.halfExtents, mass, target); + return target; + } + + static calculateInertia(halfExtents, mass, target) { + const e = halfExtents; + target.x = (1.0 / 12.0) * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z); + target.y = (1.0 / 12.0) * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z); + target.z = (1.0 / 12.0) * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x); + } + /** + * Get the box 6 side normals + * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in. + * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame. + */ + + getSideNormals(sixTargetVectors, quat) { + const sides = sixTargetVectors; + const ex = this.halfExtents; + sides[0].set(ex.x, 0, 0); + sides[1].set(0, ex.y, 0); + sides[2].set(0, 0, ex.z); + sides[3].set(-ex.x, 0, 0); + sides[4].set(0, -ex.y, 0); + sides[5].set(0, 0, -ex.z); + + if (quat !== undefined) { + for (let i = 0; i !== sides.length; i++) { + quat.vmult(sides[i], sides[i]); + } + } + + return sides; + } + /** + * Returns the volume of the box. + */ + + volume() { + return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z; + } + /** + * updateBoundingSphereRadius + */ + + updateBoundingSphereRadius() { + this.boundingSphereRadius = this.halfExtents.length(); + } + /** + * forEachWorldCorner + */ + + forEachWorldCorner(pos, quat, callback) { + const e = this.halfExtents; + const corners = [ + [e.x, e.y, e.z], + [-e.x, e.y, e.z], + [-e.x, -e.y, e.z], + [-e.x, -e.y, -e.z], + [e.x, -e.y, -e.z], + [e.x, e.y, -e.z], + [-e.x, e.y, -e.z], + [e.x, -e.y, e.z], + ]; + + for (let i = 0; i < corners.length; i++) { + worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]); + quat.vmult(worldCornerTempPos, worldCornerTempPos); + pos.vadd(worldCornerTempPos, worldCornerTempPos); + callback( + worldCornerTempPos.x, + worldCornerTempPos.y, + worldCornerTempPos.z + ); + } + } + /** + * calculateWorldAABB + */ + + calculateWorldAABB(pos, quat, min, max) { + const e = this.halfExtents; + worldCornersTemp[0].set(e.x, e.y, e.z); + worldCornersTemp[1].set(-e.x, e.y, e.z); + worldCornersTemp[2].set(-e.x, -e.y, e.z); + worldCornersTemp[3].set(-e.x, -e.y, -e.z); + worldCornersTemp[4].set(e.x, -e.y, -e.z); + worldCornersTemp[5].set(e.x, e.y, -e.z); + worldCornersTemp[6].set(-e.x, e.y, -e.z); + worldCornersTemp[7].set(e.x, -e.y, e.z); + const wc = worldCornersTemp[0]; + quat.vmult(wc, wc); + pos.vadd(wc, wc); + max.copy(wc); + min.copy(wc); + + for (let i = 1; i < 8; i++) { + const wc = worldCornersTemp[i]; + quat.vmult(wc, wc); + pos.vadd(wc, wc); + const x = wc.x; + const y = wc.y; + const z = wc.z; + + if (x > max.x) { + max.x = x; + } + + if (y > max.y) { + max.y = y; + } + + if (z > max.z) { + max.z = z; + } + + if (x < min.x) { + min.x = x; + } + + if (y < min.y) { + min.y = y; + } + + if (z < min.z) { + min.z = z; + } + } // Get each axis max + // min.set(Infinity,Infinity,Infinity); + // max.set(-Infinity,-Infinity,-Infinity); + // this.forEachWorldCorner(pos,quat,function(x,y,z){ + // if(x > max.x){ + // max.x = x; + // } + // if(y > max.y){ + // max.y = y; + // } + // if(z > max.z){ + // max.z = z; + // } + // if(x < min.x){ + // min.x = x; + // } + // if(y < min.y){ + // min.y = y; + // } + // if(z < min.z){ + // min.z = z; + // } + // }); + } + } + const worldCornerTempPos = new Vec3(); + const worldCornersTemp = [ + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + ]; + + /** + * BODY_TYPES + */ + const BODY_TYPES = { + /** DYNAMIC */ + DYNAMIC: 1, + + /** STATIC */ + STATIC: 2, + + /** KINEMATIC */ + KINEMATIC: 4, + }; + /** + * BodyType + */ + + /** + * BODY_SLEEP_STATES + */ + const BODY_SLEEP_STATES = { + /** AWAKE */ + AWAKE: 0, + + /** SLEEPY */ + SLEEPY: 1, + + /** SLEEPING */ + SLEEPING: 2, + }; + /** + * BodySleepState + */ + + /** + * Base class for all body types. + * @example + * const shape = new CANNON.Sphere(1) + * const body = new CANNON.Body({ + * mass: 1, + * shape, + * }) + * world.addBody(body) + */ + class Body extends EventTarget { + /** + * Dispatched after two bodies collide. This event is dispatched on each + * of the two bodies involved in the collision. + * @event collide + * @param body The body that was involved in the collision. + * @param contact The details of the collision. + */ + + /** + * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. + */ + + /** + * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies. + */ + + /** + * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies. + */ + + /** + * AWAKE + */ + + /** + * SLEEPY + */ + + /** + * SLEEPING + */ + + /** + * Dispatched after a sleeping body has woken up. + * @event wakeup + */ + + /** + * Dispatched after a body has gone in to the sleepy state. + * @event sleepy + */ + + /** + * Dispatched after a body has fallen asleep. + * @event sleep + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + super(); + this.id = Body.idCounter++; + this.index = -1; + this.world = null; + this.vlambda = new Vec3(); + this.collisionFilterGroup = + typeof options.collisionFilterGroup === "number" + ? options.collisionFilterGroup + : 1; + this.collisionFilterMask = + typeof options.collisionFilterMask === "number" + ? options.collisionFilterMask + : -1; + this.collisionResponse = + typeof options.collisionResponse === "boolean" + ? options.collisionResponse + : true; + this.position = new Vec3(); + this.previousPosition = new Vec3(); + this.interpolatedPosition = new Vec3(); + this.initPosition = new Vec3(); + + if (options.position) { + this.position.copy(options.position); + this.previousPosition.copy(options.position); + this.interpolatedPosition.copy(options.position); + this.initPosition.copy(options.position); + } + + this.velocity = new Vec3(); + + if (options.velocity) { + this.velocity.copy(options.velocity); + } + + this.initVelocity = new Vec3(); + this.force = new Vec3(); + const mass = typeof options.mass === "number" ? options.mass : 0; + this.mass = mass; + this.invMass = mass > 0 ? 1.0 / mass : 0; + this.material = options.material || null; + this.linearDamping = + typeof options.linearDamping === "number" ? options.linearDamping : 0.01; + this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC; + + if (typeof options.type === typeof Body.STATIC) { + this.type = options.type; + } + + this.allowSleep = + typeof options.allowSleep !== "undefined" ? options.allowSleep : true; + this.sleepState = Body.AWAKE; + this.sleepSpeedLimit = + typeof options.sleepSpeedLimit !== "undefined" + ? options.sleepSpeedLimit + : 0.1; + this.sleepTimeLimit = + typeof options.sleepTimeLimit !== "undefined" + ? options.sleepTimeLimit + : 1; + this.timeLastSleepy = 0; + this.wakeUpAfterNarrowphase = false; + this.torque = new Vec3(); + this.quaternion = new Quaternion(); + this.initQuaternion = new Quaternion(); + this.previousQuaternion = new Quaternion(); + this.interpolatedQuaternion = new Quaternion(); + + if (options.quaternion) { + this.quaternion.copy(options.quaternion); + this.initQuaternion.copy(options.quaternion); + this.previousQuaternion.copy(options.quaternion); + this.interpolatedQuaternion.copy(options.quaternion); + } + + this.angularVelocity = new Vec3(); + + if (options.angularVelocity) { + this.angularVelocity.copy(options.angularVelocity); + } + + this.initAngularVelocity = new Vec3(); + this.shapes = []; + this.shapeOffsets = []; + this.shapeOrientations = []; + this.inertia = new Vec3(); + this.invInertia = new Vec3(); + this.invInertiaWorld = new Mat3(); + this.invMassSolve = 0; + this.invInertiaSolve = new Vec3(); + this.invInertiaWorldSolve = new Mat3(); + this.fixedRotation = + typeof options.fixedRotation !== "undefined" + ? options.fixedRotation + : false; + this.angularDamping = + typeof options.angularDamping !== "undefined" + ? options.angularDamping + : 0.01; + this.linearFactor = new Vec3(1, 1, 1); + + if (options.linearFactor) { + this.linearFactor.copy(options.linearFactor); + } + + this.angularFactor = new Vec3(1, 1, 1); + + if (options.angularFactor) { + this.angularFactor.copy(options.angularFactor); + } + + this.aabb = new AABB(); + this.aabbNeedsUpdate = true; + this.boundingRadius = 0; + this.wlambda = new Vec3(); + this.isTrigger = Boolean(options.isTrigger); + + if (options.shape) { + this.addShape(options.shape); + } + + this.updateMassProperties(); + } + /** + * Wake the body up. + */ + + wakeUp() { + const prevState = this.sleepState; + this.sleepState = Body.AWAKE; + this.wakeUpAfterNarrowphase = false; + + if (prevState === Body.SLEEPING) { + this.dispatchEvent(Body.wakeupEvent); + } + } + /** + * Force body sleep + */ + + sleep() { + this.sleepState = Body.SLEEPING; + this.velocity.set(0, 0, 0); + this.angularVelocity.set(0, 0, 0); + this.wakeUpAfterNarrowphase = false; + } + /** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @param time The world time in seconds + */ + + sleepTick(time) { + if (this.allowSleep) { + const sleepState = this.sleepState; + const speedSquared = + this.velocity.lengthSquared() + this.angularVelocity.lengthSquared(); + const speedLimitSquared = this.sleepSpeedLimit ** 2; + + if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) { + this.sleepState = Body.SLEEPY; // Sleepy + + this.timeLastSleepy = time; + this.dispatchEvent(Body.sleepyEvent); + } else if ( + sleepState === Body.SLEEPY && + speedSquared > speedLimitSquared + ) { + this.wakeUp(); // Wake up + } else if ( + sleepState === Body.SLEEPY && + time - this.timeLastSleepy > this.sleepTimeLimit + ) { + this.sleep(); // Sleeping + + this.dispatchEvent(Body.sleepEvent); + } + } + } + /** + * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass". + */ + + updateSolveMassProperties() { + if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) { + this.invMassSolve = 0; + this.invInertiaSolve.setZero(); + this.invInertiaWorldSolve.setZero(); + } else { + this.invMassSolve = this.invMass; + this.invInertiaSolve.copy(this.invInertia); + this.invInertiaWorldSolve.copy(this.invInertiaWorld); + } + } + /** + * Convert a world point to local body frame. + */ + + pointToLocalFrame(worldPoint, result) { + if (result === void 0) { + result = new Vec3(); + } + + worldPoint.vsub(this.position, result); + this.quaternion.conjugate().vmult(result, result); + return result; + } + /** + * Convert a world vector to local body frame. + */ + + vectorToLocalFrame(worldVector, result) { + if (result === void 0) { + result = new Vec3(); + } + + this.quaternion.conjugate().vmult(worldVector, result); + return result; + } + /** + * Convert a local body point to world frame. + */ + + pointToWorldFrame(localPoint, result) { + if (result === void 0) { + result = new Vec3(); + } + + this.quaternion.vmult(localPoint, result); + result.vadd(this.position, result); + return result; + } + /** + * Convert a local body point to world frame. + */ + + vectorToWorldFrame(localVector, result) { + if (result === void 0) { + result = new Vec3(); + } + + this.quaternion.vmult(localVector, result); + return result; + } + /** + * Add a shape to the body with a local offset and orientation. + * @return The body object, for chainability. + */ + + addShape(shape, _offset, _orientation) { + const offset = new Vec3(); + const orientation = new Quaternion(); + + if (_offset) { + offset.copy(_offset); + } + + if (_orientation) { + orientation.copy(_orientation); + } + + this.shapes.push(shape); + this.shapeOffsets.push(offset); + this.shapeOrientations.push(orientation); + this.updateMassProperties(); + this.updateBoundingRadius(); + this.aabbNeedsUpdate = true; + shape.body = this; + return this; + } + /** + * Remove a shape from the body. + * @return The body object, for chainability. + */ + + removeShape(shape) { + const index = this.shapes.indexOf(shape); + + if (index === -1) { + console.warn("Shape does not belong to the body"); + return this; + } + + this.shapes.splice(index, 1); + this.shapeOffsets.splice(index, 1); + this.shapeOrientations.splice(index, 1); + this.updateMassProperties(); + this.updateBoundingRadius(); + this.aabbNeedsUpdate = true; + shape.body = null; + return this; + } + /** + * Update the bounding radius of the body. Should be done if any of the shapes are changed. + */ + + updateBoundingRadius() { + const shapes = this.shapes; + const shapeOffsets = this.shapeOffsets; + const N = shapes.length; + let radius = 0; + + for (let i = 0; i !== N; i++) { + const shape = shapes[i]; + shape.updateBoundingSphereRadius(); + const offset = shapeOffsets[i].length(); + const r = shape.boundingSphereRadius; + + if (offset + r > radius) { + radius = offset + r; + } + } + + this.boundingRadius = radius; + } + /** + * Updates the .aabb + */ + + updateAABB() { + const shapes = this.shapes; + const shapeOffsets = this.shapeOffsets; + const shapeOrientations = this.shapeOrientations; + const N = shapes.length; + const offset = tmpVec; + const orientation = tmpQuat; + const bodyQuat = this.quaternion; + const aabb = this.aabb; + const shapeAABB = updateAABB_shapeAABB; + + for (let i = 0; i !== N; i++) { + const shape = shapes[i]; // Get shape world position + + bodyQuat.vmult(shapeOffsets[i], offset); + offset.vadd(this.position, offset); // Get shape world quaternion + + bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB + + shape.calculateWorldAABB( + offset, + orientation, + shapeAABB.lowerBound, + shapeAABB.upperBound + ); + + if (i === 0) { + aabb.copy(shapeAABB); + } else { + aabb.extend(shapeAABB); + } + } + + this.aabbNeedsUpdate = false; + } + /** + * Update `.inertiaWorld` and `.invInertiaWorld` + */ + + updateInertiaWorld(force) { + const I = this.invInertia; + + if (I.x === I.y && I.y === I.z && !force); + else { + const m1 = uiw_m1; + const m2 = uiw_m2; + m1.setRotationFromQuaternion(this.quaternion); + m1.transpose(m2); + m1.scale(I, m1); + m1.mmult(m2, this.invInertiaWorld); + } + } + /** + * Apply force to a point of the body. This could for example be a point on the Body surface. + * Applying force this way will add to Body.force and Body.torque. + * @param force The amount of force to add. + * @param relativePoint A point relative to the center of mass to apply the force on. + */ + + applyForce(force, relativePoint) { + if (relativePoint === void 0) { + relativePoint = new Vec3(); + } + + // Needed? + if (this.type !== Body.DYNAMIC) { + return; + } + + if (this.sleepState === Body.SLEEPING) { + this.wakeUp(); + } // Compute produced rotational force + + const rotForce = Body_applyForce_rotForce; + relativePoint.cross(force, rotForce); // Add linear force + + this.force.vadd(force, this.force); // Add rotational force + + this.torque.vadd(rotForce, this.torque); + } + /** + * Apply force to a local point in the body. + * @param force The force vector to apply, defined locally in the body frame. + * @param localPoint A local point in the body to apply the force on. + */ + + applyLocalForce(localForce, localPoint) { + if (localPoint === void 0) { + localPoint = new Vec3(); + } + + if (this.type !== Body.DYNAMIC) { + return; + } + + const worldForce = Body_applyLocalForce_worldForce; + const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space + + this.vectorToWorldFrame(localForce, worldForce); + this.vectorToWorldFrame(localPoint, relativePointWorld); + this.applyForce(worldForce, relativePointWorld); + } + /** + * Apply torque to the body. + * @param torque The amount of torque to add. + */ + + applyTorque(torque) { + if (this.type !== Body.DYNAMIC) { + return; + } + + if (this.sleepState === Body.SLEEPING) { + this.wakeUp(); + } // Add rotational force + + this.torque.vadd(torque, this.torque); + } + /** + * Apply impulse to a point of the body. This could for example be a point on the Body surface. + * An impulse is a force added to a body during a short period of time (impulse = force * time). + * Impulses will be added to Body.velocity and Body.angularVelocity. + * @param impulse The amount of impulse to add. + * @param relativePoint A point relative to the center of mass to apply the force on. + */ + + applyImpulse(impulse, relativePoint) { + if (relativePoint === void 0) { + relativePoint = new Vec3(); + } + + if (this.type !== Body.DYNAMIC) { + return; + } + + if (this.sleepState === Body.SLEEPING) { + this.wakeUp(); + } // Compute point position relative to the body center + + const r = relativePoint; // Compute produced central impulse velocity + + const velo = Body_applyImpulse_velo; + velo.copy(impulse); + velo.scale(this.invMass, velo); // Add linear impulse + + this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity + + const rotVelo = Body_applyImpulse_rotVelo; + r.cross(impulse, rotVelo); + /* + rotVelo.x *= this.invInertia.x; + rotVelo.y *= this.invInertia.y; + rotVelo.z *= this.invInertia.z; + */ + + this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse + + this.angularVelocity.vadd(rotVelo, this.angularVelocity); + } + /** + * Apply locally-defined impulse to a local point in the body. + * @param force The force vector to apply, defined locally in the body frame. + * @param localPoint A local point in the body to apply the force on. + */ + + applyLocalImpulse(localImpulse, localPoint) { + if (localPoint === void 0) { + localPoint = new Vec3(); + } + + if (this.type !== Body.DYNAMIC) { + return; + } + + const worldImpulse = Body_applyLocalImpulse_worldImpulse; + const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space + + this.vectorToWorldFrame(localImpulse, worldImpulse); + this.vectorToWorldFrame(localPoint, relativePointWorld); + this.applyImpulse(worldImpulse, relativePointWorld); + } + /** + * Should be called whenever you change the body shape or mass. + */ + + updateMassProperties() { + const halfExtents = Body_updateMassProperties_halfExtents; + this.invMass = this.mass > 0 ? 1.0 / this.mass : 0; + const I = this.inertia; + const fixed = this.fixedRotation; // Approximate with AABB box + + this.updateAABB(); + halfExtents.set( + (this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2, + (this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2, + (this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2 + ); + Box.calculateInertia(halfExtents, this.mass, I); + this.invInertia.set( + I.x > 0 && !fixed ? 1.0 / I.x : 0, + I.y > 0 && !fixed ? 1.0 / I.y : 0, + I.z > 0 && !fixed ? 1.0 / I.z : 0 + ); + this.updateInertiaWorld(true); + } + /** + * Get world velocity of a point in the body. + * @param worldPoint + * @param result + * @return The result vector. + */ + + getVelocityAtWorldPoint(worldPoint, result) { + const r = new Vec3(); + worldPoint.vsub(this.position, r); + this.angularVelocity.cross(r, result); + this.velocity.vadd(result, result); + return result; + } + /** + * Move the body forward in time. + * @param dt Time step + * @param quatNormalize Set to true to normalize the body quaternion + * @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization + */ + + integrate(dt, quatNormalize, quatNormalizeFast) { + // Save previous position + this.previousPosition.copy(this.position); + this.previousQuaternion.copy(this.quaternion); + + if ( + !(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || + this.sleepState === Body.SLEEPING + ) { + // Only for dynamic + return; + } + + const velo = this.velocity; + const angularVelo = this.angularVelocity; + const pos = this.position; + const force = this.force; + const torque = this.torque; + const quat = this.quaternion; + const invMass = this.invMass; + const invInertia = this.invInertiaWorld; + const linearFactor = this.linearFactor; + const iMdt = invMass * dt; + velo.x += force.x * iMdt * linearFactor.x; + velo.y += force.y * iMdt * linearFactor.y; + velo.z += force.z * iMdt * linearFactor.z; + const e = invInertia.elements; + const angularFactor = this.angularFactor; + const tx = torque.x * angularFactor.x; + const ty = torque.y * angularFactor.y; + const tz = torque.z * angularFactor.z; + angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz); + angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz); + angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog + + pos.x += velo.x * dt; + pos.y += velo.y * dt; + pos.z += velo.z * dt; + quat.integrate(this.angularVelocity, dt, this.angularFactor, quat); + + if (quatNormalize) { + if (quatNormalizeFast) { + quat.normalizeFast(); + } else { + quat.normalize(); + } + } + + this.aabbNeedsUpdate = true; // Update world inertia + + this.updateInertiaWorld(); + } + } + Body.idCounter = 0; + Body.COLLIDE_EVENT_NAME = "collide"; + Body.DYNAMIC = BODY_TYPES.DYNAMIC; + Body.STATIC = BODY_TYPES.STATIC; + Body.KINEMATIC = BODY_TYPES.KINEMATIC; + Body.AWAKE = BODY_SLEEP_STATES.AWAKE; + Body.SLEEPY = BODY_SLEEP_STATES.SLEEPY; + Body.SLEEPING = BODY_SLEEP_STATES.SLEEPING; + Body.wakeupEvent = { + type: "wakeup", + }; + Body.sleepyEvent = { + type: "sleepy", + }; + Body.sleepEvent = { + type: "sleep", + }; + const tmpVec = new Vec3(); + const tmpQuat = new Quaternion(); + const updateAABB_shapeAABB = new AABB(); + const uiw_m1 = new Mat3(); + const uiw_m2 = new Mat3(); + new Mat3(); + const Body_applyForce_rotForce = new Vec3(); + const Body_applyLocalForce_worldForce = new Vec3(); + const Body_applyLocalForce_relativePointWorld = new Vec3(); + const Body_applyImpulse_velo = new Vec3(); + const Body_applyImpulse_rotVelo = new Vec3(); + const Body_applyLocalImpulse_worldImpulse = new Vec3(); + const Body_applyLocalImpulse_relativePoint = new Vec3(); + const Body_updateMassProperties_halfExtents = new Vec3(); + + /** + * Base class for broadphase implementations + * @author schteppe + */ + class Broadphase { + /** + * The world to search for collisions in. + */ + + /** + * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres. + */ + + /** + * Set to true if the objects in the world moved. + */ + constructor() { + this.world = null; + this.useBoundingBoxes = false; + this.dirty = true; + } + /** + * Get the collision pairs from the world + * @param world The world to search in + * @param p1 Empty array to be filled with body objects + * @param p2 Empty array to be filled with body objects + */ + + collisionPairs(world, p1, p2) { + throw new Error( + "collisionPairs not implemented for this BroadPhase class!" + ); + } + /** + * Check if a body pair needs to be intersection tested at all. + */ + + needBroadphaseCollision(bodyA, bodyB) { + // Check collision filter masks + if ( + (bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || + (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0 + ) { + return false; + } // Check types + + if ( + ((bodyA.type & Body.STATIC) !== 0 || + bodyA.sleepState === Body.SLEEPING) && + ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING) + ) { + // Both bodies are static or sleeping. Skip. + return false; + } + + return true; + } + /** + * Check if the bounding volumes of two bodies intersect. + */ + + intersectionTest(bodyA, bodyB, pairs1, pairs2) { + if (this.useBoundingBoxes) { + this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2); + } else { + this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2); + } + } + /** + * Check if the bounding spheres of two bodies are intersecting. + * @param pairs1 bodyA is appended to this array if intersection + * @param pairs2 bodyB is appended to this array if intersection + */ + + doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) { + const r = Broadphase_collisionPairs_r; + bodyB.position.vsub(bodyA.position, r); + const boundingRadiusSum2 = + (bodyA.boundingRadius + bodyB.boundingRadius) ** 2; + const norm2 = r.lengthSquared(); + + if (norm2 < boundingRadiusSum2) { + pairs1.push(bodyA); + pairs2.push(bodyB); + } + } + /** + * Check if the bounding boxes of two bodies are intersecting. + */ + + doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) { + if (bodyA.aabbNeedsUpdate) { + bodyA.updateAABB(); + } + + if (bodyB.aabbNeedsUpdate) { + bodyB.updateAABB(); + } // Check AABB / AABB + + if (bodyA.aabb.overlaps(bodyB.aabb)) { + pairs1.push(bodyA); + pairs2.push(bodyB); + } + } + /** + * Removes duplicate pairs from the pair arrays. + */ + + makePairsUnique(pairs1, pairs2) { + const t = Broadphase_makePairsUnique_temp; + const p1 = Broadphase_makePairsUnique_p1; + const p2 = Broadphase_makePairsUnique_p2; + const N = pairs1.length; + + for (let i = 0; i !== N; i++) { + p1[i] = pairs1[i]; + p2[i] = pairs2[i]; + } + + pairs1.length = 0; + pairs2.length = 0; + + for (let i = 0; i !== N; i++) { + const id1 = p1[i].id; + const id2 = p2[i].id; + const key = id1 < id2 ? `${id1},${id2}` : `${id2},${id1}`; + t[key] = i; + t.keys.push(key); + } + + for (let i = 0; i !== t.keys.length; i++) { + const key = t.keys.pop(); + const pairIndex = t[key]; + pairs1.push(p1[pairIndex]); + pairs2.push(p2[pairIndex]); + delete t[key]; + } + } + /** + * To be implemented by subcasses + */ + + setWorld(world) {} + /** + * Check if the bounding spheres of two bodies overlap. + */ + + static boundingSphereCheck(bodyA, bodyB) { + const dist = new Vec3(); // bsc_dist; + + bodyA.position.vsub(bodyB.position, dist); + const sa = bodyA.shapes[0]; + const sb = bodyB.shapes[0]; + return ( + Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > + dist.lengthSquared() + ); + } + /** + * Returns all the bodies within the AABB. + */ + + aabbQuery(world, aabb, result) { + console.warn(".aabbQuery is not implemented in this Broadphase subclass."); + return []; + } + } // Temp objects + + const Broadphase_collisionPairs_r = new Vec3(); + new Vec3(); + new Quaternion(); + new Vec3(); + const Broadphase_makePairsUnique_temp = { + keys: [], + }; + const Broadphase_makePairsUnique_p1 = []; + const Broadphase_makePairsUnique_p2 = []; + new Vec3(); + + /** + * Axis aligned uniform grid broadphase. + * @todo Needs support for more than just planes and spheres. + */ + class GridBroadphase extends Broadphase { + /** + * Number of boxes along x + */ + + /** + * Number of boxes along y + */ + + /** + * Number of boxes along z + */ + + /** + * aabbMin + */ + + /** + * aabbMax + */ + + /** + * bins + */ + + /** + * binLengths + */ + + /** + * @param nx Number of boxes along x. + * @param ny Number of boxes along y. + * @param nz Number of boxes along z. + */ + constructor(aabbMin, aabbMax, nx, ny, nz) { + if (aabbMin === void 0) { + aabbMin = new Vec3(100, 100, 100); + } + + if (aabbMax === void 0) { + aabbMax = new Vec3(-100, -100, -100); + } + + if (nx === void 0) { + nx = 10; + } + + if (ny === void 0) { + ny = 10; + } + + if (nz === void 0) { + nz = 10; + } + + super(); + this.nx = nx; + this.ny = ny; + this.nz = nz; + this.aabbMin = aabbMin; + this.aabbMax = aabbMax; + const nbins = this.nx * this.ny * this.nz; + + if (nbins <= 0) { + throw "GridBroadphase: Each dimension's n must be >0"; + } + + this.bins = []; + this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow + + this.bins.length = nbins; + this.binLengths.length = nbins; + + for (let i = 0; i < nbins; i++) { + this.bins[i] = []; + this.binLengths[i] = 0; + } + } + /** + * Get all the collision pairs in the physics world + */ + + collisionPairs(world, pairs1, pairs2) { + const N = world.bodies.length; + const bodies = world.bodies; + const max = this.aabbMax; + const min = this.aabbMin; + const nx = this.nx; + const ny = this.ny; + const nz = this.nz; + const xstep = ny * nz; + const ystep = nz; + const zstep = 1; + const xmax = max.x; + const ymax = max.y; + const zmax = max.z; + const xmin = min.x; + const ymin = min.y; + const zmin = min.z; + const xmult = nx / (xmax - xmin); + const ymult = ny / (ymax - ymin); + const zmult = nz / (zmax - zmin); + const binsizeX = (xmax - xmin) / nx; + const binsizeY = (ymax - ymin) / ny; + const binsizeZ = (zmax - zmin) / nz; + const binRadius = + Math.sqrt( + binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ + ) * 0.5; + const types = Shape.types; + const SPHERE = types.SPHERE; + const PLANE = types.PLANE; + types.BOX; + types.COMPOUND; + types.CONVEXPOLYHEDRON; + const bins = this.bins; + const binLengths = this.binLengths; + const Nbins = this.bins.length; // Reset bins + + for (let i = 0; i !== Nbins; i++) { + binLengths[i] = 0; + } + + const ceil = Math.ceil; + + function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) { + let xoff0 = ((x0 - xmin) * xmult) | 0; + let yoff0 = ((y0 - ymin) * ymult) | 0; + let zoff0 = ((z0 - zmin) * zmult) | 0; + let xoff1 = ceil((x1 - xmin) * xmult); + let yoff1 = ceil((y1 - ymin) * ymult); + let zoff1 = ceil((z1 - zmin) * zmult); + + if (xoff0 < 0) { + xoff0 = 0; + } else if (xoff0 >= nx) { + xoff0 = nx - 1; + } + + if (yoff0 < 0) { + yoff0 = 0; + } else if (yoff0 >= ny) { + yoff0 = ny - 1; + } + + if (zoff0 < 0) { + zoff0 = 0; + } else if (zoff0 >= nz) { + zoff0 = nz - 1; + } + + if (xoff1 < 0) { + xoff1 = 0; + } else if (xoff1 >= nx) { + xoff1 = nx - 1; + } + + if (yoff1 < 0) { + yoff1 = 0; + } else if (yoff1 >= ny) { + yoff1 = ny - 1; + } + + if (zoff1 < 0) { + zoff1 = 0; + } else if (zoff1 >= nz) { + zoff1 = nz - 1; + } + + xoff0 *= xstep; + yoff0 *= ystep; + zoff0 *= zstep; + xoff1 *= xstep; + yoff1 *= ystep; + zoff1 *= zstep; + + for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) { + for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) { + for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) { + const idx = xoff + yoff + zoff; + bins[idx][binLengths[idx]++] = bi; + } + } + } + } // Put all bodies into the bins + + for (let i = 0; i !== N; i++) { + const bi = bodies[i]; + const si = bi.shapes[0]; + + switch (si.type) { + case SPHERE: { + const shape = si; // Put in bin + // check if overlap with other bins + + const x = bi.position.x; + const y = bi.position.y; + const z = bi.position.z; + const r = shape.radius; + addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi); + break; + } + + case PLANE: { + const shape = si; + + if (shape.worldNormalNeedsUpdate) { + shape.computeWorldNormal(bi.quaternion); + } + + const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin + //Incremented as we iterate through the bins + + const xreset = xmin + binsizeX * 0.5 - bi.position.x; + const yreset = ymin + binsizeY * 0.5 - bi.position.y; + const zreset = zmin + binsizeZ * 0.5 - bi.position.z; + const d = GridBroadphase_collisionPairs_d; + d.set(xreset, yreset, zreset); + + for ( + let xi = 0, xoff = 0; + xi !== nx; + xi++, xoff += xstep, d.y = yreset, d.x += binsizeX + ) { + for ( + let yi = 0, yoff = 0; + yi !== ny; + yi++, yoff += ystep, d.z = zreset, d.y += binsizeY + ) { + for ( + let zi = 0, zoff = 0; + zi !== nz; + zi++, zoff += zstep, d.z += binsizeZ + ) { + if (d.dot(planeNormal) < binRadius) { + const idx = xoff + yoff + zoff; + bins[idx][binLengths[idx]++] = bi; + } + } + } + } + + break; + } + + default: { + if (bi.aabbNeedsUpdate) { + bi.updateAABB(); + } + + addBoxToBins( + bi.aabb.lowerBound.x, + bi.aabb.lowerBound.y, + bi.aabb.lowerBound.z, + bi.aabb.upperBound.x, + bi.aabb.upperBound.y, + bi.aabb.upperBound.z, + bi + ); + break; + } + } + } // Check each bin + + for (let i = 0; i !== Nbins; i++) { + const binLength = binLengths[i]; //Skip bins with no potential collisions + + if (binLength > 1) { + const bin = bins[i]; // Do N^2 broadphase inside + + for (let xi = 0; xi !== binLength; xi++) { + const bi = bin[xi]; + + for (let yi = 0; yi !== xi; yi++) { + const bj = bin[yi]; + + if (this.needBroadphaseCollision(bi, bj)) { + this.intersectionTest(bi, bj, pairs1, pairs2); + } + } + } + } + } // for (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) { + // console.log("layer "+zi); + // for (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) { + // const row = ''; + // for (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) { + // const idx = xoff + yoff + zoff; + // row += ' ' + binLengths[idx]; + // } + // console.log(row); + // } + // } + + this.makePairsUnique(pairs1, pairs2); + } + } + const GridBroadphase_collisionPairs_d = new Vec3(); + new Vec3(); + + /** + * Naive broadphase implementation, used in lack of better ones. + * + * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_ + */ + class NaiveBroadphase extends Broadphase { + /** + * @todo Remove useless constructor + */ + constructor() { + super(); + } + /** + * Get all the collision pairs in the physics world + */ + + collisionPairs(world, pairs1, pairs2) { + const bodies = world.bodies; + const n = bodies.length; + let bi; + let bj; // Naive N^2 ftw! + + for (let i = 0; i !== n; i++) { + for (let j = 0; j !== i; j++) { + bi = bodies[i]; + bj = bodies[j]; + + if (!this.needBroadphaseCollision(bi, bj)) { + continue; + } + + this.intersectionTest(bi, bj, pairs1, pairs2); + } + } + } + /** + * Returns all the bodies within an AABB. + * @param result An array to store resulting bodies in. + */ + + aabbQuery(world, aabb, result) { + if (result === void 0) { + result = []; + } + + for (let i = 0; i < world.bodies.length; i++) { + const b = world.bodies[i]; + + if (b.aabbNeedsUpdate) { + b.updateAABB(); + } // Ugly hack until Body gets aabb + + if (b.aabb.overlaps(aabb)) { + result.push(b); + } + } + + return result; + } + } + + /** + * Storage for Ray casting data + */ + class RaycastResult { + /** + * rayFromWorld + */ + + /** + * rayToWorld + */ + + /** + * hitNormalWorld + */ + + /** + * hitPointWorld + */ + + /** + * hasHit + */ + + /** + * shape + */ + + /** + * body + */ + + /** + * The index of the hit triangle, if the hit shape was a trimesh + */ + + /** + * Distance to the hit. Will be set to -1 if there was no hit + */ + + /** + * If the ray should stop traversing the bodies + */ + constructor() { + this.rayFromWorld = new Vec3(); + this.rayToWorld = new Vec3(); + this.hitNormalWorld = new Vec3(); + this.hitPointWorld = new Vec3(); + this.hasHit = false; + this.shape = null; + this.body = null; + this.hitFaceIndex = -1; + this.distance = -1; + this.shouldStop = false; + } + /** + * Reset all result data. + */ + + reset() { + this.rayFromWorld.setZero(); + this.rayToWorld.setZero(); + this.hitNormalWorld.setZero(); + this.hitPointWorld.setZero(); + this.hasHit = false; + this.shape = null; + this.body = null; + this.hitFaceIndex = -1; + this.distance = -1; + this.shouldStop = false; + } + /** + * abort + */ + + abort() { + this.shouldStop = true; + } + /** + * Set result data. + */ + + set( + rayFromWorld, + rayToWorld, + hitNormalWorld, + hitPointWorld, + shape, + body, + distance + ) { + this.rayFromWorld.copy(rayFromWorld); + this.rayToWorld.copy(rayToWorld); + this.hitNormalWorld.copy(hitNormalWorld); + this.hitPointWorld.copy(hitPointWorld); + this.shape = shape; + this.body = body; + this.distance = distance; + } + } + + let _Shape$types$SPHERE, + _Shape$types$PLANE, + _Shape$types$BOX, + _Shape$types$CYLINDER, + _Shape$types$CONVEXPO, + _Shape$types$HEIGHTFI, + _Shape$types$TRIMESH; + + /** + * RAY_MODES + */ + const RAY_MODES = { + /** CLOSEST */ + CLOSEST: 1, + + /** ANY */ + ANY: 2, + + /** ALL */ + ALL: 4, + }; + /** + * RayMode + */ + + _Shape$types$SPHERE = Shape.types.SPHERE; + _Shape$types$PLANE = Shape.types.PLANE; + _Shape$types$BOX = Shape.types.BOX; + _Shape$types$CYLINDER = Shape.types.CYLINDER; + _Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON; + _Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD; + _Shape$types$TRIMESH = Shape.types.TRIMESH; + + /** + * A line in 3D space that intersects bodies and return points. + */ + class Ray { + /** + * from + */ + + /** + * to + */ + + /** + * direction + */ + + /** + * The precision of the ray. Used when checking parallelity etc. + * @default 0.0001 + */ + + /** + * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes. + * @default true + */ + + /** + * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0. + * @default false + */ + + /** + * collisionFilterMask + * @default -1 + */ + + /** + * collisionFilterGroup + * @default -1 + */ + + /** + * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST. + * @default RAY.ANY + */ + + /** + * Current result object. + */ + + /** + * Will be set to `true` during intersectWorld() if the ray hit anything. + */ + + /** + * User-provided result callback. Will be used if mode is Ray.ALL. + */ + + /** + * CLOSEST + */ + + /** + * ANY + */ + + /** + * ALL + */ + get [_Shape$types$SPHERE]() { + return this._intersectSphere; + } + + get [_Shape$types$PLANE]() { + return this._intersectPlane; + } + + get [_Shape$types$BOX]() { + return this._intersectBox; + } + + get [_Shape$types$CYLINDER]() { + return this._intersectConvex; + } + + get [_Shape$types$CONVEXPO]() { + return this._intersectConvex; + } + + get [_Shape$types$HEIGHTFI]() { + return this._intersectHeightfield; + } + + get [_Shape$types$TRIMESH]() { + return this._intersectTrimesh; + } + + constructor(from, to) { + if (from === void 0) { + from = new Vec3(); + } + + if (to === void 0) { + to = new Vec3(); + } + + this.from = from.clone(); + this.to = to.clone(); + this.direction = new Vec3(); + this.precision = 0.0001; + this.checkCollisionResponse = true; + this.skipBackfaces = false; + this.collisionFilterMask = -1; + this.collisionFilterGroup = -1; + this.mode = Ray.ANY; + this.result = new RaycastResult(); + this.hasHit = false; + + this.callback = (result) => {}; + } + /** + * Do itersection against all bodies in the given World. + * @return True if the ray hit anything, otherwise false. + */ + + intersectWorld(world, options) { + this.mode = options.mode || Ray.ANY; + this.result = options.result || new RaycastResult(); + this.skipBackfaces = !!options.skipBackfaces; + this.collisionFilterMask = + typeof options.collisionFilterMask !== "undefined" + ? options.collisionFilterMask + : -1; + this.collisionFilterGroup = + typeof options.collisionFilterGroup !== "undefined" + ? options.collisionFilterGroup + : -1; + this.checkCollisionResponse = + typeof options.checkCollisionResponse !== "undefined" + ? options.checkCollisionResponse + : true; + + if (options.from) { + this.from.copy(options.from); + } + + if (options.to) { + this.to.copy(options.to); + } + + this.callback = options.callback || (() => {}); + + this.hasHit = false; + this.result.reset(); + this.updateDirection(); + this.getAABB(tmpAABB$1); + tmpArray.length = 0; + world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray); + this.intersectBodies(tmpArray); + return this.hasHit; + } + /** + * Shoot a ray at a body, get back information about the hit. + * @deprecated @param result set the result property of the Ray instead. + */ + + intersectBody(body, result) { + if (result) { + this.result = result; + this.updateDirection(); + } + + const checkCollisionResponse = this.checkCollisionResponse; + + if (checkCollisionResponse && !body.collisionResponse) { + return; + } + + if ( + (this.collisionFilterGroup & body.collisionFilterMask) === 0 || + (body.collisionFilterGroup & this.collisionFilterMask) === 0 + ) { + return; + } + + const xi = intersectBody_xi; + const qi = intersectBody_qi; + + for (let i = 0, N = body.shapes.length; i < N; i++) { + const shape = body.shapes[i]; + + if (checkCollisionResponse && !shape.collisionResponse) { + continue; // Skip + } + + body.quaternion.mult(body.shapeOrientations[i], qi); + body.quaternion.vmult(body.shapeOffsets[i], xi); + xi.vadd(body.position, xi); + this.intersectShape(shape, qi, xi, body); + + if (this.result.shouldStop) { + break; + } + } + } + /** + * Shoot a ray at an array bodies, get back information about the hit. + * @param bodies An array of Body objects. + * @deprecated @param result set the result property of the Ray instead. + * + */ + + intersectBodies(bodies, result) { + if (result) { + this.result = result; + this.updateDirection(); + } + + for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) { + this.intersectBody(bodies[i]); + } + } + /** + * Updates the direction vector. + */ + + updateDirection() { + this.to.vsub(this.from, this.direction); + this.direction.normalize(); + } + + intersectShape(shape, quat, position, body) { + const from = this.from; // Checking boundingSphere + + const distance = distanceFromIntersection(from, this.direction, position); + + if (distance > shape.boundingSphereRadius) { + return; + } + + const intersectMethod = this[shape.type]; + + if (intersectMethod) { + intersectMethod.call(this, shape, quat, position, body, shape); + } + } + + _intersectBox(box, quat, position, body, reportedShape) { + return this._intersectConvex( + box.convexPolyhedronRepresentation, + quat, + position, + body, + reportedShape + ); + } + + _intersectPlane(shape, quat, position, body, reportedShape) { + const from = this.from; + const to = this.to; + const direction = this.direction; // Get plane normal + + const worldNormal = new Vec3(0, 0, 1); + quat.vmult(worldNormal, worldNormal); + const len = new Vec3(); + from.vsub(position, len); + const planeToFrom = len.dot(worldNormal); + to.vsub(position, len); + const planeToTo = len.dot(worldNormal); + + if (planeToFrom * planeToTo > 0) { + // "from" and "to" are on the same side of the plane... bail out + return; + } + + if (from.distanceTo(to) < planeToFrom) { + return; + } + + const n_dot_dir = worldNormal.dot(direction); + + if (Math.abs(n_dot_dir) < this.precision) { + // No intersection + return; + } + + const planePointToFrom = new Vec3(); + const dir_scaled_with_t = new Vec3(); + const hitPointWorld = new Vec3(); + from.vsub(position, planePointToFrom); + const t = -worldNormal.dot(planePointToFrom) / n_dot_dir; + direction.scale(t, dir_scaled_with_t); + from.vadd(dir_scaled_with_t, hitPointWorld); + this.reportIntersection( + worldNormal, + hitPointWorld, + reportedShape, + body, + -1 + ); + } + /** + * Get the world AABB of the ray. + */ + + getAABB(aabb) { + const { lowerBound, upperBound } = aabb; + const to = this.to; + const from = this.from; + lowerBound.x = Math.min(to.x, from.x); + lowerBound.y = Math.min(to.y, from.y); + lowerBound.z = Math.min(to.z, from.z); + upperBound.x = Math.max(to.x, from.x); + upperBound.y = Math.max(to.y, from.y); + upperBound.z = Math.max(to.z, from.z); + } + + _intersectHeightfield(shape, quat, position, body, reportedShape) { + shape.data; + shape.elementSize; // Convert the ray to local heightfield coordinates + + const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to); + + localRay.from.copy(this.from); + localRay.to.copy(this.to); + Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from); + Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to); + localRay.updateDirection(); // Get the index of the data points to test against + + const index = intersectHeightfield_index; + let iMinX; + let iMinY; + let iMaxX; + let iMaxY; // Set to max + + iMinX = iMinY = 0; + iMaxX = iMaxY = shape.data.length - 1; + const aabb = new AABB(); + localRay.getAABB(aabb); + shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true); + iMinX = Math.max(iMinX, index[0]); + iMinY = Math.max(iMinY, index[1]); + shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true); + iMaxX = Math.min(iMaxX, index[0] + 1); + iMaxY = Math.min(iMaxY, index[1] + 1); + + for (let i = iMinX; i < iMaxX; i++) { + for (let j = iMinY; j < iMaxY; j++) { + if (this.result.shouldStop) { + return; + } + + shape.getAabbAtIndex(i, j, aabb); + + if (!aabb.overlapsRay(localRay)) { + continue; + } // Lower triangle + + shape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame( + position, + quat, + shape.pillarOffset, + worldPillarOffset + ); + + this._intersectConvex( + shape.pillarConvex, + quat, + worldPillarOffset, + body, + reportedShape, + intersectConvexOptions + ); + + if (this.result.shouldStop) { + return; + } // Upper triangle + + shape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame( + position, + quat, + shape.pillarOffset, + worldPillarOffset + ); + + this._intersectConvex( + shape.pillarConvex, + quat, + worldPillarOffset, + body, + reportedShape, + intersectConvexOptions + ); + } + } + } + + _intersectSphere(sphere, quat, position, body, reportedShape) { + const from = this.from; + const to = this.to; + const r = sphere.radius; + const a = + (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2; + const b = + 2 * + ((to.x - from.x) * (from.x - position.x) + + (to.y - from.y) * (from.y - position.y) + + (to.z - from.z) * (from.z - position.z)); + const c = + (from.x - position.x) ** 2 + + (from.y - position.y) ** 2 + + (from.z - position.z) ** 2 - + r ** 2; + const delta = b ** 2 - 4 * a * c; + const intersectionPoint = Ray_intersectSphere_intersectionPoint; + const normal = Ray_intersectSphere_normal; + + if (delta < 0) { + // No intersection + return; + } else if (delta === 0) { + // single intersection point + from.lerp(to, delta, intersectionPoint); + intersectionPoint.vsub(position, normal); + normal.normalize(); + this.reportIntersection( + normal, + intersectionPoint, + reportedShape, + body, + -1 + ); + } else { + const d1 = (-b - Math.sqrt(delta)) / (2 * a); + const d2 = (-b + Math.sqrt(delta)) / (2 * a); + + if (d1 >= 0 && d1 <= 1) { + from.lerp(to, d1, intersectionPoint); + intersectionPoint.vsub(position, normal); + normal.normalize(); + this.reportIntersection( + normal, + intersectionPoint, + reportedShape, + body, + -1 + ); + } + + if (this.result.shouldStop) { + return; + } + + if (d2 >= 0 && d2 <= 1) { + from.lerp(to, d2, intersectionPoint); + intersectionPoint.vsub(position, normal); + normal.normalize(); + this.reportIntersection( + normal, + intersectionPoint, + reportedShape, + body, + -1 + ); + } + } + } + + _intersectConvex(shape, quat, position, body, reportedShape, options) { + const normal = intersectConvex_normal; + const vector = intersectConvex_vector; + const faceList = (options && options.faceList) || null; // Checking faces + + const faces = shape.faces; + const vertices = shape.vertices; + const normals = shape.faceNormals; + const direction = this.direction; + const from = this.from; + const to = this.to; + const fromToDistance = from.distanceTo(to); + const Nfaces = faceList ? faceList.length : faces.length; + const result = this.result; + + for (let j = 0; !result.shouldStop && j < Nfaces; j++) { + const fi = faceList ? faceList[j] : j; + const face = faces[fi]; + const faceNormal = normals[fi]; + const q = quat; + const x = position; // determine if ray intersects the plane of the face + // note: this works regardless of the direction of the face normal + // Get plane point in world coordinates... + + vector.copy(vertices[face[0]]); + q.vmult(vector, vector); + vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later. + + vector.vsub(from, vector); // Get plane normal + + q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting + + const dot = direction.dot(normal); // Bail out if ray and plane are parallel + + if (Math.abs(dot) < this.precision) { + continue; + } // calc distance to plane + + const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray + + if (scalar < 0) { + continue; + } // if (dot < 0) { + // Intersection point is from + direction * scalar + + direction.scale(scalar, intersectPoint); + intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with. + + a.copy(vertices[face[0]]); + q.vmult(a, a); + x.vadd(a, a); + + for (let i = 1; !result.shouldStop && i < face.length - 1; i++) { + // Transform 3 vertices to world coords + b.copy(vertices[face[i]]); + c.copy(vertices[face[i + 1]]); + q.vmult(b, b); + q.vmult(c, c); + x.vadd(b, b); + x.vadd(c, c); + const distance = intersectPoint.distanceTo(from); + + if ( + !( + Ray.pointInTriangle(intersectPoint, a, b, c) || + Ray.pointInTriangle(intersectPoint, b, a, c) + ) || + distance > fromToDistance + ) { + continue; + } + + this.reportIntersection( + normal, + intersectPoint, + reportedShape, + body, + fi + ); + } // } + } + } + /** + * @todo Optimize by transforming the world to local space first. + * @todo Use Octree lookup + */ + + _intersectTrimesh(mesh, quat, position, body, reportedShape, options) { + const normal = intersectTrimesh_normal; + const triangles = intersectTrimesh_triangles; + const treeTransform = intersectTrimesh_treeTransform; + const vector = intersectConvex_vector; + const localDirection = intersectTrimesh_localDirection; + const localFrom = intersectTrimesh_localFrom; + const localTo = intersectTrimesh_localTo; + const worldIntersectPoint = intersectTrimesh_worldIntersectPoint; + const worldNormal = intersectTrimesh_worldNormal; // Checking faces + + const indices = mesh.indices; + mesh.vertices; // const normals = mesh.faceNormals + + const from = this.from; + const to = this.to; + const direction = this.direction; + treeTransform.position.copy(position); + treeTransform.quaternion.copy(quat); // Transform ray to local space! + + Transform.vectorToLocalFrame(position, quat, direction, localDirection); + Transform.pointToLocalFrame(position, quat, from, localFrom); + Transform.pointToLocalFrame(position, quat, to, localTo); + localTo.x *= mesh.scale.x; + localTo.y *= mesh.scale.y; + localTo.z *= mesh.scale.z; + localFrom.x *= mesh.scale.x; + localFrom.y *= mesh.scale.y; + localFrom.z *= mesh.scale.z; + localTo.vsub(localFrom, localDirection); + localDirection.normalize(); + const fromToDistanceSquared = localFrom.distanceSquared(localTo); + mesh.tree.rayQuery(this, treeTransform, triangles); + + for ( + let i = 0, N = triangles.length; + !this.result.shouldStop && i !== N; + i++ + ) { + const trianglesIndex = triangles[i]; + mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face + // note: this works regardless of the direction of the face normal + // Get plane point in world coordinates... + + mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later. + + a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting + + const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel + // if (Math.abs( dot ) < this.precision){ + // continue; + // } + // calc distance to plane + + const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray + + if (scalar < 0) { + continue; + } // Intersection point is from + direction * scalar + + localDirection.scale(scalar, intersectPoint); + intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices + + mesh.getVertex(indices[trianglesIndex * 3 + 1], b); + mesh.getVertex(indices[trianglesIndex * 3 + 2], c); + const squaredDistance = intersectPoint.distanceSquared(localFrom); + + if ( + !( + Ray.pointInTriangle(intersectPoint, b, a, c) || + Ray.pointInTriangle(intersectPoint, a, b, c) + ) || + squaredDistance > fromToDistanceSquared + ) { + continue; + } // transform intersectpoint and normal to world + + Transform.vectorToWorldFrame(quat, normal, worldNormal); + Transform.pointToWorldFrame( + position, + quat, + intersectPoint, + worldIntersectPoint + ); + this.reportIntersection( + worldNormal, + worldIntersectPoint, + reportedShape, + body, + trianglesIndex + ); + } + + triangles.length = 0; + } + /** + * @return True if the intersections should continue + */ + + reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) { + const from = this.from; + const to = this.to; + const distance = from.distanceTo(hitPointWorld); + const result = this.result; // Skip back faces? + + if (this.skipBackfaces && normal.dot(this.direction) > 0) { + return; + } + + result.hitFaceIndex = + typeof hitFaceIndex !== "undefined" ? hitFaceIndex : -1; + + switch (this.mode) { + case Ray.ALL: + this.hasHit = true; + result.set(from, to, normal, hitPointWorld, shape, body, distance); + result.hasHit = true; + this.callback(result); + break; + + case Ray.CLOSEST: + // Store if closer than current closest + if (distance < result.distance || !result.hasHit) { + this.hasHit = true; + result.hasHit = true; + result.set(from, to, normal, hitPointWorld, shape, body, distance); + } + + break; + + case Ray.ANY: + // Report and stop. + this.hasHit = true; + result.hasHit = true; + result.set(from, to, normal, hitPointWorld, shape, body, distance); + result.shouldStop = true; + break; + } + } + /** + * As per "Barycentric Technique" as named + * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division + */ + + static pointInTriangle(p, a, b, c) { + c.vsub(a, v0); + b.vsub(a, v1); + p.vsub(a, v2); + const dot00 = v0.dot(v0); + const dot01 = v0.dot(v1); + const dot02 = v0.dot(v2); + const dot11 = v1.dot(v1); + const dot12 = v1.dot(v2); + let u; + let v; + return ( + (u = dot11 * dot02 - dot01 * dot12) >= 0 && + (v = dot00 * dot12 - dot01 * dot02) >= 0 && + u + v < dot00 * dot11 - dot01 * dot01 + ); + } + } + Ray.CLOSEST = RAY_MODES.CLOSEST; + Ray.ANY = RAY_MODES.ANY; + Ray.ALL = RAY_MODES.ALL; + const tmpAABB$1 = new AABB(); + const tmpArray = []; + const v1 = new Vec3(); + const v2 = new Vec3(); + const intersectBody_xi = new Vec3(); + const intersectBody_qi = new Quaternion(); + const intersectPoint = new Vec3(); + const a = new Vec3(); + const b = new Vec3(); + const c = new Vec3(); + new Vec3(); + new RaycastResult(); + const intersectConvexOptions = { + faceList: [0], + }; + const worldPillarOffset = new Vec3(); + const intersectHeightfield_localRay = new Ray(); + const intersectHeightfield_index = []; + const Ray_intersectSphere_intersectionPoint = new Vec3(); + const Ray_intersectSphere_normal = new Vec3(); + const intersectConvex_normal = new Vec3(); + new Vec3(); + new Vec3(); + const intersectConvex_vector = new Vec3(); + const intersectTrimesh_normal = new Vec3(); + const intersectTrimesh_localDirection = new Vec3(); + const intersectTrimesh_localFrom = new Vec3(); + const intersectTrimesh_localTo = new Vec3(); + const intersectTrimesh_worldNormal = new Vec3(); + const intersectTrimesh_worldIntersectPoint = new Vec3(); + new AABB(); + const intersectTrimesh_triangles = []; + const intersectTrimesh_treeTransform = new Transform(); + const v0 = new Vec3(); + const intersect = new Vec3(); + + function distanceFromIntersection(from, direction, position) { + // v0 is vector from from to position + position.vsub(from, v0); + const dot = v0.dot(direction); // intersect = direction*dot + from + + direction.scale(dot, intersect); + intersect.vadd(from, intersect); + const distance = position.distanceTo(intersect); + return distance; + } + + /** + * Sweep and prune broadphase along one axis. + */ + class SAPBroadphase extends Broadphase { + /** + * List of bodies currently in the broadphase. + */ + + /** + * The world to search in. + */ + + /** + * Axis to sort the bodies along. + * Set to 0 for x axis, and 1 for y axis. + * For best performance, pick the axis where bodies are most distributed. + */ + + /** + * Check if the bounds of two bodies overlap, along the given SAP axis. + */ + static checkBounds(bi, bj, axisIndex) { + let biPos; + let bjPos; + + if (axisIndex === 0) { + biPos = bi.position.x; + bjPos = bj.position.x; + } else if (axisIndex === 1) { + biPos = bi.position.y; + bjPos = bj.position.y; + } else if (axisIndex === 2) { + biPos = bi.position.z; + bjPos = bj.position.z; + } + + const ri = bi.boundingRadius, + rj = bj.boundingRadius, + boundA2 = biPos + ri, + boundB1 = bjPos - rj; + return boundB1 < boundA2; + } // Note: these are identical, save for x/y/z lowerbound + + /** + * insertionSortX + */ + + static insertionSortX(a) { + for (let i = 1, l = a.length; i < l; i++) { + const v = a[i]; + let j; + + for (j = i - 1; j >= 0; j--) { + if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) { + break; + } + + a[j + 1] = a[j]; + } + + a[j + 1] = v; + } + + return a; + } + /** + * insertionSortY + */ + + static insertionSortY(a) { + for (let i = 1, l = a.length; i < l; i++) { + const v = a[i]; + let j; + + for (j = i - 1; j >= 0; j--) { + if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) { + break; + } + + a[j + 1] = a[j]; + } + + a[j + 1] = v; + } + + return a; + } + /** + * insertionSortZ + */ + + static insertionSortZ(a) { + for (let i = 1, l = a.length; i < l; i++) { + const v = a[i]; + let j; + + for (j = i - 1; j >= 0; j--) { + if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) { + break; + } + + a[j + 1] = a[j]; + } + + a[j + 1] = v; + } + + return a; + } + + constructor(world) { + super(); + this.axisList = []; + this.world = null; + this.axisIndex = 0; + const axisList = this.axisList; + + this._addBodyHandler = (event) => { + axisList.push(event.body); + }; + + this._removeBodyHandler = (event) => { + const idx = axisList.indexOf(event.body); + + if (idx !== -1) { + axisList.splice(idx, 1); + } + }; + + if (world) { + this.setWorld(world); + } + } + /** + * Change the world + */ + + setWorld(world) { + // Clear the old axis array + this.axisList.length = 0; // Add all bodies from the new world + + for (let i = 0; i < world.bodies.length; i++) { + this.axisList.push(world.bodies[i]); + } // Remove old handlers, if any + + world.removeEventListener("addBody", this._addBodyHandler); + world.removeEventListener("removeBody", this._removeBodyHandler); // Add handlers to update the list of bodies. + + world.addEventListener("addBody", this._addBodyHandler); + world.addEventListener("removeBody", this._removeBodyHandler); + this.world = world; + this.dirty = true; + } + /** + * Collect all collision pairs + */ + + collisionPairs(world, p1, p2) { + const bodies = this.axisList; + const N = bodies.length; + const axisIndex = this.axisIndex; + let i; + let j; + + if (this.dirty) { + this.sortList(); + this.dirty = false; + } // Look through the list + + for (i = 0; i !== N; i++) { + const bi = bodies[i]; + + for (j = i + 1; j < N; j++) { + const bj = bodies[j]; + + if (!this.needBroadphaseCollision(bi, bj)) { + continue; + } + + if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) { + break; + } + + this.intersectionTest(bi, bj, p1, p2); + } + } + } + + sortList() { + const axisList = this.axisList; + const axisIndex = this.axisIndex; + const N = axisList.length; // Update AABBs + + for (let i = 0; i !== N; i++) { + const bi = axisList[i]; + + if (bi.aabbNeedsUpdate) { + bi.updateAABB(); + } + } // Sort the list + + if (axisIndex === 0) { + SAPBroadphase.insertionSortX(axisList); + } else if (axisIndex === 1) { + SAPBroadphase.insertionSortY(axisList); + } else if (axisIndex === 2) { + SAPBroadphase.insertionSortZ(axisList); + } + } + /** + * Computes the variance of the body positions and estimates the best axis to use. + * Will automatically set property `axisIndex`. + */ + + autoDetectAxis() { + let sumX = 0; + let sumX2 = 0; + let sumY = 0; + let sumY2 = 0; + let sumZ = 0; + let sumZ2 = 0; + const bodies = this.axisList; + const N = bodies.length; + const invN = 1 / N; + + for (let i = 0; i !== N; i++) { + const b = bodies[i]; + const centerX = b.position.x; + sumX += centerX; + sumX2 += centerX * centerX; + const centerY = b.position.y; + sumY += centerY; + sumY2 += centerY * centerY; + const centerZ = b.position.z; + sumZ += centerZ; + sumZ2 += centerZ * centerZ; + } + + const varianceX = sumX2 - sumX * sumX * invN; + const varianceY = sumY2 - sumY * sumY * invN; + const varianceZ = sumZ2 - sumZ * sumZ * invN; + + if (varianceX > varianceY) { + if (varianceX > varianceZ) { + this.axisIndex = 0; + } else { + this.axisIndex = 2; + } + } else if (varianceY > varianceZ) { + this.axisIndex = 1; + } else { + this.axisIndex = 2; + } + } + /** + * Returns all the bodies within an AABB. + * @param result An array to store resulting bodies in. + */ + + aabbQuery(world, aabb, result) { + if (result === void 0) { + result = []; + } + + if (this.dirty) { + this.sortList(); + this.dirty = false; + } + + const axisIndex = this.axisIndex; + let axis = "x"; + + if (axisIndex === 1) { + axis = "y"; + } + + if (axisIndex === 2) { + axis = "z"; + } + + const axisList = this.axisList; + aabb.lowerBound[axis]; + aabb.upperBound[axis]; + + for (let i = 0; i < axisList.length; i++) { + const b = axisList[i]; + + if (b.aabbNeedsUpdate) { + b.updateAABB(); + } + + if (b.aabb.overlaps(aabb)) { + result.push(b); + } + } + + return result; + } + } + + class Utils { + /** + * Extend an options object with default values. + * @param options The options object. May be falsy: in this case, a new object is created and returned. + * @param defaults An object containing default values. + * @return The modified options object. + */ + static defaults(options, defaults) { + if (options === void 0) { + options = {}; + } + + for (let key in defaults) { + if (!(key in options)) { + options[key] = defaults[key]; + } + } + + return options; + } + } + + /** + * Constraint base class + */ + class Constraint { + /** + * Equations to be solved in this constraint. + */ + + /** + * Body A. + */ + + /** + * Body B. + */ + + /** + * Set to false if you don't want the bodies to collide when they are connected. + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + options = Utils.defaults(options, { + collideConnected: true, + wakeUpBodies: true, + }); + this.equations = []; + this.bodyA = bodyA; + this.bodyB = bodyB; + this.id = Constraint.idCounter++; + this.collideConnected = options.collideConnected; + + if (options.wakeUpBodies) { + if (bodyA) { + bodyA.wakeUp(); + } + + if (bodyB) { + bodyB.wakeUp(); + } + } + } + /** + * Update all the equations with data. + */ + + update() { + throw new Error( + "method update() not implmemented in this Constraint subclass!" + ); + } + /** + * Enables all equations in the constraint. + */ + + enable() { + const eqs = this.equations; + + for (let i = 0; i < eqs.length; i++) { + eqs[i].enabled = true; + } + } + /** + * Disables all equations in the constraint. + */ + + disable() { + const eqs = this.equations; + + for (let i = 0; i < eqs.length; i++) { + eqs[i].enabled = false; + } + } + } + Constraint.idCounter = 0; + + /** + * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom. + */ + + class JacobianElement { + /** + * spatial + */ + + /** + * rotational + */ + constructor() { + this.spatial = new Vec3(); + this.rotational = new Vec3(); + } + /** + * Multiply with other JacobianElement + */ + + multiplyElement(element) { + return ( + element.spatial.dot(this.spatial) + + element.rotational.dot(this.rotational) + ); + } + /** + * Multiply with two vectors + */ + + multiplyVectors(spatial, rotational) { + return spatial.dot(this.spatial) + rotational.dot(this.rotational); + } + } + + /** + * Equation base class. + * + * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation. + */ + class Equation { + /** + * Minimum (read: negative max) force to be applied by the constraint. + */ + + /** + * Maximum (read: positive max) force to be applied by the constraint. + */ + + /** + * SPOOK parameter + */ + + /** + * SPOOK parameter + */ + + /** + * SPOOK parameter + */ + + /** + * A number, proportional to the force added to the bodies. + */ + constructor(bi, bj, minForce, maxForce) { + if (minForce === void 0) { + minForce = -1e6; + } + + if (maxForce === void 0) { + maxForce = 1e6; + } + + this.id = Equation.idCounter++; + this.minForce = minForce; + this.maxForce = maxForce; + this.bi = bi; + this.bj = bj; + this.a = 0.0; // SPOOK parameter + + this.b = 0.0; // SPOOK parameter + + this.eps = 0.0; // SPOOK parameter + + this.jacobianElementA = new JacobianElement(); + this.jacobianElementB = new JacobianElement(); + this.enabled = true; + this.multiplier = 0; + this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params + } + /** + * Recalculates a, b, and eps. + * + * The Equation constructor sets typical SPOOK parameters as such: + * * `stiffness` = 1e7 + * * `relaxation` = 4 + * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._ + */ + + setSpookParams(stiffness, relaxation, timeStep) { + const d = relaxation; + const k = stiffness; + const h = timeStep; + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.eps = 4.0 / (h * h * k * (1 + 4 * d)); + } + /** + * Computes the right hand side of the SPOOK equation + */ + + computeB(a, b, h) { + const GW = this.computeGW(); + const Gq = this.computeGq(); + const GiMf = this.computeGiMf(); + return -Gq * a - GW * b - GiMf * h; + } + /** + * Computes G*q, where q are the generalized body coordinates + */ + + computeGq() { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const xi = bi.position; + const xj = bj.position; + return GA.spatial.dot(xi) + GB.spatial.dot(xj); + } + /** + * Computes G*W, where W are the body velocities + */ + + computeGW() { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const vi = bi.velocity; + const vj = bj.velocity; + const wi = bi.angularVelocity; + const wj = bj.angularVelocity; + return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj); + } + /** + * Computes G*Wlambda, where W are the body velocities + */ + + computeGWlambda() { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const vi = bi.vlambda; + const vj = bj.vlambda; + const wi = bi.wlambda; + const wj = bj.wlambda; + return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj); + } + /** + * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + */ + + computeGiMf() { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const fi = bi.force; + const ti = bi.torque; + const fj = bj.force; + const tj = bj.torque; + const invMassi = bi.invMassSolve; + const invMassj = bj.invMassSolve; + fi.scale(invMassi, iMfi); + fj.scale(invMassj, iMfj); + bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui); + bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj); + return ( + GA.multiplyVectors(iMfi, invIi_vmult_taui) + + GB.multiplyVectors(iMfj, invIj_vmult_tauj) + ); + } + /** + * Computes G*inv(M)*G' + */ + + computeGiMGt() { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const invMassi = bi.invMassSolve; + const invMassj = bj.invMassSolve; + const invIi = bi.invInertiaWorldSolve; + const invIj = bj.invInertiaWorldSolve; + let result = invMassi + invMassj; + invIi.vmult(GA.rotational, tmp); + result += tmp.dot(GA.rotational); + invIj.vmult(GB.rotational, tmp); + result += tmp.dot(GB.rotational); + return result; + } + /** + * Add constraint velocity to the bodies. + */ + + addToWlambda(deltalambda) { + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const bi = this.bi; + const bj = this.bj; + const temp = addToWlambda_temp; // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + + bi.vlambda.addScaledVector( + bi.invMassSolve * deltalambda, + GA.spatial, + bi.vlambda + ); + bj.vlambda.addScaledVector( + bj.invMassSolve * deltalambda, + GB.spatial, + bj.vlambda + ); // Add to angular velocity + + bi.invInertiaWorldSolve.vmult(GA.rotational, temp); + bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda); + bj.invInertiaWorldSolve.vmult(GB.rotational, temp); + bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda); + } + /** + * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps + */ + + computeC() { + return this.computeGiMGt() + this.eps; + } + } + Equation.idCounter = 0; + const iMfi = new Vec3(); + const iMfj = new Vec3(); + const invIi_vmult_taui = new Vec3(); + const invIj_vmult_tauj = new Vec3(); + const tmp = new Vec3(); + const addToWlambda_temp = new Vec3(); + + /** + * Contact/non-penetration constraint equation + */ + class ContactEquation extends Equation { + /** + * "bounciness": u1 = -e*u0 + */ + + /** + * World-oriented vector that goes from the center of bi to the contact point. + */ + + /** + * World-oriented vector that starts in body j position and goes to the contact point. + */ + + /** + * Contact normal, pointing out of body i. + */ + constructor(bodyA, bodyB, maxForce) { + if (maxForce === void 0) { + maxForce = 1e6; + } + + super(bodyA, bodyB, 0, maxForce); + this.restitution = 0.0; + this.ri = new Vec3(); + this.rj = new Vec3(); + this.ni = new Vec3(); + } + + computeB(h) { + const a = this.a; + const b = this.b; + const bi = this.bi; + const bj = this.bj; + const ri = this.ri; + const rj = this.rj; + const rixn = ContactEquation_computeB_temp1; + const rjxn = ContactEquation_computeB_temp2; + const vi = bi.velocity; + const wi = bi.angularVelocity; + bi.force; + bi.torque; + const vj = bj.velocity; + const wj = bj.angularVelocity; + bj.force; + bj.torque; + const penetrationVec = ContactEquation_computeB_temp3; + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + const n = this.ni; // Caluclate cross products + + ri.cross(n, rixn); + rj.cross(n, rjxn); // g = xj+rj -(xi+ri) + // G = [ -ni -rixn ni rjxn ] + + n.negate(GA.spatial); + rixn.negate(GA.rotational); + GB.spatial.copy(n); + GB.rotational.copy(rjxn); // Calculate the penetration vector + + penetrationVec.copy(bj.position); + penetrationVec.vadd(rj, penetrationVec); + penetrationVec.vsub(bi.position, penetrationVec); + penetrationVec.vsub(ri, penetrationVec); + const g = n.dot(penetrationVec); // Compute iteration + + const ePlusOne = this.restitution + 1; + const GW = + ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn); + const GiMf = this.computeGiMf(); + const B = -g * a - GW * b - h * GiMf; + return B; + } + /** + * Get the current relative velocity in the contact point. + */ + + getImpactVelocityAlongNormal() { + const vi = ContactEquation_getImpactVelocityAlongNormal_vi; + const vj = ContactEquation_getImpactVelocityAlongNormal_vj; + const xi = ContactEquation_getImpactVelocityAlongNormal_xi; + const xj = ContactEquation_getImpactVelocityAlongNormal_xj; + const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel; + this.bi.position.vadd(this.ri, xi); + this.bj.position.vadd(this.rj, xj); + this.bi.getVelocityAtWorldPoint(xi, vi); + this.bj.getVelocityAtWorldPoint(xj, vj); + vi.vsub(vj, relVel); + return this.ni.dot(relVel); + } + } + const ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors + + const ContactEquation_computeB_temp2 = new Vec3(); + const ContactEquation_computeB_temp3 = new Vec3(); + const ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3(); + const ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3(); + const ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3(); + const ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3(); + const ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3(); + + /** + * Connects two bodies at given offset points. + * @example + * const bodyA = new Body({ mass: 1 }) + * const bodyB = new Body({ mass: 1 }) + * bodyA.position.set(-1, 0, 0) + * bodyB.position.set(1, 0, 0) + * bodyA.addShape(shapeA) + * bodyB.addShape(shapeB) + * world.addBody(bodyA) + * world.addBody(bodyB) + * const localPivotA = new Vec3(1, 0, 0) + * const localPivotB = new Vec3(-1, 0, 0) + * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB) + * world.addConstraint(constraint) + */ + class PointToPointConstraint extends Constraint { + /** + * Pivot, defined locally in bodyA. + */ + + /** + * Pivot, defined locally in bodyB. + */ + + /** + * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point. + * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to. + * @param maxForce The maximum force that should be applied to constrain the bodies. + */ + constructor(bodyA, pivotA, bodyB, pivotB, maxForce) { + if (pivotA === void 0) { + pivotA = new Vec3(); + } + + if (pivotB === void 0) { + pivotB = new Vec3(); + } + + if (maxForce === void 0) { + maxForce = 1e6; + } + + super(bodyA, bodyB); + this.pivotA = pivotA.clone(); + this.pivotB = pivotB.clone(); + const x = (this.equationX = new ContactEquation(bodyA, bodyB)); + const y = (this.equationY = new ContactEquation(bodyA, bodyB)); + const z = (this.equationZ = new ContactEquation(bodyA, bodyB)); // Equations to be fed to the solver + + this.equations.push(x, y, z); // Make the equations bidirectional + + x.minForce = y.minForce = z.minForce = -maxForce; + x.maxForce = y.maxForce = z.maxForce = maxForce; + x.ni.set(1, 0, 0); + y.ni.set(0, 1, 0); + z.ni.set(0, 0, 1); + } + + update() { + const bodyA = this.bodyA; + const bodyB = this.bodyB; + const x = this.equationX; + const y = this.equationY; + const z = this.equationZ; // Rotate the pivots to world space + + bodyA.quaternion.vmult(this.pivotA, x.ri); + bodyB.quaternion.vmult(this.pivotB, x.rj); + y.ri.copy(x.ri); + y.rj.copy(x.rj); + z.ri.copy(x.ri); + z.rj.copy(x.rj); + } + } + + /** + * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other. + */ + class ConeEquation extends Equation { + /** + * Local axis in A + */ + + /** + * Local axis in B + */ + + /** + * The "cone angle" to keep + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + const maxForce = + typeof options.maxForce !== "undefined" ? options.maxForce : 1e6; + super(bodyA, bodyB, -maxForce, maxForce); + this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0); + this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0); + this.angle = typeof options.angle !== "undefined" ? options.angle : 0; + } + + computeB(h) { + const a = this.a; + const b = this.b; + const ni = this.axisA; + const nj = this.axisB; + const nixnj = tmpVec1$2; + const njxni = tmpVec2$2; + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; // Caluclate cross products + + ni.cross(nj, nixnj); + nj.cross(ni, njxni); // The angle between two vector is: + // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b + // g = a * b + // gdot = (b x a) * wi + (a x b) * wj + // G = [0 bxa 0 axb] + // W = [vi wi vj wj] + + GA.rotational.copy(njxni); + GB.rotational.copy(nixnj); + const g = Math.cos(this.angle) - ni.dot(nj); + const GW = this.computeGW(); + const GiMf = this.computeGiMf(); + const B = -g * a - GW * b - h * GiMf; + return B; + } + } + const tmpVec1$2 = new Vec3(); + const tmpVec2$2 = new Vec3(); + + /** + * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space. + */ + class RotationalEquation extends Equation { + /** + * World oriented rotational axis. + */ + + /** + * World oriented rotational axis. + */ + + /** + * maxAngle + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + const maxForce = + typeof options.maxForce !== "undefined" ? options.maxForce : 1e6; + super(bodyA, bodyB, -maxForce, maxForce); + this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0); + this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0); + this.maxAngle = Math.PI / 2; + } + + computeB(h) { + const a = this.a; + const b = this.b; + const ni = this.axisA; + const nj = this.axisB; + const nixnj = tmpVec1$1; + const njxni = tmpVec2$1; + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; // Caluclate cross products + + ni.cross(nj, nixnj); + nj.cross(ni, njxni); // g = ni * nj + // gdot = (nj x ni) * wi + (ni x nj) * wj + // G = [0 njxni 0 nixnj] + // W = [vi wi vj wj] + + GA.rotational.copy(njxni); + GB.rotational.copy(nixnj); + const g = Math.cos(this.maxAngle) - ni.dot(nj); + const GW = this.computeGW(); + const GiMf = this.computeGiMf(); + const B = -g * a - GW * b - h * GiMf; + return B; + } + } + const tmpVec1$1 = new Vec3(); + const tmpVec2$1 = new Vec3(); + + /** + * A Cone Twist constraint, useful for ragdolls. + */ + class ConeTwistConstraint extends PointToPointConstraint { + /** + * The axis direction for the constraint of the body A. + */ + + /** + * The axis direction for the constraint of the body B. + */ + + /** + * The aperture angle of the cone. + */ + + /** + * The twist angle of the joint. + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + const maxForce = + typeof options.maxForce !== "undefined" ? options.maxForce : 1e6; // Set pivot point in between + + const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3(); + const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3(); + super(bodyA, pivotA, bodyB, pivotB, maxForce); + this.axisA = options.axisA ? options.axisA.clone() : new Vec3(); + this.axisB = options.axisB ? options.axisB.clone() : new Vec3(); + this.collideConnected = !!options.collideConnected; + this.angle = typeof options.angle !== "undefined" ? options.angle : 0; + const c = (this.coneEquation = new ConeEquation(bodyA, bodyB, options)); + const t = (this.twistEquation = new RotationalEquation( + bodyA, + bodyB, + options + )); + this.twistAngle = + typeof options.twistAngle !== "undefined" ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward + + c.maxForce = 0; + c.minForce = -maxForce; // Make the twist equation add torque toward the initial position + + t.maxForce = 0; + t.minForce = -maxForce; + this.equations.push(c, t); + } + + update() { + const bodyA = this.bodyA; + const bodyB = this.bodyB; + const cone = this.coneEquation; + const twist = this.twistEquation; + super.update(); // Update the axes to the cone constraint + + bodyA.vectorToWorldFrame(this.axisA, cone.axisA); + bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint + + this.axisA.tangents(twist.axisA, twist.axisA); + bodyA.vectorToWorldFrame(twist.axisA, twist.axisA); + this.axisB.tangents(twist.axisB, twist.axisB); + bodyB.vectorToWorldFrame(twist.axisB, twist.axisB); + cone.angle = this.angle; + twist.maxAngle = this.twistAngle; + } + } + new Vec3(); + new Vec3(); + + /** + * Constrains two bodies to be at a constant distance from each others center of mass. + */ + class DistanceConstraint extends Constraint { + /** + * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB + */ + + /** + * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB. + * @param maxForce The maximum force that should be applied to constrain the bodies. + */ + constructor(bodyA, bodyB, distance, maxForce) { + if (maxForce === void 0) { + maxForce = 1e6; + } + + super(bodyA, bodyB); + + if (typeof distance === "undefined") { + distance = bodyA.position.distanceTo(bodyB.position); + } + + this.distance = distance; + const eq = (this.distanceEquation = new ContactEquation(bodyA, bodyB)); + this.equations.push(eq); // Make it bidirectional + + eq.minForce = -maxForce; + eq.maxForce = maxForce; + } + /** + * update + */ + + update() { + const bodyA = this.bodyA; + const bodyB = this.bodyB; + const eq = this.distanceEquation; + const halfDist = this.distance * 0.5; + const normal = eq.ni; + bodyB.position.vsub(bodyA.position, normal); + normal.normalize(); + normal.scale(halfDist, eq.ri); + normal.scale(-halfDist, eq.rj); + } + } + + /** + * Lock constraint. Will remove all degrees of freedom between the bodies. + */ + class LockConstraint extends PointToPointConstraint { + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + const maxForce = + typeof options.maxForce !== "undefined" ? options.maxForce : 1e6; // Set pivot point in between + + const pivotA = new Vec3(); + const pivotB = new Vec3(); + const halfWay = new Vec3(); + bodyA.position.vadd(bodyB.position, halfWay); + halfWay.scale(0.5, halfWay); + bodyB.pointToLocalFrame(halfWay, pivotB); + bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies + + super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces + + this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X); + this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X); + this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y); + this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y); + this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z); + this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place + + const r1 = (this.rotationalEquation1 = new RotationalEquation( + bodyA, + bodyB, + options + )); + const r2 = (this.rotationalEquation2 = new RotationalEquation( + bodyA, + bodyB, + options + )); + const r3 = (this.rotationalEquation3 = new RotationalEquation( + bodyA, + bodyB, + options + )); + this.equations.push(r1, r2, r3); + } + /** + * update + */ + + update() { + const bodyA = this.bodyA; + const bodyB = this.bodyB; + this.motorEquation; + const r1 = this.rotationalEquation1; + const r2 = this.rotationalEquation2; + const r3 = this.rotationalEquation3; + super.update(); // These vector pairs must be orthogonal + + bodyA.vectorToWorldFrame(this.xA, r1.axisA); + bodyB.vectorToWorldFrame(this.yB, r1.axisB); + bodyA.vectorToWorldFrame(this.yA, r2.axisA); + bodyB.vectorToWorldFrame(this.zB, r2.axisB); + bodyA.vectorToWorldFrame(this.zA, r3.axisA); + bodyB.vectorToWorldFrame(this.xB, r3.axisB); + } + } + new Vec3(); + new Vec3(); + + /** + * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value. + */ + class RotationalMotorEquation extends Equation { + /** + * World oriented rotational axis. + */ + + /** + * World oriented rotational axis. + */ + + /** + * Motor velocity. + */ + constructor(bodyA, bodyB, maxForce) { + if (maxForce === void 0) { + maxForce = 1e6; + } + + super(bodyA, bodyB, -maxForce, maxForce); + this.axisA = new Vec3(); + this.axisB = new Vec3(); + this.targetVelocity = 0; + } + + computeB(h) { + this.a; + const b = this.b; + this.bi; + this.bj; + const axisA = this.axisA; + const axisB = this.axisB; + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; // g = 0 + // gdot = axisA * wi - axisB * wj + // gdot = G * W = G * [vi wi vj wj] + // => + // G = [0 axisA 0 -axisB] + + GA.rotational.copy(axisA); + axisB.negate(GB.rotational); + const GW = this.computeGW() - this.targetVelocity; + const GiMf = this.computeGiMf(); + const B = -GW * b - h * GiMf; + return B; + } + } + + /** + * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation. + */ + class HingeConstraint extends PointToPointConstraint { + /** + * Rotation axis, defined locally in bodyA. + */ + + /** + * Rotation axis, defined locally in bodyB. + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + const maxForce = + typeof options.maxForce !== "undefined" ? options.maxForce : 1e6; + const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3(); + const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3(); + super(bodyA, pivotA, bodyB, pivotB, maxForce); + const axisA = (this.axisA = options.axisA + ? options.axisA.clone() + : new Vec3(1, 0, 0)); + axisA.normalize(); + const axisB = (this.axisB = options.axisB + ? options.axisB.clone() + : new Vec3(1, 0, 0)); + axisB.normalize(); + this.collideConnected = !!options.collideConnected; + const rotational1 = (this.rotationalEquation1 = new RotationalEquation( + bodyA, + bodyB, + options + )); + const rotational2 = (this.rotationalEquation2 = new RotationalEquation( + bodyA, + bodyB, + options + )); + const motor = (this.motorEquation = new RotationalMotorEquation( + bodyA, + bodyB, + maxForce + )); + motor.enabled = false; // Not enabled by default + // Equations to be fed to the solver + + this.equations.push(rotational1, rotational2, motor); + } + /** + * enableMotor + */ + + enableMotor() { + this.motorEquation.enabled = true; + } + /** + * disableMotor + */ + + disableMotor() { + this.motorEquation.enabled = false; + } + /** + * setMotorSpeed + */ + + setMotorSpeed(speed) { + this.motorEquation.targetVelocity = speed; + } + /** + * setMotorMaxForce + */ + + setMotorMaxForce(maxForce) { + this.motorEquation.maxForce = maxForce; + this.motorEquation.minForce = -maxForce; + } + /** + * update + */ + + update() { + const bodyA = this.bodyA; + const bodyB = this.bodyB; + const motor = this.motorEquation; + const r1 = this.rotationalEquation1; + const r2 = this.rotationalEquation2; + const worldAxisA = HingeConstraint_update_tmpVec1; + const worldAxisB = HingeConstraint_update_tmpVec2; + const axisA = this.axisA; + const axisB = this.axisB; + super.update(); // Get world axes + + bodyA.quaternion.vmult(axisA, worldAxisA); + bodyB.quaternion.vmult(axisB, worldAxisB); + worldAxisA.tangents(r1.axisA, r2.axisA); + r1.axisB.copy(worldAxisB); + r2.axisB.copy(worldAxisB); + + if (this.motorEquation.enabled) { + bodyA.quaternion.vmult(this.axisA, motor.axisA); + bodyB.quaternion.vmult(this.axisB, motor.axisB); + } + } + } + const HingeConstraint_update_tmpVec1 = new Vec3(); + const HingeConstraint_update_tmpVec2 = new Vec3(); + + /** + * Constrains the slipping in a contact along a tangent + */ + class FrictionEquation extends Equation { + // Tangent + + /** + * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g + */ + constructor(bodyA, bodyB, slipForce) { + super(bodyA, bodyB, -slipForce, slipForce); + this.ri = new Vec3(); + this.rj = new Vec3(); + this.t = new Vec3(); + } + + computeB(h) { + this.a; + const b = this.b; + this.bi; + this.bj; + const ri = this.ri; + const rj = this.rj; + const rixt = FrictionEquation_computeB_temp1; + const rjxt = FrictionEquation_computeB_temp2; + const t = this.t; // Caluclate cross products + + ri.cross(t, rixt); + rj.cross(t, rjxt); // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + + const GA = this.jacobianElementA; + const GB = this.jacobianElementB; + t.negate(GA.spatial); + rixt.negate(GA.rotational); + GB.spatial.copy(t); + GB.rotational.copy(rjxt); + const GW = this.computeGW(); + const GiMf = this.computeGiMf(); + const B = -GW * b - h * GiMf; + return B; + } + } + const FrictionEquation_computeB_temp1 = new Vec3(); + const FrictionEquation_computeB_temp2 = new Vec3(); + + /** + * Defines what happens when two materials meet. + * @todo Refactor materials to materialA and materialB + */ + class ContactMaterial { + /** + * Identifier of this material. + */ + + /** + * Participating materials. + */ + + /** + * Friction coefficient. + * @default 0.3 + */ + + /** + * Restitution coefficient. + * @default 0.3 + */ + + /** + * Stiffness of the produced contact equations. + * @default 1e7 + */ + + /** + * Relaxation time of the produced contact equations. + * @default 3 + */ + + /** + * Stiffness of the produced friction equations. + * @default 1e7 + */ + + /** + * Relaxation time of the produced friction equations + * @default 3 + */ + constructor(m1, m2, options) { + options = Utils.defaults(options, { + friction: 0.3, + restitution: 0.3, + contactEquationStiffness: 1e7, + contactEquationRelaxation: 3, + frictionEquationStiffness: 1e7, + frictionEquationRelaxation: 3, + }); + this.id = ContactMaterial.idCounter++; + this.materials = [m1, m2]; + this.friction = options.friction; + this.restitution = options.restitution; + this.contactEquationStiffness = options.contactEquationStiffness; + this.contactEquationRelaxation = options.contactEquationRelaxation; + this.frictionEquationStiffness = options.frictionEquationStiffness; + this.frictionEquationRelaxation = options.frictionEquationRelaxation; + } + } + ContactMaterial.idCounter = 0; + + /** + * Defines a physics material. + */ + class Material { + /** + * Material name. + * If options is a string, name will be set to that string. + * @todo Deprecate this + */ + + /** Material id. */ + + /** + * Friction for this material. + * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used. + */ + + /** + * Restitution for this material. + * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used. + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + let name = ""; // Backwards compatibility fix + + if (typeof options === "string") { + //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`) + name = options; + options = {}; + } + + this.name = name; + this.id = Material.idCounter++; + this.friction = + typeof options.friction !== "undefined" ? options.friction : -1; + this.restitution = + typeof options.restitution !== "undefined" ? options.restitution : -1; + } + } + Material.idCounter = 0; + + /** + * A spring, connecting two bodies. + * @example + * const spring = new Spring(boxBody, sphereBody, { + * restLength: 0, + * stiffness: 50, + * damping: 1, + * }) + * + * // Compute the force after each step + * world.addEventListener('postStep', (event) => { + * spring.applyForce() + * }) + */ + class Spring { + /** + * Rest length of the spring. A number > 0. + * @default 1 + */ + + /** + * Stiffness of the spring. A number >= 0. + * @default 100 + */ + + /** + * Damping of the spring. A number >= 0. + * @default 1 + */ + + /** + * First connected body. + */ + + /** + * Second connected body. + */ + + /** + * Anchor for bodyA in local bodyA coordinates. + * Where to hook the spring to body A, in local body coordinates. + * @default new Vec3() + */ + + /** + * Anchor for bodyB in local bodyB coordinates. + * Where to hook the spring to body B, in local body coordinates. + * @default new Vec3() + */ + constructor(bodyA, bodyB, options) { + if (options === void 0) { + options = {}; + } + + this.restLength = + typeof options.restLength === "number" ? options.restLength : 1; + this.stiffness = options.stiffness || 100; + this.damping = options.damping || 1; + this.bodyA = bodyA; + this.bodyB = bodyB; + this.localAnchorA = new Vec3(); + this.localAnchorB = new Vec3(); + + if (options.localAnchorA) { + this.localAnchorA.copy(options.localAnchorA); + } + + if (options.localAnchorB) { + this.localAnchorB.copy(options.localAnchorB); + } + + if (options.worldAnchorA) { + this.setWorldAnchorA(options.worldAnchorA); + } + + if (options.worldAnchorB) { + this.setWorldAnchorB(options.worldAnchorB); + } + } + /** + * Set the anchor point on body A, using world coordinates. + */ + + setWorldAnchorA(worldAnchorA) { + this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA); + } + /** + * Set the anchor point on body B, using world coordinates. + */ + + setWorldAnchorB(worldAnchorB) { + this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB); + } + /** + * Get the anchor point on body A, in world coordinates. + * @param result The vector to store the result in. + */ + + getWorldAnchorA(result) { + this.bodyA.pointToWorldFrame(this.localAnchorA, result); + } + /** + * Get the anchor point on body B, in world coordinates. + * @param result The vector to store the result in. + */ + + getWorldAnchorB(result) { + this.bodyB.pointToWorldFrame(this.localAnchorB, result); + } + /** + * Apply the spring force to the connected bodies. + */ + + applyForce() { + const k = this.stiffness; + const d = this.damping; + const l = this.restLength; + const bodyA = this.bodyA; + const bodyB = this.bodyB; + const r = applyForce_r; + const r_unit = applyForce_r_unit; + const u = applyForce_u; + const f = applyForce_f; + const tmp = applyForce_tmp; + const worldAnchorA = applyForce_worldAnchorA; + const worldAnchorB = applyForce_worldAnchorB; + const ri = applyForce_ri; + const rj = applyForce_rj; + const ri_x_f = applyForce_ri_x_f; + const rj_x_f = applyForce_rj_x_f; // Get world anchors + + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); // Get offset points + + worldAnchorA.vsub(bodyA.position, ri); + worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points + + worldAnchorB.vsub(worldAnchorA, r); + const rlen = r.length(); + r_unit.copy(r); + r_unit.normalize(); // Compute relative velocity of the anchor points, u + + bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity + + bodyB.angularVelocity.cross(rj, tmp); + u.vadd(tmp, u); + bodyA.angularVelocity.cross(ri, tmp); + u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u ) + + r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies + + bodyA.force.vsub(f, bodyA.force); + bodyB.force.vadd(f, bodyB.force); // Angular force + + ri.cross(f, ri_x_f); + rj.cross(f, rj_x_f); + bodyA.torque.vsub(ri_x_f, bodyA.torque); + bodyB.torque.vadd(rj_x_f, bodyB.torque); + } + } + const applyForce_r = new Vec3(); + const applyForce_r_unit = new Vec3(); + const applyForce_u = new Vec3(); + const applyForce_f = new Vec3(); + const applyForce_worldAnchorA = new Vec3(); + const applyForce_worldAnchorB = new Vec3(); + const applyForce_ri = new Vec3(); + const applyForce_rj = new Vec3(); + const applyForce_ri_x_f = new Vec3(); + const applyForce_rj_x_f = new Vec3(); + const applyForce_tmp = new Vec3(); + + /** + * WheelInfo + */ + class WheelInfo { + /** + * Max travel distance of the suspension, in meters. + * @default 1 + */ + + /** + * Speed to apply to the wheel rotation when the wheel is sliding. + * @default -0.1 + */ + + /** + * If the customSlidingRotationalSpeed should be used. + * @default false + */ + + /** + * sliding + */ + + /** + * Connection point, defined locally in the chassis body frame. + */ + + /** + * chassisConnectionPointWorld + */ + + /** + * directionLocal + */ + + /** + * directionWorld + */ + + /** + * axleLocal + */ + + /** + * axleWorld + */ + + /** + * suspensionRestLength + * @default 1 + */ + + /** + * suspensionMaxLength + * @default 2 + */ + + /** + * radius + * @default 1 + */ + + /** + * suspensionStiffness + * @default 100 + */ + + /** + * dampingCompression + * @default 10 + */ + + /** + * dampingRelaxation + * @default 10 + */ + + /** + * frictionSlip + * @default 10.5 + */ + + /** forwardAcceleration */ + + /** sideAcceleration */ + + /** + * steering + * @default 0 + */ + + /** + * Rotation value, in radians. + * @default 0 + */ + + /** + * deltaRotation + * @default 0 + */ + + /** + * rollInfluence + * @default 0.01 + */ + + /** + * maxSuspensionForce + */ + + /** + * engineForce + */ + + /** + * brake + */ + + /** + * isFrontWheel + * @default true + */ + + /** + * clippedInvContactDotSuspension + * @default 1 + */ + + /** + * suspensionRelativeVelocity + * @default 0 + */ + + /** + * suspensionForce + * @default 0 + */ + + /** + * slipInfo + */ + + /** + * skidInfo + * @default 0 + */ + + /** + * suspensionLength + * @default 0 + */ + + /** + * sideImpulse + */ + + /** + * forwardImpulse + */ + + /** + * The result from raycasting. + */ + + /** + * Wheel world transform. + */ + + /** + * isInContact + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + options = Utils.defaults(options, { + chassisConnectionPointLocal: new Vec3(), + chassisConnectionPointWorld: new Vec3(), + directionLocal: new Vec3(), + directionWorld: new Vec3(), + axleLocal: new Vec3(), + axleWorld: new Vec3(), + suspensionRestLength: 1, + suspensionMaxLength: 2, + radius: 1, + suspensionStiffness: 100, + dampingCompression: 10, + dampingRelaxation: 10, + frictionSlip: 10.5, + forwardAcceleration: 1, + sideAcceleration: 1, + steering: 0, + rotation: 0, + deltaRotation: 0, + rollInfluence: 0.01, + maxSuspensionForce: Number.MAX_VALUE, + isFrontWheel: true, + clippedInvContactDotSuspension: 1, + suspensionRelativeVelocity: 0, + suspensionForce: 0, + slipInfo: 0, + skidInfo: 0, + suspensionLength: 0, + maxSuspensionTravel: 1, + useCustomSlidingRotationalSpeed: false, + customSlidingRotationalSpeed: -0.1, + }); + this.maxSuspensionTravel = options.maxSuspensionTravel; + this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed; + this.useCustomSlidingRotationalSpeed = + options.useCustomSlidingRotationalSpeed; + this.sliding = false; + this.chassisConnectionPointLocal = + options.chassisConnectionPointLocal.clone(); + this.chassisConnectionPointWorld = + options.chassisConnectionPointWorld.clone(); + this.directionLocal = options.directionLocal.clone(); + this.directionWorld = options.directionWorld.clone(); + this.axleLocal = options.axleLocal.clone(); + this.axleWorld = options.axleWorld.clone(); + this.suspensionRestLength = options.suspensionRestLength; + this.suspensionMaxLength = options.suspensionMaxLength; + this.radius = options.radius; + this.suspensionStiffness = options.suspensionStiffness; + this.dampingCompression = options.dampingCompression; + this.dampingRelaxation = options.dampingRelaxation; + this.frictionSlip = options.frictionSlip; + this.forwardAcceleration = options.forwardAcceleration; + this.sideAcceleration = options.sideAcceleration; + this.steering = 0; + this.rotation = 0; + this.deltaRotation = 0; + this.rollInfluence = options.rollInfluence; + this.maxSuspensionForce = options.maxSuspensionForce; + this.engineForce = 0; + this.brake = 0; + this.isFrontWheel = options.isFrontWheel; + this.clippedInvContactDotSuspension = 1; + this.suspensionRelativeVelocity = 0; + this.suspensionForce = 0; + this.slipInfo = 0; + this.skidInfo = 0; + this.suspensionLength = 0; + this.sideImpulse = 0; + this.forwardImpulse = 0; + this.raycastResult = new RaycastResult(); + this.worldTransform = new Transform(); + this.isInContact = false; + } + + updateWheel(chassis) { + const raycastResult = this.raycastResult; + + if (this.isInContact) { + const project = raycastResult.hitNormalWorld.dot( + raycastResult.directionWorld + ); + raycastResult.hitPointWorld.vsub(chassis.position, relpos); + chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint); + const projVel = raycastResult.hitNormalWorld.dot( + chassis_velocity_at_contactPoint + ); + + if (project >= -0.1) { + this.suspensionRelativeVelocity = 0.0; + this.clippedInvContactDotSuspension = 1.0 / 0.1; + } else { + const inv = -1 / project; + this.suspensionRelativeVelocity = projVel * inv; + this.clippedInvContactDotSuspension = inv; + } + } else { + // Not in contact : position wheel in a nice (rest length) position + raycastResult.suspensionLength = this.suspensionRestLength; + this.suspensionRelativeVelocity = 0.0; + raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld); + this.clippedInvContactDotSuspension = 1.0; + } + } + } + const chassis_velocity_at_contactPoint = new Vec3(); + const relpos = new Vec3(); + + /** + * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces. + */ + class RaycastVehicle { + /** The car chassis body. */ + + /** The wheels. */ + + /** Will be set to true if the car is sliding. */ + + /** Index of the right axis. x=0, y=1, z=2 */ + + /** Index of the forward axis. x=0, y=1, z=2 */ + + /** Index of the up axis. x=0, y=1, z=2 */ + + /** The constraints. */ + + /** Optional pre-step callback. */ + + /** Number of wheels on the ground. */ + constructor(options) { + this.chassisBody = options.chassisBody; + this.wheelInfos = []; + this.sliding = false; + this.world = null; + this.indexRightAxis = + typeof options.indexRightAxis !== "undefined" + ? options.indexRightAxis + : 2; + this.indexForwardAxis = + typeof options.indexForwardAxis !== "undefined" + ? options.indexForwardAxis + : 0; + this.indexUpAxis = + typeof options.indexUpAxis !== "undefined" ? options.indexUpAxis : 1; + this.constraints = []; + + this.preStepCallback = () => {}; + + this.currentVehicleSpeedKmHour = 0; + this.numWheelsOnGround = 0; + } + /** + * Add a wheel. For information about the options, see `WheelInfo`. + */ + + addWheel(options) { + if (options === void 0) { + options = {}; + } + + const info = new WheelInfo(options); + const index = this.wheelInfos.length; + this.wheelInfos.push(info); + return index; + } + /** + * Set the steering value of a wheel. + */ + + setSteeringValue(value, wheelIndex) { + const wheel = this.wheelInfos[wheelIndex]; + wheel.steering = value; + } + /** + * Set the wheel force to apply on one of the wheels each time step + */ + + applyEngineForce(value, wheelIndex) { + this.wheelInfos[wheelIndex].engineForce = value; + } + /** + * Set the braking force of a wheel + */ + + setBrake(brake, wheelIndex) { + this.wheelInfos[wheelIndex].brake = brake; + } + /** + * Add the vehicle including its constraints to the world. + */ + + addToWorld(world) { + world.addBody(this.chassisBody); + const that = this; + + this.preStepCallback = () => { + that.updateVehicle(world.dt); + }; + + world.addEventListener("preStep", this.preStepCallback); + this.world = world; + } + /** + * Get one of the wheel axles, world-oriented. + */ + + getVehicleAxisWorld(axisIndex, result) { + result.set( + axisIndex === 0 ? 1 : 0, + axisIndex === 1 ? 1 : 0, + axisIndex === 2 ? 1 : 0 + ); + this.chassisBody.vectorToWorldFrame(result, result); + } + + updateVehicle(timeStep) { + const wheelInfos = this.wheelInfos; + const numWheels = wheelInfos.length; + const chassisBody = this.chassisBody; + + for (let i = 0; i < numWheels; i++) { + this.updateWheelTransform(i); + } + + this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length(); + const forwardWorld = new Vec3(); + this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld); + + if (forwardWorld.dot(chassisBody.velocity) < 0) { + this.currentVehicleSpeedKmHour *= -1; + } // simulate suspension + + for (let i = 0; i < numWheels; i++) { + this.castRay(wheelInfos[i]); + } + + this.updateSuspension(timeStep); + const impulse = new Vec3(); + const relpos = new Vec3(); + + for (let i = 0; i < numWheels; i++) { + //apply suspension force + const wheel = wheelInfos[i]; + let suspensionForce = wheel.suspensionForce; + + if (suspensionForce > wheel.maxSuspensionForce) { + suspensionForce = wheel.maxSuspensionForce; + } + + wheel.raycastResult.hitNormalWorld.scale( + suspensionForce * timeStep, + impulse + ); + wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos); + chassisBody.applyImpulse(impulse, relpos); + } + + this.updateFriction(timeStep); + const hitNormalWorldScaledWithProj = new Vec3(); + const fwd = new Vec3(); + const vel = new Vec3(); + + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; //const relpos = new Vec3(); + //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos); + + chassisBody.getVelocityAtWorldPoint( + wheel.chassisConnectionPointWorld, + vel + ); // Hack to get the rotation in the correct direction + + let m = 1; + + switch (this.indexUpAxis) { + case 1: + m = -1; + break; + } + + if (wheel.isInContact) { + this.getVehicleAxisWorld(this.indexForwardAxis, fwd); + const proj = fwd.dot(wheel.raycastResult.hitNormalWorld); + wheel.raycastResult.hitNormalWorld.scale( + proj, + hitNormalWorldScaledWithProj + ); + fwd.vsub(hitNormalWorldScaledWithProj, fwd); + const proj2 = fwd.dot(vel); + wheel.deltaRotation = (m * proj2 * timeStep) / wheel.radius; + } + + if ( + (wheel.sliding || !wheel.isInContact) && + wheel.engineForce !== 0 && + wheel.useCustomSlidingRotationalSpeed + ) { + // Apply custom rotation when accelerating and sliding + wheel.deltaRotation = + (wheel.engineForce > 0 ? 1 : -1) * + wheel.customSlidingRotationalSpeed * + timeStep; + } // Lock wheels + + if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) { + wheel.deltaRotation = 0; + } + + wheel.rotation += wheel.deltaRotation; // Use the old value + + wheel.deltaRotation *= 0.99; // damping of rotation when not in contact + } + } + + updateSuspension(deltaTime) { + const chassisBody = this.chassisBody; + const chassisMass = chassisBody.mass; + const wheelInfos = this.wheelInfos; + const numWheels = wheelInfos.length; + + for (let w_it = 0; w_it < numWheels; w_it++) { + const wheel = wheelInfos[w_it]; + + if (wheel.isInContact) { + let force; // Spring + + const susp_length = wheel.suspensionRestLength; + const current_length = wheel.suspensionLength; + const length_diff = susp_length - current_length; + force = + wheel.suspensionStiffness * + length_diff * + wheel.clippedInvContactDotSuspension; // Damper + + const projected_rel_vel = wheel.suspensionRelativeVelocity; + let susp_damping; + + if (projected_rel_vel < 0) { + susp_damping = wheel.dampingCompression; + } else { + susp_damping = wheel.dampingRelaxation; + } + + force -= susp_damping * projected_rel_vel; + wheel.suspensionForce = force * chassisMass; + + if (wheel.suspensionForce < 0) { + wheel.suspensionForce = 0; + } + } else { + wheel.suspensionForce = 0; + } + } + } + /** + * Remove the vehicle including its constraints from the world. + */ + + removeFromWorld(world) { + this.constraints; + world.removeBody(this.chassisBody); + world.removeEventListener("preStep", this.preStepCallback); + this.world = null; + } + + castRay(wheel) { + const rayvector = castRay_rayvector; + const target = castRay_target; + this.updateWheelTransformWorld(wheel); + const chassisBody = this.chassisBody; + let depth = -1; + const raylen = wheel.suspensionRestLength + wheel.radius; + wheel.directionWorld.scale(raylen, rayvector); + const source = wheel.chassisConnectionPointWorld; + source.vadd(rayvector, target); + const raycastResult = wheel.raycastResult; + raycastResult.reset(); // Turn off ray collision with the chassis temporarily + + const oldState = chassisBody.collisionResponse; + chassisBody.collisionResponse = false; // Cast ray against world + + this.world.rayTest(source, target, raycastResult); + chassisBody.collisionResponse = oldState; + const object = raycastResult.body; + wheel.raycastResult.groundObject = 0; + + if (object) { + depth = raycastResult.distance; + wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld; + wheel.isInContact = true; + const hitDistance = raycastResult.distance; + wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel + + const minSuspensionLength = + wheel.suspensionRestLength - wheel.maxSuspensionTravel; + const maxSuspensionLength = + wheel.suspensionRestLength + wheel.maxSuspensionTravel; + + if (wheel.suspensionLength < minSuspensionLength) { + wheel.suspensionLength = minSuspensionLength; + } + + if (wheel.suspensionLength > maxSuspensionLength) { + wheel.suspensionLength = maxSuspensionLength; + wheel.raycastResult.reset(); + } + + const denominator = wheel.raycastResult.hitNormalWorld.dot( + wheel.directionWorld + ); + const chassis_velocity_at_contactPoint = new Vec3(); + chassisBody.getVelocityAtWorldPoint( + wheel.raycastResult.hitPointWorld, + chassis_velocity_at_contactPoint + ); + const projVel = wheel.raycastResult.hitNormalWorld.dot( + chassis_velocity_at_contactPoint + ); + + if (denominator >= -0.1) { + wheel.suspensionRelativeVelocity = 0; + wheel.clippedInvContactDotSuspension = 1 / 0.1; + } else { + const inv = -1 / denominator; + wheel.suspensionRelativeVelocity = projVel * inv; + wheel.clippedInvContactDotSuspension = inv; + } + } else { + //put wheel info as in rest position + wheel.suspensionLength = + wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel; + wheel.suspensionRelativeVelocity = 0.0; + wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld); + wheel.clippedInvContactDotSuspension = 1.0; + } + + return depth; + } + + updateWheelTransformWorld(wheel) { + wheel.isInContact = false; + const chassisBody = this.chassisBody; + chassisBody.pointToWorldFrame( + wheel.chassisConnectionPointLocal, + wheel.chassisConnectionPointWorld + ); + chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld); + chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld); + } + /** + * Update one of the wheel transform. + * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example. + * @param wheelIndex The wheel index to update. + */ + + updateWheelTransform(wheelIndex) { + const up = tmpVec4; + const right = tmpVec5; + const fwd = tmpVec6; + const wheel = this.wheelInfos[wheelIndex]; + this.updateWheelTransformWorld(wheel); + wheel.directionLocal.scale(-1, up); + right.copy(wheel.axleLocal); + up.cross(right, fwd); + fwd.normalize(); + right.normalize(); // Rotate around steering over the wheelAxle + + const steering = wheel.steering; + const steeringOrn = new Quaternion(); + steeringOrn.setFromAxisAngle(up, steering); + const rotatingOrn = new Quaternion(); + rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel + + const q = wheel.worldTransform.quaternion; + this.chassisBody.quaternion.mult(steeringOrn, q); + q.mult(rotatingOrn, q); + q.normalize(); // world position of the wheel + + const p = wheel.worldTransform.position; + p.copy(wheel.directionWorld); + p.scale(wheel.suspensionLength, p); + p.vadd(wheel.chassisConnectionPointWorld, p); + } + /** + * Get the world transform of one of the wheels + */ + + getWheelTransformWorld(wheelIndex) { + return this.wheelInfos[wheelIndex].worldTransform; + } + + updateFriction(timeStep) { + const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards + + const wheelInfos = this.wheelInfos; + const numWheels = wheelInfos.length; + const chassisBody = this.chassisBody; + const forwardWS = updateFriction_forwardWS; + const axle = updateFriction_axle; + this.numWheelsOnGround = 0; + + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; + const groundObject = wheel.raycastResult.body; + + if (groundObject) { + this.numWheelsOnGround++; + } + + wheel.sideImpulse = 0; + wheel.forwardImpulse = 0; + + if (!forwardWS[i]) { + forwardWS[i] = new Vec3(); + } + + if (!axle[i]) { + axle[i] = new Vec3(); + } + } + + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; + const groundObject = wheel.raycastResult.body; + + if (groundObject) { + const axlei = axle[i]; + const wheelTrans = this.getWheelTransformWorld(i); // Get world axle + + wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei); + const surfNormalWS = wheel.raycastResult.hitNormalWorld; + const proj = axlei.dot(surfNormalWS); + surfNormalWS.scale(proj, surfNormalWS_scaled_proj); + axlei.vsub(surfNormalWS_scaled_proj, axlei); + axlei.normalize(); + surfNormalWS.cross(axlei, forwardWS[i]); + forwardWS[i].normalize(); + wheel.sideImpulse = resolveSingleBilateral( + chassisBody, + wheel.raycastResult.hitPointWorld, + groundObject, + wheel.raycastResult.hitPointWorld, + axlei + ); + wheel.sideImpulse *= sideFrictionStiffness2; + } + } + + const sideFactor = 1; + const fwdFactor = 0.5; + this.sliding = false; + + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; + const groundObject = wheel.raycastResult.body; + let rollingFriction = 0; + wheel.slipInfo = 1; + + if (groundObject) { + const defaultRollingFrictionImpulse = 0; + const maxImpulse = wheel.brake + ? wheel.brake + : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse); + // rollingFriction = calcRollingFriction(contactPt); + + rollingFriction = calcRollingFriction( + chassisBody, + groundObject, + wheel.raycastResult.hitPointWorld, + forwardWS[i], + maxImpulse + ); + rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0; + + const factor = maxImpulse / rollingFriction; + wheel.slipInfo *= factor; + } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break) + + wheel.forwardImpulse = 0; + wheel.skidInfo = 1; + + if (groundObject) { + wheel.skidInfo = 1; + const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip; + const maximpSide = maximp; + const maximpSquared = maximp * maximpSide; + wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep; + + const x = + (wheel.forwardImpulse * fwdFactor) / wheel.forwardAcceleration; + const y = (wheel.sideImpulse * sideFactor) / wheel.sideAcceleration; + const impulseSquared = x * x + y * y; + wheel.sliding = false; + + if (impulseSquared > maximpSquared) { + this.sliding = true; + wheel.sliding = true; + const factor = maximp / Math.sqrt(impulseSquared); + wheel.skidInfo *= factor; + } + } + } + + if (this.sliding) { + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; + + if (wheel.sideImpulse !== 0) { + if (wheel.skidInfo < 1) { + wheel.forwardImpulse *= wheel.skidInfo; + wheel.sideImpulse *= wheel.skidInfo; + } + } + } + } // apply the impulses + + for (let i = 0; i < numWheels; i++) { + const wheel = wheelInfos[i]; + const rel_pos = new Vec3(); + wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position + //rel_pos.copy(wheel.raycastResult.hitPointWorld); + + if (wheel.forwardImpulse !== 0) { + const impulse = new Vec3(); + forwardWS[i].scale(wheel.forwardImpulse, impulse); + chassisBody.applyImpulse(impulse, rel_pos); + } + + if (wheel.sideImpulse !== 0) { + const groundObject = wheel.raycastResult.body; + const rel_pos2 = new Vec3(); + wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld); + + const sideImp = new Vec3(); + axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence. + // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over). + + chassisBody.vectorToLocalFrame(rel_pos, rel_pos); + rel_pos["xyz"[this.indexUpAxis]] *= wheel.rollInfluence; + chassisBody.vectorToWorldFrame(rel_pos, rel_pos); + chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground + + sideImp.scale(-1, sideImp); + groundObject.applyImpulse(sideImp, rel_pos2); + } + } + } + } + new Vec3(); + new Vec3(); + new Vec3(); + const tmpVec4 = new Vec3(); + const tmpVec5 = new Vec3(); + const tmpVec6 = new Vec3(); + new Ray(); + new Vec3(); + const castRay_rayvector = new Vec3(); + const castRay_target = new Vec3(); + const directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)]; + const updateFriction_surfNormalWS_scaled_proj = new Vec3(); + const updateFriction_axle = []; + const updateFriction_forwardWS = []; + const sideFrictionStiffness2 = 1; + const calcRollingFriction_vel1 = new Vec3(); + const calcRollingFriction_vel2 = new Vec3(); + const calcRollingFriction_vel = new Vec3(); + + function calcRollingFriction( + body0, + body1, + frictionPosWorld, + frictionDirectionWorld, + maxImpulse + ) { + let j1 = 0; + const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3(); + // const rel_pos2 = new Vec3(); + + const vel1 = calcRollingFriction_vel1; + const vel2 = calcRollingFriction_vel2; + const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1); + // contactPosWorld.vsub(body1.position, rel_pos2); + + body0.getVelocityAtWorldPoint(contactPosWorld, vel1); + body1.getVelocityAtWorldPoint(contactPosWorld, vel2); + vel1.vsub(vel2, vel); + const vrel = frictionDirectionWorld.dot(vel); + const denom0 = computeImpulseDenominator( + body0, + frictionPosWorld, + frictionDirectionWorld + ); + const denom1 = computeImpulseDenominator( + body1, + frictionPosWorld, + frictionDirectionWorld + ); + const relaxation = 1; + const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity + + j1 = -vrel * jacDiagABInv; + + if (maxImpulse < j1) { + j1 = maxImpulse; + } + + if (j1 < -maxImpulse) { + j1 = -maxImpulse; + } + + return j1; + } + + const computeImpulseDenominator_r0 = new Vec3(); + const computeImpulseDenominator_c0 = new Vec3(); + const computeImpulseDenominator_vec = new Vec3(); + const computeImpulseDenominator_m = new Vec3(); + + function computeImpulseDenominator(body, pos, normal) { + const r0 = computeImpulseDenominator_r0; + const c0 = computeImpulseDenominator_c0; + const vec = computeImpulseDenominator_vec; + const m = computeImpulseDenominator_m; + pos.vsub(body.position, r0); + r0.cross(normal, c0); + body.invInertiaWorld.vmult(c0, m); + m.cross(r0, vec); + return body.invMass + normal.dot(vec); + } + + const resolveSingleBilateral_vel1 = new Vec3(); + const resolveSingleBilateral_vel2 = new Vec3(); + const resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects + + function resolveSingleBilateral(body1, pos1, body2, pos2, normal) { + const normalLenSqr = normal.lengthSquared(); + + if (normalLenSqr > 1.1) { + return 0; // no impulse + } // const rel_pos1 = new Vec3(); + // const rel_pos2 = new Vec3(); + // pos1.vsub(body1.position, rel_pos1); + // pos2.vsub(body2.position, rel_pos2); + + const vel1 = resolveSingleBilateral_vel1; + const vel2 = resolveSingleBilateral_vel2; + const vel = resolveSingleBilateral_vel; + body1.getVelocityAtWorldPoint(pos1, vel1); + body2.getVelocityAtWorldPoint(pos2, vel2); + vel1.vsub(vel2, vel); + const rel_vel = normal.dot(vel); + const contactDamping = 0.2; + const massTerm = 1 / (body1.invMass + body2.invMass); + const impulse = -contactDamping * rel_vel * massTerm; + return impulse; + } + + /** + * Spherical shape + * @example + * const radius = 1 + * const sphereShape = new CANNON.Sphere(radius) + * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape }) + * world.addBody(sphereBody) + */ + class Sphere extends Shape { + /** + * The radius of the sphere. + */ + + /** + * + * @param radius The radius of the sphere, a non-negative number. + */ + constructor(radius) { + super({ + type: Shape.types.SPHERE, + }); + this.radius = radius !== undefined ? radius : 1.0; + + if (this.radius < 0) { + throw new Error("The sphere radius cannot be negative."); + } + + this.updateBoundingSphereRadius(); + } + /** calculateLocalInertia */ + + calculateLocalInertia(mass, target) { + if (target === void 0) { + target = new Vec3(); + } + + const I = (2.0 * mass * this.radius * this.radius) / 5.0; + target.x = I; + target.y = I; + target.z = I; + return target; + } + /** volume */ + + volume() { + return (4.0 * Math.PI * Math.pow(this.radius, 3)) / 3.0; + } + + updateBoundingSphereRadius() { + this.boundingSphereRadius = this.radius; + } + + calculateWorldAABB(pos, quat, min, max) { + const r = this.radius; + const axes = ["x", "y", "z"]; + + for (let i = 0; i < axes.length; i++) { + const ax = axes[i]; + min[ax] = pos[ax] - r; + max[ax] = pos[ax] + r; + } + } + } + + /** + * Simple vehicle helper class with spherical rigid body wheels. + */ + class RigidVehicle { + /** + * The bodies of the wheels. + */ + + /** + * The chassis body. + */ + + /** + * The constraints. + */ + + /** + * The wheel axes. + */ + + /** + * The wheel forces. + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + this.wheelBodies = []; + this.coordinateSystem = + typeof options.coordinateSystem !== "undefined" + ? options.coordinateSystem.clone() + : new Vec3(1, 2, 3); + + if (options.chassisBody) { + this.chassisBody = options.chassisBody; + } else { + // No chassis body given. Create it! + this.chassisBody = new Body({ + mass: 1, + shape: new Box(new Vec3(5, 0.5, 2)), + }); + } + + this.constraints = []; + this.wheelAxes = []; + this.wheelForces = []; + } + /** + * Add a wheel + */ + + addWheel(options) { + if (options === void 0) { + options = {}; + } + + let wheelBody; + + if (options.body) { + wheelBody = options.body; + } else { + // No wheel body given. Create it! + wheelBody = new Body({ + mass: 1, + shape: new Sphere(1.2), + }); + } + + this.wheelBodies.push(wheelBody); + this.wheelForces.push(0); // Position constrain wheels + + const position = + typeof options.position !== "undefined" + ? options.position.clone() + : new Vec3(); // Set position locally to the chassis + + const worldPosition = new Vec3(); + this.chassisBody.pointToWorldFrame(position, worldPosition); + wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel + + const axis = + typeof options.axis !== "undefined" + ? options.axis.clone() + : new Vec3(0, 0, 1); + this.wheelAxes.push(axis); + const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, { + pivotA: position, + axisA: axis, + pivotB: Vec3.ZERO, + axisB: axis, + collideConnected: false, + }); + this.constraints.push(hingeConstraint); + return this.wheelBodies.length - 1; + } + /** + * Set the steering value of a wheel. + * @todo check coordinateSystem + */ + + setSteeringValue(value, wheelIndex) { + // Set angle of the hinge axis + const axis = this.wheelAxes[wheelIndex]; + const c = Math.cos(value); + const s = Math.sin(value); + const x = axis.x; + const z = axis.z; + this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z); + } + /** + * Set the target rotational speed of the hinge constraint. + */ + + setMotorSpeed(value, wheelIndex) { + const hingeConstraint = this.constraints[wheelIndex]; + hingeConstraint.enableMotor(); + hingeConstraint.motorTargetVelocity = value; + } + /** + * Set the target rotational speed of the hinge constraint. + */ + + disableMotor(wheelIndex) { + const hingeConstraint = this.constraints[wheelIndex]; + hingeConstraint.disableMotor(); + } + /** + * Set the wheel force to apply on one of the wheels each time step + */ + + setWheelForce(value, wheelIndex) { + this.wheelForces[wheelIndex] = value; + } + /** + * Apply a torque on one of the wheels. + */ + + applyWheelForce(value, wheelIndex) { + const axis = this.wheelAxes[wheelIndex]; + const wheelBody = this.wheelBodies[wheelIndex]; + const bodyTorque = wheelBody.torque; + axis.scale(value, torque); + wheelBody.vectorToWorldFrame(torque, torque); + bodyTorque.vadd(torque, bodyTorque); + } + /** + * Add the vehicle including its constraints to the world. + */ + + addToWorld(world) { + const constraints = this.constraints; + const bodies = this.wheelBodies.concat([this.chassisBody]); + + for (let i = 0; i < bodies.length; i++) { + world.addBody(bodies[i]); + } + + for (let i = 0; i < constraints.length; i++) { + world.addConstraint(constraints[i]); + } + + world.addEventListener("preStep", this._update.bind(this)); + } + + _update() { + const wheelForces = this.wheelForces; + + for (let i = 0; i < wheelForces.length; i++) { + this.applyWheelForce(wheelForces[i], i); + } + } + /** + * Remove the vehicle including its constraints from the world. + */ + + removeFromWorld(world) { + const constraints = this.constraints; + const bodies = this.wheelBodies.concat([this.chassisBody]); + + for (let i = 0; i < bodies.length; i++) { + world.removeBody(bodies[i]); + } + + for (let i = 0; i < constraints.length; i++) { + world.removeConstraint(constraints[i]); + } + } + /** + * Get current rotational velocity of a wheel + */ + + getWheelSpeed(wheelIndex) { + const axis = this.wheelAxes[wheelIndex]; + const wheelBody = this.wheelBodies[wheelIndex]; + const w = wheelBody.angularVelocity; + this.chassisBody.vectorToWorldFrame(axis, worldAxis); + return w.dot(worldAxis); + } + } + const torque = new Vec3(); + const worldAxis = new Vec3(); + + /** + * Smoothed-particle hydrodynamics system + * @todo Make parameters customizable in the constructor + */ + class SPHSystem { + /** + * The particles array. + */ + + /** + * Density of the system (kg/m3). + * @default 1 + */ + + /** + * Distance below which two particles are considered to be neighbors. + * It should be adjusted so there are about 15-20 neighbor particles within this radius. + * @default 1 + */ + + /** + * @default 1 + */ + + /** + * Viscosity of the system. + * @default 0.01 + */ + + /** + * @default 0.000001 + */ + constructor() { + this.particles = []; + this.density = 1; + this.smoothingRadius = 1; + this.speedOfSound = 1; + this.viscosity = 0.01; + this.eps = 0.000001; // Stuff Computed per particle + + this.pressures = []; + this.densities = []; + this.neighbors = []; + } + /** + * Add a particle to the system. + */ + + add(particle) { + this.particles.push(particle); + + if (this.neighbors.length < this.particles.length) { + this.neighbors.push([]); + } + } + /** + * Remove a particle from the system. + */ + + remove(particle) { + const idx = this.particles.indexOf(particle); + + if (idx !== -1) { + this.particles.splice(idx, 1); + + if (this.neighbors.length > this.particles.length) { + this.neighbors.pop(); + } + } + } + /** + * Get neighbors within smoothing volume, save in the array neighbors + */ + + getNeighbors(particle, neighbors) { + const N = this.particles.length; + const id = particle.id; + const R2 = this.smoothingRadius * this.smoothingRadius; + const dist = SPHSystem_getNeighbors_dist; + + for (let i = 0; i !== N; i++) { + const p = this.particles[i]; + p.position.vsub(particle.position, dist); + + if (id !== p.id && dist.lengthSquared() < R2) { + neighbors.push(p); + } + } + } + + update() { + const N = this.particles.length; + const dist = SPHSystem_update_dist; + const cs = this.speedOfSound; + const eps = this.eps; + + for (let i = 0; i !== N; i++) { + const p = this.particles[i]; // Current particle + + const neighbors = this.neighbors[i]; // Get neighbors + + neighbors.length = 0; + this.getNeighbors(p, neighbors); + neighbors.push(this.particles[i]); // Add current too + + const numNeighbors = neighbors.length; // Accumulate density for the particle + + let sum = 0.0; + + for (let j = 0; j !== numNeighbors; j++) { + //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z()); + p.position.vsub(neighbors[j].position, dist); + const len = dist.length(); + const weight = this.w(len); + sum += neighbors[j].mass * weight; + } // Save + + this.densities[i] = sum; + this.pressures[i] = cs * cs * (this.densities[i] - this.density); + } // Add forces + // Sum to these accelerations + + const a_pressure = SPHSystem_update_a_pressure; + const a_visc = SPHSystem_update_a_visc; + const gradW = SPHSystem_update_gradW; + const r_vec = SPHSystem_update_r_vec; + const u = SPHSystem_update_u; + + for (let i = 0; i !== N; i++) { + const particle = this.particles[i]; + a_pressure.set(0, 0, 0); + a_visc.set(0, 0, 0); // Init vars + + let Pij; + let nabla; + + const neighbors = this.neighbors[i]; + const numNeighbors = neighbors.length; //printf("Neighbors: "); + + for (let j = 0; j !== numNeighbors; j++) { + const neighbor = neighbors[j]; //printf("%d ",nj); + // Get r once for all.. + + particle.position.vsub(neighbor.position, r_vec); + const r = r_vec.length(); // Pressure contribution + + Pij = + -neighbor.mass * + (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + + this.pressures[j] / (this.densities[j] * this.densities[j] + eps)); + this.gradw(r_vec, gradW); // Add to pressure acceleration + + gradW.scale(Pij, gradW); + a_pressure.vadd(gradW, a_pressure); // Viscosity contribution + + neighbor.velocity.vsub(particle.velocity, u); + u.scale( + (1.0 / (0.0001 + this.densities[i] * this.densities[j])) * + this.viscosity * + neighbor.mass, + u + ); + nabla = this.nablaw(r); + u.scale(nabla, u); // Add to viscosity acceleration + + a_visc.vadd(u, a_visc); + } // Calculate force + + a_visc.scale(particle.mass, a_visc); + a_pressure.scale(particle.mass, a_pressure); // Add force to particles + + particle.force.vadd(a_visc, particle.force); + particle.force.vadd(a_pressure, particle.force); + } + } // Calculate the weight using the W(r) weightfunction + + w(r) { + // 315 + const h = this.smoothingRadius; + return (315.0 / (64.0 * Math.PI * h ** 9)) * (h * h - r * r) ** 3; + } // calculate gradient of the weight function + + gradw(rVec, resultVec) { + const r = rVec.length(); + const h = this.smoothingRadius; + rVec.scale( + (945.0 / (32.0 * Math.PI * h ** 9)) * (h * h - r * r) ** 2, + resultVec + ); + } // Calculate nabla(W) + + nablaw(r) { + const h = this.smoothingRadius; + const nabla = + (945.0 / (32.0 * Math.PI * h ** 9)) * + (h * h - r * r) * + (7 * r * r - 3 * h * h); + return nabla; + } + } + const SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation + + const SPHSystem_update_dist = new Vec3(); // Relative velocity + + const SPHSystem_update_a_pressure = new Vec3(); + const SPHSystem_update_a_visc = new Vec3(); + const SPHSystem_update_gradW = new Vec3(); + const SPHSystem_update_r_vec = new Vec3(); + const SPHSystem_update_u = new Vec3(); + + /** + * Cylinder class. + * @example + * const radiusTop = 0.5 + * const radiusBottom = 0.5 + * const height = 2 + * const numSegments = 12 + * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments) + * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape }) + * world.addBody(cylinderBody) + */ + + class Cylinder extends ConvexPolyhedron { + /** The radius of the top of the Cylinder. */ + + /** The radius of the bottom of the Cylinder. */ + + /** The height of the Cylinder. */ + + /** The number of segments to build the cylinder out of. */ + + /** + * @param radiusTop The radius of the top of the Cylinder. + * @param radiusBottom The radius of the bottom of the Cylinder. + * @param height The height of the Cylinder. + * @param numSegments The number of segments to build the cylinder out of. + */ + constructor(radiusTop, radiusBottom, height, numSegments) { + if (radiusTop === void 0) { + radiusTop = 1; + } + + if (radiusBottom === void 0) { + radiusBottom = 1; + } + + if (height === void 0) { + height = 1; + } + + if (numSegments === void 0) { + numSegments = 8; + } + + if (radiusTop < 0) { + throw new Error("The cylinder radiusTop cannot be negative."); + } + + if (radiusBottom < 0) { + throw new Error("The cylinder radiusBottom cannot be negative."); + } + + const N = numSegments; + const vertices = []; + const axes = []; + const faces = []; + const bottomface = []; + const topface = []; + const cos = Math.cos; + const sin = Math.sin; // First bottom point + + vertices.push( + new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)) + ); + bottomface.push(0); // First top point + + vertices.push( + new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)) + ); + topface.push(1); + + for (let i = 0; i < N; i++) { + const theta = ((2 * Math.PI) / N) * (i + 1); + const thetaN = ((2 * Math.PI) / N) * (i + 0.5); + + if (i < N - 1) { + // Bottom + vertices.push( + new Vec3( + -radiusBottom * sin(theta), + -height * 0.5, + radiusBottom * cos(theta) + ) + ); + bottomface.push(2 * i + 2); // Top + + vertices.push( + new Vec3( + -radiusTop * sin(theta), + height * 0.5, + radiusTop * cos(theta) + ) + ); + topface.push(2 * i + 3); // Face + + faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]); + } else { + faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect + } // Axis: we can cut off half of them if we have even number of segments + + if (N % 2 === 1 || i < N / 2) { + axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN))); + } + } + + faces.push(bottomface); + axes.push(new Vec3(0, 1, 0)); // Reorder top face + + const temp = []; + + for (let i = 0; i < topface.length; i++) { + temp.push(topface[topface.length - i - 1]); + } + + faces.push(temp); + super({ + vertices, + faces, + axes, + }); + this.type = Shape.types.CYLINDER; + this.radiusTop = radiusTop; + this.radiusBottom = radiusBottom; + this.height = height; + this.numSegments = numSegments; + } + } + + /** + * Particle shape. + * @example + * const particleShape = new CANNON.Particle() + * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape }) + * world.addBody(particleBody) + */ + class Particle extends Shape { + constructor() { + super({ + type: Shape.types.PARTICLE, + }); + } + /** + * calculateLocalInertia + */ + + calculateLocalInertia(mass, target) { + if (target === void 0) { + target = new Vec3(); + } + + target.set(0, 0, 0); + return target; + } + + volume() { + return 0; + } + + updateBoundingSphereRadius() { + this.boundingSphereRadius = 0; + } + + calculateWorldAABB(pos, quat, min, max) { + // Get each axis max + min.copy(pos); + max.copy(pos); + } + } + + /** + * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos. + * @example + * const planeShape = new CANNON.Plane() + * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape }) + * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up + * world.addBody(planeBody) + */ + class Plane extends Shape { + /** worldNormal */ + + /** worldNormalNeedsUpdate */ + constructor() { + super({ + type: Shape.types.PLANE, + }); // World oriented normal + + this.worldNormal = new Vec3(); + this.worldNormalNeedsUpdate = true; + this.boundingSphereRadius = Number.MAX_VALUE; + } + /** computeWorldNormal */ + + computeWorldNormal(quat) { + const n = this.worldNormal; + n.set(0, 0, 1); + quat.vmult(n, n); + this.worldNormalNeedsUpdate = false; + } + + calculateLocalInertia(mass, target) { + if (target === void 0) { + target = new Vec3(); + } + + return target; + } + + volume() { + return ( + // The plane is infinite... + Number.MAX_VALUE + ); + } + + calculateWorldAABB(pos, quat, min, max) { + // The plane AABB is infinite, except if the normal is pointing along any axis + tempNormal.set(0, 0, 1); // Default plane normal is z + + quat.vmult(tempNormal, tempNormal); + const maxVal = Number.MAX_VALUE; + min.set(-maxVal, -maxVal, -maxVal); + max.set(maxVal, maxVal, maxVal); + + if (tempNormal.x === 1) { + max.x = pos.x; + } else if (tempNormal.x === -1) { + min.x = pos.x; + } + + if (tempNormal.y === 1) { + max.y = pos.y; + } else if (tempNormal.y === -1) { + min.y = pos.y; + } + + if (tempNormal.z === 1) { + max.z = pos.z; + } else if (tempNormal.z === -1) { + min.z = pos.z; + } + } + + updateBoundingSphereRadius() { + this.boundingSphereRadius = Number.MAX_VALUE; + } + } + const tempNormal = new Vec3(); + + /** + * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance. + * @todo Should be possible to use along all axes, not just y + * @todo should be possible to scale along all axes + * @todo Refactor elementSize to elementSizeX and elementSizeY + * + * @example + * // Generate some height data (y-values). + * const data = [] + * for (let i = 0; i < 1000; i++) { + * const y = 0.5 * Math.cos(0.2 * i) + * data.push(y) + * } + * + * // Create the heightfield shape + * const heightfieldShape = new CANNON.Heightfield(data, { + * elementSize: 1 // Distance between the data points in X and Y directions + * }) + * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape }) + * world.addBody(heightfieldBody) + */ + class Heightfield extends Shape { + /** + * An array of numbers, or height values, that are spread out along the x axis. + */ + + /** + * Max value of the data points in the data array. + */ + + /** + * Minimum value of the data points in the data array. + */ + + /** + * World spacing between the data points in X and Y direction. + * @todo elementSizeX and Y + * @default 1 + */ + + /** + * @default true + */ + + /** + * @param data An array of numbers, or height values, that are spread out along the x axis. + */ + constructor(data, options) { + if (options === void 0) { + options = {}; + } + + options = Utils.defaults(options, { + maxValue: null, + minValue: null, + elementSize: 1, + }); + super({ + type: Shape.types.HEIGHTFIELD, + }); + this.data = data; + this.maxValue = options.maxValue; + this.minValue = options.minValue; + this.elementSize = options.elementSize; + + if (options.minValue === null) { + this.updateMinValue(); + } + + if (options.maxValue === null) { + this.updateMaxValue(); + } + + this.cacheEnabled = true; + this.pillarConvex = new ConvexPolyhedron(); + this.pillarOffset = new Vec3(); + this.updateBoundingSphereRadius(); // "i_j_isUpper" => { convex: ..., offset: ... } + // for example: + // _cachedPillars["0_2_1"] + + this._cachedPillars = {}; + } + /** + * Call whenever you change the data array. + */ + + update() { + this._cachedPillars = {}; + } + /** + * Update the `minValue` property + */ + + updateMinValue() { + const data = this.data; + let minValue = data[0][0]; + + for (let i = 0; i !== data.length; i++) { + for (let j = 0; j !== data[i].length; j++) { + const v = data[i][j]; + + if (v < minValue) { + minValue = v; + } + } + } + + this.minValue = minValue; + } + /** + * Update the `maxValue` property + */ + + updateMaxValue() { + const data = this.data; + let maxValue = data[0][0]; + + for (let i = 0; i !== data.length; i++) { + for (let j = 0; j !== data[i].length; j++) { + const v = data[i][j]; + + if (v > maxValue) { + maxValue = v; + } + } + } + + this.maxValue = maxValue; + } + /** + * Set the height value at an index. Don't forget to update maxValue and minValue after you're done. + */ + + setHeightValueAtIndex(xi, yi, value) { + const data = this.data; + data[xi][yi] = value; // Invalidate cache + + this.clearCachedConvexTrianglePillar(xi, yi, false); + + if (xi > 0) { + this.clearCachedConvexTrianglePillar(xi - 1, yi, true); + this.clearCachedConvexTrianglePillar(xi - 1, yi, false); + } + + if (yi > 0) { + this.clearCachedConvexTrianglePillar(xi, yi - 1, true); + this.clearCachedConvexTrianglePillar(xi, yi - 1, false); + } + + if (yi > 0 && xi > 0) { + this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true); + } + } + /** + * Get max/min in a rectangle in the matrix data + * @param result An array to store the results in. + * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1. + */ + + getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result) { + if (result === void 0) { + result = []; + } + + // Get max and min of the data + const data = this.data; // Set first value + + let max = this.minValue; + + for (let i = iMinX; i <= iMaxX; i++) { + for (let j = iMinY; j <= iMaxY; j++) { + const height = data[i][j]; + + if (height > max) { + max = height; + } + } + } + + result[0] = this.minValue; + result[1] = max; + } + /** + * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1. + * @param result Two-element array + * @param clamp If the position should be clamped to the heightfield edge. + */ + + getIndexOfPosition(x, y, result, clamp) { + // Get the index of the data points to test against + const w = this.elementSize; + const data = this.data; + let xi = Math.floor(x / w); + let yi = Math.floor(y / w); + result[0] = xi; + result[1] = yi; + + if (clamp) { + // Clamp index to edges + if (xi < 0) { + xi = 0; + } + + if (yi < 0) { + yi = 0; + } + + if (xi >= data.length - 1) { + xi = data.length - 1; + } + + if (yi >= data[0].length - 1) { + yi = data[0].length - 1; + } + } // Bail out if we are out of the terrain + + if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) { + return false; + } + + return true; + } + + getTriangleAt(x, y, edgeClamp, a, b, c) { + const idx = getHeightAt_idx; + this.getIndexOfPosition(x, y, idx, edgeClamp); + let xi = idx[0]; + let yi = idx[1]; + const data = this.data; + + if (edgeClamp) { + xi = Math.min(data.length - 2, Math.max(0, xi)); + yi = Math.min(data[0].length - 2, Math.max(0, yi)); + } + + const elementSize = this.elementSize; + const lowerDist2 = + (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2; + const upperDist2 = + (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2; + const upper = lowerDist2 > upperDist2; + this.getTriangle(xi, yi, upper, a, b, c); + return upper; + } + + getNormalAt(x, y, edgeClamp, result) { + const a = getNormalAt_a; + const b = getNormalAt_b; + const c = getNormalAt_c; + const e0 = getNormalAt_e0; + const e1 = getNormalAt_e1; + this.getTriangleAt(x, y, edgeClamp, a, b, c); + b.vsub(a, e0); + c.vsub(a, e1); + e0.cross(e1, result); + result.normalize(); + } + /** + * Get an AABB of a square in the heightfield + * @param xi + * @param yi + * @param result + */ + + getAabbAtIndex(xi, yi, _ref) { + let { lowerBound, upperBound } = _ref; + const data = this.data; + const elementSize = this.elementSize; + lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]); + upperBound.set( + (xi + 1) * elementSize, + (yi + 1) * elementSize, + data[xi + 1][yi + 1] + ); + } + /** + * Get the height in the heightfield at a given position + */ + + getHeightAt(x, y, edgeClamp) { + const data = this.data; + const a = getHeightAt_a; + const b = getHeightAt_b; + const c = getHeightAt_c; + const idx = getHeightAt_idx; + this.getIndexOfPosition(x, y, idx, edgeClamp); + let xi = idx[0]; + let yi = idx[1]; + + if (edgeClamp) { + xi = Math.min(data.length - 2, Math.max(0, xi)); + yi = Math.min(data[0].length - 2, Math.max(0, yi)); + } + + const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c); + barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights); + const w = getHeightAt_weights; + + if (upper) { + // Top triangle verts + return ( + data[xi + 1][yi + 1] * w.x + + data[xi][yi + 1] * w.y + + data[xi + 1][yi] * w.z + ); + } else { + // Top triangle verts + return ( + data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z + ); + } + } + + getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) { + return `${xi}_${yi}_${getUpperTriangle ? 1 : 0}`; + } + + getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) { + return this._cachedPillars[ + this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) + ]; + } + + setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) { + this._cachedPillars[ + this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) + ] = { + convex, + offset, + }; + } + + clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) { + delete this._cachedPillars[ + this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) + ]; + } + /** + * Get a triangle from the heightfield + */ + + getTriangle(xi, yi, upper, a, b, c) { + const data = this.data; + const elementSize = this.elementSize; + + if (upper) { + // Top triangle verts + a.set( + (xi + 1) * elementSize, + (yi + 1) * elementSize, + data[xi + 1][yi + 1] + ); + b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]); + c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]); + } else { + // Top triangle verts + a.set(xi * elementSize, yi * elementSize, data[xi][yi]); + b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]); + c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]); + } + } + /** + * Get a triangle in the terrain in the form of a triangular convex shape. + */ + + getConvexTrianglePillar(xi, yi, getUpperTriangle) { + let result = this.pillarConvex; + let offsetResult = this.pillarOffset; + + if (this.cacheEnabled) { + const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle); + + if (data) { + this.pillarConvex = data.convex; + this.pillarOffset = data.offset; + return; + } + + result = new ConvexPolyhedron(); + offsetResult = new Vec3(); + this.pillarConvex = result; + this.pillarOffset = offsetResult; + } + + const data = this.data; + const elementSize = this.elementSize; + const faces = result.faces; // Reuse verts if possible + + result.vertices.length = 6; + + for (let i = 0; i < 6; i++) { + if (!result.vertices[i]) { + result.vertices[i] = new Vec3(); + } + } // Reuse faces if possible + + faces.length = 5; + + for (let i = 0; i < 5; i++) { + if (!faces[i]) { + faces[i] = []; + } + } + + const verts = result.vertices; + const h = + (Math.min( + data[xi][yi], + data[xi + 1][yi], + data[xi][yi + 1], + data[xi + 1][yi + 1] + ) - + this.minValue) / + 2 + + this.minValue; + + if (!getUpperTriangle) { + // Center of the triangle pillar - all polygons are given relative to this one + offsetResult.set( + (xi + 0.25) * elementSize, // sort of center of a triangle + (yi + 0.25) * elementSize, + h // vertical center + ); // Top triangle verts + + verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h); + verts[1].set( + 0.75 * elementSize, + -0.25 * elementSize, + data[xi + 1][yi] - h + ); + verts[2].set( + -0.25 * elementSize, + 0.75 * elementSize, + data[xi][yi + 1] - h + ); // bottom triangle verts + + verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1); + verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1); + verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle + + faces[0][0] = 0; + faces[0][1] = 1; + faces[0][2] = 2; // bottom triangle + + faces[1][0] = 5; + faces[1][1] = 4; + faces[1][2] = 3; // -x facing quad + + faces[2][0] = 0; + faces[2][1] = 2; + faces[2][2] = 5; + faces[2][3] = 3; // -y facing quad + + faces[3][0] = 1; + faces[3][1] = 0; + faces[3][2] = 3; + faces[3][3] = 4; // +xy facing quad + + faces[4][0] = 4; + faces[4][1] = 5; + faces[4][2] = 2; + faces[4][3] = 1; + } else { + // Center of the triangle pillar - all polygons are given relative to this one + offsetResult.set( + (xi + 0.75) * elementSize, // sort of center of a triangle + (yi + 0.75) * elementSize, + h // vertical center + ); // Top triangle verts + + verts[0].set( + 0.25 * elementSize, + 0.25 * elementSize, + data[xi + 1][yi + 1] - h + ); + verts[1].set( + -0.75 * elementSize, + 0.25 * elementSize, + data[xi][yi + 1] - h + ); + verts[2].set( + 0.25 * elementSize, + -0.75 * elementSize, + data[xi + 1][yi] - h + ); // bottom triangle verts + + verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1); + verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1); + verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle + + faces[0][0] = 0; + faces[0][1] = 1; + faces[0][2] = 2; // bottom triangle + + faces[1][0] = 5; + faces[1][1] = 4; + faces[1][2] = 3; // +x facing quad + + faces[2][0] = 2; + faces[2][1] = 5; + faces[2][2] = 3; + faces[2][3] = 0; // +y facing quad + + faces[3][0] = 3; + faces[3][1] = 4; + faces[3][2] = 1; + faces[3][3] = 0; // -xy facing quad + + faces[4][0] = 1; + faces[4][1] = 4; + faces[4][2] = 5; + faces[4][3] = 2; + } + + result.computeNormals(); + result.computeEdges(); + result.updateBoundingSphereRadius(); + this.setCachedConvexTrianglePillar( + xi, + yi, + getUpperTriangle, + result, + offsetResult + ); + } + + calculateLocalInertia(mass, target) { + if (target === void 0) { + target = new Vec3(); + } + + target.set(0, 0, 0); + return target; + } + + volume() { + return ( + // The terrain is infinite + Number.MAX_VALUE + ); + } + + calculateWorldAABB(pos, quat, min, max) { + /** @TODO do it properly */ + min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + } + + updateBoundingSphereRadius() { + // Use the bounding box of the min/max values + const data = this.data; + const s = this.elementSize; + this.boundingSphereRadius = new Vec3( + data.length * s, + data[0].length * s, + Math.max(Math.abs(this.maxValue), Math.abs(this.minValue)) + ).length(); + } + /** + * Sets the height values from an image. Currently only supported in browser. + */ + + setHeightsFromImage(image, scale) { + const { x, z, y } = scale; + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0); + const imageData = context.getImageData(0, 0, image.width, image.height); + const matrix = this.data; + matrix.length = 0; + this.elementSize = Math.abs(x) / imageData.width; + + for (let i = 0; i < imageData.height; i++) { + const row = []; + + for (let j = 0; j < imageData.width; j++) { + const a = imageData.data[(i * imageData.height + j) * 4]; + const b = imageData.data[(i * imageData.height + j) * 4 + 1]; + const c = imageData.data[(i * imageData.height + j) * 4 + 2]; + const height = ((a + b + c) / 4 / 255) * z; + + if (x < 0) { + row.push(height); + } else { + row.unshift(height); + } + } + + if (y < 0) { + matrix.unshift(row); + } else { + matrix.push(row); + } + } + + this.updateMaxValue(); + this.updateMinValue(); + this.update(); + } + } + const getHeightAt_idx = []; + const getHeightAt_weights = new Vec3(); + const getHeightAt_a = new Vec3(); + const getHeightAt_b = new Vec3(); + const getHeightAt_c = new Vec3(); + const getNormalAt_a = new Vec3(); + const getNormalAt_b = new Vec3(); + const getNormalAt_c = new Vec3(); + const getNormalAt_e0 = new Vec3(); + const getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system + + function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) { + result.x = + ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / + ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy)); + result.y = + ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / + ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy)); + result.z = 1 - result.x - result.y; + } + + /** + * OctreeNode + */ + class OctreeNode { + /** The root node */ + + /** Boundary of this node */ + + /** Contained data at the current node level */ + + /** Children to this node */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + this.root = options.root || null; + this.aabb = options.aabb ? options.aabb.clone() : new AABB(); + this.data = []; + this.children = []; + } + /** + * reset + */ + + reset() { + this.children.length = this.data.length = 0; + } + /** + * Insert data into this node + * @return True if successful, otherwise false + */ + + insert(aabb, elementData, level) { + if (level === void 0) { + level = 0; + } + + const nodeData = this.data; // Ignore objects that do not belong in this node + + if (!this.aabb.contains(aabb)) { + return false; // object cannot be added + } + + const children = this.children; + const maxDepth = this.maxDepth || this.root.maxDepth; + + if (level < maxDepth) { + // Subdivide if there are no children yet + let subdivided = false; + + if (!children.length) { + this.subdivide(); + subdivided = true; + } // add to whichever node will accept it + + for (let i = 0; i !== 8; i++) { + if (children[i].insert(aabb, elementData, level + 1)) { + return true; + } + } + + if (subdivided) { + // No children accepted! Might as well just remove em since they contain none + children.length = 0; + } + } // Too deep, or children didnt want it. add it in current node + + nodeData.push(elementData); + return true; + } + /** + * Create 8 equally sized children nodes and put them in the `children` array. + */ + + subdivide() { + const aabb = this.aabb; + const l = aabb.lowerBound; + const u = aabb.upperBound; + const children = this.children; + children.push( + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(0, 0, 0), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(1, 0, 0), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(1, 1, 0), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(1, 1, 1), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(0, 1, 1), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(0, 0, 1), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(1, 0, 1), + }), + }), + new OctreeNode({ + aabb: new AABB({ + lowerBound: new Vec3(0, 1, 0), + }), + }) + ); + u.vsub(l, halfDiagonal); + halfDiagonal.scale(0.5, halfDiagonal); + const root = this.root || this; + + for (let i = 0; i !== 8; i++) { + const child = children[i]; // Set current node as root + + child.root = root; // Compute bounds + + const lowerBound = child.aabb.lowerBound; + lowerBound.x *= halfDiagonal.x; + lowerBound.y *= halfDiagonal.y; + lowerBound.z *= halfDiagonal.z; + lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal + + lowerBound.vadd(halfDiagonal, child.aabb.upperBound); + } + } + /** + * Get all data, potentially within an AABB + * @return The "result" object + */ + + aabbQuery(aabb, result) { + this.data; // abort if the range does not intersect this node + // if (!this.aabb.overlaps(aabb)){ + // return result; + // } + // Add objects at this level + // Array.prototype.push.apply(result, nodeData); + // Add child data + // @todo unwrap recursion into a queue / loop, that's faster in JS + + this.children; // for (let i = 0, N = this.children.length; i !== N; i++) { + // children[i].aabbQuery(aabb, result); + // } + + const queue = [this]; + + while (queue.length) { + const node = queue.pop(); + + if (node.aabb.overlaps(aabb)) { + Array.prototype.push.apply(result, node.data); + } + + Array.prototype.push.apply(queue, node.children); + } + + return result; + } + /** + * Get all data, potentially intersected by a ray. + * @return The "result" object + */ + + rayQuery(ray, treeTransform, result) { + // Use aabb query for now. + + /** @todo implement real ray query which needs less lookups */ + ray.getAABB(tmpAABB); + tmpAABB.toLocalFrame(treeTransform, tmpAABB); + this.aabbQuery(tmpAABB, result); + return result; + } + /** + * removeEmptyNodes + */ + + removeEmptyNodes() { + for (let i = this.children.length - 1; i >= 0; i--) { + this.children[i].removeEmptyNodes(); + + if (!this.children[i].children.length && !this.children[i].data.length) { + this.children.splice(i, 1); + } + } + } + } + /** + * Octree + */ + + class Octree extends OctreeNode { + /** + * Maximum subdivision depth + * @default 8 + */ + + /** + * @param aabb The total AABB of the tree + */ + constructor(aabb, options) { + if (options === void 0) { + options = {}; + } + + super({ + root: null, + aabb, + }); + this.maxDepth = + typeof options.maxDepth !== "undefined" ? options.maxDepth : 8; + } + } + const halfDiagonal = new Vec3(); + const tmpAABB = new AABB(); + + /** + * Trimesh. + * @example + * // How to make a mesh with a single triangle + * const vertices = [ + * 0, 0, 0, // vertex 0 + * 1, 0, 0, // vertex 1 + * 0, 1, 0 // vertex 2 + * ] + * const indices = [ + * 0, 1, 2 // triangle 0 + * ] + * const trimeshShape = new CANNON.Trimesh(vertices, indices) + */ + class Trimesh extends Shape { + /** + * vertices + */ + + /** + * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles. + */ + + /** + * The normals data. + */ + + /** + * The local AABB of the mesh. + */ + + /** + * References to vertex pairs, making up all unique edges in the trimesh. + */ + + /** + * Local scaling of the mesh. Use .setScale() to set it. + */ + + /** + * The indexed triangles. Use .updateTree() to update it. + */ + constructor(vertices, indices) { + super({ + type: Shape.types.TRIMESH, + }); + this.vertices = new Float32Array(vertices); + this.indices = new Int16Array(indices); + this.normals = new Float32Array(indices.length); + this.aabb = new AABB(); + this.edges = null; + this.scale = new Vec3(1, 1, 1); + this.tree = new Octree(); + this.updateEdges(); + this.updateNormals(); + this.updateAABB(); + this.updateBoundingSphereRadius(); + this.updateTree(); + } + /** + * updateTree + */ + + updateTree() { + const tree = this.tree; + tree.reset(); + tree.aabb.copy(this.aabb); + const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled + + tree.aabb.lowerBound.x *= 1 / scale.x; + tree.aabb.lowerBound.y *= 1 / scale.y; + tree.aabb.lowerBound.z *= 1 / scale.z; + tree.aabb.upperBound.x *= 1 / scale.x; + tree.aabb.upperBound.y *= 1 / scale.y; + tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles + + const triangleAABB = new AABB(); + const a = new Vec3(); + const b = new Vec3(); + const c = new Vec3(); + const points = [a, b, c]; + + for (let i = 0; i < this.indices.length / 3; i++) { + //this.getTriangleVertices(i, a, b, c); + // Get unscaled triangle verts + const i3 = i * 3; + + this._getUnscaledVertex(this.indices[i3], a); + + this._getUnscaledVertex(this.indices[i3 + 1], b); + + this._getUnscaledVertex(this.indices[i3 + 2], c); + + triangleAABB.setFromPoints(points); + tree.insert(triangleAABB, i); + } + + tree.removeEmptyNodes(); + } + /** + * Get triangles in a local AABB from the trimesh. + * @param result An array of integers, referencing the queried triangles. + */ + + getTrianglesInAABB(aabb, result) { + unscaledAABB.copy(aabb); // Scale it to local + + const scale = this.scale; + const isx = scale.x; + const isy = scale.y; + const isz = scale.z; + const l = unscaledAABB.lowerBound; + const u = unscaledAABB.upperBound; + l.x /= isx; + l.y /= isy; + l.z /= isz; + u.x /= isx; + u.y /= isy; + u.z /= isz; + return this.tree.aabbQuery(unscaledAABB, result); + } + /** + * setScale + */ + + setScale(scale) { + const wasUniform = + this.scale.x === this.scale.y && this.scale.y === this.scale.z; + const isUniform = scale.x === scale.y && scale.y === scale.z; + + if (!(wasUniform && isUniform)) { + // Non-uniform scaling. Need to update normals. + this.updateNormals(); + } + + this.scale.copy(scale); + this.updateAABB(); + this.updateBoundingSphereRadius(); + } + /** + * Compute the normals of the faces. Will save in the `.normals` array. + */ + + updateNormals() { + const n = computeNormals_n; // Generate normals + + const normals = this.normals; + + for (let i = 0; i < this.indices.length / 3; i++) { + const i3 = i * 3; + const a = this.indices[i3]; + const b = this.indices[i3 + 1]; + const c = this.indices[i3 + 2]; + this.getVertex(a, va); + this.getVertex(b, vb); + this.getVertex(c, vc); + Trimesh.computeNormal(vb, va, vc, n); + normals[i3] = n.x; + normals[i3 + 1] = n.y; + normals[i3 + 2] = n.z; + } + } + /** + * Update the `.edges` property + */ + + updateEdges() { + const edges = {}; + + const add = (a, b) => { + const key = a < b ? `${a}_${b}` : `${b}_${a}`; + edges[key] = true; + }; + + for (let i = 0; i < this.indices.length / 3; i++) { + const i3 = i * 3; + const a = this.indices[i3]; + const b = this.indices[i3 + 1]; + const c = this.indices[i3 + 2]; + add(a, b); + add(b, c); + add(c, a); + } + + const keys = Object.keys(edges); + this.edges = new Int16Array(keys.length * 2); + + for (let i = 0; i < keys.length; i++) { + const indices = keys[i].split("_"); + this.edges[2 * i] = parseInt(indices[0], 10); + this.edges[2 * i + 1] = parseInt(indices[1], 10); + } + } + /** + * Get an edge vertex + * @param firstOrSecond 0 or 1, depending on which one of the vertices you need. + * @param vertexStore Where to store the result + */ + + getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) { + const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)]; + this.getVertex(vertexIndex, vertexStore); + } + /** + * Get a vector along an edge. + */ + + getEdgeVector(edgeIndex, vectorStore) { + const va = getEdgeVector_va; + const vb = getEdgeVector_vb; + this.getEdgeVertex(edgeIndex, 0, va); + this.getEdgeVertex(edgeIndex, 1, vb); + vb.vsub(va, vectorStore); + } + /** + * Get face normal given 3 vertices + */ + + static computeNormal(va, vb, vc, target) { + vb.vsub(va, ab); + vc.vsub(vb, cb); + cb.cross(ab, target); + + if (!target.isZero()) { + target.normalize(); + } + } + /** + * Get vertex i. + * @return The "out" vector object + */ + + getVertex(i, out) { + const scale = this.scale; + + this._getUnscaledVertex(i, out); + + out.x *= scale.x; + out.y *= scale.y; + out.z *= scale.z; + return out; + } + /** + * Get raw vertex i + * @return The "out" vector object + */ + + _getUnscaledVertex(i, out) { + const i3 = i * 3; + const vertices = this.vertices; + return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]); + } + /** + * Get a vertex from the trimesh,transformed by the given position and quaternion. + * @return The "out" vector object + */ + + getWorldVertex(i, pos, quat, out) { + this.getVertex(i, out); + Transform.pointToWorldFrame(pos, quat, out, out); + return out; + } + /** + * Get the three vertices for triangle i. + */ + + getTriangleVertices(i, a, b, c) { + const i3 = i * 3; + this.getVertex(this.indices[i3], a); + this.getVertex(this.indices[i3 + 1], b); + this.getVertex(this.indices[i3 + 2], c); + } + /** + * Compute the normal of triangle i. + * @return The "target" vector object + */ + + getNormal(i, target) { + const i3 = i * 3; + return target.set( + this.normals[i3], + this.normals[i3 + 1], + this.normals[i3 + 2] + ); + } + /** + * @return The "target" vector object + */ + + calculateLocalInertia(mass, target) { + // Approximate with box inertia + // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it + this.computeLocalAABB(cli_aabb); + const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x; + const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y; + const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z; + return target.set( + (1.0 / 12.0) * mass * (2 * y * 2 * y + 2 * z * 2 * z), + (1.0 / 12.0) * mass * (2 * x * 2 * x + 2 * z * 2 * z), + (1.0 / 12.0) * mass * (2 * y * 2 * y + 2 * x * 2 * x) + ); + } + /** + * Compute the local AABB for the trimesh + */ + + computeLocalAABB(aabb) { + const l = aabb.lowerBound; + const u = aabb.upperBound; + const n = this.vertices.length; + this.vertices; + const v = computeLocalAABB_worldVert; + this.getVertex(0, v); + l.copy(v); + u.copy(v); + + for (let i = 0; i !== n; i++) { + this.getVertex(i, v); + + if (v.x < l.x) { + l.x = v.x; + } else if (v.x > u.x) { + u.x = v.x; + } + + if (v.y < l.y) { + l.y = v.y; + } else if (v.y > u.y) { + u.y = v.y; + } + + if (v.z < l.z) { + l.z = v.z; + } else if (v.z > u.z) { + u.z = v.z; + } + } + } + /** + * Update the `.aabb` property + */ + + updateAABB() { + this.computeLocalAABB(this.aabb); + } + /** + * Will update the `.boundingSphereRadius` property + */ + + updateBoundingSphereRadius() { + // Assume points are distributed with local (0,0,0) as center + let max2 = 0; + const vertices = this.vertices; + const v = new Vec3(); + + for (let i = 0, N = vertices.length / 3; i !== N; i++) { + this.getVertex(i, v); + const norm2 = v.lengthSquared(); + + if (norm2 > max2) { + max2 = norm2; + } + } + + this.boundingSphereRadius = Math.sqrt(max2); + } + /** + * calculateWorldAABB + */ + + calculateWorldAABB(pos, quat, min, max) { + /* + const n = this.vertices.length / 3, + verts = this.vertices; + const minx,miny,minz,maxx,maxy,maxz; + const v = tempWorldVertex; + for(let i=0; i maxx || maxx===undefined){ + maxx = v.x; + } + if (v.y < miny || miny===undefined){ + miny = v.y; + } else if(v.y > maxy || maxy===undefined){ + maxy = v.y; + } + if (v.z < minz || minz===undefined){ + minz = v.z; + } else if(v.z > maxz || maxz===undefined){ + maxz = v.z; + } + } + min.set(minx,miny,minz); + max.set(maxx,maxy,maxz); + */ + // Faster approximation using local AABB + const frame = calculateWorldAABB_frame; + const result = calculateWorldAABB_aabb; + frame.position = pos; + frame.quaternion = quat; + this.aabb.toWorldFrame(frame, result); + min.copy(result.lowerBound); + max.copy(result.upperBound); + } + /** + * Get approximate volume + */ + + volume() { + return (4.0 * Math.PI * this.boundingSphereRadius) / 3.0; + } + /** + * Create a Trimesh instance, shaped as a torus. + */ + + static createTorus(radius, tube, radialSegments, tubularSegments, arc) { + if (radius === void 0) { + radius = 1; + } + + if (tube === void 0) { + tube = 0.5; + } + + if (radialSegments === void 0) { + radialSegments = 8; + } + + if (tubularSegments === void 0) { + tubularSegments = 6; + } + + if (arc === void 0) { + arc = Math.PI * 2; + } + + const vertices = []; + const indices = []; + + for (let j = 0; j <= radialSegments; j++) { + for (let i = 0; i <= tubularSegments; i++) { + const u = (i / tubularSegments) * arc; + const v = (j / radialSegments) * Math.PI * 2; + const x = (radius + tube * Math.cos(v)) * Math.cos(u); + const y = (radius + tube * Math.cos(v)) * Math.sin(u); + const z = tube * Math.sin(v); + vertices.push(x, y, z); + } + } + + for (let j = 1; j <= radialSegments; j++) { + for (let i = 1; i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + + return new Trimesh(vertices, indices); + } + } + const computeNormals_n = new Vec3(); + const unscaledAABB = new AABB(); + const getEdgeVector_va = new Vec3(); + const getEdgeVector_vb = new Vec3(); + const cb = new Vec3(); + const ab = new Vec3(); + const va = new Vec3(); + const vb = new Vec3(); + const vc = new Vec3(); + const cli_aabb = new AABB(); + const computeLocalAABB_worldVert = new Vec3(); + const calculateWorldAABB_frame = new Transform(); + const calculateWorldAABB_aabb = new AABB(); + + /** + * Constraint equation solver base class. + */ + class Solver { + /** + * All equations to be solved + */ + + /** + * @todo remove useless constructor + */ + constructor() { + this.equations = []; + } + /** + * Should be implemented in subclasses! + * @todo use abstract + * @return number of iterations performed + */ + + solve(dt, world) { + return ( + // Should return the number of iterations done! + 0 + ); + } + /** + * Add an equation + */ + + addEquation(eq) { + if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) { + this.equations.push(eq); + } + } + /** + * Remove an equation + */ + + removeEquation(eq) { + const eqs = this.equations; + const i = eqs.indexOf(eq); + + if (i !== -1) { + eqs.splice(i, 1); + } + } + /** + * Add all equations + */ + + removeAllEquations() { + this.equations.length = 0; + } + } + + /** + * Constraint equation Gauss-Seidel solver. + * @todo The spook parameters should be specified for each constraint, not globally. + * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf + */ + class GSSolver extends Solver { + /** + * The number of solver iterations determines quality of the constraints in the world. + * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations. + */ + + /** + * When tolerance is reached, the system is assumed to be converged. + */ + + /** + * @todo remove useless constructor + */ + constructor() { + super(); + this.iterations = 10; + this.tolerance = 1e-7; + } + /** + * Solve + * @return number of iterations performed + */ + + solve(dt, world) { + let iter = 0; + const maxIter = this.iterations; + const tolSquared = this.tolerance * this.tolerance; + const equations = this.equations; + const Neq = equations.length; + const bodies = world.bodies; + const Nbodies = bodies.length; + const h = dt; + let B; + let invC; + let deltalambda; + let deltalambdaTot; + let GWlambda; + let lambdaj; // Update solve mass + + if (Neq !== 0) { + for (let i = 0; i !== Nbodies; i++) { + bodies[i].updateSolveMassProperties(); + } + } // Things that do not change during iteration can be computed once + + const invCs = GSSolver_solve_invCs; + const Bs = GSSolver_solve_Bs; + const lambda = GSSolver_solve_lambda; + invCs.length = Neq; + Bs.length = Neq; + lambda.length = Neq; + + for (let i = 0; i !== Neq; i++) { + const c = equations[i]; + lambda[i] = 0.0; + Bs[i] = c.computeB(h); + invCs[i] = 1.0 / c.computeC(); + } + + if (Neq !== 0) { + // Reset vlambda + for (let i = 0; i !== Nbodies; i++) { + const b = bodies[i]; + const vlambda = b.vlambda; + const wlambda = b.wlambda; + vlambda.set(0, 0, 0); + wlambda.set(0, 0, 0); + } // Iterate over equations + + for (iter = 0; iter !== maxIter; iter++) { + // Accumulate the total error for each iteration. + deltalambdaTot = 0.0; + + for (let j = 0; j !== Neq; j++) { + const c = equations[j]; // Compute iteration + + B = Bs[j]; + invC = invCs[j]; + lambdaj = lambda[j]; + GWlambda = c.computeGWlambda(); + deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval + + if (lambdaj + deltalambda < c.minForce) { + deltalambda = c.minForce - lambdaj; + } else if (lambdaj + deltalambda > c.maxForce) { + deltalambda = c.maxForce - lambdaj; + } + + lambda[j] += deltalambda; + deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda) + + c.addToWlambda(deltalambda); + } // If the total error is small enough - stop iterate + + if (deltalambdaTot * deltalambdaTot < tolSquared) { + break; + } + } // Add result to velocity + + for (let i = 0; i !== Nbodies; i++) { + const b = bodies[i]; + const v = b.velocity; + const w = b.angularVelocity; + b.vlambda.vmul(b.linearFactor, b.vlambda); + v.vadd(b.vlambda, v); + b.wlambda.vmul(b.angularFactor, b.wlambda); + w.vadd(b.wlambda, w); + } // Set the `.multiplier` property of each equation + + let l = equations.length; + const invDt = 1 / h; + + while (l--) { + equations[l].multiplier = lambda[l] * invDt; + } + } + + return iter; + } + } // Just temporary number holders that we want to reuse each iteration. + + const GSSolver_solve_lambda = []; + const GSSolver_solve_invCs = []; + const GSSolver_solve_Bs = []; + + /** + * Splits the equations into islands and solves them independently. Can improve performance. + */ + class SplitSolver extends Solver { + /** + * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations. + */ + + /** + * When tolerance is reached, the system is assumed to be converged. + */ + + /** subsolver */ + constructor(subsolver) { + super(); + this.iterations = 10; + this.tolerance = 1e-7; + this.subsolver = subsolver; + this.nodes = []; + this.nodePool = []; // Create needed nodes, reuse if possible + + while (this.nodePool.length < 128) { + this.nodePool.push(this.createNode()); + } + } + /** + * createNode + */ + + createNode() { + return { + body: null, + children: [], + eqs: [], + visited: false, + }; + } + /** + * Solve the subsystems + * @return number of iterations performed + */ + + solve(dt, world) { + const nodes = SplitSolver_solve_nodes; + const nodePool = this.nodePool; + const bodies = world.bodies; + const equations = this.equations; + const Neq = equations.length; + const Nbodies = bodies.length; + const subsolver = this.subsolver; // Create needed nodes, reuse if possible + + while (nodePool.length < Nbodies) { + nodePool.push(this.createNode()); + } + + nodes.length = Nbodies; + + for (let i = 0; i < Nbodies; i++) { + nodes[i] = nodePool[i]; + } // Reset node values + + for (let i = 0; i !== Nbodies; i++) { + const node = nodes[i]; + node.body = bodies[i]; + node.children.length = 0; + node.eqs.length = 0; + node.visited = false; + } + + for (let k = 0; k !== Neq; k++) { + const eq = equations[k]; + const i = bodies.indexOf(eq.bi); + const j = bodies.indexOf(eq.bj); + const ni = nodes[i]; + const nj = nodes[j]; + ni.children.push(nj); + ni.eqs.push(eq); + nj.children.push(ni); + nj.eqs.push(eq); + } + + let child; + let n = 0; + let eqs = SplitSolver_solve_eqs; + subsolver.tolerance = this.tolerance; + subsolver.iterations = this.iterations; + const dummyWorld = SplitSolver_solve_dummyWorld; + + while ((child = getUnvisitedNode(nodes))) { + eqs.length = 0; + dummyWorld.bodies.length = 0; + bfs(child, visitFunc, dummyWorld.bodies, eqs); + const Neqs = eqs.length; + eqs = eqs.sort(sortById); + + for (let i = 0; i !== Neqs; i++) { + subsolver.addEquation(eqs[i]); + } + + subsolver.solve(dt, dummyWorld); + subsolver.removeAllEquations(); + n++; + } + + return n; + } + } // Returns the number of subsystems + + const SplitSolver_solve_nodes = []; // All allocated node objects + + const SplitSolver_solve_eqs = []; // Temp array + + const SplitSolver_solve_dummyWorld = { + bodies: [], + }; // Temp object + + const STATIC = Body.STATIC; + + function getUnvisitedNode(nodes) { + const Nnodes = nodes.length; + + for (let i = 0; i !== Nnodes; i++) { + const node = nodes[i]; + + if (!node.visited && !(node.body.type & STATIC)) { + return node; + } + } + + return false; + } + + const queue = []; + + function bfs(root, visitFunc, bds, eqs) { + queue.push(root); + root.visited = true; + visitFunc(root, bds, eqs); + + while (queue.length) { + const node = queue.pop(); // Loop over unvisited child nodes + + let child; + + while ((child = getUnvisitedNode(node.children))) { + child.visited = true; + visitFunc(child, bds, eqs); + queue.push(child); + } + } + } + + function visitFunc(node, bds, eqs) { + bds.push(node.body); + const Neqs = node.eqs.length; + + for (let i = 0; i !== Neqs; i++) { + const eq = node.eqs[i]; + + if (!eqs.includes(eq)) { + eqs.push(eq); + } + } + } + + function sortById(a, b) { + return b.id - a.id; + } + + /** + * For pooling objects that can be reused. + */ + class Pool { + constructor() { + this.objects = []; + this.type = Object; + } + + /** + * Release an object after use + */ + release() { + const Nargs = arguments.length; + + for (let i = 0; i !== Nargs; i++) { + this.objects.push( + i < 0 || arguments.length <= i ? undefined : arguments[i] + ); + } + + return this; + } + /** + * Get an object + */ + + get() { + if (this.objects.length === 0) { + return this.constructObject(); + } else { + return this.objects.pop(); + } + } + /** + * Construct an object. Should be implemented in each subclass. + */ + + constructObject() { + throw new Error( + "constructObject() not implemented in this Pool subclass yet!" + ); + } + /** + * @return Self, for chaining + */ + + resize(size) { + const objects = this.objects; + + while (objects.length > size) { + objects.pop(); + } + + while (objects.length < size) { + objects.push(this.constructObject()); + } + + return this; + } + } + + /** + * Vec3Pool + */ + + class Vec3Pool extends Pool { + constructor() { + super(...arguments); + this.type = Vec3; + } + + /** + * Construct a vector + */ + constructObject() { + return new Vec3(); + } + } + + // Naming rule: based of the order in SHAPE_TYPES, + // the first part of the method is formed by the + // shape type that comes before, in the second part + // there is the shape type that comes after in the SHAPE_TYPES list + const COLLISION_TYPES = { + sphereSphere: Shape.types.SPHERE, + spherePlane: Shape.types.SPHERE | Shape.types.PLANE, + boxBox: Shape.types.BOX | Shape.types.BOX, + sphereBox: Shape.types.SPHERE | Shape.types.BOX, + planeBox: Shape.types.PLANE | Shape.types.BOX, + convexConvex: Shape.types.CONVEXPOLYHEDRON, + sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON, + planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON, + boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON, + sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD, + boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD, + convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD, + sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE, + planeParticle: Shape.types.PLANE | Shape.types.PARTICLE, + boxParticle: Shape.types.BOX | Shape.types.PARTICLE, + convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON, + cylinderCylinder: Shape.types.CYLINDER, + sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER, + planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER, + boxCylinder: Shape.types.BOX | Shape.types.CYLINDER, + convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER, + heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER, + particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER, + sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH, + planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH, + }; + + /** + * Helper class for the World. Generates ContactEquations. + * @todo Sphere-ConvexPolyhedron contacts + * @todo Contact reduction + * @todo should move methods to prototype + */ + class Narrowphase { + /** + * Internal storage of pooled contact points. + */ + + /** + * Pooled vectors. + */ + get [COLLISION_TYPES.sphereSphere]() { + return this.sphereSphere; + } + + get [COLLISION_TYPES.spherePlane]() { + return this.spherePlane; + } + + get [COLLISION_TYPES.boxBox]() { + return this.boxBox; + } + + get [COLLISION_TYPES.sphereBox]() { + return this.sphereBox; + } + + get [COLLISION_TYPES.planeBox]() { + return this.planeBox; + } + + get [COLLISION_TYPES.convexConvex]() { + return this.convexConvex; + } + + get [COLLISION_TYPES.sphereConvex]() { + return this.sphereConvex; + } + + get [COLLISION_TYPES.planeConvex]() { + return this.planeConvex; + } + + get [COLLISION_TYPES.boxConvex]() { + return this.boxConvex; + } + + get [COLLISION_TYPES.sphereHeightfield]() { + return this.sphereHeightfield; + } + + get [COLLISION_TYPES.boxHeightfield]() { + return this.boxHeightfield; + } + + get [COLLISION_TYPES.convexHeightfield]() { + return this.convexHeightfield; + } + + get [COLLISION_TYPES.sphereParticle]() { + return this.sphereParticle; + } + + get [COLLISION_TYPES.planeParticle]() { + return this.planeParticle; + } + + get [COLLISION_TYPES.boxParticle]() { + return this.boxParticle; + } + + get [COLLISION_TYPES.convexParticle]() { + return this.convexParticle; + } + + get [COLLISION_TYPES.cylinderCylinder]() { + return this.convexConvex; + } + + get [COLLISION_TYPES.sphereCylinder]() { + return this.sphereConvex; + } + + get [COLLISION_TYPES.planeCylinder]() { + return this.planeConvex; + } + + get [COLLISION_TYPES.boxCylinder]() { + return this.boxConvex; + } + + get [COLLISION_TYPES.convexCylinder]() { + return this.convexConvex; + } + + get [COLLISION_TYPES.heightfieldCylinder]() { + return this.heightfieldCylinder; + } + + get [COLLISION_TYPES.particleCylinder]() { + return this.particleCylinder; + } + + get [COLLISION_TYPES.sphereTrimesh]() { + return this.sphereTrimesh; + } + + get [COLLISION_TYPES.planeTrimesh]() { + return this.planeTrimesh; + } // get [COLLISION_TYPES.convexTrimesh]() { + // return this.convexTrimesh + // } + + constructor(world) { + this.contactPointPool = []; + this.frictionEquationPool = []; + this.result = []; + this.frictionResult = []; + this.v3pool = new Vec3Pool(); + this.world = world; + this.currentContactMaterial = world.defaultContactMaterial; + this.enableFrictionReduction = false; + } + /** + * Make a contact object, by using the internal pool or creating a new one. + */ + + createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) { + let c; + + if (this.contactPointPool.length) { + c = this.contactPointPool.pop(); + c.bi = bi; + c.bj = bj; + } else { + c = new ContactEquation(bi, bj); + } + + c.enabled = + bi.collisionResponse && + bj.collisionResponse && + si.collisionResponse && + sj.collisionResponse; + const cm = this.currentContactMaterial; + c.restitution = cm.restitution; + c.setSpookParams( + cm.contactEquationStiffness, + cm.contactEquationRelaxation, + this.world.dt + ); + const matA = si.material || bi.material; + const matB = sj.material || bj.material; + + if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) { + c.restitution = matA.restitution * matB.restitution; + } + + c.si = overrideShapeA || si; + c.sj = overrideShapeB || sj; + return c; + } + + createFrictionEquationsFromContact(contactEquation, outArray) { + const bodyA = contactEquation.bi; + const bodyB = contactEquation.bj; + const shapeA = contactEquation.si; + const shapeB = contactEquation.sj; + const world = this.world; + const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them + + let friction = cm.friction; + const matA = shapeA.material || bodyA.material; + const matB = shapeB.material || bodyB.material; + + if (matA && matB && matA.friction >= 0 && matB.friction >= 0) { + friction = matA.friction * matB.friction; + } + + if (friction > 0) { + // Create 2 tangent equations + // Users may provide a force different from global gravity to use when computing contact friction. + const mug = friction * (world.frictionGravity || world.gravity).length(); + let reducedMass = bodyA.invMass + bodyB.invMass; + + if (reducedMass > 0) { + reducedMass = 1 / reducedMass; + } + + const pool = this.frictionEquationPool; + const c1 = pool.length + ? pool.pop() + : new FrictionEquation(bodyA, bodyB, mug * reducedMass); + const c2 = pool.length + ? pool.pop() + : new FrictionEquation(bodyA, bodyB, mug * reducedMass); + c1.bi = c2.bi = bodyA; + c1.bj = c2.bj = bodyB; + c1.minForce = c2.minForce = -mug * reducedMass; + c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors + + c1.ri.copy(contactEquation.ri); + c1.rj.copy(contactEquation.rj); + c2.ri.copy(contactEquation.ri); + c2.rj.copy(contactEquation.rj); // Construct tangents + + contactEquation.ni.tangents(c1.t, c2.t); // Set spook params + + c1.setSpookParams( + cm.frictionEquationStiffness, + cm.frictionEquationRelaxation, + world.dt + ); + c2.setSpookParams( + cm.frictionEquationStiffness, + cm.frictionEquationRelaxation, + world.dt + ); + c1.enabled = c2.enabled = contactEquation.enabled; + outArray.push(c1, c2); + return true; + } + + return false; + } + /** + * Take the average N latest contact point on the plane. + */ + + createFrictionFromAverage(numContacts) { + // The last contactEquation + let c = this.result[this.result.length - 1]; // Create the result: two "average" friction equations + + if ( + !this.createFrictionEquationsFromContact(c, this.frictionResult) || + numContacts === 1 + ) { + return; + } + + const f1 = this.frictionResult[this.frictionResult.length - 2]; + const f2 = this.frictionResult[this.frictionResult.length - 1]; + averageNormal.setZero(); + averageContactPointA.setZero(); + averageContactPointB.setZero(); + const bodyA = c.bi; + c.bj; + + for (let i = 0; i !== numContacts; i++) { + c = this.result[this.result.length - 1 - i]; + + if (c.bi !== bodyA) { + averageNormal.vadd(c.ni, averageNormal); + averageContactPointA.vadd(c.ri, averageContactPointA); + averageContactPointB.vadd(c.rj, averageContactPointB); + } else { + averageNormal.vsub(c.ni, averageNormal); + averageContactPointA.vadd(c.rj, averageContactPointA); + averageContactPointB.vadd(c.ri, averageContactPointB); + } + } + + const invNumContacts = 1 / numContacts; + averageContactPointA.scale(invNumContacts, f1.ri); + averageContactPointB.scale(invNumContacts, f1.rj); + f2.ri.copy(f1.ri); // Should be the same + + f2.rj.copy(f1.rj); + averageNormal.normalize(); + averageNormal.tangents(f1.t, f2.t); // return eq; + } + /** + * Generate all contacts between a list of body pairs + * @param p1 Array of body indices + * @param p2 Array of body indices + * @param result Array to store generated contacts + * @param oldcontacts Optional. Array of reusable contact objects + */ + + getContacts( + p1, + p2, + world, + result, + oldcontacts, + frictionResult, + frictionPool + ) { + // Save old contact objects + this.contactPointPool = oldcontacts; + this.frictionEquationPool = frictionPool; + this.result = result; + this.frictionResult = frictionResult; + const qi = tmpQuat1; + const qj = tmpQuat2; + const xi = tmpVec1; + const xj = tmpVec2; + + for (let k = 0, N = p1.length; k !== N; k++) { + // Get current collision bodies + const bi = p1[k]; + const bj = p2[k]; // Get contact material + + let bodyContactMaterial = null; + + if (bi.material && bj.material) { + bodyContactMaterial = + world.getContactMaterial(bi.material, bj.material) || null; + } + + const justTest = + (bi.type & Body.KINEMATIC && bj.type & Body.STATIC) || + (bi.type & Body.STATIC && bj.type & Body.KINEMATIC) || + (bi.type & Body.KINEMATIC && bj.type & Body.KINEMATIC); + + for (let i = 0; i < bi.shapes.length; i++) { + bi.quaternion.mult(bi.shapeOrientations[i], qi); + bi.quaternion.vmult(bi.shapeOffsets[i], xi); + xi.vadd(bi.position, xi); + const si = bi.shapes[i]; + + for (let j = 0; j < bj.shapes.length; j++) { + // Compute world transform of shapes + bj.quaternion.mult(bj.shapeOrientations[j], qj); + bj.quaternion.vmult(bj.shapeOffsets[j], xj); + xj.vadd(bj.position, xj); + const sj = bj.shapes[j]; + + if ( + !( + si.collisionFilterMask & sj.collisionFilterGroup && + sj.collisionFilterMask & si.collisionFilterGroup + ) + ) { + continue; + } + + if ( + xi.distanceTo(xj) > + si.boundingSphereRadius + sj.boundingSphereRadius + ) { + continue; + } // Get collision material + + let shapeContactMaterial = null; + + if (si.material && sj.material) { + shapeContactMaterial = + world.getContactMaterial(si.material, sj.material) || null; + } + + this.currentContactMaterial = + shapeContactMaterial || + bodyContactMaterial || + world.defaultContactMaterial; // Get contacts + + const resolverIndex = si.type | sj.type; + const resolver = this[resolverIndex]; + + if (resolver) { + let retval = false; // TO DO: investigate why sphereParticle and convexParticle + // resolvers expect si and sj shapes to be in reverse order + // (i.e. larger integer value type first instead of smaller first) + + if (si.type < sj.type) { + retval = resolver.call( + this, + si, + sj, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } else { + retval = resolver.call( + this, + sj, + si, + xj, + xi, + qj, + qi, + bj, + bi, + si, + sj, + justTest + ); + } + + if (retval && justTest) { + // Register overlap + world.shapeOverlapKeeper.set(si.id, sj.id); + world.bodyOverlapKeeper.set(bi.id, bj.id); + } + } + } + } + } + } + + sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + if (justTest) { + return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2; + } // We will have only one contact in this case + + const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal + + xj.vsub(xi, contactEq.ni); + contactEq.ni.normalize(); // Contact point locations + + contactEq.ri.copy(contactEq.ni); + contactEq.rj.copy(contactEq.ni); + contactEq.ri.scale(si.radius, contactEq.ri); + contactEq.rj.scale(-sj.radius, contactEq.rj); + contactEq.ri.vadd(xi, contactEq.ri); + contactEq.ri.vsub(bi.position, contactEq.ri); + contactEq.rj.vadd(xj, contactEq.rj); + contactEq.rj.vsub(bj.position, contactEq.rj); + this.result.push(contactEq); + this.createFrictionEquationsFromContact(contactEq, this.frictionResult); + } + + spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + // We will have one contact in this case + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal + + r.ni.set(0, 0, 1); + qj.vmult(r.ni, r.ni); + r.ni.negate(r.ni); // body i is the sphere, flip normal + + r.ni.normalize(); // Needed? + // Vector from sphere center to contact point + + r.ni.scale(si.radius, r.ri); // Project down sphere on plane + + xi.vsub(xj, point_on_plane_to_sphere); + r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho); + point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane + + if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) { + if (justTest) { + return true; + } // Make it relative to the body + + const ri = r.ri; + const rj = r.rj; + ri.vadd(xi, ri); + ri.vsub(bi.position, ri); + rj.vadd(xj, rj); + rj.vsub(bj.position, rj); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + + boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + si.convexPolyhedronRepresentation.material = si.material; + sj.convexPolyhedronRepresentation.material = sj.material; + si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse; + sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse; + return this.convexConvex( + si.convexPolyhedronRepresentation, + sj.convexPolyhedronRepresentation, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } + + sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + const v3pool = this.v3pool; // we refer to the box as body j + + const sides = sphereBox_sides; + xi.vsub(xj, box_to_sphere); + sj.getSideNormals(sides, qj); + const R = si.radius; + + let found = false; // Store the resulting side penetration info + + const side_ns = sphereBox_side_ns; + const side_ns1 = sphereBox_side_ns1; + const side_ns2 = sphereBox_side_ns2; + let side_h = null; + let side_penetrations = 0; + let side_dot1 = 0; + let side_dot2 = 0; + let side_distance = null; + + for ( + let idx = 0, nsides = sides.length; + idx !== nsides && found === false; + idx++ + ) { + // Get the plane side normal (ns) + const ns = sphereBox_ns; + ns.copy(sides[idx]); + const h = ns.length(); + ns.normalize(); // The normal/distance dot product tells which side of the plane we are + + const dot = box_to_sphere.dot(ns); + + if (dot < h + R && dot > 0) { + // Intersects plane. Now check the other two dimensions + const ns1 = sphereBox_ns1; + const ns2 = sphereBox_ns2; + ns1.copy(sides[(idx + 1) % 3]); + ns2.copy(sides[(idx + 2) % 3]); + const h1 = ns1.length(); + const h2 = ns2.length(); + ns1.normalize(); + ns2.normalize(); + const dot1 = box_to_sphere.dot(ns1); + const dot2 = box_to_sphere.dot(ns2); + + if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) { + const dist = Math.abs(dot - h - R); + + if (side_distance === null || dist < side_distance) { + side_distance = dist; + side_dot1 = dot1; + side_dot2 = dot2; + side_h = h; + side_ns.copy(ns); + side_ns1.copy(ns1); + side_ns2.copy(ns2); + side_penetrations++; + + if (justTest) { + return true; + } + } + } + } + } + + if (side_penetrations) { + found = true; + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + side_ns.scale(-R, r.ri); // Sphere r + + r.ni.copy(side_ns); + r.ni.negate(r.ni); // Normal should be out of sphere + + side_ns.scale(side_h, side_ns); + side_ns1.scale(side_dot1, side_ns1); + side_ns.vadd(side_ns1, side_ns); + side_ns2.scale(side_dot2, side_ns2); + side_ns.vadd(side_ns2, r.rj); // Make relative to bodies + + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } // Check corners + + let rj = v3pool.get(); + const sphere_to_corner = sphereBox_sphere_to_corner; + + for (let j = 0; j !== 2 && !found; j++) { + for (let k = 0; k !== 2 && !found; k++) { + for (let l = 0; l !== 2 && !found; l++) { + rj.set(0, 0, 0); + + if (j) { + rj.vadd(sides[0], rj); + } else { + rj.vsub(sides[0], rj); + } + + if (k) { + rj.vadd(sides[1], rj); + } else { + rj.vsub(sides[1], rj); + } + + if (l) { + rj.vadd(sides[2], rj); + } else { + rj.vsub(sides[2], rj); + } // World position of corner + + xj.vadd(rj, sphere_to_corner); + sphere_to_corner.vsub(xi, sphere_to_corner); + + if (sphere_to_corner.lengthSquared() < R * R) { + if (justTest) { + return true; + } + + found = true; + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + r.ri.copy(sphere_to_corner); + r.ri.normalize(); + r.ni.copy(r.ri); + r.ri.scale(R, r.ri); + r.rj.copy(rj); // Make relative to bodies + + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + } + } + + v3pool.release(rj); + rj = null; // Check edges + + const edgeTangent = v3pool.get(); + const edgeCenter = v3pool.get(); + const r = v3pool.get(); // r = edge center to sphere center + + const orthogonal = v3pool.get(); + const dist = v3pool.get(); + const Nsides = sides.length; + + for (let j = 0; j !== Nsides && !found; j++) { + for (let k = 0; k !== Nsides && !found; k++) { + if (j % 3 !== k % 3) { + // Get edge tangent + sides[k].cross(sides[j], edgeTangent); + edgeTangent.normalize(); + sides[j].vadd(sides[k], edgeCenter); + r.copy(xi); + r.vsub(edgeCenter, r); + r.vsub(xj, r); + const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction + + edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction + // Find the third side orthogonal to this one + + let l = 0; + + while (l === j % 3 || l === k % 3) { + l++; + } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent + + dist.copy(xi); + dist.vsub(orthogonal, dist); + dist.vsub(edgeCenter, dist); + dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it + + const tdist = Math.abs(orthonorm); + const ndist = dist.length(); + + if (tdist < sides[l].length() && ndist < R) { + if (justTest) { + return true; + } + + found = true; + const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + edgeCenter.vadd(orthogonal, res.rj); // box rj + + res.rj.copy(res.rj); + dist.negate(res.ni); + res.ni.normalize(); + res.ri.copy(res.rj); + res.ri.vadd(xj, res.ri); + res.ri.vsub(xi, res.ri); + res.ri.normalize(); + res.ri.scale(R, res.ri); // Make relative to bodies + + res.ri.vadd(xi, res.ri); + res.ri.vsub(bi.position, res.ri); + res.rj.vadd(xj, res.rj); + res.rj.vsub(bj.position, res.rj); + this.result.push(res); + this.createFrictionEquationsFromContact(res, this.frictionResult); + } + } + } + } + + v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist); + } + + planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + sj.convexPolyhedronRepresentation.material = sj.material; + sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse; + sj.convexPolyhedronRepresentation.id = sj.id; + return this.planeConvex( + si, + sj.convexPolyhedronRepresentation, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } + + convexConvex( + si, + sj, + xi, + xj, + qi, + qj, + bi, + bj, + rsi, + rsj, + justTest, + faceListA, + faceListB + ) { + const sepAxis = convexConvex_sepAxis; + + if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) { + return; + } + + if ( + si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB) + ) { + const res = []; + const q = convexConvex_q; + si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res); + let numContacts = 0; + + for (let j = 0; j !== res.length; j++) { + if (justTest) { + return true; + } + + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + const ri = r.ri; + const rj = r.rj; + sepAxis.negate(r.ni); + res[j].normal.negate(q); + q.scale(res[j].depth, q); + res[j].point.vadd(q, ri); + rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative + + ri.vsub(xi, ri); + rj.vsub(xj, rj); // Make relative to bodies + + ri.vadd(xi, ri); + ri.vsub(bi.position, ri); + rj.vadd(xj, rj); + rj.vsub(bj.position, rj); + this.result.push(r); + numContacts++; + + if (!this.enableFrictionReduction) { + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + + if (this.enableFrictionReduction && numContacts) { + this.createFrictionFromAverage(numContacts); + } + } + } + + sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + const v3pool = this.v3pool; + xi.vsub(xj, convex_to_sphere); + const normals = sj.faceNormals; + const faces = sj.faces; + const verts = sj.vertices; + const R = si.radius; + // return; + // } + + let found = false; // Check corners + + for (let i = 0; i !== verts.length; i++) { + const v = verts[i]; // World position of corner + + const worldCorner = sphereConvex_worldCorner; + qj.vmult(v, worldCorner); + xj.vadd(worldCorner, worldCorner); + const sphere_to_corner = sphereConvex_sphereToCorner; + worldCorner.vsub(xi, sphere_to_corner); + + if (sphere_to_corner.lengthSquared() < R * R) { + if (justTest) { + return true; + } + + found = true; + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + r.ri.copy(sphere_to_corner); + r.ri.normalize(); + r.ni.copy(r.ri); + r.ri.scale(R, r.ri); + worldCorner.vsub(xj, r.rj); // Should be relative to the body. + + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); // Should be relative to the body. + + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + return; + } + } // Check side (plane) intersections + + for ( + let i = 0, nfaces = faces.length; + i !== nfaces && found === false; + i++ + ) { + const normal = normals[i]; + const face = faces[i]; // Get world-transformed normal of the face + + const worldNormal = sphereConvex_worldNormal; + qj.vmult(normal, worldNormal); // Get a world vertex from the face + + const worldPoint = sphereConvex_worldPoint; + qj.vmult(verts[face[0]], worldPoint); + worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal + + const worldSpherePointClosestToPlane = + sphereConvex_worldSpherePointClosestToPlane; + worldNormal.scale(-R, worldSpherePointClosestToPlane); + xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere + + const penetrationVec = sphereConvex_penetrationVec; + worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap. + + const penetration = penetrationVec.dot(worldNormal); + const worldPointToSphere = sphereConvex_sphereToWorldPoint; + xi.vsub(worldPoint, worldPointToSphere); + + if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) { + // Intersects plane. Now check if the sphere is inside the face polygon + const faceVerts = []; // Face vertices, in world coords + + for (let j = 0, Nverts = face.length; j !== Nverts; j++) { + const worldVertex = v3pool.get(); + qj.vmult(verts[face[j]], worldVertex); + xj.vadd(worldVertex, worldVertex); + faceVerts.push(worldVertex); + } + + if (pointInPolygon(faceVerts, worldNormal, xi)) { + // Is the sphere center in the face polygon? + if (justTest) { + return true; + } + + found = true; + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact + + worldNormal.negate(r.ni); // Normal pointing out of sphere + + const penetrationVec2 = v3pool.get(); + worldNormal.scale(-penetration, penetrationVec2); + const penetrationSpherePoint = v3pool.get(); + worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj); + + xi.vsub(xj, r.rj); + r.rj.vadd(penetrationSpherePoint, r.rj); + r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body. + + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); // Should be relative to the body. + + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + v3pool.release(penetrationVec2); + v3pool.release(penetrationSpherePoint); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices + + for ( + let j = 0, Nfaceverts = faceVerts.length; + j !== Nfaceverts; + j++ + ) { + v3pool.release(faceVerts[j]); + } + + return; // We only expect *one* face contact + } else { + // Edge? + for (let j = 0; j !== face.length; j++) { + // Get two world transformed vertices + const v1 = v3pool.get(); + const v2 = v3pool.get(); + qj.vmult(verts[face[(j + 1) % face.length]], v1); + qj.vmult(verts[face[(j + 2) % face.length]], v2); + xj.vadd(v1, v1); + xj.vadd(v2, v2); // Construct edge vector + + const edge = sphereConvex_edge; + v2.vsub(v1, edge); // Construct the same vector, but normalized + + const edgeUnit = sphereConvex_edgeUnit; + edge.unit(edgeUnit); // p is xi projected onto the edge + + const p = v3pool.get(); + const v1_to_xi = v3pool.get(); + xi.vsub(v1, v1_to_xi); + const dot = v1_to_xi.dot(edgeUnit); + edgeUnit.scale(dot, p); + p.vadd(v1, p); // Compute a vector from p to the center of the sphere + + const xi_to_p = v3pool.get(); + p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius + // AND if p is in between v1 and v2 + + if ( + dot > 0 && + dot * dot < edge.lengthSquared() && + xi_to_p.lengthSquared() < R * R + ) { + // Collision if the edge-sphere distance is less than the radius + // Edge contact! + if (justTest) { + return true; + } + + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + p.vsub(xj, r.rj); + p.vsub(xi, r.ni); + r.ni.normalize(); + r.ni.scale(R, r.ri); // Should be relative to the body. + + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); // Should be relative to the body. + + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices + + for ( + let j = 0, Nfaceverts = faceVerts.length; + j !== Nfaceverts; + j++ + ) { + v3pool.release(faceVerts[j]); + } + + v3pool.release(v1); + v3pool.release(v2); + v3pool.release(p); + v3pool.release(xi_to_p); + v3pool.release(v1_to_xi); + return; + } + + v3pool.release(v1); + v3pool.release(v2); + v3pool.release(p); + v3pool.release(xi_to_p); + v3pool.release(v1_to_xi); + } + } // Release world vertices + + for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) { + v3pool.release(faceVerts[j]); + } + } + } + } + + planeConvex( + planeShape, + convexShape, + planePosition, + convexPosition, + planeQuat, + convexQuat, + planeBody, + convexBody, + si, + sj, + justTest + ) { + // Simply return the points behind the plane. + const worldVertex = planeConvex_v; + const worldNormal = planeConvex_normal; + worldNormal.set(0, 0, 1); + planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation + + let numContacts = 0; + const relpos = planeConvex_relpos; + + for (let i = 0; i !== convexShape.vertices.length; i++) { + // Get world convex vertex + worldVertex.copy(convexShape.vertices[i]); + convexQuat.vmult(worldVertex, worldVertex); + convexPosition.vadd(worldVertex, worldVertex); + worldVertex.vsub(planePosition, relpos); + const dot = worldNormal.dot(relpos); + + if (dot <= 0.0) { + if (justTest) { + return true; + } + + const r = this.createContactEquation( + planeBody, + convexBody, + planeShape, + convexShape, + si, + sj + ); // Get vertex position projected on plane + + const projected = planeConvex_projected; + worldNormal.scale(worldNormal.dot(relpos), projected); + worldVertex.vsub(projected, projected); + projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane + + r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane + // rj is now just the vector from the convex center to the vertex + + worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body + + r.ri.vadd(planePosition, r.ri); + r.ri.vsub(planeBody.position, r.ri); + r.rj.vadd(convexPosition, r.rj); + r.rj.vsub(convexBody.position, r.rj); + this.result.push(r); + numContacts++; + + if (!this.enableFrictionReduction) { + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + } + + if (this.enableFrictionReduction && numContacts) { + this.createFrictionFromAverage(numContacts); + } + } + + boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + si.convexPolyhedronRepresentation.material = si.material; + si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse; + return this.convexConvex( + si.convexPolyhedronRepresentation, + sj, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } + + sphereHeightfield( + sphereShape, + hfShape, + spherePos, + hfPos, + sphereQuat, + hfQuat, + sphereBody, + hfBody, + rsi, + rsj, + justTest + ) { + const data = hfShape.data; + const radius = sphereShape.radius; + const w = hfShape.elementSize; + const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local! + + const localSpherePos = sphereHeightfield_tmp1; + Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against + + let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1; + let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1; + let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1; + let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain + + if ( + iMaxX < 0 || + iMaxY < 0 || + iMinX > data.length || + iMinY > data[0].length + ) { + return; + } // Clamp index to edges + + if (iMinX < 0) { + iMinX = 0; + } + + if (iMaxX < 0) { + iMaxX = 0; + } + + if (iMinY < 0) { + iMinY = 0; + } + + if (iMaxY < 0) { + iMaxY = 0; + } + + if (iMinX >= data.length) { + iMinX = data.length - 1; + } + + if (iMaxX >= data.length) { + iMaxX = data.length - 1; + } + + if (iMaxY >= data[0].length) { + iMaxY = data[0].length - 1; + } + + if (iMinY >= data[0].length) { + iMinY = data[0].length - 1; + } + + const minMax = []; + hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax); + const min = minMax[0]; + const max = minMax[1]; // Bail out if we can't touch the bounding height box + + if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) { + return; + } + + const result = this.result; + + for (let i = iMinX; i < iMaxX; i++) { + for (let j = iMinY; j < iMaxY; j++) { + const numContactsBefore = result.length; + let intersecting = false; // Lower triangle + + hfShape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame( + hfPos, + hfQuat, + hfShape.pillarOffset, + worldPillarOffset + ); + + if ( + spherePos.distanceTo(worldPillarOffset) < + hfShape.pillarConvex.boundingSphereRadius + + sphereShape.boundingSphereRadius + ) { + intersecting = this.sphereConvex( + sphereShape, + hfShape.pillarConvex, + spherePos, + worldPillarOffset, + sphereQuat, + hfQuat, + sphereBody, + hfBody, + sphereShape, + hfShape, + justTest + ); + } + + if (justTest && intersecting) { + return true; + } // Upper triangle + + hfShape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame( + hfPos, + hfQuat, + hfShape.pillarOffset, + worldPillarOffset + ); + + if ( + spherePos.distanceTo(worldPillarOffset) < + hfShape.pillarConvex.boundingSphereRadius + + sphereShape.boundingSphereRadius + ) { + intersecting = this.sphereConvex( + sphereShape, + hfShape.pillarConvex, + spherePos, + worldPillarOffset, + sphereQuat, + hfQuat, + sphereBody, + hfBody, + sphereShape, + hfShape, + justTest + ); + } + + if (justTest && intersecting) { + return true; + } + + const numContacts = result.length - numContactsBefore; + + if (numContacts > 2) { + return; + } + /* + // Skip all but 1 + for (let k = 0; k < numContacts - 1; k++) { + result.pop(); + } + */ + } + } + } + + boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + si.convexPolyhedronRepresentation.material = si.material; + si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse; + return this.convexHeightfield( + si.convexPolyhedronRepresentation, + sj, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } + + convexHeightfield( + convexShape, + hfShape, + convexPos, + hfPos, + convexQuat, + hfQuat, + convexBody, + hfBody, + rsi, + rsj, + justTest + ) { + const data = hfShape.data; + const w = hfShape.elementSize; + const radius = convexShape.boundingSphereRadius; + const worldPillarOffset = convexHeightfield_tmp2; + const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local! + + const localConvexPos = convexHeightfield_tmp1; + Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against + + let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1; + let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1; + let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1; + let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain + + if ( + iMaxX < 0 || + iMaxY < 0 || + iMinX > data.length || + iMinY > data[0].length + ) { + return; + } // Clamp index to edges + + if (iMinX < 0) { + iMinX = 0; + } + + if (iMaxX < 0) { + iMaxX = 0; + } + + if (iMinY < 0) { + iMinY = 0; + } + + if (iMaxY < 0) { + iMaxY = 0; + } + + if (iMinX >= data.length) { + iMinX = data.length - 1; + } + + if (iMaxX >= data.length) { + iMaxX = data.length - 1; + } + + if (iMaxY >= data[0].length) { + iMaxY = data[0].length - 1; + } + + if (iMinY >= data[0].length) { + iMinY = data[0].length - 1; + } + + const minMax = []; + hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax); + const min = minMax[0]; + const max = minMax[1]; // Bail out if we're cant touch the bounding height box + + if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) { + return; + } + + for (let i = iMinX; i < iMaxX; i++) { + for (let j = iMinY; j < iMaxY; j++) { + let intersecting = false; // Lower triangle + + hfShape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame( + hfPos, + hfQuat, + hfShape.pillarOffset, + worldPillarOffset + ); + + if ( + convexPos.distanceTo(worldPillarOffset) < + hfShape.pillarConvex.boundingSphereRadius + + convexShape.boundingSphereRadius + ) { + intersecting = this.convexConvex( + convexShape, + hfShape.pillarConvex, + convexPos, + worldPillarOffset, + convexQuat, + hfQuat, + convexBody, + hfBody, + null, + null, + justTest, + faceList, + null + ); + } + + if (justTest && intersecting) { + return true; + } // Upper triangle + + hfShape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame( + hfPos, + hfQuat, + hfShape.pillarOffset, + worldPillarOffset + ); + + if ( + convexPos.distanceTo(worldPillarOffset) < + hfShape.pillarConvex.boundingSphereRadius + + convexShape.boundingSphereRadius + ) { + intersecting = this.convexConvex( + convexShape, + hfShape.pillarConvex, + convexPos, + worldPillarOffset, + convexQuat, + hfQuat, + convexBody, + hfBody, + null, + null, + justTest, + faceList, + null + ); + } + + if (justTest && intersecting) { + return true; + } + } + } + } + + sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) { + // The normal is the unit vector from sphere center to particle center + const normal = particleSphere_normal; + normal.set(0, 0, 1); + xi.vsub(xj, normal); + const lengthSquared = normal.lengthSquared(); + + if (lengthSquared <= sj.radius * sj.radius) { + if (justTest) { + return true; + } + + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + normal.normalize(); + r.rj.copy(normal); + r.rj.scale(sj.radius, r.rj); + r.ni.copy(normal); // Contact normal + + r.ni.negate(r.ni); + r.ri.set(0, 0, 0); // Center of particle + + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + + planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) { + const normal = particlePlane_normal; + normal.set(0, 0, 1); + bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation + + const relpos = particlePlane_relpos; + xi.vsub(bj.position, relpos); + const dot = normal.dot(relpos); + + if (dot <= 0.0) { + if (justTest) { + return true; + } + + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + r.ni.copy(normal); // Contact normal is the plane normal + + r.ni.negate(r.ni); + r.ri.set(0, 0, 0); // Center of particle + // Get particle position projected on plane + + const projected = particlePlane_projected; + normal.scale(normal.dot(xi), projected); + xi.vsub(projected, projected); //projected.vadd(bj.position,projected); + // rj is now the projected world position minus plane position + + r.rj.copy(projected); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + + boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + si.convexPolyhedronRepresentation.material = si.material; + si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse; + return this.convexParticle( + si.convexPolyhedronRepresentation, + sj, + xi, + xj, + qi, + qj, + bi, + bj, + si, + sj, + justTest + ); + } + + convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) { + let penetratedFaceIndex = -1; + const penetratedFaceNormal = convexParticle_penetratedFaceNormal; + const worldPenetrationVec = convexParticle_worldPenetrationVec; + let minPenetration = null; + + const local = convexParticle_local; + local.copy(xi); + local.vsub(xj, local); // Convert position to relative the convex origin + + qj.conjugate(cqj); + cqj.vmult(local, local); + + if (sj.pointIsInside(local)) { + if (sj.worldVerticesNeedsUpdate) { + sj.computeWorldVertices(xj, qj); + } + + if (sj.worldFaceNormalsNeedsUpdate) { + sj.computeWorldFaceNormals(qj); + } // For each world polygon in the polyhedra + + for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) { + // Construct world face vertices + const verts = [sj.worldVertices[sj.faces[i][0]]]; + const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane. + + xi.vsub(verts[0], convexParticle_vertexToParticle); + const penetration = -normal.dot(convexParticle_vertexToParticle); + + if ( + minPenetration === null || + Math.abs(penetration) < Math.abs(minPenetration) + ) { + if (justTest) { + return true; + } + + minPenetration = penetration; + penetratedFaceIndex = i; + penetratedFaceNormal.copy(normal); + } + } + + if (penetratedFaceIndex !== -1) { + // Setup contact + const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); + penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face + + worldPenetrationVec.vadd(xi, worldPenetrationVec); + worldPenetrationVec.vsub(xj, worldPenetrationVec); + r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec); + //projectedToFace.copy(r.rj); + //qj.vmult(r.rj,r.rj); + + penetratedFaceNormal.negate(r.ni); // Contact normal + + r.ri.set(0, 0, 0); // Center of particle + + const ri = r.ri; + const rj = r.rj; // Make relative to bodies + + ri.vadd(xi, ri); + ri.vsub(bi.position, ri); + rj.vadd(xj, rj); + rj.vsub(bj.position, rj); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } else { + console.warn( + "Point found inside convex, but did not find penetrating face!" + ); + } + } + } + + heightfieldCylinder( + hfShape, + convexShape, + hfPos, + convexPos, + hfQuat, + convexQuat, + hfBody, + convexBody, + rsi, + rsj, + justTest + ) { + return this.convexHeightfield( + convexShape, + hfShape, + convexPos, + hfPos, + convexQuat, + hfQuat, + convexBody, + hfBody, + rsi, + rsj, + justTest + ); + } + + particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) { + return this.convexParticle( + sj, + si, + xj, + xi, + qj, + qi, + bj, + bi, + rsi, + rsj, + justTest + ); + } + + sphereTrimesh( + sphereShape, + trimeshShape, + spherePos, + trimeshPos, + sphereQuat, + trimeshQuat, + sphereBody, + trimeshBody, + rsi, + rsj, + justTest + ) { + const edgeVertexA = sphereTrimesh_edgeVertexA; + const edgeVertexB = sphereTrimesh_edgeVertexB; + const edgeVector = sphereTrimesh_edgeVector; + const edgeVectorUnit = sphereTrimesh_edgeVectorUnit; + const localSpherePos = sphereTrimesh_localSpherePos; + const tmp = sphereTrimesh_tmp; + const localSphereAABB = sphereTrimesh_localSphereAABB; + const v2 = sphereTrimesh_v2; + const relpos = sphereTrimesh_relpos; + const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh + + Transform.pointToLocalFrame( + trimeshPos, + trimeshQuat, + spherePos, + localSpherePos + ); // Get the aabb of the sphere locally in the trimesh + + const sphereRadius = sphereShape.radius; + localSphereAABB.lowerBound.set( + localSpherePos.x - sphereRadius, + localSpherePos.y - sphereRadius, + localSpherePos.z - sphereRadius + ); + localSphereAABB.upperBound.set( + localSpherePos.x + sphereRadius, + localSpherePos.y + sphereRadius, + localSpherePos.z + sphereRadius + ); + trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All + // Vertices + + const v = sphereTrimesh_v; + const radiusSquared = sphereShape.radius * sphereShape.radius; + + for (let i = 0; i < triangles.length; i++) { + for (let j = 0; j < 3; j++) { + trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere + + v.vsub(localSpherePos, relpos); + + if (relpos.lengthSquared() <= radiusSquared) { + // Safe up + v2.copy(v); + Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); + v.vsub(spherePos, relpos); + + if (justTest) { + return true; + } + + let r = this.createContactEquation( + sphereBody, + trimeshBody, + sphereShape, + trimeshShape, + rsi, + rsj + ); + r.ni.copy(relpos); + r.ni.normalize(); // ri is the vector from sphere center to the sphere surface + + r.ri.copy(r.ni); + r.ri.scale(sphereShape.radius, r.ri); + r.ri.vadd(spherePos, r.ri); + r.ri.vsub(sphereBody.position, r.ri); + r.rj.copy(v); + r.rj.vsub(trimeshBody.position, r.rj); // Store result + + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + } // Check all edges + + for (let i = 0; i < triangles.length; i++) { + for (let j = 0; j < 3; j++) { + trimeshShape.getVertex( + trimeshShape.indices[triangles[i] * 3 + j], + edgeVertexA + ); + trimeshShape.getVertex( + trimeshShape.indices[triangles[i] * 3 + ((j + 1) % 3)], + edgeVertexB + ); + edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge + + localSpherePos.vsub(edgeVertexB, tmp); + const positionAlongEdgeB = tmp.dot(edgeVector); + localSpherePos.vsub(edgeVertexA, tmp); + let positionAlongEdgeA = tmp.dot(edgeVector); + + if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) { + // Now check the orthogonal distance from edge to sphere center + localSpherePos.vsub(edgeVertexA, tmp); + edgeVectorUnit.copy(edgeVector); + edgeVectorUnit.normalize(); + positionAlongEdgeA = tmp.dot(edgeVectorUnit); + edgeVectorUnit.scale(positionAlongEdgeA, tmp); + tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame + + const dist = tmp.distanceTo(localSpherePos); + + if (dist < sphereShape.radius) { + if (justTest) { + return true; + } + + const r = this.createContactEquation( + sphereBody, + trimeshBody, + sphereShape, + trimeshShape, + rsi, + rsj + ); + tmp.vsub(localSpherePos, r.ni); + r.ni.normalize(); + r.ni.scale(sphereShape.radius, r.ri); + r.ri.vadd(spherePos, r.ri); + r.ri.vsub(sphereBody.position, r.ri); + Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp); + tmp.vsub(trimeshBody.position, r.rj); + Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni); + Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + } + } // Triangle faces + + const va = sphereTrimesh_va; + const vb = sphereTrimesh_vb; + const vc = sphereTrimesh_vc; + const normal = sphereTrimesh_normal; + + for (let i = 0, N = triangles.length; i !== N; i++) { + trimeshShape.getTriangleVertices(triangles[i], va, vb, vc); + trimeshShape.getNormal(triangles[i], normal); + localSpherePos.vsub(va, tmp); + let dist = tmp.dot(normal); + normal.scale(dist, tmp); + localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane + + dist = tmp.distanceTo(localSpherePos); + + if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) { + if (justTest) { + return true; + } + + let r = this.createContactEquation( + sphereBody, + trimeshBody, + sphereShape, + trimeshShape, + rsi, + rsj + ); + tmp.vsub(localSpherePos, r.ni); + r.ni.normalize(); + r.ni.scale(sphereShape.radius, r.ri); + r.ri.vadd(spherePos, r.ri); + r.ri.vsub(sphereBody.position, r.ri); + Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp); + tmp.vsub(trimeshBody.position, r.rj); + Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni); + Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri); + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + + triangles.length = 0; + } + + planeTrimesh( + planeShape, + trimeshShape, + planePos, + trimeshPos, + planeQuat, + trimeshQuat, + planeBody, + trimeshBody, + rsi, + rsj, + justTest + ) { + // Make contacts! + const v = new Vec3(); + const normal = planeTrimesh_normal; + normal.set(0, 0, 1); + planeQuat.vmult(normal, normal); // Turn normal according to plane + + for (let i = 0; i < trimeshShape.vertices.length / 3; i++) { + // Get world vertex from trimesh + trimeshShape.getVertex(i, v); // Safe up + + const v2 = new Vec3(); + v2.copy(v); + Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side + + const relpos = planeTrimesh_relpos; + v.vsub(planePos, relpos); + const dot = normal.dot(relpos); + + if (dot <= 0.0) { + if (justTest) { + return true; + } + + const r = this.createContactEquation( + planeBody, + trimeshBody, + planeShape, + trimeshShape, + rsi, + rsj + ); + r.ni.copy(normal); // Contact normal is the plane normal + // Get vertex position projected on plane + + const projected = planeTrimesh_projected; + normal.scale(relpos.dot(normal), projected); + v.vsub(projected, projected); // ri is the projected world position minus plane position + + r.ri.copy(projected); + r.ri.vsub(planeBody.position, r.ri); + r.rj.copy(v); + r.rj.vsub(trimeshBody.position, r.rj); // Store result + + this.result.push(r); + this.createFrictionEquationsFromContact(r, this.frictionResult); + } + } + } // convexTrimesh( + // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion, + // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null, + // faceListA?: number[] | null, faceListB?: number[] | null, + // ) { + // const sepAxis = convexConvex_sepAxis; + // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){ + // return; + // } + // // Construct a temp hull for each triangle + // const hullB = new ConvexPolyhedron(); + // hullB.faces = [[0,1,2]]; + // const va = new Vec3(); + // const vb = new Vec3(); + // const vc = new Vec3(); + // hullB.vertices = [ + // va, + // vb, + // vc + // ]; + // for (let i = 0; i < sj.indices.length / 3; i++) { + // const triangleNormal = new Vec3(); + // sj.getNormal(i, triangleNormal); + // hullB.faceNormals = [triangleNormal]; + // sj.getTriangleVertices(i, va, vb, vc); + // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj); + // if(!d){ + // triangleNormal.scale(-1, triangleNormal); + // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj); + // if(!d){ + // continue; + // } + // } + // const res: ConvexPolyhedronContactPoint[] = []; + // const q = convexConvex_q; + // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res); + // for(let j = 0; j !== res.length; j++){ + // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj), + // ri = r.ri, + // rj = r.rj; + // r.ni.copy(triangleNormal); + // r.ni.negate(r.ni); + // res[j].normal.negate(q); + // q.mult(res[j].depth, q); + // res[j].point.vadd(q, ri); + // rj.copy(res[j].point); + // // Contact points are in world coordinates. Transform back to relative + // ri.vsub(xi,ri); + // rj.vsub(xj,rj); + // // Make relative to bodies + // ri.vadd(xi, ri); + // ri.vsub(bi.position, ri); + // rj.vadd(xj, rj); + // rj.vsub(bj.position, rj); + // result.push(r); + // } + // } + // } + } + const averageNormal = new Vec3(); + const averageContactPointA = new Vec3(); + const averageContactPointB = new Vec3(); + const tmpVec1 = new Vec3(); + const tmpVec2 = new Vec3(); + const tmpQuat1 = new Quaternion(); + const tmpQuat2 = new Quaternion(); + + const planeTrimesh_normal = new Vec3(); + const planeTrimesh_relpos = new Vec3(); + const planeTrimesh_projected = new Vec3(); + const sphereTrimesh_normal = new Vec3(); + const sphereTrimesh_relpos = new Vec3(); + new Vec3(); + const sphereTrimesh_v = new Vec3(); + const sphereTrimesh_v2 = new Vec3(); + const sphereTrimesh_edgeVertexA = new Vec3(); + const sphereTrimesh_edgeVertexB = new Vec3(); + const sphereTrimesh_edgeVector = new Vec3(); + const sphereTrimesh_edgeVectorUnit = new Vec3(); + const sphereTrimesh_localSpherePos = new Vec3(); + const sphereTrimesh_tmp = new Vec3(); + const sphereTrimesh_va = new Vec3(); + const sphereTrimesh_vb = new Vec3(); + const sphereTrimesh_vc = new Vec3(); + const sphereTrimesh_localSphereAABB = new AABB(); + const sphereTrimesh_triangles = []; + const point_on_plane_to_sphere = new Vec3(); + const plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html + + const pointInPolygon_edge = new Vec3(); + const pointInPolygon_edge_x_normal = new Vec3(); + const pointInPolygon_vtp = new Vec3(); + + function pointInPolygon(verts, normal, p) { + let positiveResult = null; + const N = verts.length; + + for (let i = 0; i !== N; i++) { + const v = verts[i]; // Get edge to the next vertex + + const edge = pointInPolygon_edge; + verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge + + const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3(); + + edge.cross(normal, edge_x_normal); // Get vector between point and current vertex + + const vertex_to_p = pointInPolygon_vtp; + p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is + + const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon. + + if ( + positiveResult === null || + (r > 0 && positiveResult === true) || + (r <= 0 && positiveResult === false) + ) { + if (positiveResult === null) { + positiveResult = r > 0; + } + + continue; + } else { + return false; // Encountered some other sign. Exit. + } + } // If we got here, all dot products were of the same sign. + + return true; + } + + const box_to_sphere = new Vec3(); + const sphereBox_ns = new Vec3(); + const sphereBox_ns1 = new Vec3(); + const sphereBox_ns2 = new Vec3(); + const sphereBox_sides = [ + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + new Vec3(), + ]; + const sphereBox_sphere_to_corner = new Vec3(); + const sphereBox_side_ns = new Vec3(); + const sphereBox_side_ns1 = new Vec3(); + const sphereBox_side_ns2 = new Vec3(); + const convex_to_sphere = new Vec3(); + const sphereConvex_edge = new Vec3(); + const sphereConvex_edgeUnit = new Vec3(); + const sphereConvex_sphereToCorner = new Vec3(); + const sphereConvex_worldCorner = new Vec3(); + const sphereConvex_worldNormal = new Vec3(); + const sphereConvex_worldPoint = new Vec3(); + const sphereConvex_worldSpherePointClosestToPlane = new Vec3(); + const sphereConvex_penetrationVec = new Vec3(); + const sphereConvex_sphereToWorldPoint = new Vec3(); + new Vec3(); + new Vec3(); + const planeConvex_v = new Vec3(); + const planeConvex_normal = new Vec3(); + const planeConvex_relpos = new Vec3(); + const planeConvex_projected = new Vec3(); + const convexConvex_sepAxis = new Vec3(); + const convexConvex_q = new Vec3(); + const particlePlane_normal = new Vec3(); + const particlePlane_relpos = new Vec3(); + const particlePlane_projected = new Vec3(); + const particleSphere_normal = new Vec3(); // WIP + + const cqj = new Quaternion(); + const convexParticle_local = new Vec3(); + new Vec3(); + const convexParticle_penetratedFaceNormal = new Vec3(); + const convexParticle_vertexToParticle = new Vec3(); + const convexParticle_worldPenetrationVec = new Vec3(); + const convexHeightfield_tmp1 = new Vec3(); + const convexHeightfield_tmp2 = new Vec3(); + const convexHeightfield_faceList = [0]; + const sphereHeightfield_tmp1 = new Vec3(); + const sphereHeightfield_tmp2 = new Vec3(); + + class OverlapKeeper { + /** + * @todo Remove useless constructor + */ + constructor() { + this.current = []; + this.previous = []; + } + /** + * getKey + */ + + getKey(i, j) { + if (j < i) { + const temp = j; + j = i; + i = temp; + } + + return (i << 16) | j; + } + /** + * set + */ + + set(i, j) { + // Insertion sort. This way the diff will have linear complexity. + const key = this.getKey(i, j); + const current = this.current; + let index = 0; + + while (key > current[index]) { + index++; + } + + if (key === current[index]) { + return; // Pair was already added + } + + for (let j = current.length - 1; j >= index; j--) { + current[j + 1] = current[j]; + } + + current[index] = key; + } + /** + * tick + */ + + tick() { + const tmp = this.current; + this.current = this.previous; + this.previous = tmp; + this.current.length = 0; + } + /** + * getDiff + */ + + getDiff(additions, removals) { + const a = this.current; + const b = this.previous; + const al = a.length; + const bl = b.length; + let j = 0; + + for (let i = 0; i < al; i++) { + let found = false; + const keyA = a[i]; + + while (keyA > b[j]) { + j++; + } + + found = keyA === b[j]; + + if (!found) { + unpackAndPush(additions, keyA); + } + } + + j = 0; + + for (let i = 0; i < bl; i++) { + let found = false; + const keyB = b[i]; + + while (keyB > a[j]) { + j++; + } + + found = a[j] === keyB; + + if (!found) { + unpackAndPush(removals, keyB); + } + } + } + } + + function unpackAndPush(array, key) { + array.push((key & 0xffff0000) >> 16, key & 0x0000ffff); + } + + const getKey = (i, j) => (i < j ? `${i}-${j}` : `${j}-${i}`); + /** + * TupleDictionary + */ + + class TupleDictionary { + constructor() { + this.data = { + keys: [], + }; + } + + /** get */ + get(i, j) { + const key = getKey(i, j); + return this.data[key]; + } + /** set */ + + set(i, j, value) { + const key = getKey(i, j); // Check if key already exists + + if (!this.get(i, j)) { + this.data.keys.push(key); + } + + this.data[key] = value; + } + /** delete */ + + delete(i, j) { + const key = getKey(i, j); + const index = this.data.keys.indexOf(key); + + if (index !== -1) { + this.data.keys.splice(index, 1); + } + + delete this.data[key]; + } + /** reset */ + + reset() { + const data = this.data; + const keys = data.keys; + + while (keys.length > 0) { + const key = keys.pop(); + delete data[key]; + } + } + } + + /** + * The physics world + */ + class World extends EventTarget { + /** + * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks. + */ + + /** + * Makes bodies go to sleep when they've been inactive. + * @default false + */ + + /** + * All the current contacts (instances of ContactEquation) in the world. + */ + + /** + * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong). + * @default 0 + */ + + /** + * Set to true to use fast quaternion normalization. It is often enough accurate to use. + * If bodies tend to explode, set to false. + * @default false + */ + + /** + * The wall-clock time since simulation start. + */ + + /** + * Number of timesteps taken since start. + */ + + /** + * Default and last timestep sizes. + */ + + /** + * The gravity of the world. + */ + + /** + * Gravity to use when approximating the friction max force (mu*mass*gravity). + * If undefined, global gravity will be used. + * Use to enable friction in a World with a null gravity vector (no gravity). + */ + + /** + * The broadphase algorithm to use. + * @default NaiveBroadphase + */ + + /** + * All bodies in this world + */ + + /** + * True if any bodies are not sleeping, false if every body is sleeping. + */ + + /** + * The solver algorithm to use. + * @default GSSolver + */ + + /** + * collisionMatrix + */ + + /** + * CollisionMatrix from the previous step. + */ + + /** + * All added contactmaterials. + */ + + /** + * Used to look up a ContactMaterial given two instances of Material. + */ + + /** + * The default material of the bodies. + */ + + /** + * This contact material is used if no suitable contactmaterial is found for a contact. + */ + + /** + * Time accumulator for interpolation. + * @see https://gafferongames.com/game-physics/fix-your-timestep/ + */ + + /** + * Dispatched after a body has been added to the world. + */ + + /** + * Dispatched after a body has been removed from the world. + */ + constructor(options) { + if (options === void 0) { + options = {}; + } + + super(); + this.dt = -1; + this.allowSleep = !!options.allowSleep; + this.contacts = []; + this.frictionEquations = []; + this.quatNormalizeSkip = + options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0; + this.quatNormalizeFast = + options.quatNormalizeFast !== undefined + ? options.quatNormalizeFast + : false; + this.time = 0.0; + this.stepnumber = 0; + this.default_dt = 1 / 60; + this.nextId = 0; + this.gravity = new Vec3(); + + if (options.gravity) { + this.gravity.copy(options.gravity); + } + + if (options.frictionGravity) { + this.frictionGravity = new Vec3(); + this.frictionGravity.copy(options.frictionGravity); + } + + this.broadphase = + options.broadphase !== undefined + ? options.broadphase + : new NaiveBroadphase(); + this.bodies = []; + this.hasActiveBodies = false; + this.solver = + options.solver !== undefined ? options.solver : new GSSolver(); + this.constraints = []; + this.narrowphase = new Narrowphase(this); + this.collisionMatrix = new ArrayCollisionMatrix(); + this.collisionMatrixPrevious = new ArrayCollisionMatrix(); + this.bodyOverlapKeeper = new OverlapKeeper(); + this.shapeOverlapKeeper = new OverlapKeeper(); + this.contactmaterials = []; + this.contactMaterialTable = new TupleDictionary(); + this.defaultMaterial = new Material("default"); + this.defaultContactMaterial = new ContactMaterial( + this.defaultMaterial, + this.defaultMaterial, + { + friction: 0.3, + restitution: 0.0, + } + ); + this.doProfiling = false; + this.profile = { + solve: 0, + makeContactConstraints: 0, + broadphase: 0, + integrate: 0, + narrowphase: 0, + }; + this.accumulator = 0; + this.subsystems = []; + this.addBodyEvent = { + type: "addBody", + body: null, + }; + this.removeBodyEvent = { + type: "removeBody", + body: null, + }; + this.idToBodyMap = {}; + this.broadphase.setWorld(this); + } + /** + * Get the contact material between materials m1 and m2 + * @return The contact material if it was found. + */ + + getContactMaterial(m1, m2) { + return this.contactMaterialTable.get(m1.id, m2.id); + } + /** + * Store old collision state info + */ + + collisionMatrixTick() { + const temp = this.collisionMatrixPrevious; + this.collisionMatrixPrevious = this.collisionMatrix; + this.collisionMatrix = temp; + this.collisionMatrix.reset(); + this.bodyOverlapKeeper.tick(); + this.shapeOverlapKeeper.tick(); + } + /** + * Add a constraint to the simulation. + */ + + addConstraint(c) { + this.constraints.push(c); + } + /** + * Removes a constraint + */ + + removeConstraint(c) { + const idx = this.constraints.indexOf(c); + + if (idx !== -1) { + this.constraints.splice(idx, 1); + } + } + /** + * Raycast test + * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead. + */ + + rayTest(from, to, result) { + if (result instanceof RaycastResult) { + // Do raycastClosest + this.raycastClosest( + from, + to, + { + skipBackfaces: true, + }, + result + ); + } else { + // Do raycastAll + this.raycastAll( + from, + to, + { + skipBackfaces: true, + }, + result + ); + } + } + /** + * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument. + * @return True if any body was hit. + */ + + raycastAll(from, to, options, callback) { + if (options === void 0) { + options = {}; + } + + options.mode = Ray.ALL; + options.from = from; + options.to = to; + options.callback = callback; + return tmpRay.intersectWorld(this, options); + } + /** + * Ray cast, and stop at the first result. Note that the order is random - but the method is fast. + * @return True if any body was hit. + */ + + raycastAny(from, to, options, result) { + if (options === void 0) { + options = {}; + } + + options.mode = Ray.ANY; + options.from = from; + options.to = to; + options.result = result; + return tmpRay.intersectWorld(this, options); + } + /** + * Ray cast, and return information of the closest hit. + * @return True if any body was hit. + */ + + raycastClosest(from, to, options, result) { + if (options === void 0) { + options = {}; + } + + options.mode = Ray.CLOSEST; + options.from = from; + options.to = to; + options.result = result; + return tmpRay.intersectWorld(this, options); + } + /** + * Add a rigid body to the simulation. + * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case. + * @todo Adding an array of bodies should be possible. This would save some loops too + */ + + addBody(body) { + if (this.bodies.includes(body)) { + return; + } + + body.index = this.bodies.length; + this.bodies.push(body); + body.world = this; + body.initPosition.copy(body.position); + body.initVelocity.copy(body.velocity); + body.timeLastSleepy = this.time; + + if (body instanceof Body) { + body.initAngularVelocity.copy(body.angularVelocity); + body.initQuaternion.copy(body.quaternion); + } + + this.collisionMatrix.setNumObjects(this.bodies.length); + this.addBodyEvent.body = body; + this.idToBodyMap[body.id] = body; + this.dispatchEvent(this.addBodyEvent); + } + /** + * Remove a rigid body from the simulation. + */ + + removeBody(body) { + body.world = null; + const n = this.bodies.length - 1; + const bodies = this.bodies; + const idx = bodies.indexOf(body); + + if (idx !== -1) { + bodies.splice(idx, 1); // Todo: should use a garbage free method + // Recompute index + + for (let i = 0; i !== bodies.length; i++) { + bodies[i].index = i; + } + + this.collisionMatrix.setNumObjects(n); + this.removeBodyEvent.body = body; + delete this.idToBodyMap[body.id]; + this.dispatchEvent(this.removeBodyEvent); + } + } + + getBodyById(id) { + return this.idToBodyMap[id]; + } + /** + * @todo Make a faster map + */ + + getShapeById(id) { + const bodies = this.bodies; + + for (let i = 0; i < bodies.length; i++) { + const shapes = bodies[i].shapes; + + for (let j = 0; j < shapes.length; j++) { + const shape = shapes[j]; + + if (shape.id === id) { + return shape; + } + } + } + + return null; + } + /** + * Adds a contact material to the World + */ + + addContactMaterial(cmat) { + // Add contact material + this.contactmaterials.push(cmat); // Add current contact material to the material table + + this.contactMaterialTable.set( + cmat.materials[0].id, + cmat.materials[1].id, + cmat + ); + } + /** + * Removes a contact material from the World. + */ + + removeContactMaterial(cmat) { + const idx = this.contactmaterials.indexOf(cmat); + + if (idx === -1) { + return; + } + + this.contactmaterials.splice(idx, 1); + this.contactMaterialTable.delete( + cmat.materials[0].id, + cmat.materials[1].id + ); + } + /** + * Step the simulation forward keeping track of last called time + * to be able to step the world at a fixed rate, independently of framerate. + * + * @param dt The fixed time step size to use (default: 1 / 60). + * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10). + * @see https://gafferongames.com/post/fix_your_timestep/ + * @example + * // Run the simulation independently of framerate every 1 / 60 ms + * world.fixedStep() + */ + + fixedStep(dt, maxSubSteps) { + if (dt === void 0) { + dt = 1 / 60; + } + + if (maxSubSteps === void 0) { + maxSubSteps = 10; + } + + const time = performance.now() / 1000; // seconds + + if (!this.lastCallTime) { + this.step(dt, undefined, maxSubSteps); + } else { + const timeSinceLastCalled = time - this.lastCallTime; + this.step(dt, timeSinceLastCalled, maxSubSteps); + } + + this.lastCallTime = time; + } + /** + * Step the physics world forward in time. + * + * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. + * + * @param dt The fixed time step size to use. + * @param timeSinceLastCalled The time elapsed since the function was last called. + * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10). + * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F + * @example + * // fixed timestepping without interpolation + * world.step(1 / 60) + */ + + step(dt, timeSinceLastCalled, maxSubSteps) { + if (maxSubSteps === void 0) { + maxSubSteps = 10; + } + + if (timeSinceLastCalled === undefined) { + // Fixed, simple stepping + this.internalStep(dt); // Increment time + + this.time += dt; + } else { + this.accumulator += timeSinceLastCalled; + const t0 = performance.now(); + let substeps = 0; + + while (this.accumulator >= dt && substeps < maxSubSteps) { + // Do fixed steps to catch up + this.internalStep(dt); + this.accumulator -= dt; + substeps++; + + if (performance.now() - t0 > dt * 1000) { + // The framerate is not interactive anymore. + // We are below the target framerate. + // Better bail out. + break; + } + } // Remove the excess accumulator, since we may not + // have had enough substeps available to catch up + + this.accumulator = this.accumulator % dt; + const t = this.accumulator / dt; + + for (let j = 0; j !== this.bodies.length; j++) { + const b = this.bodies[j]; + b.previousPosition.lerp(b.position, t, b.interpolatedPosition); + b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion); + b.previousQuaternion.normalize(); + } + + this.time += timeSinceLastCalled; + } + } + + internalStep(dt) { + this.dt = dt; + const contacts = this.contacts; + const p1 = World_step_p1; + const p2 = World_step_p2; + const N = this.bodies.length; + const bodies = this.bodies; + const solver = this.solver; + const gravity = this.gravity; + const doProfiling = this.doProfiling; + const profile = this.profile; + const DYNAMIC = Body.DYNAMIC; + let profilingStart = -Infinity; + const constraints = this.constraints; + const frictionEquationPool = World_step_frictionEquationPool; + gravity.length(); + const gx = gravity.x; + const gy = gravity.y; + const gz = gravity.z; + let i = 0; + + if (doProfiling) { + profilingStart = performance.now(); + } // Add gravity to all objects + + for (i = 0; i !== N; i++) { + const bi = bodies[i]; + + if (bi.type === DYNAMIC) { + // Only for dynamic bodies + const f = bi.force; + const m = bi.mass; + f.x += m * gx; + f.y += m * gy; + f.z += m * gz; + } + } // Update subsystems + + for ( + let i = 0, Nsubsystems = this.subsystems.length; + i !== Nsubsystems; + i++ + ) { + this.subsystems[i].update(); + } // Collision detection + + if (doProfiling) { + profilingStart = performance.now(); + } + + p1.length = 0; // Clean up pair arrays from last step + + p2.length = 0; + this.broadphase.collisionPairs(this, p1, p2); + + if (doProfiling) { + profile.broadphase = performance.now() - profilingStart; + } // Remove constrained pairs with collideConnected == false + + let Nconstraints = constraints.length; + + for (i = 0; i !== Nconstraints; i++) { + const c = constraints[i]; + + if (!c.collideConnected) { + for (let j = p1.length - 1; j >= 0; j -= 1) { + if ( + (c.bodyA === p1[j] && c.bodyB === p2[j]) || + (c.bodyB === p1[j] && c.bodyA === p2[j]) + ) { + p1.splice(j, 1); + p2.splice(j, 1); + } + } + } + } + + this.collisionMatrixTick(); // Generate contacts + + if (doProfiling) { + profilingStart = performance.now(); + } + + const oldcontacts = World_step_oldContacts; + const NoldContacts = contacts.length; + + for (i = 0; i !== NoldContacts; i++) { + oldcontacts.push(contacts[i]); + } + + contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse + + const NoldFrictionEquations = this.frictionEquations.length; + + for (i = 0; i !== NoldFrictionEquations; i++) { + frictionEquationPool.push(this.frictionEquations[i]); + } + + this.frictionEquations.length = 0; + this.narrowphase.getContacts( + p1, + p2, + this, + contacts, + oldcontacts, // To be reused + this.frictionEquations, + frictionEquationPool + ); + + if (doProfiling) { + profile.narrowphase = performance.now() - profilingStart; + } // Loop over all collisions + + if (doProfiling) { + profilingStart = performance.now(); + } // Add all friction eqs + + for (i = 0; i < this.frictionEquations.length; i++) { + solver.addEquation(this.frictionEquations[i]); + } + + const ncontacts = contacts.length; + + for (let k = 0; k !== ncontacts; k++) { + // Current contact + const c = contacts[k]; // Get current collision indeces + + const bi = c.bi; + const bj = c.bj; + const si = c.si; + const sj = c.sj; // Get collision properties + + let cm; + + if (bi.material && bj.material) { + cm = + this.getContactMaterial(bi.material, bj.material) || + this.defaultContactMaterial; + } else { + cm = this.defaultContactMaterial; + } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + cm.friction; // c.restitution = cm.restitution; + // If friction or restitution were specified in the material, use them + + if (bi.material && bj.material) { + if (bi.material.friction >= 0 && bj.material.friction >= 0) { + bi.material.friction * bj.material.friction; + } + + if (bi.material.restitution >= 0 && bj.material.restitution >= 0) { + c.restitution = bi.material.restitution * bj.material.restitution; + } + } // c.setSpookParams( + // cm.contactEquationStiffness, + // cm.contactEquationRelaxation, + // dt + // ); + + solver.addEquation(c); // // Add friction constraint equation + // if(mu > 0){ + // // Create 2 tangent equations + // const mug = mu * gnorm; + // const reducedMass = (bi.invMass + bj.invMass); + // if(reducedMass > 0){ + // reducedMass = 1/reducedMass; + // } + // const pool = frictionEquationPool; + // const c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass); + // const c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass); + // this.frictionEquations.push(c1, c2); + // c1.bi = c2.bi = bi; + // c1.bj = c2.bj = bj; + // c1.minForce = c2.minForce = -mug*reducedMass; + // c1.maxForce = c2.maxForce = mug*reducedMass; + // // Copy over the relative vectors + // c1.ri.copy(c.ri); + // c1.rj.copy(c.rj); + // c2.ri.copy(c.ri); + // c2.rj.copy(c.rj); + // // Construct tangents + // c.ni.tangents(c1.t, c2.t); + // // Set spook params + // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt); + // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt); + // c1.enabled = c2.enabled = c.enabled; + // // Add equations to solver + // solver.addEquation(c1); + // solver.addEquation(c2); + // } + + if ( + bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ) { + const speedSquaredB = + bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared(); + const speedLimitSquaredB = bj.sleepSpeedLimit ** 2; + + if (speedSquaredB >= speedLimitSquaredB * 2) { + bi.wakeUpAfterNarrowphase = true; + } + } + + if ( + bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== Body.STATIC + ) { + const speedSquaredA = + bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared(); + const speedLimitSquaredA = bi.sleepSpeedLimit ** 2; + + if (speedSquaredA >= speedLimitSquaredA * 2) { + bj.wakeUpAfterNarrowphase = true; + } + } // Now we know that i and j are in contact. Set collision matrix state + + this.collisionMatrix.set(bi, bj, true); + + if (!this.collisionMatrixPrevious.get(bi, bj)) { + // First contact! + // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached. + World_step_collideEvent.body = bj; + World_step_collideEvent.contact = c; + bi.dispatchEvent(World_step_collideEvent); + World_step_collideEvent.body = bi; + bj.dispatchEvent(World_step_collideEvent); + } + + this.bodyOverlapKeeper.set(bi.id, bj.id); + this.shapeOverlapKeeper.set(si.id, sj.id); + } + + this.emitContactEvents(); + + if (doProfiling) { + profile.makeContactConstraints = performance.now() - profilingStart; + profilingStart = performance.now(); + } // Wake up bodies + + for (i = 0; i !== N; i++) { + const bi = bodies[i]; + + if (bi.wakeUpAfterNarrowphase) { + bi.wakeUp(); + bi.wakeUpAfterNarrowphase = false; + } + } // Add user-added constraints + + Nconstraints = constraints.length; + + for (i = 0; i !== Nconstraints; i++) { + const c = constraints[i]; + c.update(); + + for (let j = 0, Neq = c.equations.length; j !== Neq; j++) { + const eq = c.equations[j]; + solver.addEquation(eq); + } + } // Solve the constrained system + + solver.solve(dt, this); + + if (doProfiling) { + profile.solve = performance.now() - profilingStart; + } // Remove all contacts from solver + + solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details + + const pow = Math.pow; + + for (i = 0; i !== N; i++) { + const bi = bodies[i]; + + if (bi.type & DYNAMIC) { + // Only for dynamic bodies + const ld = pow(1.0 - bi.linearDamping, dt); + const v = bi.velocity; + v.scale(ld, v); + const av = bi.angularVelocity; + + if (av) { + const ad = pow(1.0 - bi.angularDamping, dt); + av.scale(ad, av); + } + } + } + + this.dispatchEvent(World_step_preStepEvent); // Leap frog + // vnew = v + h*f/m + // xnew = x + h*vnew + + if (doProfiling) { + profilingStart = performance.now(); + } + + const stepnumber = this.stepnumber; + const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0; + const quatNormalizeFast = this.quatNormalizeFast; + + for (i = 0; i !== N; i++) { + bodies[i].integrate(dt, quatNormalize, quatNormalizeFast); + } + + this.clearForces(); + this.broadphase.dirty = true; + + if (doProfiling) { + profile.integrate = performance.now() - profilingStart; + } // Update step number + + this.stepnumber += 1; + this.dispatchEvent(World_step_postStepEvent); // Sleeping update + + let hasActiveBodies = true; + + if (this.allowSleep) { + hasActiveBodies = false; + + for (i = 0; i !== N; i++) { + const bi = bodies[i]; + bi.sleepTick(this.time); + + if (bi.sleepState !== Body.SLEEPING) { + hasActiveBodies = true; + } + } + } + + this.hasActiveBodies = hasActiveBodies; + } + + emitContactEvents() { + const hasBeginContact = this.hasAnyEventListener("beginContact"); + const hasEndContact = this.hasAnyEventListener("endContact"); + + if (hasBeginContact || hasEndContact) { + this.bodyOverlapKeeper.getDiff(additions, removals); + } + + if (hasBeginContact) { + for (let i = 0, l = additions.length; i < l; i += 2) { + beginContactEvent.bodyA = this.getBodyById(additions[i]); + beginContactEvent.bodyB = this.getBodyById(additions[i + 1]); + this.dispatchEvent(beginContactEvent); + } + + beginContactEvent.bodyA = beginContactEvent.bodyB = null; + } + + if (hasEndContact) { + for (let i = 0, l = removals.length; i < l; i += 2) { + endContactEvent.bodyA = this.getBodyById(removals[i]); + endContactEvent.bodyB = this.getBodyById(removals[i + 1]); + this.dispatchEvent(endContactEvent); + } + + endContactEvent.bodyA = endContactEvent.bodyB = null; + } + + additions.length = removals.length = 0; + const hasBeginShapeContact = this.hasAnyEventListener("beginShapeContact"); + const hasEndShapeContact = this.hasAnyEventListener("endShapeContact"); + + if (hasBeginShapeContact || hasEndShapeContact) { + this.shapeOverlapKeeper.getDiff(additions, removals); + } + + if (hasBeginShapeContact) { + for (let i = 0, l = additions.length; i < l; i += 2) { + const shapeA = this.getShapeById(additions[i]); + const shapeB = this.getShapeById(additions[i + 1]); + beginShapeContactEvent.shapeA = shapeA; + beginShapeContactEvent.shapeB = shapeB; + if (shapeA) beginShapeContactEvent.bodyA = shapeA.body; + if (shapeB) beginShapeContactEvent.bodyB = shapeB.body; + this.dispatchEvent(beginShapeContactEvent); + } + + beginShapeContactEvent.bodyA = + beginShapeContactEvent.bodyB = + beginShapeContactEvent.shapeA = + beginShapeContactEvent.shapeB = + null; + } + + if (hasEndShapeContact) { + for (let i = 0, l = removals.length; i < l; i += 2) { + const shapeA = this.getShapeById(removals[i]); + const shapeB = this.getShapeById(removals[i + 1]); + endShapeContactEvent.shapeA = shapeA; + endShapeContactEvent.shapeB = shapeB; + if (shapeA) endShapeContactEvent.bodyA = shapeA.body; + if (shapeB) endShapeContactEvent.bodyB = shapeB.body; + this.dispatchEvent(endShapeContactEvent); + } + + endShapeContactEvent.bodyA = + endShapeContactEvent.bodyB = + endShapeContactEvent.shapeA = + endShapeContactEvent.shapeB = + null; + } + } + /** + * Sets all body forces in the world to zero. + */ + + clearForces() { + const bodies = this.bodies; + const N = bodies.length; + + for (let i = 0; i !== N; i++) { + const b = bodies[i]; + b.force; + b.torque; + b.force.set(0, 0, 0); + b.torque.set(0, 0, 0); + } + } + } // Temp stuff + + new AABB(); + const tmpRay = new Ray(); // performance.now() fallback on Date.now() + + const performance = + (require$$0 && require$$0.performance) || {}; + + if (!performance.now) { + let nowOffset = Date.now(); + + if (performance.timing && performance.timing.navigationStart) { + nowOffset = performance.timing.navigationStart; + } + + performance.now = () => Date.now() - nowOffset; + } + + new Vec3(); // Dispatched after the world has stepped forward in time. + // Reusable event objects to save memory. + + const World_step_postStepEvent = { + type: "postStep", + }; // Dispatched before the world steps forward in time. + + const World_step_preStepEvent = { + type: "preStep", + }; + const World_step_collideEvent = { + type: Body.COLLIDE_EVENT_NAME, + body: null, + contact: null, + }; // Pools for unused objects + + const World_step_oldContacts = []; + const World_step_frictionEquationPool = []; // Reusable arrays for collision pairs + + const World_step_p1 = []; + const World_step_p2 = []; // Stuff for emitContactEvents + + const additions = []; + const removals = []; + const beginContactEvent = { + type: "beginContact", + bodyA: null, + bodyB: null, + }; + const endContactEvent = { + type: "endContact", + bodyA: null, + bodyB: null, + }; + const beginShapeContactEvent = { + type: "beginShapeContact", + bodyA: null, + bodyB: null, + shapeA: null, + shapeB: null, + }; + const endShapeContactEvent = { + type: "endShapeContact", + bodyA: null, + bodyB: null, + shapeA: null, + shapeB: null, + }; + + var AABB_1 = cannon.AABB = AABB; + var ArrayCollisionMatrix_1 = cannon.ArrayCollisionMatrix = ArrayCollisionMatrix; + var BODY_SLEEP_STATES_1 = cannon.BODY_SLEEP_STATES = BODY_SLEEP_STATES; + var BODY_TYPES_1 = cannon.BODY_TYPES = BODY_TYPES; + var Body_1 = cannon.Body = Body; + var Box_1 = cannon.Box = Box; + var Broadphase_1 = cannon.Broadphase = Broadphase; + var COLLISION_TYPES_1 = cannon.COLLISION_TYPES = COLLISION_TYPES; + var ConeTwistConstraint_1 = cannon.ConeTwistConstraint = ConeTwistConstraint; + var Constraint_1 = cannon.Constraint = Constraint; + var ContactEquation_1 = cannon.ContactEquation = ContactEquation; + var ContactMaterial_1 = cannon.ContactMaterial = ContactMaterial; + var ConvexPolyhedron_1 = cannon.ConvexPolyhedron = ConvexPolyhedron; + var Cylinder_1 = cannon.Cylinder = Cylinder; + var DistanceConstraint_1 = cannon.DistanceConstraint = DistanceConstraint; + var Equation_1 = cannon.Equation = Equation; + var EventTarget_1 = cannon.EventTarget = EventTarget; + var FrictionEquation_1 = cannon.FrictionEquation = FrictionEquation; + var GSSolver_1 = cannon.GSSolver = GSSolver; + var GridBroadphase_1 = cannon.GridBroadphase = GridBroadphase; + var Heightfield_1 = cannon.Heightfield = Heightfield; + var HingeConstraint_1 = cannon.HingeConstraint = HingeConstraint; + var JacobianElement_1 = cannon.JacobianElement = JacobianElement; + var LockConstraint_1 = cannon.LockConstraint = LockConstraint; + var Mat3_1 = cannon.Mat3 = Mat3; + var Material_1 = cannon.Material = Material; + var NaiveBroadphase_1 = cannon.NaiveBroadphase = NaiveBroadphase; + var Narrowphase_1 = cannon.Narrowphase = Narrowphase; + var ObjectCollisionMatrix_1 = cannon.ObjectCollisionMatrix = ObjectCollisionMatrix; + var Particle_1 = cannon.Particle = Particle; + var Plane_1 = cannon.Plane = Plane; + var PointToPointConstraint_1 = cannon.PointToPointConstraint = PointToPointConstraint; + var Pool_1 = cannon.Pool = Pool; + var Quaternion_1 = cannon.Quaternion = Quaternion; + var RAY_MODES_1 = cannon.RAY_MODES = RAY_MODES; + var Ray_1 = cannon.Ray = Ray; + var RaycastResult_1 = cannon.RaycastResult = RaycastResult; + var RaycastVehicle_1 = cannon.RaycastVehicle = RaycastVehicle; + var RigidVehicle_1 = cannon.RigidVehicle = RigidVehicle; + var RotationalEquation_1 = cannon.RotationalEquation = RotationalEquation; + var RotationalMotorEquation_1 = cannon.RotationalMotorEquation = RotationalMotorEquation; + var SAPBroadphase_1 = cannon.SAPBroadphase = SAPBroadphase; + var SHAPE_TYPES_1 = cannon.SHAPE_TYPES = SHAPE_TYPES; + var SPHSystem_1 = cannon.SPHSystem = SPHSystem; + var Shape_1 = cannon.Shape = Shape; + var Solver_1 = cannon.Solver = Solver; + var Sphere_1 = cannon.Sphere = Sphere; + var SplitSolver_1 = cannon.SplitSolver = SplitSolver; + var Spring_1 = cannon.Spring = Spring; + var Transform_1 = cannon.Transform = Transform; + var Trimesh_1 = cannon.Trimesh = Trimesh; + var Vec3_1 = cannon.Vec3 = Vec3; + var Vec3Pool_1 = cannon.Vec3Pool = Vec3Pool; + var WheelInfo_1 = cannon.WheelInfo = WheelInfo; + var World_1 = cannon.World = World; + + exports.AABB = AABB_1; + exports.ArrayCollisionMatrix = ArrayCollisionMatrix_1; + exports.BODY_SLEEP_STATES = BODY_SLEEP_STATES_1; + exports.BODY_TYPES = BODY_TYPES_1; + exports.Body = Body_1; + exports.Box = Box_1; + exports.Broadphase = Broadphase_1; + exports.COLLISION_TYPES = COLLISION_TYPES_1; + exports.ConeTwistConstraint = ConeTwistConstraint_1; + exports.Constraint = Constraint_1; + exports.ContactEquation = ContactEquation_1; + exports.ContactMaterial = ContactMaterial_1; + exports.ConvexPolyhedron = ConvexPolyhedron_1; + exports.Cylinder = Cylinder_1; + exports.DistanceConstraint = DistanceConstraint_1; + exports.Equation = Equation_1; + exports.EventTarget = EventTarget_1; + exports.FrictionEquation = FrictionEquation_1; + exports.GSSolver = GSSolver_1; + exports.GridBroadphase = GridBroadphase_1; + exports.Heightfield = Heightfield_1; + exports.HingeConstraint = HingeConstraint_1; + exports.JacobianElement = JacobianElement_1; + exports.LockConstraint = LockConstraint_1; + exports.Mat3 = Mat3_1; + exports.Material = Material_1; + exports.NaiveBroadphase = NaiveBroadphase_1; + exports.Narrowphase = Narrowphase_1; + exports.ObjectCollisionMatrix = ObjectCollisionMatrix_1; + exports.Particle = Particle_1; + exports.Plane = Plane_1; + exports.PointToPointConstraint = PointToPointConstraint_1; + exports.Pool = Pool_1; + exports.Quaternion = Quaternion_1; + exports.RAY_MODES = RAY_MODES_1; + exports.Ray = Ray_1; + exports.RaycastResult = RaycastResult_1; + exports.RaycastVehicle = RaycastVehicle_1; + exports.RigidVehicle = RigidVehicle_1; + exports.RotationalEquation = RotationalEquation_1; + exports.RotationalMotorEquation = RotationalMotorEquation_1; + exports.SAPBroadphase = SAPBroadphase_1; + exports.SHAPE_TYPES = SHAPE_TYPES_1; + exports.SPHSystem = SPHSystem_1; + exports.Shape = Shape_1; + exports.Solver = Solver_1; + exports.Sphere = Sphere_1; + exports.SplitSolver = SplitSolver_1; + exports.Spring = Spring_1; + exports.Transform = Transform_1; + exports.Trimesh = Trimesh_1; + exports.Vec3 = Vec3_1; + exports.Vec3Pool = Vec3Pool_1; + exports.WheelInfo = WheelInfo_1; + exports.World = World_1; + exports.default = cannon; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/activities/3DVolume.activity/lib/debug.js b/activities/3DVolume.activity/lib/debug.js new file mode 100644 index 0000000000..4766e9f6d2 --- /dev/null +++ b/activities/3DVolume.activity/lib/debug.js @@ -0,0 +1,306 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('cannon'), require('three')) : + typeof define === 'function' && define.amd ? define(['cannon', 'three'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.CannonDebugger = factory(global.CANNON, global.THREE)); + })(this, (function (cannon, three) { 'use strict'; + + function CannonDebugger(scene, world, _temp) { + let { + color = 0x00ff00, + scale = 1, + onInit, + onUpdate + } = _temp === void 0 ? {} : _temp; + const _meshes = []; + + const _material = new THREE.MeshBasicMaterial({ + color: color != null ? color : 0x00ff00, + wireframe: true + }); + + const _tempVec0 = new CANNON.Vec3(); + + const _tempVec1 = new CANNON.Vec3(); + + const _tempVec2 = new CANNON.Vec3(); + + const _tempQuat0 = new CANNON.Quaternion(); + + const _sphereGeometry = new THREE.SphereGeometry(1); + + const _boxGeometry = new THREE.BoxGeometry(1, 1, 1); + + const _planeGeometry = new THREE.PlaneGeometry(10, 10, 10, 10); // Move the planeGeometry forward a little bit to prevent z-fighting + + + _planeGeometry.translate(0, 0, 0.0001); + + function createConvexPolyhedronGeometry(shape) { + const geometry = new THREE.BufferGeometry(); // Add vertices + + const positions = []; + + for (let i = 0; i < shape.vertices.length; i++) { + const vertex = shape.vertices[i]; + positions.push(vertex.x, vertex.y, vertex.z); + } + + geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); // Add faces + + const indices = []; + + for (let i = 0; i < shape.faces.length; i++) { + const face = shape.faces[i]; + const a = face[0]; + + for (let j = 1; j < face.length - 1; j++) { + const b = face[j]; + const c = face[j + 1]; + indices.push(a, b, c); + } + } + + geometry.setIndex(indices); + geometry.computeBoundingSphere(); + geometry.computeVertexNormals(); + return geometry; + } + + function createTrimeshGeometry(shape) { + const geometry = new THREE.BufferGeometry(); + const positions = []; + const v0 = _tempVec0; + const v1 = _tempVec1; + const v2 = _tempVec2; + + for (let i = 0; i < shape.indices.length / 3; i++) { + shape.getTriangleVertices(i, v0, v1, v2); + positions.push(v0.x, v0.y, v0.z); + positions.push(v1.x, v1.y, v1.z); + positions.push(v2.x, v2.y, v2.z); + } + + geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + geometry.computeVertexNormals(); + return geometry; + } + + function createHeightfieldGeometry(shape) { + const geometry = new THREE.BufferGeometry(); + const s = shape.elementSize || 1; // assumes square heightfield, else i*x, j*y + + const positions = shape.data.flatMap((row, i) => row.flatMap((z, j) => [i * s, j * s, z])); + const indices = []; + + for (let xi = 0; xi < shape.data.length - 1; xi++) { + for (let yi = 0; yi < shape.data[xi].length - 1; yi++) { + const stride = shape.data[xi].length; + const index = xi * stride + yi; + indices.push(index + 1, index + stride, index + stride + 1); + indices.push(index + stride, index + 1, index); + } + } + + geometry.setIndex(indices); + geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + geometry.computeVertexNormals(); + return geometry; + } + + function createMesh(shape) { + let mesh = new THREE.Mesh(); + const { + SPHERE, + BOX, + PLANE, + CYLINDER, + CONVEXPOLYHEDRON, + TRIMESH, + HEIGHTFIELD + } = CANNON.Shape.types; + + switch (shape.type) { + case SPHERE: + { + mesh = new THREE.Mesh(_sphereGeometry, _material); + break; + } + + case BOX: + { + mesh = new THREE.Mesh(_boxGeometry, _material); + break; + } + + case PLANE: + { + mesh = new THREE.Mesh(_planeGeometry, _material); + break; + } + + case CYLINDER: + { + const geometry = new THREE.CylinderGeometry(shape.radiusTop, shape.radiusBottom, shape.height, shape.numSegments); + mesh = new THREE.Mesh(geometry, _material); + shape.geometryId = geometry.id; + break; + } + + case CONVEXPOLYHEDRON: + { + const geometry = createConvexPolyhedronGeometry(shape); + mesh = new THREE.Mesh(geometry, _material); + shape.geometryId = geometry.id; + break; + } + + case TRIMESH: + { + const geometry = createTrimeshGeometry(shape); + mesh = new THREE.Mesh(geometry, _material); + shape.geometryId = geometry.id; + break; + } + + case HEIGHTFIELD: + { + const geometry = createHeightfieldGeometry(shape); + mesh = new THREE.Mesh(geometry, _material); + shape.geometryId = geometry.id; + break; + } + } + + scene.add(mesh); + return mesh; + } + + function scaleMesh(mesh, shape) { + const { + SPHERE, + BOX, + PLANE, + CYLINDER, + CONVEXPOLYHEDRON, + TRIMESH, + HEIGHTFIELD + } = CANNON.Shape.types; + + switch (shape.type) { + case SPHERE: + { + const { + radius + } = shape; + mesh.scale.set(radius * scale, radius * scale, radius * scale); + break; + } + + case BOX: + { + mesh.scale.copy(shape.halfExtents); + mesh.scale.multiplyScalar(2 * scale); + break; + } + + case PLANE: + { + break; + } + + case CYLINDER: + { + mesh.scale.set(1 * scale, 1 * scale, 1 * scale); + break; + } + + case CONVEXPOLYHEDRON: + { + mesh.scale.set(1 * scale, 1 * scale, 1 * scale); + break; + } + + case TRIMESH: + { + mesh.scale.copy(shape.scale).multiplyScalar(scale); + break; + } + + case HEIGHTFIELD: + { + mesh.scale.set(1 * scale, 1 * scale, 1 * scale); + break; + } + } + } + + function typeMatch(mesh, shape) { + if (!mesh) return false; + const { + geometry + } = mesh; + return geometry instanceof THREE.SphereGeometry && shape.type === CANNON.Shape.types.SPHERE || geometry instanceof THREE.BoxGeometry && shape.type === CANNON.Shape.types.BOX || geometry instanceof THREE.PlaneGeometry && shape.type === CANNON.Shape.types.PLANE || geometry.id === shape.geometryId && shape.type === CANNON.Shape.types.CYLINDER || geometry.id === shape.geometryId && shape.type === CANNON.Shape.types.CONVEXPOLYHEDRON || geometry.id === shape.geometryId && shape.type === CANNON.Shape.types.TRIMESH || geometry.id === shape.geometryId && shape.type === CANNON.Shape.types.HEIGHTFIELD; + } + + function updateMesh(index, shape) { + let mesh = _meshes[index]; + let didCreateNewMesh = false; + + if (!typeMatch(mesh, shape)) { + if (mesh) scene.remove(mesh); + _meshes[index] = mesh = createMesh(shape); + didCreateNewMesh = true; + } + + scaleMesh(mesh, shape); + return didCreateNewMesh; + } + + function update() { + const meshes = _meshes; + const shapeWorldPosition = _tempVec0; + const shapeWorldQuaternion = _tempQuat0; + let meshIndex = 0; + + for (const body of world.bodies) { + for (let i = 0; i !== body.shapes.length; i++) { + const shape = body.shapes[i]; + const didCreateNewMesh = updateMesh(meshIndex, shape); + const mesh = meshes[meshIndex]; + + if (mesh) { + // Get world position + body.quaternion.vmult(body.shapeOffsets[i], shapeWorldPosition); + body.position.vadd(shapeWorldPosition, shapeWorldPosition); // Get world quaternion + + body.quaternion.mult(body.shapeOrientations[i], shapeWorldQuaternion); // Copy to meshes + + mesh.position.copy(shapeWorldPosition); + mesh.quaternion.copy(shapeWorldQuaternion); + if (didCreateNewMesh && onInit instanceof Function) onInit(body, mesh, shape); + if (!didCreateNewMesh && onUpdate instanceof Function) onUpdate(body, mesh, shape); + } + + meshIndex++; + } + } + + for (let i = meshIndex; i < meshes.length; i++) { + const mesh = meshes[i]; + if (mesh) scene.remove(mesh); + } + + meshes.length = meshIndex; + } + + return { + update + }; + } + + return CannonDebugger; + + })); + \ No newline at end of file diff --git a/activities/3DVolume.activity/lib/domReady.js b/activities/3DVolume.activity/lib/domReady.js new file mode 100644 index 0000000000..2b54122098 --- /dev/null +++ b/activities/3DVolume.activity/lib/domReady.js @@ -0,0 +1,129 @@ +/** + * @license RequireJS domReady 2.0.1 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/requirejs/domReady for details + */ +/*jslint */ +/*global require: false, define: false, requirejs: false, + window: false, clearInterval: false, document: false, + self: false, setInterval: false */ + + +define(function () { + 'use strict'; + + var isTop, testDiv, scrollIntervalId, + isBrowser = typeof window !== "undefined" && window.document, + isPageLoaded = !isBrowser, + doc = isBrowser ? document : null, + readyCalls = []; + + function runCallbacks(callbacks) { + var i; + for (i = 0; i < callbacks.length; i += 1) { + callbacks[i](doc); + } + } + + function callReady() { + var callbacks = readyCalls; + + if (isPageLoaded) { + //Call the DOM ready callbacks + if (callbacks.length) { + readyCalls = []; + runCallbacks(callbacks); + } + } + } + + /** + * Sets the page as loaded. + */ + function pageLoaded() { + if (!isPageLoaded) { + isPageLoaded = true; + if (scrollIntervalId) { + clearInterval(scrollIntervalId); + } + + callReady(); + } + } + + if (isBrowser) { + if (document.addEventListener) { + //Standards. Hooray! Assumption here that if standards based, + //it knows about DOMContentLoaded. + document.addEventListener("DOMContentLoaded", pageLoaded, false); + window.addEventListener("load", pageLoaded, false); + } else if (window.attachEvent) { + window.attachEvent("onload", pageLoaded); + + testDiv = document.createElement('div'); + try { + isTop = window.frameElement === null; + } catch (e) {} + + //DOMContentLoaded approximation that uses a doScroll, as found by + //Diego Perini: http://javascript.nwbox.com/IEContentLoaded/, + //but modified by other contributors, including jdalton + if (testDiv.doScroll && isTop && window.external) { + scrollIntervalId = setInterval(function () { + try { + testDiv.doScroll(); + pageLoaded(); + } catch (e) {} + }, 30); + } + } + + //Check if document already complete, and if so, just trigger page load + //listeners. Latest webkit browsers also use "interactive", and + //will fire the onDOMContentLoaded before "interactive" but not after + //entering "interactive" or "complete". More details: + //http://dev.w3.org/html5/spec/the-end.html#the-end + //http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded + //Hmm, this is more complicated on further use, see "firing too early" + //bug: https://github.com/requirejs/domReady/issues/1 + //so removing the || document.readyState === "interactive" test. + //There is still a window.onload binding that should get fired if + //DOMContentLoaded is missed. + if (document.readyState === "complete") { + pageLoaded(); + } + } + + /** START OF PUBLIC API **/ + + /** + * Registers a callback for DOM ready. If DOM is already ready, the + * callback is called immediately. + * @param {Function} callback + */ + function domReady(callback) { + if (isPageLoaded) { + callback(doc); + } else { + readyCalls.push(callback); + } + return domReady; + } + + domReady.version = '2.0.1'; + + /** + * Loader Plugin API method + */ + domReady.load = function (name, req, onLoad, config) { + if (config.isBuild) { + onLoad(null); + } else { + domReady(onLoad); + } + }; + + /** END OF PUBLIC API **/ + + return domReady; +}); diff --git a/activities/3DVolume.activity/lib/i18next.min.js b/activities/3DVolume.activity/lib/i18next.min.js new file mode 100644 index 0000000000..08f5469cfe --- /dev/null +++ b/activities/3DVolume.activity/lib/i18next.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).i18next=t()}(this,function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function n(e){for(var n=1;n1&&void 0!==arguments[1]?arguments[1]:{};i(this,e),this.init(t,n)}return r(e,[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=t.prefix||"i18next:",this.logger=e||p,this.options=t,this.debug=t.debug}},{key:"setDebug",value:function(e){this.debug=e}},{key:"log",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1?t-1:0),i=1;i-1?e.replace(/###/g,"."):e}function o(){return!e||"string"==typeof e}for(var r="string"!=typeof t?[].concat(t):t.split(".");r.length>1;){if(o())return{};var a=i(r.shift());!e[a]&&n&&(e[a]=new n),e=Object.prototype.hasOwnProperty.call(e,a)?e[a]:{}}return o()?{}:{obj:e,k:i(r.shift())}}function y(e,t,n){var i=v(e,t,Object);i.obj[i.k]=n}function m(e,t){var n=v(e,t),i=n.obj,o=n.k;if(i)return i[o]}function b(e,t,n){var i=m(e,n);return void 0!==i?i:m(t,n)}function k(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var x={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function S(e){return"string"==typeof e?e.replace(/[&<>"'\/]/g,function(e){return x[e]}):e}var w="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1;var L=function(e){function t(e){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return i(this,t),n=s(this,u(t).call(this)),w&&f.call(a(n)),n.data=e||{},n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),void 0===n.options.ignoreJSONStructure&&(n.options.ignoreJSONStructure=!0),n}return c(t,f),r(t,[{key:"addNamespaces",value:function(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}},{key:"removeNamespaces",value:function(e){var t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}},{key:"getResource",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,r=void 0!==i.ignoreJSONStructure?i.ignoreJSONStructure:this.options.ignoreJSONStructure,a=[e,t];n&&"string"!=typeof n&&(a=a.concat(n)),n&&"string"==typeof n&&(a=a.concat(o?n.split(o):n)),e.indexOf(".")>-1&&(a=e.split("."));var s=m(this.data,a);return s||!r||"string"!=typeof n?s:function e(t,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(t){if(t[n])return t[n];for(var o=n.split(i),r=t,a=0;aa+s;)s++,l=r[u=o.slice(a,a+s).join(i)];if(void 0===l)return;if("string"==typeof l)return l;if(u&&"string"==typeof l[u])return l[u];var c=o.slice(a+s).join(i);return c?e(l,c,i):void 0}r=r[o[a]]}return r}}(this.data&&this.data[e]&&this.data[e][t],n,o)}},{key:"addResource",value:function(e,t,n,i){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},r=this.options.keySeparator;void 0===r&&(r=".");var a=[e,t];n&&(a=a.concat(r?n.split(r):n)),e.indexOf(".")>-1&&(i=t,t=(a=e.split("."))[1]),this.addNamespaces(t),y(this.data,a,i),o.silent||this.emit("added",e,t,n,i)}},{key:"addResources",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var o in n)"string"!=typeof n[o]&&"[object Array]"!==Object.prototype.toString.apply(n[o])||this.addResource(e,t,o,n[o],{silent:!0});i.silent||this.emit("added",e,t,n)}},{key:"addResourceBundle",value:function(e,t,i,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},s=[e,t];e.indexOf(".")>-1&&(o=i,i=t,t=(s=e.split("."))[1]),this.addNamespaces(t);var u=m(this.data,s)||{};o?function e(t,n,i){for(var o in n)"__proto__"!==o&&"constructor"!==o&&(o in t?"string"==typeof t[o]||t[o]instanceof String||"string"==typeof n[o]||n[o]instanceof String?i&&(t[o]=n[o]):e(t[o],n[o],i):t[o]=n[o]);return t}(u,i,r):u=n({},u,i),y(this.data,s,u),a.silent||this.emit("added",e,t,i)}},{key:"removeResourceBundle",value:function(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}},{key:"hasResourceBundle",value:function(e,t){return void 0!==this.getResource(e,t)}},{key:"getResourceBundle",value:function(e,t){return t||(t=this.options.defaultNS),"v1"===this.options.compatibilityAPI?n({},{},this.getResource(e,t)):this.getResource(e,t)}},{key:"getDataByLanguage",value:function(e){return this.data[e]}},{key:"toJSON",value:function(){return this.data}}]),t}(),O={processors:{},addPostProcessor:function(e){this.processors[e.name]=e},handle:function(e,t,n,i,o){var r=this;return e.forEach(function(e){r.processors[e]&&(t=r.processors[e].process(t,n,i,o))}),t}},N={},R=function(t){function o(e){var t,n,r,l,c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return i(this,o),t=s(this,u(o).call(this)),w&&f.call(a(t)),n=["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],r=e,l=a(t),n.forEach(function(e){r[e]&&(l[e]=r[e])}),t.options=c,void 0===t.options.keySeparator&&(t.options.keySeparator="."),t.logger=g.create("translator"),t}return c(o,f),r(o,[{key:"changeLanguage",value:function(e){e&&(this.language=e)}},{key:"exists",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}},n=this.resolve(e,t);return n&&void 0!==n.res}},{key:"extractFromKey",value:function(e,t){var n=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===n&&(n=":");var i=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator,o=t.ns||this.options.defaultNS;if(n&&e.indexOf(n)>-1){var r=e.match(this.interpolator.nestingRegexp);if(r&&r.length>0)return{key:e,namespaces:o};var a=e.split(n);(n!==i||n===i&&this.options.ns.indexOf(a[0])>-1)&&(o=a.shift()),e=a.join(i)}return"string"==typeof o&&(o=[o]),{key:e,namespaces:o}}},{key:"translate",value:function(t,i,r){var a=this;if("object"!==e(i)&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),i||(i={}),null==t)return"";Array.isArray(t)||(t=[String(t)]);var s=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,u=this.extractFromKey(t[t.length-1],i),l=u.key,c=u.namespaces,p=c[c.length-1],g=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(g&&"cimode"===g.toLowerCase()){if(f){var h=i.nsSeparator||this.options.nsSeparator;return p+h+l}return l}var d=this.resolve(t,i),v=d&&d.res,y=d&&d.usedKey||l,m=d&&d.exactUsedKey||l,b=Object.prototype.toString.apply(v),k=void 0!==i.joinArrays?i.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject;if(x&&v&&("string"!=typeof v&&"boolean"!=typeof v&&"number"!=typeof v)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(b)<0&&("string"!=typeof k||"[object Array]"!==b)){if(!i.returnObjects&&!this.options.returnObjects)return this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,v,i):"key '".concat(l," (").concat(this.language,")' returned an object instead of string.");if(s){var S="[object Array]"===b,w=S?[]:{},L=S?m:y;for(var O in v)if(Object.prototype.hasOwnProperty.call(v,O)){var N="".concat(L).concat(s).concat(O);w[O]=this.translate(N,n({},i,{joinArrays:!1,ns:c})),w[O]===N&&(w[O]=v[O])}v=w}}else if(x&&"string"==typeof k&&"[object Array]"===b)(v=v.join(k))&&(v=this.extendTranslation(v,t,i,r));else{var R=!1,C=!1,j=void 0!==i.count&&"string"!=typeof i.count,E=o.hasDefaultValue(i),P=j?this.pluralResolver.getSuffix(g,i.count):"",F=i["defaultValue".concat(P)]||i.defaultValue;!this.isValidLookup(v)&&E&&(R=!0,v=F),this.isValidLookup(v)||(C=!0,v=l);var V=E&&F!==v&&this.options.updateMissing;if(C||R||V){if(this.logger.log(V?"updateKey":"missingKey",g,p,l,V?F:v),s){var T=this.resolve(l,n({},i,{keySeparator:!1}));T&&T.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var A=[],U=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if("fallback"===this.options.saveMissingTo&&U&&U[0])for(var I=0;I1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof e&&(e=[e]),e.forEach(function(e){if(!a.isValidLookup(t)){var u=a.extractFromKey(e,s),l=u.key;n=l;var c=u.namespaces;a.options.fallbackNS&&(c=c.concat(a.options.fallbackNS));var p=void 0!==s.count&&"string"!=typeof s.count,g=void 0!==s.context&&"string"==typeof s.context&&""!==s.context,f=s.lngs?s.lngs:a.languageUtils.toResolveHierarchy(s.lng||a.language,s.fallbackLng);c.forEach(function(e){a.isValidLookup(t)||(r=e,!N["".concat(f[0],"-").concat(e)]&&a.utils&&a.utils.hasLoadedNamespace&&!a.utils.hasLoadedNamespace(r)&&(N["".concat(f[0],"-").concat(e)]=!0,a.logger.warn('key "'.concat(n,'" for languages "').concat(f.join(", "),'" won\'t get resolved as namespace "').concat(r,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),f.forEach(function(n){if(!a.isValidLookup(t)){o=n;var r,u,c=l,f=[c];if(a.i18nFormat&&a.i18nFormat.addLookupKeys)a.i18nFormat.addLookupKeys(f,l,n,e,s);else p&&(r=a.pluralResolver.getSuffix(n,s.count)),p&&g&&f.push(c+r),g&&f.push(c+="".concat(a.options.contextSeparator).concat(s.context)),p&&f.push(c+=r);for(;u=f.pop();)a.isValidLookup(t)||(i=u,t=a.getResource(n,e,u,s))}}))})}}),{res:t,usedKey:n,exactUsedKey:i,usedLng:o,usedNS:r}}},{key:"isValidLookup",value:function(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}},{key:"getResource",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,n,i):this.resourceStore.getResource(e,t,n,i)}}],[{key:"hasDefaultValue",value:function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&"defaultValue"===t.substring(0,"defaultValue".length)&&void 0!==e[t])return!0;return!1}}]),o}();function C(e){return e.charAt(0).toUpperCase()+e.slice(1)}var j=function(){function e(t){i(this,e),this.options=t,this.whitelist=this.options.supportedLngs||!1,this.supportedLngs=this.options.supportedLngs||!1,this.logger=g.create("languageUtils")}return r(e,[{key:"getScriptPartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return null;var t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}},{key:"getLanguagePartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return e;var t=e.split("-");return this.formatLanguageCode(t[0])}},{key:"formatLanguageCode",value:function(e){if("string"==typeof e&&e.indexOf("-")>-1){var t=["hans","hant","latn","cyrl","cans","mong","arab"],n=e.split("-");return this.options.lowerCaseLng?n=n.map(function(e){return e.toLowerCase()}):2===n.length?(n[0]=n[0].toLowerCase(),n[1]=n[1].toUpperCase(),t.indexOf(n[1].toLowerCase())>-1&&(n[1]=C(n[1].toLowerCase()))):3===n.length&&(n[0]=n[0].toLowerCase(),2===n[1].length&&(n[1]=n[1].toUpperCase()),"sgn"!==n[0]&&2===n[2].length&&(n[2]=n[2].toUpperCase()),t.indexOf(n[1].toLowerCase())>-1&&(n[1]=C(n[1].toLowerCase())),t.indexOf(n[2].toLowerCase())>-1&&(n[2]=C(n[2].toLowerCase()))),n.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}},{key:"isWhitelisted",value:function(e){return this.logger.deprecate("languageUtils.isWhitelisted",'function "isWhitelisted" will be renamed to "isSupportedCode" in the next major - please make sure to rename it\'s usage asap.'),this.isSupportedCode(e)}},{key:"isSupportedCode",value:function(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}},{key:"getBestMatchFromCodes",value:function(e){var t,n=this;return e?(e.forEach(function(e){if(!t){var i=n.formatLanguageCode(e);n.options.supportedLngs&&!n.isSupportedCode(i)||(t=i)}}),!t&&this.options.supportedLngs&&e.forEach(function(e){if(!t){var i=n.getLanguagePartFromCode(e);if(n.isSupportedCode(i))return t=i;t=n.options.supportedLngs.find(function(e){if(0===e.indexOf(i))return e})}}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t):null}},{key:"getFallbackCodes",value:function(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),"string"==typeof e&&(e=[e]),"[object Array]"===Object.prototype.toString.apply(e))return e;if(!t)return e.default||[];var n=e[t];return n||(n=e[this.getScriptPartFromCode(t)]),n||(n=e[this.formatLanguageCode(t)]),n||(n=e[this.getLanguagePartFromCode(t)]),n||(n=e.default),n||[]}},{key:"toResolveHierarchy",value:function(e,t){var n=this,i=this.getFallbackCodes(t||this.options.fallbackLng||[],e),o=[],r=function(e){e&&(n.isSupportedCode(e)?o.push(e):n.logger.warn("rejecting language code not found in supportedLngs: ".concat(e)))};return"string"==typeof e&&e.indexOf("-")>-1?("languageOnly"!==this.options.load&&r(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&r(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&r(this.getLanguagePartFromCode(e))):"string"==typeof e&&r(this.formatLanguageCode(e)),i.forEach(function(e){o.indexOf(e)<0&&r(n.formatLanguageCode(e))}),o}}]),e}(),E=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],P={1:function(e){return Number(e>1)},2:function(e){return Number(1!=e)},3:function(e){return 0},4:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},5:function(e){return Number(0==e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5)},6:function(e){return Number(1==e?0:e>=2&&e<=4?1:2)},7:function(e){return Number(1==e?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},8:function(e){return Number(1==e?0:2==e?1:8!=e&&11!=e?2:3)},9:function(e){return Number(e>=2)},10:function(e){return Number(1==e?0:2==e?1:e<7?2:e<11?3:4)},11:function(e){return Number(1==e||11==e?0:2==e||12==e?1:e>2&&e<20?2:3)},12:function(e){return Number(e%10!=1||e%100==11)},13:function(e){return Number(0!==e)},14:function(e){return Number(1==e?0:2==e?1:3==e?2:3)},15:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2)},16:function(e){return Number(e%10==1&&e%100!=11?0:0!==e?1:2)},17:function(e){return Number(1==e||e%10==1&&e%100!=11?0:1)},18:function(e){return Number(0==e?0:1==e?1:2)},19:function(e){return Number(1==e?0:0==e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3)},20:function(e){return Number(1==e?0:0==e||e%100>0&&e%100<20?1:2)},21:function(e){return Number(e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0)},22:function(e){return Number(1==e?0:2==e?1:(e<0||e>10)&&e%10==0?2:3)}};var F=function(){function e(t){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};i(this,e),this.languageUtils=t,this.options=o,this.logger=g.create("pluralResolver"),this.rules=(n={},E.forEach(function(e){e.lngs.forEach(function(t){n[t]={numbers:e.nr,plurals:P[e.fc]}})}),n)}return r(e,[{key:"addRule",value:function(e,t){this.rules[e]=t}},{key:"getRule",value:function(e){return this.rules[e]||this.rules[this.languageUtils.getLanguagePartFromCode(e)]}},{key:"needsPlural",value:function(e){var t=this.getRule(e);return t&&t.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(e,t){return this.getSuffixes(e).map(function(e){return t+e})}},{key:"getSuffixes",value:function(e){var t=this,n=this.getRule(e);return n?n.numbers.map(function(n){return t.getSuffix(e,n)}):[]}},{key:"getSuffix",value:function(e,t){var n=this,i=this.getRule(e);if(i){var o=i.noAbs?i.plurals(t):i.plurals(Math.abs(t)),r=i.numbers[o];this.options.simplifyPluralSuffix&&2===i.numbers.length&&1===i.numbers[0]&&(2===r?r="plural":1===r&&(r=""));var a=function(){return n.options.prepend&&r.toString()?n.options.prepend+r.toString():r.toString()};return"v1"===this.options.compatibilityJSON?1===r?"":"number"==typeof r?"_plural_".concat(r.toString()):a():"v2"===this.options.compatibilityJSON?a():this.options.simplifyPluralSuffix&&2===i.numbers.length&&1===i.numbers[0]?a():this.options.prepend&&o.toString()?this.options.prepend+o.toString():o.toString()}return this.logger.warn("no plural rule found for: ".concat(e)),""}}]),e}(),V=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};i(this,e),this.logger=g.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||function(e){return e},this.init(t)}return r(e,[{key:"init",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.interpolation||(e.interpolation={escapeValue:!0});var t=e.interpolation;this.escape=void 0!==t.escape?t.escape:S,this.escapeValue=void 0===t.escapeValue||t.escapeValue,this.useRawValueToEscape=void 0!==t.useRawValueToEscape&&t.useRawValueToEscape,this.prefix=t.prefix?k(t.prefix):t.prefixEscaped||"{{",this.suffix=t.suffix?k(t.suffix):t.suffixEscaped||"}}",this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||",",this.unescapePrefix=t.unescapeSuffix?"":t.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":t.unescapeSuffix||"",this.nestingPrefix=t.nestingPrefix?k(t.nestingPrefix):t.nestingPrefixEscaped||k("$t("),this.nestingSuffix=t.nestingSuffix?k(t.nestingSuffix):t.nestingSuffixEscaped||k(")"),this.nestingOptionsSeparator=t.nestingOptionsSeparator?t.nestingOptionsSeparator:t.nestingOptionsSeparator||",",this.maxReplaces=t.maxReplaces?t.maxReplaces:1e3,this.alwaysFormat=void 0!==t.alwaysFormat&&t.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var e="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(e,"g");var t="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(t,"g");var n="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(n,"g")}},{key:"interpolate",value:function(e,t,i,o){var r,a,s,u=this,l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function c(e){return e.replace(/\$/g,"$$$$")}var p=function(e){if(e.indexOf(u.formatSeparator)<0){var r=b(t,l,e);return u.alwaysFormat?u.format(r,void 0,i,n({},o,t,{interpolationkey:e})):r}var a=e.split(u.formatSeparator),s=a.shift().trim(),c=a.join(u.formatSeparator).trim();return u.format(b(t,l,s),c,i,n({},o,t,{interpolationkey:s}))};this.resetRegExp();var g=o&&o.missingInterpolationHandler||this.options.missingInterpolationHandler,f=o&&o.interpolation&&o.interpolation.skipOnVariables||this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(e){return c(e)}},{regex:this.regexp,safeValue:function(e){return u.escapeValue?c(u.escape(e)):c(e)}}].forEach(function(t){for(s=0;r=t.regex.exec(e);){if(void 0===(a=p(r[1].trim())))if("function"==typeof g){var n=g(e,r,o);a="string"==typeof n?n:""}else{if(f){a=r[0];continue}u.logger.warn("missed to pass in variable ".concat(r[1]," for interpolating ").concat(e)),a=""}else"string"==typeof a||u.useRawValueToEscape||(a=d(a));var i=t.safeValue(a);if(e=e.replace(r[0],i),f?(t.regex.lastIndex+=i.length,t.regex.lastIndex-=r[0].length):t.regex.lastIndex=0,++s>=u.maxReplaces)break}}),e}},{key:"nest",value:function(e,t){var i,o,r=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=n({},a);function u(e,t){var i=this.nestingOptionsSeparator;if(e.indexOf(i)<0)return e;var o=e.split(new RegExp("".concat(i,"[ ]*{"))),r="{".concat(o[1]);e=o[0],r=(r=this.interpolate(r,s)).replace(/'/g,'"');try{s=JSON.parse(r),t&&(s=n({},t,s))}catch(t){return this.logger.warn("failed parsing options string in nesting for key ".concat(e),t),"".concat(e).concat(i).concat(r)}return delete s.defaultValue,e}for(s.applyPostProcessor=!1,delete s.defaultValue;i=this.nestingRegexp.exec(e);){var l=[],c=!1;if(-1!==i[0].indexOf(this.formatSeparator)&&!/{.*}/.test(i[1])){var p=i[1].split(this.formatSeparator).map(function(e){return e.trim()});i[1]=p.shift(),l=p,c=!0}if((o=t(u.call(this,i[1].trim(),s),s))&&i[0]===e&&"string"!=typeof o)return o;"string"!=typeof o&&(o=d(o)),o||(this.logger.warn("missed to resolve ".concat(i[1]," for nesting ").concat(e)),o=""),c&&(o=l.reduce(function(e,t){return r.format(e,t,a.lng,n({},a,{interpolationkey:i[1].trim()}))},o.trim())),e=e.replace(i[0],o),this.regexp.lastIndex=0}return e}}]),e}();var T=function(e){function t(e,n,o){var r,l=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return i(this,t),r=s(this,u(t).call(this)),w&&f.call(a(r)),r.backend=e,r.store=n,r.services=o,r.languageUtils=o.languageUtils,r.options=l,r.logger=g.create("backendConnector"),r.state={},r.queue=[],r.backend&&r.backend.init&&r.backend.init(o,l.backend,l),r}return c(t,f),r(t,[{key:"queueLoad",value:function(e,t,n,i){var o=this,r=[],a=[],s=[],u=[];return e.forEach(function(e){var i=!0;t.forEach(function(t){var s="".concat(e,"|").concat(t);!n.reload&&o.store.hasResourceBundle(e,t)?o.state[s]=2:o.state[s]<0||(1===o.state[s]?a.indexOf(s)<0&&a.push(s):(o.state[s]=1,i=!1,a.indexOf(s)<0&&a.push(s),r.indexOf(s)<0&&r.push(s),u.indexOf(t)<0&&u.push(t)))}),i||s.push(e)}),(r.length||a.length)&&this.queue.push({pending:a,loaded:{},errors:[],callback:i}),{toLoad:r,pending:a,toLoadLanguages:s,toLoadNamespaces:u}}},{key:"loaded",value:function(e,t,n){var i=e.split("|"),o=i[0],r=i[1];t&&this.emit("failedLoading",o,r,t),n&&this.store.addResourceBundle(o,r,n),this.state[e]=t?-1:2;var a={};this.queue.forEach(function(n){var i,s,u,l,c,p;i=n.loaded,s=r,l=v(i,[o],Object),c=l.obj,p=l.k,c[p]=c[p]||[],u&&(c[p]=c[p].concat(s)),u||c[p].push(s),function(e,t){for(var n=e.indexOf(t);-1!==n;)e.splice(n,1),n=e.indexOf(t)}(n.pending,e),t&&n.errors.push(t),0!==n.pending.length||n.done||(Object.keys(n.loaded).forEach(function(e){a[e]||(a[e]=[]),n.loaded[e].length&&n.loaded[e].forEach(function(t){a[e].indexOf(t)<0&&a[e].push(t)})}),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(function(e){return!e.done})}},{key:"read",value:function(e,t,n){var i=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:350,a=arguments.length>5?arguments[5]:void 0;return e.length?this.backend[n](e,t,function(s,u){s&&u&&o<5?setTimeout(function(){i.read.call(i,e,t,n,o+1,2*r,a)},r):a(s,u)}):a(null,{})}},{key:"prepareLoading",value:function(e,t){var n=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();"string"==typeof e&&(e=this.languageUtils.toResolveHierarchy(e)),"string"==typeof t&&(t=[t]);var r=this.queueLoad(e,t,i,o);if(!r.toLoad.length)return r.pending.length||o(),null;r.toLoad.forEach(function(e){n.loadOne(e)})}},{key:"load",value:function(e,t,n){this.prepareLoading(e,t,{},n)}},{key:"reload",value:function(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}},{key:"loadOne",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=e.split("|"),o=i[0],r=i[1];this.read(o,r,"read",void 0,void 0,function(i,a){i&&t.logger.warn("".concat(n,"loading namespace ").concat(r," for language ").concat(o," failed"),i),!i&&a&&t.logger.log("".concat(n,"loaded namespace ").concat(r," for language ").concat(o),a),t.loaded(e,i,a)})}},{key:"saveMissing",value:function(e,t,i,o,r){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t)?this.logger.warn('did not save key "'.concat(i,'" as the namespace "').concat(t,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"):null!=i&&""!==i&&(this.backend&&this.backend.create&&this.backend.create(e,t,i,o,null,n({},a,{isUpdate:r})),e&&e[0]&&this.store.addResource(e[0],t,i,o))}}]),t}();function A(e){return"string"==typeof e.ns&&(e.ns=[e.ns]),"string"==typeof e.fallbackLng&&(e.fallbackLng=[e.fallbackLng]),"string"==typeof e.fallbackNS&&(e.fallbackNS=[e.fallbackNS]),e.whitelist&&(e.whitelist&&e.whitelist.indexOf("cimode")<0&&(e.whitelist=e.whitelist.concat(["cimode"])),e.supportedLngs=e.whitelist),e.nonExplicitWhitelist&&(e.nonExplicitSupportedLngs=e.nonExplicitWhitelist),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function U(){}return new(function(t){function o(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(i(this,o),e=s(this,u(o).call(this)),w&&f.call(a(e)),e.options=A(t),e.services={},e.logger=g,e.modules={external:[]},n&&!e.isInitialized&&!t.isClone){if(!e.options.initImmediate)return e.init(t,n),s(e,a(e));setTimeout(function(){e.init(t,n)},0)}return e}return c(o,f),r(o,[{key:"init",value:function(){var t=this,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1?arguments[1]:void 0;function r(e){return e?"function"==typeof e?new e:e:null}if("function"==typeof i&&(o=i,i={}),i.whitelist&&!i.supportedLngs&&this.logger.deprecate("whitelist",'option "whitelist" will be renamed to "supportedLngs" in the next major - please make sure to rename this option asap.'),i.nonExplicitWhitelist&&!i.nonExplicitSupportedLngs&&this.logger.deprecate("whitelist",'options "nonExplicitWhitelist" will be renamed to "nonExplicitSupportedLngs" in the next major - please make sure to rename this option asap.'),this.options=n({},{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,whitelist:!1,nonExplicitWhitelist:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){var n={};if("object"===e(t[1])&&(n=t[1]),"string"==typeof t[1]&&(n.defaultValue=t[1]),"string"==typeof t[2]&&(n.tDescription=t[2]),"object"===e(t[2])||"object"===e(t[3])){var i=t[3]||t[2];Object.keys(i).forEach(function(e){n[e]=i[e]})}return n},interpolation:{escapeValue:!0,format:function(e,t,n,i){return e},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!1}},this.options,A(i)),this.format=this.options.interpolation.format,o||(o=U),!this.options.isClone){this.modules.logger?g.init(r(this.modules.logger),this.options):g.init(null,this.options);var a=new j(this.options);this.store=new L(this.options.resources,this.options);var s=this.services;s.logger=g,s.resourceStore=this.store,s.languageUtils=a,s.pluralResolver=new F(a,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),s.interpolator=new V(this.options),s.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},s.backendConnector=new T(r(this.modules.backend),s.resourceStore,s,this.options),s.backendConnector.on("*",function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o1?n-1:0),o=1;o0&&"dev"!==u[0]&&(this.options.lng=u[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments)}});["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(function(e){t[e]=function(){var n;return(n=t.store)[e].apply(n,arguments),t}});var l=h(),c=function(){var e=function(e,n){t.isInitialized&&t.logger.warn("init: i18next is already initialized. You should call init just once!"),t.isInitialized=!0,t.options.isClone||t.logger.log("initialized",t.options),t.emit("initialized",t.options),l.resolve(n),o(e,n)};if(t.languages&&"v1"!==t.options.compatibilityAPI&&!t.isInitialized)return e(null,t.t.bind(t));t.changeLanguage(t.options.lng,e)};return this.options.resources||!this.options.initImmediate?c():setTimeout(c,0),l}},{key:"loadResources",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:U,i="string"==typeof e?e:this.language;if("function"==typeof e&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(i&&"cimode"===i.toLowerCase())return n();var o=[],r=function(e){e&&t.services.languageUtils.toResolveHierarchy(e).forEach(function(e){o.indexOf(e)<0&&o.push(e)})};if(i)r(i);else this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(function(e){return r(e)});this.options.preload&&this.options.preload.forEach(function(e){return r(e)}),this.services.backendConnector.load(o,this.options.ns,n)}else n(null)}},{key:"reloadResources",value:function(e,t,n){var i=h();return e||(e=this.languages),t||(t=this.options.ns),n||(n=U),this.services.backendConnector.reload(e,t,function(e){i.resolve(),n(e)}),i}},{key:"use",value:function(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&O.addPostProcessor(e),"3rdParty"===e.type&&this.modules.external.push(e),this}},{key:"changeLanguage",value:function(e,t){var n=this;this.isLanguageChangingTo=e;var i=h();this.emit("languageChanging",e);var o=function(e){var o="string"==typeof e?e:n.services.languageUtils.getBestMatchFromCodes(e);o&&(n.language||(n.language=o,n.languages=n.services.languageUtils.toResolveHierarchy(o)),n.translator.language||n.translator.changeLanguage(o),n.services.languageDetector&&n.services.languageDetector.cacheUserLanguage(o)),n.loadResources(o,function(e){!function(e,o){o?(n.language=o,n.languages=n.services.languageUtils.toResolveHierarchy(o),n.translator.changeLanguage(o),n.isLanguageChangingTo=void 0,n.emit("languageChanged",o),n.logger.log("languageChanged",o)):n.isLanguageChangingTo=void 0,i.resolve(function(){return n.t.apply(n,arguments)}),t&&t(e,function(){return n.t.apply(n,arguments)})}(e,o)})};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect(o):o(e):o(this.services.languageDetector.detect()),i}},{key:"getFixedT",value:function(t,i){var o=this,r=function t(i,r){var a;if("object"!==e(r)){for(var s=arguments.length,u=new Array(s>2?s-2:0),l=2;l1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var i=this.languages[0],o=!!this.options&&this.options.fallbackLng,r=this.languages[this.languages.length-1];if("cimode"===i.toLowerCase())return!0;var a=function(e,n){var i=t.services.backendConnector.state["".concat(e,"|").concat(n)];return-1===i||2===i};if(n.precheck){var s=n.precheck(this,a);if(void 0!==s)return s}return!!this.hasResourceBundle(i,e)||(!this.services.backendConnector.backend||!(!a(i,e)||o&&!a(r,e)))}},{key:"loadNamespaces",value:function(e,t){var n=this,i=h();return this.options.ns?("string"==typeof e&&(e=[e]),e.forEach(function(e){n.options.ns.indexOf(e)<0&&n.options.ns.push(e)}),this.loadResources(function(e){i.resolve(),t&&t(e)}),i):(t&&t(),Promise.resolve())}},{key:"loadLanguages",value:function(e,t){var n=h();"string"==typeof e&&(e=[e]);var i=this.options.preload||[],o=e.filter(function(e){return i.indexOf(e)<0});return o.length?(this.options.preload=i.concat(o),this.loadResources(function(e){n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}},{key:"dir",value:function(e){if(e||(e=this.languages&&this.languages.length>0?this.languages[0]:this.language),!e)return"rtl";return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam"].indexOf(this.services.languageUtils.getLanguagePartFromCode(e))>=0?"rtl":"ltr"}},{key:"createInstance",value:function(){return new o(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}},{key:"cloneInstance",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:U,r=n({},this.options,t,{isClone:!0}),a=new o(r);return["store","services","language"].forEach(function(t){a[t]=e[t]}),a.services=n({},this.services),a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a.translator=new R(a.services,a.options),a.translator.on("*",function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;it.length)&&(e=t.length);for(var n=0,i=new Array(e);n1&&void 0!==arguments[1]?arguments[1]:"introjs-stamp";return t[n]=t[n]||0,void 0===e[n]&&(e[n]=t[n]++),e[n]}}();function r(t,e,n){if(t)for(var i=0,o=t.length;i0&&c[0]<4?1:+(c[0]+c[1])),!u&&F&&(!(c=F.match(/Edge\/(\d+)/))||c[1]>=74)&&(c=F.match(/Chrome\/(\d+)/))&&(u=+c[1]);var U=u,W=!!Object.getOwnPropertySymbols&&!p((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&U&&U<41})),K=W&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Y=f.Object,X=K?function(t){return"symbol"==typeof t}:function(t){var e=H("Symbol");return M(e)&&D(e.prototype,Y(t))},J=f.String,Q=function(t){try{return J(t)}catch(t){return"Object"}},Z=f.TypeError,tt=function(t){if(M(t))return t;throw Z(Q(t)+" is not a function")},et=function(t,e){var n=t[e];return null==n?void 0:tt(n)},nt=f.TypeError,it=Object.defineProperty,ot=function(t,e){try{it(f,t,{value:e,configurable:!0,writable:!0})}catch(n){f[t]=e}return e},rt="__core-js_shared__",at=f[rt]||ot(rt,{}),st=l((function(t){(t.exports=function(t,e){return at[t]||(at[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.21.1",mode:"global",copyright:"© 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.21.1/LICENSE",source:"https://github.com/zloirock/core-js"})})),lt=f.Object,ct=function(t){return lt(P(t))},ut=A({}.hasOwnProperty),ht=Object.hasOwn||function(t,e){return ut(ct(t),e)},ft=0,pt=Math.random(),dt=A(1..toString),gt=function(t){return"Symbol("+(void 0===t?"":t)+")_"+dt(++ft+pt,36)},vt=st("wks"),mt=f.Symbol,bt=mt&&mt.for,yt=K?mt:mt&&mt.withoutSetter||gt,wt=function(t){if(!ht(vt,t)||!W&&"string"!=typeof vt[t]){var e="Symbol."+t;W&&ht(mt,t)?vt[t]=mt[t]:vt[t]=K&&bt?bt(e):yt(e)}return vt[t]},_t=f.TypeError,St=wt("toPrimitive"),xt=function(t,e){if(!q(t)||X(t))return t;var n,i=et(t,St);if(i){if(void 0===e&&(e="default"),n=m(i,t,e),!q(n)||X(n))return n;throw _t("Can't convert object to primitive value")}return void 0===e&&(e="number"),function(t,e){var n,i;if("string"===e&&M(n=t.toString)&&!q(i=m(n,t)))return i;if(M(n=t.valueOf)&&!q(i=m(n,t)))return i;if("string"!==e&&M(n=t.toString)&&!q(i=m(n,t)))return i;throw nt("Can't convert object to primitive value")}(t,e)},jt=function(t){var e=xt(t,"string");return X(e)?e:e+""},Ct=f.document,At=q(Ct)&&q(Ct.createElement),kt=function(t){return At?Ct.createElement(t):{}},Et=!d&&!p((function(){return 7!=Object.defineProperty(kt("div"),"a",{get:function(){return 7}}).a})),Tt=Object.getOwnPropertyDescriptor,It={f:d?Tt:function(t,e){if(t=R(t),e=jt(e),Et)try{return Tt(t,e)}catch(t){}if(ht(t,e))return _(!m(w.f,t,e),t[e])}},Nt=d&&p((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Lt=f.String,Ot=f.TypeError,Pt=function(t){if(q(t))return t;throw Ot(Lt(t)+" is not an object")},Rt=f.TypeError,Mt=Object.defineProperty,qt=Object.getOwnPropertyDescriptor,Bt="enumerable",Ht="configurable",Dt="writable",Ft={f:d?Nt?function(t,e,n){if(Pt(t),e=jt(e),Pt(n),"function"==typeof t&&"prototype"===e&&"value"in n&&Dt in n&&!n.writable){var i=qt(t,e);i&&i.writable&&(t[e]=n.value,n={configurable:Ht in n?n.configurable:i.configurable,enumerable:Bt in n?n.enumerable:i.enumerable,writable:!1})}return Mt(t,e,n)}:Mt:function(t,e,n){if(Pt(t),e=jt(e),Pt(n),Et)try{return Mt(t,e,n)}catch(t){}if("get"in n||"set"in n)throw Rt("Accessors not supported");return"value"in n&&(t[e]=n.value),t}},$t=d?function(t,e,n){return Ft.f(t,e,_(1,n))}:function(t,e,n){return t[e]=n,t},Gt=A(Function.toString);M(at.inspectSource)||(at.inspectSource=function(t){return Gt(t)});var Vt,zt,Ut,Wt=at.inspectSource,Kt=f.WeakMap,Yt=M(Kt)&&/native code/.test(Wt(Kt)),Xt=st("keys"),Jt=function(t){return Xt[t]||(Xt[t]=gt(t))},Qt={},Zt="Object already initialized",te=f.TypeError,ee=f.WeakMap;if(Yt||at.state){var ne=at.state||(at.state=new ee),ie=A(ne.get),oe=A(ne.has),re=A(ne.set);Vt=function(t,e){if(oe(ne,t))throw new te(Zt);return e.facade=t,re(ne,t,e),e},zt=function(t){return ie(ne,t)||{}},Ut=function(t){return oe(ne,t)}}else{var ae=Jt("state");Qt[ae]=!0,Vt=function(t,e){if(ht(t,ae))throw new te(Zt);return e.facade=t,$t(t,ae,e),e},zt=function(t){return ht(t,ae)?t[ae]:{}},Ut=function(t){return ht(t,ae)}}var se={set:Vt,get:zt,has:Ut,enforce:function(t){return Ut(t)?zt(t):Vt(t,{})},getterFor:function(t){return function(e){var n;if(!q(e)||(n=zt(e)).type!==t)throw te("Incompatible receiver, "+t+" required");return n}}},le=Function.prototype,ce=d&&Object.getOwnPropertyDescriptor,ue=ht(le,"name"),he={EXISTS:ue,PROPER:ue&&"something"===function(){}.name,CONFIGURABLE:ue&&(!d||d&&ce(le,"name").configurable)},fe=l((function(t){var e=he.CONFIGURABLE,n=se.get,i=se.enforce,o=String(String).split("String");(t.exports=function(t,n,r,a){var s,l=!!a&&!!a.unsafe,c=!!a&&!!a.enumerable,u=!!a&&!!a.noTargetGet,h=a&&void 0!==a.name?a.name:n;M(r)&&("Symbol("===String(h).slice(0,7)&&(h="["+String(h).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!ht(r,"name")||e&&r.name!==h)&&$t(r,"name",h),(s=i(r)).source||(s.source=o.join("string"==typeof h?h:""))),t!==f?(l?!u&&t[n]&&(c=!0):delete t[n],c?t[n]=r:$t(t,n,r)):c?t[n]=r:ot(n,r)})(Function.prototype,"toString",(function(){return M(this)&&n(this).source||Wt(this)}))})),pe=Math.ceil,de=Math.floor,ge=function(t){var e=+t;return e!=e||0===e?0:(e>0?de:pe)(e)},ve=Math.max,me=Math.min,be=function(t,e){var n=ge(t);return n<0?ve(n+e,0):me(n,e)},ye=Math.min,we=function(t){return t>0?ye(ge(t),9007199254740991):0},_e=function(t){return we(t.length)},Se=function(t){return function(e,n,i){var o,r=R(e),a=_e(r),s=be(i,a);if(t&&n!=n){for(;a>s;)if((o=r[s++])!=o)return!0}else for(;a>s;s++)if((t||s in r)&&r[s]===n)return t||s||0;return!t&&-1}},xe={includes:Se(!0),indexOf:Se(!1)},je=xe.indexOf,Ce=A([].push),Ae=function(t,e){var n,i=R(t),o=0,r=[];for(n in i)!ht(Qt,n)&&ht(i,n)&&Ce(r,n);for(;e.length>o;)ht(i,n=e[o++])&&(~je(r,n)||Ce(r,n));return r},ke=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ee=ke.concat("length","prototype"),Te={f:Object.getOwnPropertyNames||function(t){return Ae(t,Ee)}},Ie={f:Object.getOwnPropertySymbols},Ne=A([].concat),Le=H("Reflect","ownKeys")||function(t){var e=Te.f(Pt(t)),n=Ie.f;return n?Ne(e,n(t)):e},Oe=function(t,e,n){for(var i=Le(e),o=Ft.f,r=It.f,a=0;aa;)Ft.f(t,n=o[a++],i[n]);return t},an={f:rn},sn=H("document","documentElement"),ln=Jt("IE_PROTO"),cn=function(){},un=function(t){return"