├── .eslintrc.js ├── .gitignore ├── LICENSE ├── README.md ├── code.html ├── dist └── bundle.js ├── index.html ├── lib ├── CCDIKSolver.js ├── MMDLoader.js ├── MMDPhysics.js ├── TGALoader.js └── mmdparser.js ├── package.json ├── play.html ├── res └── phone.png ├── screenshot.png ├── src └── index.js ├── style.css ├── vendor └── js-aruco │ ├── LICENSE.txt │ ├── aruco.js │ ├── cv.js │ ├── posit1-patched.js │ ├── posit1.js │ ├── posit2.js │ └── svd.js └── webpack.config.js /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "env": { 3 | "browser": true, 4 | "commonjs": true, 5 | "es6": true 6 | }, 7 | "extends": "eslint:recommended", 8 | "parserOptions": { 9 | "sourceType": "module" 10 | }, 11 | "rules": { 12 | "indent": [ 13 | "error", 14 | 4 15 | ], 16 | "linebreak-style": [ 17 | "error", 18 | "unix" 19 | ], 20 | "quotes": [ 21 | "error", 22 | "single" 23 | ], 24 | "semi": [ 25 | "error", 26 | "always" 27 | ] 28 | } 29 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 当轩 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ar-demo-mobile-browser 2 | A AR demo on mobile browser(Android yet) powered by JavaScript 3 | 4 | Access at: https://codefalling.github.io/ar-demo-mobile-browser 5 | 6 | # SceenShot 7 | 8 | ![preview](screenshot.png) 9 | 10 | # Build 11 | 12 | ```shell 13 | webpack -p 14 | ``` 15 | 16 | # What about iOS 17 | 18 | iOS (safari) do not support `MediaStreamTrack.getSources()`, `MediaDevices.enumerateDevices()` or whatever yet. 19 | 20 | # Related Projects 21 | 22 | - [js-aruco](https://github.com/jcmellado/js-aruco) 23 | 24 | - [ARLIFXController](https://github.com/sitepoint-editors/ARLIFXController) 25 | 26 | - [threex.webar](https://github.com/jeromeetienne/threex.webar) 27 | 28 | - [threejs-mmd-loader](https://github.com/mrdoob/three.js/blob/dev/examples/webgl_loader_mmd.html) 29 | -------------------------------------------------------------------------------- /code.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | AR 2017 7 | 8 | 9 | 10 |
11 |
12 |
AR
13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
34 | @当轩(codefalling) 35 |
36 |
37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | AR 2017 7 | 8 | 9 | 10 |
11 |
12 |
AR
13 | 扫码 14 | AR 码 15 | @当轩(codefalling) 16 |
17 |
18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /lib/CCDIKSolver.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author takahiro / https://github.com/takahirox 3 | * 4 | * CCD Algorithm 5 | * https://sites.google.com/site/auraliusproject/ccd-algorithm 6 | * 7 | * mesh.geometry needs to have iks array. 8 | * 9 | * // ik parameter example 10 | * // 11 | * // target, effector, index in links are bone index in skeleton. 12 | * // the bones relation should be 13 | * // <-- parent child --> 14 | * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector 15 | * ik = { 16 | * target: 1, 17 | * effector: 2, 18 | * links: [ { index: 5, limitation: new THREE.Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ], 19 | * iteration: 10, 20 | * minAngle: 0.0, 21 | * maxAngle: 1.0, 22 | * }; 23 | */ 24 | 25 | THREE.CCDIKSolver = function ( mesh ) { 26 | 27 | this.mesh = mesh; 28 | 29 | this._valid(); 30 | 31 | }; 32 | 33 | THREE.CCDIKSolver.prototype = { 34 | 35 | constructor: THREE.CCDIKSolver, 36 | 37 | _valid: function () { 38 | 39 | var iks = this.mesh.geometry.iks; 40 | var bones = this.mesh.skeleton.bones; 41 | 42 | for ( var i = 0, il = iks.length; i < il; i ++ ) { 43 | 44 | var ik = iks[ i ]; 45 | 46 | var effector = bones[ ik.effector ]; 47 | 48 | var links = ik.links; 49 | 50 | var link0, link1; 51 | 52 | link0 = effector; 53 | 54 | for ( var j = 0, jl = links.length; j < jl; j ++ ) { 55 | 56 | link1 = bones[ links[ j ].index ]; 57 | 58 | if ( link0.parent !== link1 ) { 59 | 60 | console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name ); 61 | 62 | } 63 | 64 | link0 = link1; 65 | 66 | } 67 | 68 | } 69 | 70 | }, 71 | 72 | /* 73 | * save the bone matrices before solving IK. 74 | * they're used for generating VMD and VPD. 75 | */ 76 | _saveOriginalBonesInfo: function () { 77 | 78 | var bones = this.mesh.skeleton.bones; 79 | 80 | for ( var i = 0, il = bones.length; i < il; i ++ ) { 81 | 82 | var bone = bones[ i ]; 83 | 84 | if ( bone.userData.ik === undefined ) bone.userData.ik = {}; 85 | 86 | bone.userData.ik.originalMatrix = bone.matrix.toArray(); 87 | 88 | } 89 | 90 | }, 91 | 92 | update: function ( saveOriginalBones ) { 93 | 94 | var q = new THREE.Quaternion(); 95 | 96 | var targetPos = new THREE.Vector3(); 97 | var targetVec = new THREE.Vector3(); 98 | var effectorPos = new THREE.Vector3(); 99 | var effectorVec = new THREE.Vector3(); 100 | var linkPos = new THREE.Vector3(); 101 | var invLinkQ = new THREE.Quaternion(); 102 | var linkScale = new THREE.Vector3(); 103 | var axis = new THREE.Vector3(); 104 | 105 | var bones = this.mesh.skeleton.bones; 106 | var iks = this.mesh.geometry.iks; 107 | 108 | var boneParams = this.mesh.geometry.bones; 109 | 110 | // for reference overhead reduction in loop 111 | var math = Math; 112 | 113 | this.mesh.updateMatrixWorld( true ); 114 | 115 | if ( saveOriginalBones === true ) this._saveOriginalBonesInfo(); 116 | 117 | for ( var i = 0, il = iks.length; i < il; i++ ) { 118 | 119 | var ik = iks[ i ]; 120 | var effector = bones[ ik.effector ]; 121 | var target = bones[ ik.target ]; 122 | 123 | // don't use getWorldPosition() here for the performance 124 | // because it calls updateMatrixWorld( true ) inside. 125 | targetPos.setFromMatrixPosition( target.matrixWorld ); 126 | 127 | var links = ik.links; 128 | var iteration = ik.iteration !== undefined ? ik.iteration : 1; 129 | 130 | for ( var j = 0; j < iteration; j++ ) { 131 | 132 | var rotated = false; 133 | 134 | for ( var k = 0, kl = links.length; k < kl; k++ ) { 135 | 136 | var link = bones[ links[ k ].index ]; 137 | 138 | // skip this link and following links. 139 | // this skip is used for MMD performance optimization. 140 | if ( links[ k ].enabled === false ) break; 141 | 142 | var limitation = links[ k ].limitation; 143 | 144 | // don't use getWorldPosition/Quaternion() here for the performance 145 | // because they call updateMatrixWorld( true ) inside. 146 | link.matrixWorld.decompose( linkPos, invLinkQ, linkScale ); 147 | invLinkQ.inverse(); 148 | effectorPos.setFromMatrixPosition( effector.matrixWorld ); 149 | 150 | // work in link world 151 | effectorVec.subVectors( effectorPos, linkPos ); 152 | effectorVec.applyQuaternion( invLinkQ ); 153 | effectorVec.normalize(); 154 | 155 | targetVec.subVectors( targetPos, linkPos ); 156 | targetVec.applyQuaternion( invLinkQ ); 157 | targetVec.normalize(); 158 | 159 | var angle = targetVec.dot( effectorVec ); 160 | 161 | if ( angle > 1.0 ) { 162 | 163 | angle = 1.0; 164 | 165 | } else if ( angle < -1.0 ) { 166 | 167 | angle = -1.0; 168 | 169 | } 170 | 171 | angle = math.acos( angle ); 172 | 173 | // skip if changing angle is too small to prevent vibration of bone 174 | // Refer to http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js 175 | if ( angle < 1e-5 ) continue; 176 | 177 | if ( ik.minAngle !== undefined && angle < ik.minAngle ) { 178 | 179 | angle = ik.minAngle; 180 | 181 | } 182 | 183 | if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) { 184 | 185 | angle = ik.maxAngle; 186 | 187 | } 188 | 189 | axis.crossVectors( effectorVec, targetVec ); 190 | axis.normalize(); 191 | 192 | q.setFromAxisAngle( axis, angle ); 193 | link.quaternion.multiply( q ); 194 | 195 | // TODO: re-consider the limitation specification 196 | if ( limitation !== undefined ) { 197 | 198 | var c = link.quaternion.w; 199 | 200 | if ( c > 1.0 ) { 201 | 202 | c = 1.0; 203 | 204 | } 205 | 206 | var c2 = math.sqrt( 1 - c * c ); 207 | link.quaternion.set( limitation.x * c2, 208 | limitation.y * c2, 209 | limitation.z * c2, 210 | c ); 211 | 212 | } 213 | 214 | link.updateMatrixWorld( true ); 215 | rotated = true; 216 | 217 | } 218 | 219 | if ( ! rotated ) break; 220 | 221 | } 222 | 223 | } 224 | 225 | // just in case 226 | this.mesh.updateMatrixWorld( true ); 227 | 228 | } 229 | 230 | }; 231 | 232 | 233 | THREE.CCDIKHelper = function ( mesh ) { 234 | 235 | if ( mesh.geometry.iks === undefined || mesh.skeleton === undefined ) { 236 | 237 | throw 'THREE.CCDIKHelper requires iks in mesh.geometry and skeleton in mesh.'; 238 | 239 | } 240 | 241 | THREE.Object3D.call( this ); 242 | 243 | this.root = mesh; 244 | 245 | this.matrix = mesh.matrixWorld; 246 | this.matrixAutoUpdate = false; 247 | 248 | this.sphereGeometry = new THREE.SphereBufferGeometry( 0.25, 16, 8 ); 249 | 250 | this.targetSphereMaterial = new THREE.MeshBasicMaterial( { 251 | color: new THREE.Color( 0xff8888 ), 252 | depthTest: false, 253 | depthWrite: false, 254 | transparent: true 255 | } ); 256 | 257 | this.effectorSphereMaterial = new THREE.MeshBasicMaterial( { 258 | color: new THREE.Color( 0x88ff88 ), 259 | depthTest: false, 260 | depthWrite: false, 261 | transparent: true 262 | } ); 263 | 264 | this.linkSphereMaterial = new THREE.MeshBasicMaterial( { 265 | color: new THREE.Color( 0x8888ff ), 266 | depthTest: false, 267 | depthWrite: false, 268 | transparent: true 269 | } ); 270 | 271 | this.lineMaterial = new THREE.LineBasicMaterial( { 272 | color: new THREE.Color( 0xff0000 ), 273 | depthTest: false, 274 | depthWrite: false, 275 | transparent: true 276 | } ); 277 | 278 | this._init(); 279 | this.update(); 280 | 281 | }; 282 | 283 | THREE.CCDIKHelper.prototype = Object.create( THREE.Object3D.prototype ); 284 | THREE.CCDIKHelper.prototype.constructor = THREE.CCDIKHelper; 285 | 286 | THREE.CCDIKHelper.prototype._init = function () { 287 | 288 | var self = this; 289 | var mesh = this.root; 290 | var iks = mesh.geometry.iks; 291 | 292 | function createLineGeometry( ik ) { 293 | 294 | var geometry = new THREE.BufferGeometry(); 295 | var vertices = new Float32Array( ( 2 + ik.links.length ) * 3 ); 296 | geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ); 297 | 298 | return geometry; 299 | 300 | } 301 | 302 | function createTargetMesh() { 303 | 304 | return new THREE.Mesh( self.sphereGeometry, self.targetSphereMaterial ); 305 | 306 | } 307 | 308 | function createEffectorMesh() { 309 | 310 | return new THREE.Mesh( self.sphereGeometry, self.effectorSphereMaterial ); 311 | 312 | } 313 | 314 | function createLinkMesh() { 315 | 316 | return new THREE.Mesh( self.sphereGeometry, self.linkSphereMaterial ); 317 | 318 | } 319 | 320 | function createLine( ik ) { 321 | 322 | return new THREE.Line( createLineGeometry( ik ), self.lineMaterial ); 323 | 324 | } 325 | 326 | for ( var i = 0, il = iks.length; i < il; i ++ ) { 327 | 328 | var ik = iks[ i ]; 329 | 330 | this.add( createTargetMesh() ); 331 | this.add( createEffectorMesh() ); 332 | 333 | for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) { 334 | 335 | this.add( createLinkMesh() ); 336 | 337 | } 338 | 339 | this.add( createLine( ik ) ); 340 | 341 | } 342 | 343 | }; 344 | 345 | THREE.CCDIKHelper.prototype.update = function () { 346 | 347 | var offset = 0; 348 | 349 | var mesh = this.root; 350 | var iks = mesh.geometry.iks; 351 | var bones = mesh.skeleton.bones; 352 | 353 | var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld ); 354 | var vector = new THREE.Vector3(); 355 | 356 | function getPosition( bone ) { 357 | 358 | vector.setFromMatrixPosition( bone.matrixWorld ); 359 | vector.applyMatrix4( matrixWorldInv ); 360 | 361 | return vector; 362 | 363 | } 364 | 365 | function setPositionOfBoneToAttributeArray( array, index, bone ) { 366 | 367 | var v = getPosition( bone ); 368 | 369 | array[ index * 3 + 0 ] = v.x; 370 | array[ index * 3 + 1 ] = v.y; 371 | array[ index * 3 + 2 ] = v.z; 372 | 373 | } 374 | 375 | for ( var i = 0, il = iks.length; i < il; i ++ ) { 376 | 377 | var ik = iks[ i ]; 378 | 379 | var targetBone = bones[ ik.target ]; 380 | var effectorBone = bones[ ik.effector ]; 381 | 382 | var targetMesh = this.children[ offset ++ ]; 383 | var effectorMesh = this.children[ offset ++ ]; 384 | 385 | targetMesh.position.copy( getPosition( targetBone ) ); 386 | effectorMesh.position.copy( getPosition( effectorBone ) ); 387 | 388 | for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) { 389 | 390 | var link = ik.links[ j ]; 391 | var linkBone = bones[ link.index ]; 392 | 393 | var linkMesh = this.children[ offset ++ ]; 394 | 395 | linkMesh.position.copy( getPosition( linkBone ) ); 396 | 397 | } 398 | 399 | var line = this.children[ offset ++ ]; 400 | var array = line.geometry.attributes.position.array; 401 | 402 | setPositionOfBoneToAttributeArray( array, 0, targetBone ); 403 | setPositionOfBoneToAttributeArray( array, 1, effectorBone ); 404 | 405 | for ( var j = 0, jl = ik.links.length; j < jl; j ++ ) { 406 | 407 | var link = ik.links[ j ]; 408 | var linkBone = bones[ link.index ]; 409 | setPositionOfBoneToAttributeArray( array, j + 2, linkBone ); 410 | 411 | } 412 | 413 | line.geometry.attributes.position.needsUpdate = true; 414 | 415 | } 416 | 417 | }; 418 | 419 | -------------------------------------------------------------------------------- /lib/MMDPhysics.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author takahiro / https://github.com/takahirox 3 | * 4 | * Dependencies 5 | * - Ammo.js https://github.com/kripken/ammo.js 6 | * 7 | * MMD specific Physics class. 8 | * 9 | * See THREE.MMDLoader for the passed parameter list of RigidBody/Constraint. 10 | * 11 | * Requirement: 12 | * - don't change object's scale from (1,1,1) after setting physics to object 13 | * 14 | * TODO 15 | * - optimize for the performance 16 | * - use Physijs http://chandlerprall.github.io/Physijs/ 17 | * and improve the performance by making use of Web worker. 18 | * - if possible, make this class being non-MMD specific. 19 | * - object scale change support 20 | */ 21 | 22 | THREE.MMDPhysics = function ( mesh, params ) { 23 | 24 | if ( params === undefined ) params = {}; 25 | 26 | this.mesh = mesh; 27 | this.helper = new THREE.MMDPhysics.ResourceHelper(); 28 | 29 | /* 30 | * I don't know why but 1/60 unitStep easily breaks models 31 | * so I set it 1/65 so far. 32 | * Don't set too small unitStep because 33 | * the smaller unitStep can make the performance worse. 34 | */ 35 | this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65; 36 | this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3; 37 | 38 | this.world = params.world !== undefined ? params.world : null; 39 | this.bodies = []; 40 | this.constraints = []; 41 | 42 | this.init( mesh ); 43 | 44 | }; 45 | 46 | THREE.MMDPhysics.prototype = { 47 | 48 | constructor: THREE.MMDPhysics, 49 | 50 | init: function ( mesh ) { 51 | 52 | var parent = mesh.parent; 53 | 54 | if ( parent !== null ) { 55 | 56 | parent.remove( mesh ); 57 | 58 | } 59 | 60 | var currentPosition = mesh.position.clone(); 61 | var currentRotation = mesh.rotation.clone(); 62 | var currentScale = mesh.scale.clone(); 63 | 64 | mesh.position.set( 0, 0, 0 ); 65 | mesh.rotation.set( 0, 0, 0 ); 66 | mesh.scale.set( 1, 1, 1 ); 67 | 68 | mesh.updateMatrixWorld( true ); 69 | 70 | if ( this.world === null ) this.initWorld(); 71 | this.initRigidBodies(); 72 | this.initConstraints(); 73 | 74 | if ( parent !== null ) { 75 | 76 | parent.add( mesh ); 77 | 78 | } 79 | 80 | mesh.position.copy( currentPosition ); 81 | mesh.rotation.copy( currentRotation ); 82 | mesh.scale.copy( currentScale ); 83 | 84 | mesh.updateMatrixWorld( true ); 85 | 86 | this.reset(); 87 | 88 | }, 89 | 90 | initWorld: function () { 91 | 92 | var config = new Ammo.btDefaultCollisionConfiguration(); 93 | var dispatcher = new Ammo.btCollisionDispatcher( config ); 94 | var cache = new Ammo.btDbvtBroadphase(); 95 | var solver = new Ammo.btSequentialImpulseConstraintSolver(); 96 | var world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config ); 97 | world.setGravity( new Ammo.btVector3( 0, -9.8 * 10, 0 ) ); 98 | this.world = world; 99 | 100 | }, 101 | 102 | initRigidBodies: function () { 103 | 104 | var bodies = this.mesh.geometry.rigidBodies; 105 | 106 | for ( var i = 0; i < bodies.length; i++ ) { 107 | 108 | var b = new THREE.MMDPhysics.RigidBody( this.mesh, this.world, bodies[ i ], this.helper ); 109 | this.bodies.push( b ); 110 | 111 | } 112 | 113 | }, 114 | 115 | initConstraints: function () { 116 | 117 | var constraints = this.mesh.geometry.constraints; 118 | 119 | for ( var i = 0; i < constraints.length; i++ ) { 120 | 121 | var params = constraints[ i ]; 122 | var bodyA = this.bodies[ params.rigidBodyIndex1 ]; 123 | var bodyB = this.bodies[ params.rigidBodyIndex2 ]; 124 | var c = new THREE.MMDPhysics.Constraint( this.mesh, this.world, bodyA, bodyB, params, this.helper ); 125 | this.constraints.push( c ); 126 | 127 | } 128 | 129 | 130 | }, 131 | 132 | update: function ( delta ) { 133 | 134 | this.updateRigidBodies(); 135 | this.stepSimulation( delta ); 136 | this.updateBones(); 137 | 138 | }, 139 | 140 | stepSimulation: function ( delta ) { 141 | 142 | var unitStep = this.unitStep; 143 | var stepTime = delta; 144 | var maxStepNum = ( ( delta / unitStep ) | 0 ) + 1; 145 | 146 | if ( stepTime < unitStep ) { 147 | 148 | stepTime = unitStep; 149 | maxStepNum = 1; 150 | 151 | } 152 | 153 | if ( maxStepNum > this.maxStepNum ) { 154 | 155 | maxStepNum = this.maxStepNum; 156 | 157 | } 158 | 159 | this.world.stepSimulation( stepTime, maxStepNum, unitStep ); 160 | 161 | }, 162 | 163 | updateRigidBodies: function () { 164 | 165 | for ( var i = 0; i < this.bodies.length; i++ ) { 166 | 167 | this.bodies[ i ].updateFromBone(); 168 | 169 | } 170 | 171 | }, 172 | 173 | updateBones: function () { 174 | 175 | for ( var i = 0; i < this.bodies.length; i++ ) { 176 | 177 | this.bodies[ i ].updateBone(); 178 | 179 | } 180 | 181 | }, 182 | 183 | reset: function () { 184 | 185 | for ( var i = 0; i < this.bodies.length; i++ ) { 186 | 187 | this.bodies[ i ].reset(); 188 | 189 | } 190 | 191 | }, 192 | 193 | warmup: function ( cycles ) { 194 | 195 | for ( var i = 0; i < cycles; i++ ) { 196 | 197 | this.update( 1 / 60 ); 198 | 199 | } 200 | 201 | } 202 | 203 | }; 204 | 205 | /** 206 | * This helper class responsibilies are 207 | * 208 | * 1. manage Ammo.js and Three.js object resources and 209 | * improve the performance and the memory consumption by 210 | * reusing objects. 211 | * 212 | * 2. provide simple Ammo object operations. 213 | */ 214 | THREE.MMDPhysics.ResourceHelper = function () { 215 | 216 | // for Three.js 217 | this.threeVector3s = []; 218 | this.threeMatrix4s = []; 219 | this.threeQuaternions = []; 220 | this.threeEulers = []; 221 | 222 | // for Ammo.js 223 | this.transforms = []; 224 | this.quaternions = []; 225 | this.vector3s = []; 226 | 227 | }; 228 | 229 | THREE.MMDPhysics.ResourceHelper.prototype = { 230 | 231 | allocThreeVector3: function () { 232 | 233 | return ( this.threeVector3s.length > 0 ) ? this.threeVector3s.pop() : new THREE.Vector3(); 234 | 235 | }, 236 | 237 | freeThreeVector3: function ( v ) { 238 | 239 | this.threeVector3s.push( v ); 240 | 241 | }, 242 | 243 | allocThreeMatrix4: function () { 244 | 245 | return ( this.threeMatrix4s.length > 0 ) ? this.threeMatrix4s.pop() : new THREE.Matrix4(); 246 | 247 | }, 248 | 249 | freeThreeMatrix4: function ( m ) { 250 | 251 | this.threeMatrix4s.push( m ); 252 | 253 | }, 254 | 255 | allocThreeQuaternion: function () { 256 | 257 | return ( this.threeQuaternions.length > 0 ) ? this.threeQuaternions.pop() : new THREE.Quaternion(); 258 | 259 | }, 260 | 261 | freeThreeQuaternion: function ( q ) { 262 | 263 | this.threeQuaternions.push( q ); 264 | 265 | }, 266 | 267 | allocThreeEuler: function () { 268 | 269 | return ( this.threeEulers.length > 0 ) ? this.threeEulers.pop() : new THREE.Euler(); 270 | 271 | }, 272 | 273 | freeThreeEuler: function ( e ) { 274 | 275 | this.threeEulers.push( e ); 276 | 277 | }, 278 | 279 | allocTransform: function () { 280 | 281 | return ( this.transforms.length > 0 ) ? this.transforms.pop() : new Ammo.btTransform(); 282 | 283 | }, 284 | 285 | freeTransform: function ( t ) { 286 | 287 | this.transforms.push( t ); 288 | 289 | }, 290 | 291 | allocQuaternion: function () { 292 | 293 | return ( this.quaternions.length > 0 ) ? this.quaternions.pop() : new Ammo.btQuaternion(); 294 | 295 | }, 296 | 297 | freeQuaternion: function ( q ) { 298 | 299 | this.quaternions.push( q ); 300 | 301 | }, 302 | 303 | allocVector3: function () { 304 | 305 | return ( this.vector3s.length > 0 ) ? this.vector3s.pop() : new Ammo.btVector3(); 306 | 307 | }, 308 | 309 | freeVector3: function ( v ) { 310 | 311 | this.vector3s.push( v ); 312 | 313 | }, 314 | 315 | setIdentity: function ( t ) { 316 | 317 | t.setIdentity(); 318 | 319 | }, 320 | 321 | getBasis: function ( t ) { 322 | 323 | var q = this.allocQuaternion(); 324 | t.getBasis().getRotation( q ); 325 | return q; 326 | 327 | }, 328 | 329 | getBasisAsMatrix3: function ( t ) { 330 | 331 | var q = this.getBasis( t ); 332 | var m = this.quaternionToMatrix3( q ); 333 | this.freeQuaternion( q ); 334 | return m; 335 | 336 | }, 337 | 338 | getOrigin: function( t ) { 339 | 340 | return t.getOrigin(); 341 | 342 | }, 343 | 344 | setOrigin: function( t, v ) { 345 | 346 | t.getOrigin().setValue( v.x(), v.y(), v.z() ); 347 | 348 | }, 349 | 350 | copyOrigin: function( t1, t2 ) { 351 | 352 | var o = t2.getOrigin(); 353 | this.setOrigin( t1, o ); 354 | 355 | }, 356 | 357 | setBasis: function( t, q ) { 358 | 359 | t.setRotation( q ); 360 | 361 | }, 362 | 363 | setBasisFromMatrix3: function( t, m ) { 364 | 365 | var q = this.matrix3ToQuaternion( m ); 366 | this.setBasis( t, q ); 367 | this.freeQuaternion( q ); 368 | 369 | }, 370 | 371 | setOriginFromArray3: function ( t, a ) { 372 | 373 | t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] ); 374 | 375 | }, 376 | 377 | setBasisFromArray3: function ( t, a ) { 378 | 379 | var thQ = this.allocThreeQuaternion(); 380 | var thE = this.allocThreeEuler(); 381 | thE.set( a[ 0 ], a[ 1 ], a[ 2 ] ); 382 | this.setBasisFromArray4( t, thQ.setFromEuler( thE ).toArray() ); 383 | 384 | this.freeThreeEuler( thE ); 385 | this.freeThreeQuaternion( thQ ); 386 | 387 | }, 388 | 389 | setBasisFromArray4: function ( t, a ) { 390 | 391 | var q = this.array4ToQuaternion( a ); 392 | this.setBasis( t, q ); 393 | this.freeQuaternion( q ); 394 | 395 | }, 396 | 397 | array4ToQuaternion: function( a ) { 398 | 399 | var q = this.allocQuaternion(); 400 | q.setX( a[ 0 ] ); 401 | q.setY( a[ 1 ] ); 402 | q.setZ( a[ 2 ] ); 403 | q.setW( a[ 3 ] ); 404 | return q; 405 | 406 | }, 407 | 408 | multiplyTransforms: function ( t1, t2 ) { 409 | 410 | var t = this.allocTransform(); 411 | this.setIdentity( t ); 412 | 413 | var m1 = this.getBasisAsMatrix3( t1 ); 414 | var m2 = this.getBasisAsMatrix3( t2 ); 415 | 416 | var o1 = this.getOrigin( t1 ); 417 | var o2 = this.getOrigin( t2 ); 418 | 419 | var v1 = this.multiplyMatrix3ByVector3( m1, o2 ); 420 | var v2 = this.addVector3( v1, o1 ); 421 | this.setOrigin( t, v2 ); 422 | 423 | var m3 = this.multiplyMatrices3( m1, m2 ); 424 | this.setBasisFromMatrix3( t, m3 ); 425 | 426 | this.freeVector3( v1 ); 427 | this.freeVector3( v2 ); 428 | 429 | return t; 430 | 431 | }, 432 | 433 | inverseTransform: function ( t ) { 434 | 435 | var t2 = this.allocTransform(); 436 | 437 | var m1 = this.getBasisAsMatrix3( t ); 438 | var o = this.getOrigin( t ); 439 | 440 | var m2 = this.transposeMatrix3( m1 ); 441 | var v1 = this.negativeVector3( o ); 442 | var v2 = this.multiplyMatrix3ByVector3( m2, v1 ); 443 | 444 | this.setOrigin( t2, v2 ); 445 | this.setBasisFromMatrix3( t2, m2 ); 446 | 447 | this.freeVector3( v1 ); 448 | this.freeVector3( v2 ); 449 | 450 | return t2; 451 | 452 | }, 453 | 454 | multiplyMatrices3: function ( m1, m2 ) { 455 | 456 | var m3 = []; 457 | 458 | var v10 = this.rowOfMatrix3( m1, 0 ); 459 | var v11 = this.rowOfMatrix3( m1, 1 ); 460 | var v12 = this.rowOfMatrix3( m1, 2 ); 461 | 462 | var v20 = this.columnOfMatrix3( m2, 0 ); 463 | var v21 = this.columnOfMatrix3( m2, 1 ); 464 | var v22 = this.columnOfMatrix3( m2, 2 ); 465 | 466 | m3[ 0 ] = this.dotVectors3( v10, v20 ); 467 | m3[ 1 ] = this.dotVectors3( v10, v21 ); 468 | m3[ 2 ] = this.dotVectors3( v10, v22 ); 469 | m3[ 3 ] = this.dotVectors3( v11, v20 ); 470 | m3[ 4 ] = this.dotVectors3( v11, v21 ); 471 | m3[ 5 ] = this.dotVectors3( v11, v22 ); 472 | m3[ 6 ] = this.dotVectors3( v12, v20 ); 473 | m3[ 7 ] = this.dotVectors3( v12, v21 ); 474 | m3[ 8 ] = this.dotVectors3( v12, v22 ); 475 | 476 | this.freeVector3( v10 ); 477 | this.freeVector3( v11 ); 478 | this.freeVector3( v12 ); 479 | this.freeVector3( v20 ); 480 | this.freeVector3( v21 ); 481 | this.freeVector3( v22 ); 482 | 483 | return m3; 484 | 485 | }, 486 | 487 | addVector3: function( v1, v2 ) { 488 | 489 | var v = this.allocVector3(); 490 | v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() ); 491 | return v; 492 | 493 | }, 494 | 495 | dotVectors3: function( v1, v2 ) { 496 | 497 | return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); 498 | 499 | }, 500 | 501 | rowOfMatrix3: function( m, i ) { 502 | 503 | var v = this.allocVector3(); 504 | v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] ); 505 | return v; 506 | 507 | }, 508 | 509 | columnOfMatrix3: function( m, i ) { 510 | 511 | var v = this.allocVector3(); 512 | v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] ); 513 | return v; 514 | 515 | }, 516 | 517 | negativeVector3: function( v ) { 518 | 519 | var v2 = this.allocVector3(); 520 | v2.setValue( -v.x(), -v.y(), -v.z() ); 521 | return v2; 522 | 523 | }, 524 | 525 | multiplyMatrix3ByVector3: function ( m, v ) { 526 | 527 | var v4 = this.allocVector3(); 528 | 529 | var v0 = this.rowOfMatrix3( m, 0 ); 530 | var v1 = this.rowOfMatrix3( m, 1 ); 531 | var v2 = this.rowOfMatrix3( m, 2 ); 532 | var x = this.dotVectors3( v0, v ); 533 | var y = this.dotVectors3( v1, v ); 534 | var z = this.dotVectors3( v2, v ); 535 | 536 | v4.setValue( x, y, z ); 537 | 538 | this.freeVector3( v0 ); 539 | this.freeVector3( v1 ); 540 | this.freeVector3( v2 ); 541 | 542 | return v4; 543 | 544 | }, 545 | 546 | transposeMatrix3: function( m ) { 547 | 548 | var m2 = []; 549 | m2[ 0 ] = m[ 0 ]; 550 | m2[ 1 ] = m[ 3 ]; 551 | m2[ 2 ] = m[ 6 ]; 552 | m2[ 3 ] = m[ 1 ]; 553 | m2[ 4 ] = m[ 4 ]; 554 | m2[ 5 ] = m[ 7 ]; 555 | m2[ 6 ] = m[ 2 ]; 556 | m2[ 7 ] = m[ 5 ]; 557 | m2[ 8 ] = m[ 8 ]; 558 | return m2; 559 | 560 | }, 561 | 562 | quaternionToMatrix3: function ( q ) { 563 | 564 | var m = []; 565 | 566 | var x = q.x(); 567 | var y = q.y(); 568 | var z = q.z(); 569 | var w = q.w(); 570 | 571 | var xx = x * x; 572 | var yy = y * y; 573 | var zz = z * z; 574 | 575 | var xy = x * y; 576 | var yz = y * z; 577 | var zx = z * x; 578 | 579 | var xw = x * w; 580 | var yw = y * w; 581 | var zw = z * w; 582 | 583 | m[ 0 ] = 1 - 2 * ( yy + zz ); 584 | m[ 1 ] = 2 * ( xy - zw ); 585 | m[ 2 ] = 2 * ( zx + yw ); 586 | m[ 3 ] = 2 * ( xy + zw ); 587 | m[ 4 ] = 1 - 2 * ( zz + xx ); 588 | m[ 5 ] = 2 * ( yz - xw ); 589 | m[ 6 ] = 2 * ( zx - yw ); 590 | m[ 7 ] = 2 * ( yz + xw ); 591 | m[ 8 ] = 1 - 2 * ( xx + yy ); 592 | 593 | return m; 594 | 595 | }, 596 | 597 | matrix3ToQuaternion: function( m ) { 598 | 599 | var t = m[ 0 ] + m[ 4 ] + m[ 8 ]; 600 | var s, x, y, z, w; 601 | 602 | if( t > 0 ) { 603 | 604 | s = Math.sqrt( t + 1.0 ) * 2; 605 | w = 0.25 * s; 606 | x = ( m[ 7 ] - m[ 5 ] ) / s; 607 | y = ( m[ 2 ] - m[ 6 ] ) / s; 608 | z = ( m[ 3 ] - m[ 1 ] ) / s; 609 | 610 | } else if( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) { 611 | 612 | s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2; 613 | w = ( m[ 7 ] - m[ 5 ] ) / s; 614 | x = 0.25 * s; 615 | y = ( m[ 1 ] + m[ 3 ] ) / s; 616 | z = ( m[ 2 ] + m[ 6 ] ) / s; 617 | 618 | } else if( m[ 4 ] > m[ 8 ] ) { 619 | 620 | s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2; 621 | w = ( m[ 2 ] - m[ 6 ] ) / s; 622 | x = ( m[ 1 ] + m[ 3 ] ) / s; 623 | y = 0.25 * s; 624 | z = ( m[ 5 ] + m[ 7 ] ) / s; 625 | 626 | } else { 627 | 628 | s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2; 629 | w = ( m[ 3 ] - m[ 1 ] ) / s; 630 | x = ( m[ 2 ] + m[ 6 ] ) / s; 631 | y = ( m[ 5 ] + m[ 7 ] ) / s; 632 | z = 0.25 * s; 633 | 634 | } 635 | 636 | var q = this.allocQuaternion(); 637 | q.setX( x ); 638 | q.setY( y ); 639 | q.setZ( z ); 640 | q.setW( w ); 641 | return q; 642 | 643 | } 644 | 645 | }; 646 | 647 | THREE.MMDPhysics.RigidBody = function ( mesh, world, params, helper ) { 648 | 649 | this.mesh = mesh; 650 | this.world = world; 651 | this.params = params; 652 | this.helper = helper; 653 | 654 | this.body = null; 655 | this.bone = null; 656 | this.boneOffsetForm = null; 657 | this.boneOffsetFormInverse = null; 658 | 659 | this.init(); 660 | 661 | }; 662 | 663 | THREE.MMDPhysics.RigidBody.prototype = { 664 | 665 | constructor: THREE.MMDPhysics.RigidBody, 666 | 667 | init: function () { 668 | 669 | function generateShape( p ) { 670 | 671 | switch( p.shapeType ) { 672 | 673 | case 0: 674 | return new Ammo.btSphereShape( p.width ); 675 | 676 | case 1: 677 | return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) ); 678 | 679 | case 2: 680 | return new Ammo.btCapsuleShape( p.width, p.height ); 681 | 682 | default: 683 | throw 'unknown shape type ' + p.shapeType; 684 | 685 | } 686 | 687 | } 688 | 689 | var helper = this.helper; 690 | var params = this.params; 691 | var bones = this.mesh.skeleton.bones; 692 | var bone = ( params.boneIndex === -1 ) ? new THREE.Bone() : bones[ params.boneIndex ]; 693 | 694 | var shape = generateShape( params ); 695 | var weight = ( params.type === 0 ) ? 0 : params.weight; 696 | var localInertia = helper.allocVector3(); 697 | localInertia.setValue( 0, 0, 0 ); 698 | 699 | if( weight !== 0 ) { 700 | 701 | shape.calculateLocalInertia( weight, localInertia ); 702 | 703 | } 704 | 705 | var boneOffsetForm = helper.allocTransform(); 706 | helper.setIdentity( boneOffsetForm ); 707 | helper.setOriginFromArray3( boneOffsetForm, params.position ); 708 | helper.setBasisFromArray3( boneOffsetForm, params.rotation ); 709 | 710 | var boneForm = helper.allocTransform(); 711 | helper.setIdentity( boneForm ); 712 | helper.setOriginFromArray3( boneForm, bone.getWorldPosition().toArray() ); 713 | 714 | var form = helper.multiplyTransforms( boneForm, boneOffsetForm ); 715 | var state = new Ammo.btDefaultMotionState( form ); 716 | 717 | var info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia ); 718 | info.set_m_friction( params.friction ); 719 | info.set_m_restitution( params.restitution ); 720 | 721 | var body = new Ammo.btRigidBody( info ); 722 | 723 | if ( params.type === 0 ) { 724 | 725 | body.setCollisionFlags( body.getCollisionFlags() | 2 ); 726 | 727 | /* 728 | * It'd be better to comment out this line though in general I should call this method 729 | * because I'm not sure why but physics will be more like MMD's 730 | * if I comment out. 731 | */ 732 | body.setActivationState( 4 ); 733 | 734 | } 735 | 736 | body.setDamping( params.positionDamping, params.rotationDamping ); 737 | body.setSleepingThresholds( 0, 0 ); 738 | 739 | this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget ); 740 | 741 | this.body = body; 742 | this.bone = bone; 743 | this.boneOffsetForm = boneOffsetForm; 744 | this.boneOffsetFormInverse = helper.inverseTransform( boneOffsetForm ); 745 | 746 | helper.freeVector3( localInertia ); 747 | helper.freeTransform( form ); 748 | helper.freeTransform( boneForm ); 749 | 750 | }, 751 | 752 | reset: function () { 753 | 754 | this.setTransformFromBone(); 755 | 756 | }, 757 | 758 | updateFromBone: function () { 759 | 760 | if ( this.params.boneIndex === -1 ) { 761 | 762 | return; 763 | 764 | } 765 | 766 | if ( this.params.type === 0 ) { 767 | 768 | this.setTransformFromBone(); 769 | 770 | } 771 | 772 | }, 773 | 774 | updateBone: function () { 775 | 776 | if ( this.params.type === 0 || this.params.boneIndex === -1 ) { 777 | 778 | return; 779 | 780 | } 781 | 782 | this.updateBoneRotation(); 783 | 784 | if ( this.params.type === 1 ) { 785 | 786 | this.updateBonePosition(); 787 | 788 | } 789 | 790 | this.bone.updateMatrixWorld( true ); 791 | 792 | if ( this.params.type === 2 ) { 793 | 794 | this.setPositionFromBone(); 795 | 796 | } 797 | 798 | }, 799 | 800 | getBoneTransform: function () { 801 | 802 | var helper = this.helper; 803 | var p = this.bone.getWorldPosition(); 804 | var q = this.bone.getWorldQuaternion(); 805 | 806 | var tr = helper.allocTransform(); 807 | helper.setOriginFromArray3( tr, p.toArray() ); 808 | helper.setBasisFromArray4( tr, q.toArray() ); 809 | 810 | var form = helper.multiplyTransforms( tr, this.boneOffsetForm ); 811 | 812 | helper.freeTransform( tr ); 813 | 814 | return form; 815 | 816 | }, 817 | 818 | getWorldTransformForBone: function () { 819 | 820 | var helper = this.helper; 821 | 822 | var tr = helper.allocTransform(); 823 | this.body.getMotionState().getWorldTransform( tr ); 824 | var tr2 = helper.multiplyTransforms( tr, this.boneOffsetFormInverse ); 825 | 826 | helper.freeTransform( tr ); 827 | 828 | return tr2; 829 | 830 | }, 831 | 832 | setTransformFromBone: function () { 833 | 834 | var helper = this.helper; 835 | var form = this.getBoneTransform(); 836 | 837 | // TODO: check the most appropriate way to set 838 | //this.body.setWorldTransform( form ); 839 | this.body.setCenterOfMassTransform( form ); 840 | this.body.getMotionState().setWorldTransform( form ); 841 | 842 | helper.freeTransform( form ); 843 | 844 | }, 845 | 846 | setPositionFromBone: function () { 847 | 848 | var helper = this.helper; 849 | var form = this.getBoneTransform(); 850 | 851 | var tr = helper.allocTransform(); 852 | this.body.getMotionState().getWorldTransform( tr ); 853 | helper.copyOrigin( tr, form ); 854 | 855 | // TODO: check the most appropriate way to set 856 | //this.body.setWorldTransform( tr ); 857 | this.body.setCenterOfMassTransform( tr ); 858 | this.body.getMotionState().setWorldTransform( tr ); 859 | 860 | helper.freeTransform( tr ); 861 | helper.freeTransform( form ); 862 | 863 | }, 864 | 865 | updateBoneRotation: function () { 866 | 867 | this.bone.updateMatrixWorld( true ); 868 | 869 | var helper = this.helper; 870 | 871 | var tr = this.getWorldTransformForBone(); 872 | var q = helper.getBasis( tr ); 873 | 874 | var thQ = helper.allocThreeQuaternion(); 875 | var thQ2 = helper.allocThreeQuaternion(); 876 | var thQ3 = helper.allocThreeQuaternion(); 877 | 878 | thQ.set( q.x(), q.y(), q.z(), q.w() ); 879 | thQ2.setFromRotationMatrix( this.bone.matrixWorld ); 880 | thQ2.conjugate(); 881 | thQ2.multiply( thQ ); 882 | 883 | //this.bone.quaternion.multiply( thQ2 ); 884 | 885 | thQ3.setFromRotationMatrix( this.bone.matrix ); 886 | this.bone.quaternion.copy( thQ2.multiply( thQ3 ) ); 887 | 888 | helper.freeThreeQuaternion( thQ ); 889 | helper.freeThreeQuaternion( thQ2 ); 890 | helper.freeThreeQuaternion( thQ3 ); 891 | 892 | helper.freeQuaternion( q ); 893 | helper.freeTransform( tr ); 894 | 895 | }, 896 | 897 | updateBonePosition: function () { 898 | 899 | var helper = this.helper; 900 | 901 | var tr = this.getWorldTransformForBone(); 902 | 903 | var thV = helper.allocThreeVector3(); 904 | 905 | var o = helper.getOrigin( tr ); 906 | thV.set( o.x(), o.y(), o.z() ); 907 | 908 | var v = this.bone.worldToLocal( thV ); 909 | this.bone.position.add( v ); 910 | 911 | helper.freeThreeVector3( thV ); 912 | 913 | helper.freeTransform( tr ); 914 | 915 | } 916 | 917 | }; 918 | 919 | THREE.MMDPhysics.Constraint = function ( mesh, world, bodyA, bodyB, params, helper ) { 920 | 921 | this.mesh = mesh; 922 | this.world = world; 923 | this.bodyA = bodyA; 924 | this.bodyB = bodyB; 925 | this.params = params; 926 | this.helper = helper; 927 | 928 | this.constraint = null; 929 | 930 | this.init(); 931 | 932 | }; 933 | 934 | THREE.MMDPhysics.Constraint.prototype = { 935 | 936 | constructor: THREE.MMDPhysics.Constraint, 937 | 938 | init: function () { 939 | 940 | var helper = this.helper; 941 | var params = this.params; 942 | var bodyA = this.bodyA; 943 | var bodyB = this.bodyB; 944 | 945 | var form = helper.allocTransform(); 946 | helper.setIdentity( form ); 947 | helper.setOriginFromArray3( form, params.position ); 948 | helper.setBasisFromArray3( form, params.rotation ); 949 | 950 | var formA = helper.allocTransform(); 951 | var formB = helper.allocTransform(); 952 | 953 | bodyA.body.getMotionState().getWorldTransform( formA ); 954 | bodyB.body.getMotionState().getWorldTransform( formB ); 955 | 956 | var formInverseA = helper.inverseTransform( formA ); 957 | var formInverseB = helper.inverseTransform( formB ); 958 | 959 | var formA2 = helper.multiplyTransforms( formInverseA, form ); 960 | var formB2 = helper.multiplyTransforms( formInverseB, form ); 961 | 962 | var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true ); 963 | 964 | var lll = helper.allocVector3(); 965 | var lul = helper.allocVector3(); 966 | var all = helper.allocVector3(); 967 | var aul = helper.allocVector3(); 968 | 969 | lll.setValue( params.translationLimitation1[ 0 ], 970 | params.translationLimitation1[ 1 ], 971 | params.translationLimitation1[ 2 ] ); 972 | lul.setValue( params.translationLimitation2[ 0 ], 973 | params.translationLimitation2[ 1 ], 974 | params.translationLimitation2[ 2 ] ); 975 | all.setValue( params.rotationLimitation1[ 0 ], 976 | params.rotationLimitation1[ 1 ], 977 | params.rotationLimitation1[ 2 ] ); 978 | aul.setValue( params.rotationLimitation2[ 0 ], 979 | params.rotationLimitation2[ 1 ], 980 | params.rotationLimitation2[ 2 ] ); 981 | 982 | constraint.setLinearLowerLimit( lll ); 983 | constraint.setLinearUpperLimit( lul ); 984 | constraint.setAngularLowerLimit( all ); 985 | constraint.setAngularUpperLimit( aul ); 986 | 987 | for ( var i = 0; i < 3; i++ ) { 988 | 989 | if( params.springPosition[ i ] !== 0 ) { 990 | 991 | constraint.enableSpring( i, true ); 992 | constraint.setStiffness( i, params.springPosition[ i ] ); 993 | 994 | } 995 | 996 | } 997 | 998 | for ( var i = 0; i < 3; i++ ) { 999 | 1000 | if( params.springRotation[ i ] !== 0 ) { 1001 | 1002 | constraint.enableSpring( i + 3, true ); 1003 | constraint.setStiffness( i + 3, params.springRotation[ i ] ); 1004 | 1005 | } 1006 | 1007 | } 1008 | 1009 | /* 1010 | * Currently(10/31/2016) official ammo.js doesn't support 1011 | * btGeneric6DofSpringConstraint.setParam method. 1012 | * You need custom ammo.js (add the method into idl) if you wanna use. 1013 | * By setting this parameter, physics will be more like MMD's 1014 | */ 1015 | if ( constraint.setParam !== undefined ) { 1016 | 1017 | for ( var i = 0; i < 6; i ++ ) { 1018 | 1019 | // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js 1020 | constraint.setParam( 2, 0.475, i ); 1021 | 1022 | } 1023 | 1024 | } 1025 | 1026 | this.world.addConstraint( constraint, true ); 1027 | this.constraint = constraint; 1028 | 1029 | helper.freeTransform( form ); 1030 | helper.freeTransform( formA ); 1031 | helper.freeTransform( formB ); 1032 | helper.freeTransform( formInverseA ); 1033 | helper.freeTransform( formInverseB ); 1034 | helper.freeTransform( formA2 ); 1035 | helper.freeTransform( formB2 ); 1036 | helper.freeVector3( lll ); 1037 | helper.freeVector3( lul ); 1038 | helper.freeVector3( all ); 1039 | helper.freeVector3( aul ); 1040 | 1041 | } 1042 | 1043 | }; 1044 | 1045 | 1046 | THREE.MMDPhysicsHelper = function ( mesh ) { 1047 | 1048 | if ( mesh.physics === undefined || mesh.geometry.rigidBodies === undefined ) { 1049 | 1050 | throw 'THREE.MMDPhysicsHelper requires physics in mesh and rigidBodies in mesh.geometry.'; 1051 | 1052 | } 1053 | 1054 | THREE.Object3D.call( this ); 1055 | 1056 | this.root = mesh; 1057 | 1058 | this.matrix = mesh.matrixWorld; 1059 | this.matrixAutoUpdate = false; 1060 | 1061 | this.materials = []; 1062 | 1063 | this.materials.push( 1064 | new THREE.MeshBasicMaterial( { 1065 | color: new THREE.Color( 0xff8888 ), 1066 | wireframe: true, 1067 | depthTest: false, 1068 | depthWrite: false, 1069 | opacity: 0.25, 1070 | transparent: true 1071 | } ) 1072 | ); 1073 | 1074 | this.materials.push( 1075 | new THREE.MeshBasicMaterial( { 1076 | color: new THREE.Color( 0x88ff88 ), 1077 | wireframe: true, 1078 | depthTest: false, 1079 | depthWrite: false, 1080 | opacity: 0.25, 1081 | transparent: true 1082 | } ) 1083 | ); 1084 | 1085 | this.materials.push( 1086 | new THREE.MeshBasicMaterial( { 1087 | color: new THREE.Color( 0x8888ff ), 1088 | wireframe: true, 1089 | depthTest: false, 1090 | depthWrite: false, 1091 | opacity: 0.25, 1092 | transparent: true 1093 | } ) 1094 | ); 1095 | 1096 | this._init(); 1097 | this.update(); 1098 | 1099 | }; 1100 | 1101 | THREE.MMDPhysicsHelper.prototype = Object.create( THREE.Object3D.prototype ); 1102 | THREE.MMDPhysicsHelper.prototype.constructor = THREE.MMDPhysicsHelper; 1103 | 1104 | THREE.MMDPhysicsHelper.prototype._init = function () { 1105 | 1106 | var mesh = this.root; 1107 | var rigidBodies = mesh.geometry.rigidBodies; 1108 | 1109 | function createGeometry( param ) { 1110 | 1111 | switch ( param.shapeType ) { 1112 | 1113 | case 0: 1114 | return new THREE.SphereBufferGeometry( param.width, 16, 8 ); 1115 | 1116 | case 1: 1117 | return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8); 1118 | 1119 | case 2: 1120 | return new createCapsuleGeometry( param.width, param.height, 16, 8 ); 1121 | 1122 | default: 1123 | return null; 1124 | 1125 | } 1126 | 1127 | } 1128 | 1129 | // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815 1130 | function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) { 1131 | 1132 | var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true ); 1133 | var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) ); 1134 | var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) ); 1135 | 1136 | upperSphere.position.set( 0, cylinderHeight / 2, 0 ); 1137 | lowerSphere.position.set( 0, -cylinderHeight / 2, 0 ); 1138 | 1139 | upperSphere.updateMatrix(); 1140 | lowerSphere.updateMatrix(); 1141 | 1142 | geometry.merge( upperSphere.geometry, upperSphere.matrix ); 1143 | geometry.merge( lowerSphere.geometry, lowerSphere.matrix ); 1144 | 1145 | return geometry; 1146 | 1147 | } 1148 | 1149 | for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) { 1150 | 1151 | var param = rigidBodies[ i ]; 1152 | this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) ); 1153 | 1154 | } 1155 | 1156 | }; 1157 | 1158 | THREE.MMDPhysicsHelper.prototype.update = function () { 1159 | 1160 | var mesh = this.root; 1161 | var rigidBodies = mesh.geometry.rigidBodies; 1162 | var bodies = mesh.physics.bodies; 1163 | 1164 | var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld ); 1165 | var vector = new THREE.Vector3(); 1166 | var quaternion = new THREE.Quaternion(); 1167 | var quaternion2 = new THREE.Quaternion(); 1168 | 1169 | function getPosition( origin ) { 1170 | 1171 | vector.set( origin.x(), origin.y(), origin.z() ); 1172 | vector.applyMatrix4( matrixWorldInv ); 1173 | 1174 | return vector; 1175 | 1176 | } 1177 | 1178 | function getQuaternion( rotation ) { 1179 | 1180 | quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() ); 1181 | quaternion2.setFromRotationMatrix( matrixWorldInv ); 1182 | quaternion2.multiply( quaternion ); 1183 | 1184 | return quaternion2; 1185 | 1186 | } 1187 | 1188 | for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) { 1189 | 1190 | var body = bodies[ i ].body; 1191 | var mesh = this.children[ i ]; 1192 | 1193 | var tr = body.getCenterOfMassTransform(); 1194 | 1195 | mesh.position.copy( getPosition( tr.getOrigin() ) ); 1196 | mesh.quaternion.copy( getQuaternion( tr.getRotation() ) ); 1197 | 1198 | } 1199 | 1200 | }; 1201 | 1202 | 1203 | -------------------------------------------------------------------------------- /lib/TGALoader.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @author Daosheng Mu / https://github.com/DaoshengMu/ 3 | * @author mrdoob / http://mrdoob.com/ 4 | * @author takahirox / https://github.com/takahirox/ 5 | */ 6 | 7 | THREE.TGALoader = function ( manager ) { 8 | 9 | this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; 10 | 11 | }; 12 | 13 | THREE.TGALoader.prototype.load = function ( url, onLoad, onProgress, onError ) { 14 | 15 | var scope = this; 16 | 17 | var texture = new THREE.Texture(); 18 | 19 | var loader = new THREE.FileLoader( this.manager ); 20 | loader.setResponseType( 'arraybuffer' ); 21 | 22 | loader.load( url, function ( buffer ) { 23 | 24 | texture.image = scope.parse( buffer ); 25 | texture.needsUpdate = true; 26 | 27 | if ( onLoad !== undefined ) { 28 | 29 | onLoad( texture ); 30 | 31 | } 32 | 33 | }, onProgress, onError ); 34 | 35 | return texture; 36 | 37 | }; 38 | 39 | // reference from vthibault, https://github.com/vthibault/roBrowser/blob/master/src/Loaders/Targa.js 40 | THREE.TGALoader.prototype.parse = function ( buffer ) { 41 | 42 | // TGA Constants 43 | var TGA_TYPE_NO_DATA = 0, 44 | TGA_TYPE_INDEXED = 1, 45 | TGA_TYPE_RGB = 2, 46 | TGA_TYPE_GREY = 3, 47 | TGA_TYPE_RLE_INDEXED = 9, 48 | TGA_TYPE_RLE_RGB = 10, 49 | TGA_TYPE_RLE_GREY = 11, 50 | 51 | TGA_ORIGIN_MASK = 0x30, 52 | TGA_ORIGIN_SHIFT = 0x04, 53 | TGA_ORIGIN_BL = 0x00, 54 | TGA_ORIGIN_BR = 0x01, 55 | TGA_ORIGIN_UL = 0x02, 56 | TGA_ORIGIN_UR = 0x03; 57 | 58 | 59 | if ( buffer.length < 19 ) 60 | console.error( 'THREE.TGALoader.parse: Not enough data to contain header.' ); 61 | 62 | var content = new Uint8Array( buffer ), 63 | offset = 0, 64 | header = { 65 | id_length: content[ offset ++ ], 66 | colormap_type: content[ offset ++ ], 67 | image_type: content[ offset ++ ], 68 | colormap_index: content[ offset ++ ] | content[ offset ++ ] << 8, 69 | colormap_length: content[ offset ++ ] | content[ offset ++ ] << 8, 70 | colormap_size: content[ offset ++ ], 71 | 72 | origin: [ 73 | content[ offset ++ ] | content[ offset ++ ] << 8, 74 | content[ offset ++ ] | content[ offset ++ ] << 8 75 | ], 76 | width: content[ offset ++ ] | content[ offset ++ ] << 8, 77 | height: content[ offset ++ ] | content[ offset ++ ] << 8, 78 | pixel_size: content[ offset ++ ], 79 | flags: content[ offset ++ ] 80 | }; 81 | 82 | function tgaCheckHeader( header ) { 83 | 84 | switch ( header.image_type ) { 85 | 86 | // Check indexed type 87 | case TGA_TYPE_INDEXED: 88 | case TGA_TYPE_RLE_INDEXED: 89 | if ( header.colormap_length > 256 || header.colormap_size !== 24 || header.colormap_type !== 1 ) { 90 | 91 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: Invalid type colormap data for indexed type' ); 92 | 93 | } 94 | break; 95 | 96 | // Check colormap type 97 | case TGA_TYPE_RGB: 98 | case TGA_TYPE_GREY: 99 | case TGA_TYPE_RLE_RGB: 100 | case TGA_TYPE_RLE_GREY: 101 | if ( header.colormap_type ) { 102 | 103 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: Invalid type colormap data for colormap type' ); 104 | 105 | } 106 | break; 107 | 108 | // What the need of a file without data ? 109 | case TGA_TYPE_NO_DATA: 110 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: No data' ); 111 | 112 | // Invalid type ? 113 | default: 114 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: Invalid type " ' + header.image_type + '"' ); 115 | 116 | } 117 | 118 | // Check image width and height 119 | if ( header.width <= 0 || header.height <= 0 ) { 120 | 121 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: Invalid image size' ); 122 | 123 | } 124 | 125 | // Check image pixel size 126 | if ( header.pixel_size !== 8 && 127 | header.pixel_size !== 16 && 128 | header.pixel_size !== 24 && 129 | header.pixel_size !== 32 ) { 130 | 131 | console.error( 'THREE.TGALoader.parse.tgaCheckHeader: Invalid pixel size "' + header.pixel_size + '"' ); 132 | 133 | } 134 | 135 | } 136 | 137 | // Check tga if it is valid format 138 | tgaCheckHeader( header ); 139 | 140 | if ( header.id_length + offset > buffer.length ) { 141 | 142 | console.error( 'THREE.TGALoader.parse: No data' ); 143 | 144 | } 145 | 146 | // Skip the needn't data 147 | offset += header.id_length; 148 | 149 | // Get targa information about RLE compression and palette 150 | var use_rle = false, 151 | use_pal = false, 152 | use_grey = false; 153 | 154 | switch ( header.image_type ) { 155 | 156 | case TGA_TYPE_RLE_INDEXED: 157 | use_rle = true; 158 | use_pal = true; 159 | break; 160 | 161 | case TGA_TYPE_INDEXED: 162 | use_pal = true; 163 | break; 164 | 165 | case TGA_TYPE_RLE_RGB: 166 | use_rle = true; 167 | break; 168 | 169 | case TGA_TYPE_RGB: 170 | break; 171 | 172 | case TGA_TYPE_RLE_GREY: 173 | use_rle = true; 174 | use_grey = true; 175 | break; 176 | 177 | case TGA_TYPE_GREY: 178 | use_grey = true; 179 | break; 180 | 181 | } 182 | 183 | // Parse tga image buffer 184 | function tgaParse( use_rle, use_pal, header, offset, data ) { 185 | 186 | var pixel_data, 187 | pixel_size, 188 | pixel_total, 189 | palettes; 190 | 191 | pixel_size = header.pixel_size >> 3; 192 | pixel_total = header.width * header.height * pixel_size; 193 | 194 | // Read palettes 195 | if ( use_pal ) { 196 | 197 | palettes = data.subarray( offset, offset += header.colormap_length * ( header.colormap_size >> 3 ) ); 198 | 199 | } 200 | 201 | // Read RLE 202 | if ( use_rle ) { 203 | 204 | pixel_data = new Uint8Array( pixel_total ); 205 | 206 | var c, count, i; 207 | var shift = 0; 208 | var pixels = new Uint8Array( pixel_size ); 209 | 210 | while ( shift < pixel_total ) { 211 | 212 | c = data[ offset ++ ]; 213 | count = ( c & 0x7f ) + 1; 214 | 215 | // RLE pixels. 216 | if ( c & 0x80 ) { 217 | 218 | // Bind pixel tmp array 219 | for ( i = 0; i < pixel_size; ++ i ) { 220 | 221 | pixels[ i ] = data[ offset ++ ]; 222 | 223 | } 224 | 225 | // Copy pixel array 226 | for ( i = 0; i < count; ++ i ) { 227 | 228 | pixel_data.set( pixels, shift + i * pixel_size ); 229 | 230 | } 231 | 232 | shift += pixel_size * count; 233 | 234 | } else { 235 | 236 | // Raw pixels. 237 | count *= pixel_size; 238 | for ( i = 0; i < count; ++ i ) { 239 | 240 | pixel_data[ shift + i ] = data[ offset ++ ]; 241 | 242 | } 243 | shift += count; 244 | 245 | } 246 | 247 | } 248 | 249 | } else { 250 | 251 | // RAW Pixels 252 | pixel_data = data.subarray( 253 | offset, offset += ( use_pal ? header.width * header.height : pixel_total ) 254 | ); 255 | 256 | } 257 | 258 | return { 259 | pixel_data: pixel_data, 260 | palettes: palettes 261 | }; 262 | 263 | } 264 | 265 | function tgaGetImageData8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes ) { 266 | 267 | var colormap = palettes; 268 | var color, i = 0, x, y; 269 | var width = header.width; 270 | 271 | for ( y = y_start; y !== y_end; y += y_step ) { 272 | 273 | for ( x = x_start; x !== x_end; x += x_step, i ++ ) { 274 | 275 | color = image[ i ]; 276 | imageData[ ( x + width * y ) * 4 + 3 ] = 255; 277 | imageData[ ( x + width * y ) * 4 + 2 ] = colormap[ ( color * 3 ) + 0 ]; 278 | imageData[ ( x + width * y ) * 4 + 1 ] = colormap[ ( color * 3 ) + 1 ]; 279 | imageData[ ( x + width * y ) * 4 + 0 ] = colormap[ ( color * 3 ) + 2 ]; 280 | 281 | } 282 | 283 | } 284 | 285 | return imageData; 286 | 287 | } 288 | 289 | function tgaGetImageData16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { 290 | 291 | var color, i = 0, x, y; 292 | var width = header.width; 293 | 294 | for ( y = y_start; y !== y_end; y += y_step ) { 295 | 296 | for ( x = x_start; x !== x_end; x += x_step, i += 2 ) { 297 | 298 | color = image[ i + 0 ] + ( image[ i + 1 ] << 8 ); // Inversed ? 299 | imageData[ ( x + width * y ) * 4 + 0 ] = ( color & 0x7C00 ) >> 7; 300 | imageData[ ( x + width * y ) * 4 + 1 ] = ( color & 0x03E0 ) >> 2; 301 | imageData[ ( x + width * y ) * 4 + 2 ] = ( color & 0x001F ) >> 3; 302 | imageData[ ( x + width * y ) * 4 + 3 ] = ( color & 0x8000 ) ? 0 : 255; 303 | 304 | } 305 | 306 | } 307 | 308 | return imageData; 309 | 310 | } 311 | 312 | function tgaGetImageData24bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { 313 | 314 | var i = 0, x, y; 315 | var width = header.width; 316 | 317 | for ( y = y_start; y !== y_end; y += y_step ) { 318 | 319 | for ( x = x_start; x !== x_end; x += x_step, i += 3 ) { 320 | 321 | imageData[ ( x + width * y ) * 4 + 3 ] = 255; 322 | imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; 323 | imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ]; 324 | imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ]; 325 | 326 | } 327 | 328 | } 329 | 330 | return imageData; 331 | 332 | } 333 | 334 | function tgaGetImageData32bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { 335 | 336 | var i = 0, x, y; 337 | var width = header.width; 338 | 339 | for ( y = y_start; y !== y_end; y += y_step ) { 340 | 341 | for ( x = x_start; x !== x_end; x += x_step, i += 4 ) { 342 | 343 | imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; 344 | imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ]; 345 | imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ]; 346 | imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 3 ]; 347 | 348 | } 349 | 350 | } 351 | 352 | return imageData; 353 | 354 | } 355 | 356 | function tgaGetImageDataGrey8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { 357 | 358 | var color, i = 0, x, y; 359 | var width = header.width; 360 | 361 | for ( y = y_start; y !== y_end; y += y_step ) { 362 | 363 | for ( x = x_start; x !== x_end; x += x_step, i ++ ) { 364 | 365 | color = image[ i ]; 366 | imageData[ ( x + width * y ) * 4 + 0 ] = color; 367 | imageData[ ( x + width * y ) * 4 + 1 ] = color; 368 | imageData[ ( x + width * y ) * 4 + 2 ] = color; 369 | imageData[ ( x + width * y ) * 4 + 3 ] = 255; 370 | 371 | } 372 | 373 | } 374 | 375 | return imageData; 376 | 377 | } 378 | 379 | function tgaGetImageDataGrey16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { 380 | 381 | var i = 0, x, y; 382 | var width = header.width; 383 | 384 | for ( y = y_start; y !== y_end; y += y_step ) { 385 | 386 | for ( x = x_start; x !== x_end; x += x_step, i += 2 ) { 387 | 388 | imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 0 ]; 389 | imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 0 ]; 390 | imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; 391 | imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 1 ]; 392 | 393 | } 394 | 395 | } 396 | 397 | return imageData; 398 | 399 | } 400 | 401 | function getTgaRGBA( data, width, height, image, palette ) { 402 | 403 | var x_start, 404 | y_start, 405 | x_step, 406 | y_step, 407 | x_end, 408 | y_end; 409 | 410 | switch ( ( header.flags & TGA_ORIGIN_MASK ) >> TGA_ORIGIN_SHIFT ) { 411 | default: 412 | case TGA_ORIGIN_UL: 413 | x_start = 0; 414 | x_step = 1; 415 | x_end = width; 416 | y_start = 0; 417 | y_step = 1; 418 | y_end = height; 419 | break; 420 | 421 | case TGA_ORIGIN_BL: 422 | x_start = 0; 423 | x_step = 1; 424 | x_end = width; 425 | y_start = height - 1; 426 | y_step = - 1; 427 | y_end = - 1; 428 | break; 429 | 430 | case TGA_ORIGIN_UR: 431 | x_start = width - 1; 432 | x_step = - 1; 433 | x_end = - 1; 434 | y_start = 0; 435 | y_step = 1; 436 | y_end = height; 437 | break; 438 | 439 | case TGA_ORIGIN_BR: 440 | x_start = width - 1; 441 | x_step = - 1; 442 | x_end = - 1; 443 | y_start = height - 1; 444 | y_step = - 1; 445 | y_end = - 1; 446 | break; 447 | 448 | } 449 | 450 | if ( use_grey ) { 451 | 452 | switch ( header.pixel_size ) { 453 | case 8: 454 | tgaGetImageDataGrey8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); 455 | break; 456 | case 16: 457 | tgaGetImageDataGrey16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); 458 | break; 459 | default: 460 | console.error( 'THREE.TGALoader.parse.getTgaRGBA: not support this format' ); 461 | break; 462 | } 463 | 464 | } else { 465 | 466 | switch ( header.pixel_size ) { 467 | case 8: 468 | tgaGetImageData8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image, palette ); 469 | break; 470 | 471 | case 16: 472 | tgaGetImageData16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); 473 | break; 474 | 475 | case 24: 476 | tgaGetImageData24bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); 477 | break; 478 | 479 | case 32: 480 | tgaGetImageData32bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); 481 | break; 482 | 483 | default: 484 | console.error( 'THREE.TGALoader.parse.getTgaRGBA: not support this format' ); 485 | break; 486 | } 487 | 488 | } 489 | 490 | // Load image data according to specific method 491 | // var func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; 492 | // func(data, y_start, y_step, y_end, x_start, x_step, x_end, width, image, palette ); 493 | return data; 494 | 495 | } 496 | 497 | var canvas = document.createElement( 'canvas' ); 498 | canvas.width = header.width; 499 | canvas.height = header.height; 500 | 501 | var context = canvas.getContext( '2d' ); 502 | var imageData = context.createImageData( header.width, header.height ); 503 | 504 | var result = tgaParse( use_rle, use_pal, header, offset, content ); 505 | var rgbaData = getTgaRGBA( imageData.data, header.width, header.height, result.pixel_data, result.palettes ); 506 | 507 | context.putImageData( imageData, 0, 0 ); 508 | 509 | return canvas; 510 | 511 | }; 512 | 513 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ar-2017", 3 | "version": "1.0.0", 4 | "description": "AR demo on 2017 new year ", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/codefalling/ar-2017.git" 12 | }, 13 | "keywords": [ 14 | "AR" 15 | ], 16 | "author": "codefalling", 17 | "license": "ISC", 18 | "bugs": { 19 | "url": "https://github.com/codefalling/ar-2017/issues" 20 | }, 21 | "homepage": "https://github.com/codefalling/ar-2017#readme", 22 | "devDependencies": { 23 | "babel-core": "^6.21.0", 24 | "babel-preset-es2015": "^6.18.0", 25 | "eruda": "^1.2.0", 26 | "webpack": "^2.2.0-rc.3", 27 | "webpack-node-externals": "^1.5.4" 28 | }, 29 | "dependencies": { 30 | "ammo": "^2.0.3", 31 | "babel-loader": "^6.2.10", 32 | "babel-polyfill": "^6.20.0", 33 | "mmd-parser": "^1.0.3" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /play.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | AR 2017 Player 4 | 5 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /res/phone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xcodebuild/ar-demo-mobile-browser/4c29f707a2b7904d490a81710ba263aeebe82624/res/phone.png -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xcodebuild/ar-demo-mobile-browser/4c29f707a2b7904d490a81710ba263aeebe82624/screenshot.png -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* global THREE */ 2 | /* global AR */ 3 | /* global POS */ 4 | 5 | import '../lib/MMDLoader.js'; 6 | import 'babel-polyfill'; 7 | 8 | // THREE.MMDLoader = MMDLoader; 9 | 10 | const oldOnload = window.onload; 11 | 12 | window.onload = function() { 13 | 14 | oldOnload && oldOnload(); 15 | 16 | function videoDimensions(video) { 17 | // Ratio of the video's intrisic dimensions 18 | const videoRatio = video.videoWidth / video.videoHeight; 19 | // The width and height of the video element 20 | let width = video.offsetWidth; 21 | let height = video.offsetHeight; 22 | // The ratio of the element's width to its height 23 | const elementRatio = width / height; 24 | // If the video element is short and wide 25 | if(elementRatio > videoRatio) width = height * videoRatio; 26 | // It must be tall and thin, or exactly equal to the original ratio 27 | else height = width / videoRatio; 28 | return { 29 | width: width, 30 | height: height 31 | }; 32 | } 33 | 34 | class JsArucoMarker { 35 | constructor() { 36 | this.canvasElement = document.createElement('canvas'); 37 | this.context = this.canvasElement.getContext('2d'); 38 | this.videoScaleDown = 2; 39 | this.modelSize = 15.0; // mm 40 | } 41 | 42 | detectMarkers(videoElement) { 43 | const {context, videoScaleDown, canvasElement} = this; 44 | // if no new image for videoElement do nothing 45 | if (videoElement.readyState !== videoElement.HAVE_ENOUGH_DATA){ 46 | return []; 47 | } 48 | canvasElement.width = videoElement.videoWidth / videoScaleDown; 49 | canvasElement.height = videoElement.videoHeight / videoScaleDown; 50 | 51 | context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height); 52 | const imageData = context.getImageData(0, 0, canvasElement.width, canvasElement.height); 53 | 54 | // detect markers 55 | const detector = new AR.Detector(); 56 | const markers = detector.detect(imageData); 57 | 58 | // return the result 59 | return markers; 60 | } 61 | 62 | markerToObject3D(marker, object3d, videoElement) { 63 | const {canvasElement} = this; 64 | // convert corners coordinate - not sure why 65 | // marker.corners; 66 | const corners = []; 67 | for (const corner of marker.corners){ 68 | corners.push({ 69 | x : corner.x - (canvasElement.width / 2), 70 | y : (canvasElement.height / 2) - corner.y, 71 | }); 72 | } 73 | // compute the pose from the canvas 74 | const posit = new POS.Posit(this.modelSize, canvasElement.width); 75 | const pose = posit.pose(corners); 76 | 77 | if( pose === null ) return; 78 | 79 | // Translate pose to THREE.Object3D 80 | const rotation = pose.bestRotation; 81 | const translation = pose.bestTranslation; 82 | 83 | let scaleDownX = 1; 84 | let scaleDownY = 1; 85 | const realSize = videoDimensions(videoElement); 86 | scaleDownX = videoElement.videoWidth / realSize.width; 87 | scaleDownY = videoElement.videoHeight / realSize.height; 88 | 89 | object3d.scale.x = this.modelSize / scaleDownX; 90 | object3d.scale.y = this.modelSize / scaleDownY; 91 | object3d.scale.z = this.modelSize / ((scaleDownX + scaleDownY) / 2); 92 | 93 | object3d.rotation.x = -Math.asin(-rotation[1][2]); 94 | object3d.rotation.y = -Math.atan2(rotation[0][2], rotation[2][2]); 95 | object3d.rotation.z = Math.atan2(rotation[1][0], rotation[1][1]); 96 | 97 | object3d.position.x = translation[0] / scaleDownX; 98 | object3d.position.y = translation[1] / scaleDownY; 99 | object3d.position.z = -translation[2]; 100 | } 101 | } 102 | 103 | // shim 104 | navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; 105 | window.URL = window.URL || window.webkitURL; 106 | 107 | function webcamGrabbing() { 108 | // create video element 109 | const domElement = document.createElement('video'); 110 | domElement.setAttribute('autoplay', true); 111 | 112 | domElement.style.zIndex = -1; 113 | domElement.style.position = 'absolute'; 114 | domElement.style.top = '0px'; 115 | domElement.style.left = '0px'; 116 | domElement.style.width = '100%'; 117 | domElement.style.height = '100%'; 118 | 119 | // get the media sources 120 | MediaStreamTrack.getSources(sourceInfos => { 121 | // define getUserMedia() constraints 122 | const constraints = { 123 | video: true, 124 | audio: false, 125 | }; 126 | // to mirror the video element when it isnt 'environment' 127 | 128 | // it it finds the videoSource 'environment', modify constraints.video 129 | for (const sourceInfo of sourceInfos) { 130 | if(sourceInfo.kind == 'video' && sourceInfo.facing == 'environment') { 131 | constraints.video = { 132 | optional: [{sourceId: sourceInfo.id}] 133 | }; 134 | } 135 | } 136 | 137 | // try to get user media 138 | navigator.getUserMedia( constraints, function(stream){ 139 | domElement.src = URL.createObjectURL(stream); 140 | }, error => { 141 | alert('Cant getUserMedia()! due to ', error); 142 | }); 143 | }); 144 | 145 | return domElement; 146 | } 147 | 148 | // play 149 | const renderer = new THREE.WebGLRenderer({ 150 | antialias : true, 151 | alpha : true, 152 | }); 153 | renderer.setSize( window.innerWidth, window.innerHeight ); 154 | document.body.appendChild(renderer.domElement); 155 | 156 | 157 | // array of functions for the rendering loop 158 | let onRenderFcts = []; 159 | 160 | // init scene and camera 161 | const scene = new THREE.Scene(); 162 | const camera = new THREE.PerspectiveCamera(37, window.innerWidth / window.innerHeight, 0.01, 1000); 163 | camera.position.z = 0; 164 | 165 | let markerObject3D = new THREE.Object3D(); 166 | scene.add(markerObject3D); 167 | 168 | // set 3 point lighting 169 | let object3d = new THREE.AmbientLight(0x101010); 170 | object3d.name = 'Ambient light'; 171 | scene.add(object3d); 172 | 173 | object3d = new THREE.DirectionalLight('white', 0.1*1.6); 174 | object3d.position.set(2.6,1,3).setLength(1); 175 | object3d.name = 'Back light'; 176 | scene.add(object3d); 177 | 178 | object3d = new THREE.DirectionalLight('white', 0.375*1.6); 179 | object3d.position.set(-2, -1, 0); 180 | object3d.name = 'Key light'; 181 | scene.add(object3d); 182 | 183 | object3d = new THREE.DirectionalLight('white', 0.8*1); 184 | object3d.position.set(3, 3, 2); 185 | object3d.name = 'Fill light'; 186 | scene.add(object3d); 187 | 188 | function makePhongMaterials ( materials ) { 189 | const array = []; 190 | for (const material of materials){ 191 | const m = new THREE.MeshPhongMaterial(); 192 | m.copy(material); 193 | m.needsUpdate = true; 194 | array.push( m ); 195 | } 196 | return new THREE.MultiMaterial( array ); 197 | } 198 | 199 | const onProgress = xhr => { 200 | if ( xhr.lengthComputable ) { 201 | var percentComplete = xhr.loaded / xhr.total * 100; 202 | console.log( Math.round(percentComplete, 2) + '% downloaded' ); 203 | } 204 | }; 205 | 206 | const onError = () => { 207 | alert('Download Model Error'); 208 | }; 209 | 210 | const modelFile = 'https://cdn.rawgit.com/mrdoob/three.js/dev/examples/models/mmd/miku/miku_v2.pmd'; 211 | const vmdFiles = [ 'https://cdn.rawgit.com/mrdoob/three.js/dev/examples/models/mmd/vmds/wavefile_v2.vmd' ]; 212 | 213 | const helper = new THREE.MMDHelper(); 214 | const loader = new THREE.MMDLoader(); 215 | loader.load( modelFile, vmdFiles, function (object) { 216 | const mesh = object; 217 | mesh.scale.set(1,1,1).multiplyScalar(1/35); 218 | mesh.rotation.x = Math.PI/2; 219 | mesh.material = makePhongMaterials(mesh.material.materials); 220 | 221 | markerObject3D.add( mesh ); 222 | 223 | // scene.add(mesh); 224 | for (const material of mesh.material.materials) { 225 | material.emissive.multiplyScalar(1); 226 | } 227 | helper.add(mesh); 228 | helper.setAnimation(mesh); 229 | 230 | onRenderFcts.push(function(now, delta){ 231 | helper.animate(delta/1000); 232 | }); 233 | 234 | // /* 235 | // * Note: create CCDIKHelper after calling helper.setAnimation() 236 | // */ 237 | const ikHelper = new THREE.CCDIKHelper( mesh ); 238 | ikHelper.visible = false; 239 | scene.add(ikHelper); 240 | }, onProgress, onError ); 241 | 242 | // handle window resize 243 | window.addEventListener('resize', () => { 244 | renderer.setSize(window.innerWidth, window.innerHeight); 245 | camera.aspect = window.innerWidth / window.innerHeight; 246 | camera.updateProjectionMatrix(); 247 | }, false); 248 | 249 | 250 | // render the scene 251 | onRenderFcts.push(() => { 252 | renderer.render( scene, camera ); 253 | }); 254 | 255 | // run the rendering loop 256 | let previousTime = performance.now(); 257 | requestAnimationFrame(function animate(now){ 258 | requestAnimationFrame( animate ); 259 | onRenderFcts.forEach(function(onRenderFct){ 260 | onRenderFct(now, now - previousTime); 261 | }); 262 | previousTime = now; 263 | }); 264 | 265 | // init the marker recognition 266 | const jsArucoMarker = new JsArucoMarker(); 267 | 268 | // const videoGrabbing = new THREEx.WebcamGrabbing() 269 | const domElement = webcamGrabbing(); 270 | 271 | document.body.appendChild(domElement); 272 | 273 | // process the image source with the marker recognition 274 | function reMark(){ 275 | const markers = jsArucoMarker.detectMarkers(domElement); 276 | const object3d = markerObject3D; 277 | 278 | object3d.visible = false; 279 | // see if this.markerId has been found 280 | markers.forEach(function(marker){ 281 | jsArucoMarker.markerToObject3D(marker, object3d, domElement); 282 | object3d.visible = true; 283 | }); 284 | } 285 | 286 | onRenderFcts.push(reMark); 287 | }; 288 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | .container { 2 | background: #cf3a3f; 3 | height: 100%; 4 | width: 100%; 5 | position: absolute; 6 | } 7 | 8 | .container.white { 9 | background: white; 10 | } 11 | 12 | body { 13 | margin: 0px; 14 | overflow: hidden; 15 | text-align: center; 16 | } 17 | 18 | .btn { 19 | background: #eecc90; 20 | color: #514f4c; 21 | padding: 18px 40px; 22 | display: block; 23 | margin: 15% 8% 15% 8%; 24 | text-decoration: none; 25 | border-radius: 5px; 26 | font-size: 18px; 27 | } 28 | 29 | .title { 30 | color: #b82c31; 31 | font-size: 50px; 32 | margin: 12% 0 12% 0; 33 | } 34 | 35 | .title.red { 36 | color: #cf3a3f; 37 | } 38 | 39 | .footer { 40 | color: #c3acac; 41 | font-size: 15px; 42 | position: absolute; 43 | right: 15px; 44 | bottom: 15px; 45 | } 46 | 47 | @media screen and (min-width: 800px) { 48 | .container { 49 | max-width: 326px; 50 | max-height: 560px; 51 | } 52 | .phone { 53 | background: url(./res/phone.png) no-repeat; 54 | background-size: contain; 55 | padding: 100px 12px; 56 | min-width: 325px; 57 | display: inline-block; 58 | width: 325px; 59 | height: 700px; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /vendor/js-aruco/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 Juan Mellado 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | 22 | ArUco 23 | ==== 24 | BSD License 25 | 26 | 27 | OpenCV 28 | ====== 29 | IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. 30 | 31 | By downloading, copying, installing or using the software you agree to this license. 32 | If you do not agree to this license, do not download, install, 33 | copy or use the software. 34 | 35 | 36 | License Agreement 37 | For Open Source Computer Vision Library 38 | 39 | Copyright (C) 2000-2008, Intel Corporation, all rights reserved. 40 | Copyright (C) 2009, Willow Garage Inc., all rights reserved. 41 | Third party copyrights are property of their respective owners. 42 | 43 | Redistribution and use in source and binary forms, with or without modification, 44 | are permitted provided that the following conditions are met: 45 | 46 | * Redistribution's of source code must retain the above copyright notice, 47 | this list of conditions and the following disclaimer. 48 | 49 | * Redistribution's in binary form must reproduce the above copyright notice, 50 | this list of conditions and the following disclaimer in the documentation 51 | and/or other materials provided with the distribution. 52 | 53 | * The name of the copyright holders may not be used to endorse or promote products 54 | derived from this software without specific prior written permission. 55 | 56 | This software is provided by the copyright holders and contributors "as is" and 57 | any express or implied warranties, including, but not limited to, the implied 58 | warranties of merchantability and fitness for a particular purpose are disclaimed. 59 | In no event shall the Intel Corporation or contributors be liable for any direct, 60 | indirect, incidental, special, exemplary, or consequential damages 61 | (including, but not limited to, procurement of substitute goods or services; 62 | loss of use, data, or profits; or business interruption) however caused 63 | and on any theory of liability, whether in contract, strict liability, 64 | or tort (including negligence or otherwise) arising in any way out of 65 | the use of this software, even if advised of the possibility of such damage. 66 | 67 | 68 | AForge.NET 69 | ======== 70 | GNU LESSER GENERAL PUBLIC LICENSE 71 | 72 | Version 3, 29 June 2007 73 | 74 | Copyright � 2007 Free Software Foundation, Inc. 75 | 76 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 77 | 78 | This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 79 | 80 | 0. Additional Definitions. 81 | As used herein, �this License� refers to version 3 of the GNU Lesser General Public License, and the �GNU GPL� refers to version 3 of the GNU General Public License. 82 | 83 | �The Library� refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. 84 | 85 | An �Application� is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. 86 | 87 | A �Combined Work� is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the �Linked Version�. 88 | 89 | The �Minimal Corresponding Source� for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. 90 | 91 | The �Corresponding Application Code� for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 92 | 93 | 1. Exception to Section 3 of the GNU GPL. 94 | You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 95 | 96 | 2. Conveying Modified Versions. 97 | If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: 98 | 99 | a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or 100 | b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 101 | 3. Object Code Incorporating Material from Library Header Files. 102 | The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: 103 | 104 | a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. 105 | b) Accompany the object code with a copy of the GNU GPL and this license document. 106 | 4. Combined Works. 107 | You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: 108 | 109 | a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. 110 | b) Accompany the Combined Work with a copy of the GNU GPL and this license document. 111 | c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. 112 | d) Do one of the following: 113 | 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 114 | 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. 115 | e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 116 | 5. Combined Libraries. 117 | You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: 118 | 119 | a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. 120 | b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 121 | 6. Revised Versions of the GNU Lesser General Public License. 122 | The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 123 | 124 | Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License �or any later version� applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. 125 | 126 | If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. 127 | 128 | 129 | StackBoxBlur 130 | ========== 131 | Copyright (c) 2010 Mario Klingemann 132 | 133 | Permission is hereby granted, free of charge, to any person 134 | obtaining a copy of this software and associated documentation 135 | files (the "Software"), to deal in the Software without 136 | restriction, including without limitation the rights to use, 137 | copy, modify, merge, publish, distribute, sublicense, and/or sell 138 | copies of the Software, and to permit persons to whom the 139 | Software is furnished to do so, subject to the following 140 | conditions: 141 | 142 | The above copyright notice and this permission notice shall be 143 | included in all copies or substantial portions of the Software. 144 | 145 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 146 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 147 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 148 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 149 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 150 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 151 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 152 | OTHER DEALINGS IN THE SOFTWARE. 153 | -------------------------------------------------------------------------------- /vendor/js-aruco/aruco.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2011 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "ArUco: a minimal library for Augmented Reality applications based on OpenCv" 26 | http://www.uco.es/investiga/grupos/ava/node/26 27 | */ 28 | 29 | var AR = AR || {}; 30 | 31 | AR.Marker = function(id, corners){ 32 | this.id = id; 33 | this.corners = corners; 34 | }; 35 | 36 | AR.Detector = function(){ 37 | this.grey = new CV.Image(); 38 | this.thres = new CV.Image(); 39 | this.homography = new CV.Image(); 40 | this.binary = []; 41 | this.contours = []; 42 | this.polys = []; 43 | this.candidates = []; 44 | }; 45 | 46 | AR.Detector.prototype.detect = function(image){ 47 | CV.grayscale(image, this.grey); 48 | CV.adaptiveThreshold(this.grey, this.thres, 2, 7); 49 | 50 | this.contours = CV.findContours(this.thres, this.binary); 51 | 52 | this.candidates = this.findCandidates(this.contours, image.width * 0.20, 0.05, 10); 53 | this.candidates = this.clockwiseCorners(this.candidates); 54 | this.candidates = this.notTooNear(this.candidates, 10); 55 | 56 | return this.findMarkers(this.grey, this.candidates, 49); 57 | }; 58 | 59 | AR.Detector.prototype.findCandidates = function(contours, minSize, epsilon, minLength){ 60 | var candidates = [], len = contours.length, contour, poly, i; 61 | 62 | this.polys = []; 63 | 64 | for (i = 0; i < len; ++ i){ 65 | contour = contours[i]; 66 | 67 | if (contour.length >= minSize){ 68 | poly = CV.approxPolyDP(contour, contour.length * epsilon); 69 | 70 | this.polys.push(poly); 71 | 72 | if ( (4 === poly.length) && ( CV.isContourConvex(poly) ) ){ 73 | 74 | if ( CV.minEdgeLength(poly) >= minLength){ 75 | candidates.push(poly); 76 | } 77 | } 78 | } 79 | } 80 | 81 | return candidates; 82 | }; 83 | 84 | AR.Detector.prototype.clockwiseCorners = function(candidates){ 85 | var len = candidates.length, dx1, dx2, dy1, dy2, swap, i; 86 | 87 | for (i = 0; i < len; ++ i){ 88 | dx1 = candidates[i][1].x - candidates[i][0].x; 89 | dy1 = candidates[i][1].y - candidates[i][0].y; 90 | dx2 = candidates[i][2].x - candidates[i][0].x; 91 | dy2 = candidates[i][2].y - candidates[i][0].y; 92 | 93 | if ( (dx1 * dy2 - dy1 * dx2) < 0){ 94 | swap = candidates[i][1]; 95 | candidates[i][1] = candidates[i][3]; 96 | candidates[i][3] = swap; 97 | } 98 | } 99 | 100 | return candidates; 101 | }; 102 | 103 | AR.Detector.prototype.notTooNear = function(candidates, minDist){ 104 | var notTooNear = [], len = candidates.length, dist, dx, dy, i, j, k; 105 | 106 | for (i = 0; i < len; ++ i){ 107 | 108 | for (j = i + 1; j < len; ++ j){ 109 | dist = 0; 110 | 111 | for (k = 0; k < 4; ++ k){ 112 | dx = candidates[i][k].x - candidates[j][k].x; 113 | dy = candidates[i][k].y - candidates[j][k].y; 114 | 115 | dist += dx * dx + dy * dy; 116 | } 117 | 118 | if ( (dist / 4) < (minDist * minDist) ){ 119 | 120 | if ( CV.perimeter( candidates[i] ) < CV.perimeter( candidates[j] ) ){ 121 | candidates[i].tooNear = true; 122 | }else{ 123 | candidates[j].tooNear = true; 124 | } 125 | } 126 | } 127 | } 128 | 129 | for (i = 0; i < len; ++ i){ 130 | if ( !candidates[i].tooNear ){ 131 | notTooNear.push( candidates[i] ); 132 | } 133 | } 134 | 135 | return notTooNear; 136 | }; 137 | 138 | AR.Detector.prototype.findMarkers = function(imageSrc, candidates, warpSize){ 139 | var markers = [], len = candidates.length, candidate, marker, i; 140 | 141 | for (i = 0; i < len; ++ i){ 142 | candidate = candidates[i]; 143 | 144 | CV.warp(imageSrc, this.homography, candidate, warpSize); 145 | 146 | CV.threshold(this.homography, this.homography, CV.otsu(this.homography) ); 147 | 148 | marker = this.getMarker(this.homography, candidate); 149 | if (marker){ 150 | markers.push(marker); 151 | } 152 | } 153 | 154 | return markers; 155 | }; 156 | 157 | AR.Detector.prototype.getMarker = function(imageSrc, candidate){ 158 | var width = (imageSrc.width / 7) >>> 0, 159 | minZero = (width * width) >> 1, 160 | bits = [], rotations = [], distances = [], 161 | square, pair, inc, i, j; 162 | 163 | for (i = 0; i < 7; ++ i){ 164 | inc = (0 === i || 6 === i)? 1: 6; 165 | 166 | for (j = 0; j < 7; j += inc){ 167 | square = {x: j * width, y: i * width, width: width, height: width}; 168 | if ( CV.countNonZero(imageSrc, square) > minZero){ 169 | return null; 170 | } 171 | } 172 | } 173 | 174 | for (i = 0; i < 5; ++ i){ 175 | bits[i] = []; 176 | 177 | for (j = 0; j < 5; ++ j){ 178 | square = {x: (j + 1) * width, y: (i + 1) * width, width: width, height: width}; 179 | 180 | bits[i][j] = CV.countNonZero(imageSrc, square) > minZero? 1: 0; 181 | } 182 | } 183 | 184 | rotations[0] = bits; 185 | distances[0] = this.hammingDistance( rotations[0] ); 186 | 187 | pair = {first: distances[0], second: 0}; 188 | 189 | for (i = 1; i < 4; ++ i){ 190 | rotations[i] = this.rotate( rotations[i - 1] ); 191 | distances[i] = this.hammingDistance( rotations[i] ); 192 | 193 | if (distances[i] < pair.first){ 194 | pair.first = distances[i]; 195 | pair.second = i; 196 | } 197 | } 198 | 199 | if (0 !== pair.first){ 200 | return null; 201 | } 202 | 203 | return new AR.Marker( 204 | this.mat2id( rotations[pair.second] ), 205 | this.rotate2(candidate, 4 - pair.second) ); 206 | }; 207 | 208 | AR.Detector.prototype.hammingDistance = function(bits){ 209 | var ids = [ [1,0,0,0,0], [1,0,1,1,1], [0,1,0,0,1], [0,1,1,1,0] ], 210 | dist = 0, sum, minSum, i, j, k; 211 | 212 | for (i = 0; i < 5; ++ i){ 213 | minSum = Infinity; 214 | 215 | for (j = 0; j < 4; ++ j){ 216 | sum = 0; 217 | 218 | for (k = 0; k < 5; ++ k){ 219 | sum += bits[i][k] === ids[j][k]? 0: 1; 220 | } 221 | 222 | if (sum < minSum){ 223 | minSum = sum; 224 | } 225 | } 226 | 227 | dist += minSum; 228 | } 229 | 230 | return dist; 231 | }; 232 | 233 | AR.Detector.prototype.mat2id = function(bits){ 234 | var id = 0, i; 235 | 236 | for (i = 0; i < 5; ++ i){ 237 | id <<= 1; 238 | id |= bits[i][1]; 239 | id <<= 1; 240 | id |= bits[i][3]; 241 | } 242 | 243 | return id; 244 | }; 245 | 246 | AR.Detector.prototype.rotate = function(src){ 247 | var dst = [], len = src.length, i, j; 248 | 249 | for (i = 0; i < len; ++ i){ 250 | dst[i] = []; 251 | for (j = 0; j < src[i].length; ++ j){ 252 | dst[i][j] = src[src[i].length - j - 1][i]; 253 | } 254 | } 255 | 256 | return dst; 257 | }; 258 | 259 | AR.Detector.prototype.rotate2 = function(src, rotation){ 260 | var dst = [], len = src.length, i; 261 | 262 | for (i = 0; i < len; ++ i){ 263 | dst[i] = src[ (rotation + i) % len ]; 264 | } 265 | 266 | return dst; 267 | }; 268 | -------------------------------------------------------------------------------- /vendor/js-aruco/cv.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2011 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "OpenCV: Open Computer Vision Library" 26 | http://sourceforge.net/projects/opencvlibrary/ 27 | - "Stack Blur: Fast But Goodlooking" 28 | http://incubator.quasimondo.com/processing/fast_blur_deluxe.php 29 | */ 30 | 31 | var CV = CV || {}; 32 | 33 | CV.Image = function(width, height, data){ 34 | this.width = width || 0; 35 | this.height = height || 0; 36 | this.data = data || []; 37 | }; 38 | 39 | CV.grayscale = function(imageSrc, imageDst){ 40 | var src = imageSrc.data, dst = imageDst.data, len = src.length, 41 | i = 0, j = 0; 42 | 43 | for (; i < len; i += 4){ 44 | dst[j ++] = 45 | (src[i] * 0.299 + src[i + 1] * 0.587 + src[i + 2] * 0.114 + 0.5) & 0xff; 46 | } 47 | 48 | imageDst.width = imageSrc.width; 49 | imageDst.height = imageSrc.height; 50 | 51 | return imageDst; 52 | }; 53 | 54 | CV.threshold = function(imageSrc, imageDst, threshold){ 55 | var src = imageSrc.data, dst = imageDst.data, 56 | len = src.length, tab = [], i; 57 | 58 | for (i = 0; i < 256; ++ i){ 59 | tab[i] = i <= threshold? 0: 255; 60 | } 61 | 62 | for (i = 0; i < len; ++ i){ 63 | dst[i] = tab[ src[i] ]; 64 | } 65 | 66 | imageDst.width = imageSrc.width; 67 | imageDst.height = imageSrc.height; 68 | 69 | return imageDst; 70 | }; 71 | 72 | CV.adaptiveThreshold = function(imageSrc, imageDst, kernelSize, threshold){ 73 | var src = imageSrc.data, dst = imageDst.data, len = src.length, tab = [], i; 74 | 75 | CV.stackBoxBlur(imageSrc, imageDst, kernelSize); 76 | 77 | for (i = 0; i < 768; ++ i){ 78 | tab[i] = (i - 255 <= -threshold)? 255: 0; 79 | } 80 | 81 | for (i = 0; i < len; ++ i){ 82 | dst[i] = tab[ src[i] - dst[i] + 255 ]; 83 | } 84 | 85 | imageDst.width = imageSrc.width; 86 | imageDst.height = imageSrc.height; 87 | 88 | return imageDst; 89 | }; 90 | 91 | CV.otsu = function(imageSrc){ 92 | var src = imageSrc.data, len = src.length, hist = [], 93 | threshold = 0, sum = 0, sumB = 0, wB = 0, wF = 0, max = 0, 94 | mu, between, i; 95 | 96 | for (i = 0; i < 256; ++ i){ 97 | hist[i] = 0; 98 | } 99 | 100 | for (i = 0; i < len; ++ i){ 101 | hist[ src[i] ] ++; 102 | } 103 | 104 | for (i = 0; i < 256; ++ i){ 105 | sum += hist[i] * i; 106 | } 107 | 108 | for (i = 0; i < 256; ++ i){ 109 | wB += hist[i]; 110 | if (0 !== wB){ 111 | 112 | wF = len - wB; 113 | if (0 === wF){ 114 | break; 115 | } 116 | 117 | sumB += hist[i] * i; 118 | 119 | mu = (sumB / wB) - ( (sum - sumB) / wF ); 120 | 121 | between = wB * wF * mu * mu; 122 | 123 | if (between > max){ 124 | max = between; 125 | threshold = i; 126 | } 127 | } 128 | } 129 | 130 | return threshold; 131 | }; 132 | 133 | CV.stackBoxBlurMult = 134 | [1, 171, 205, 293, 57, 373, 79, 137, 241, 27, 391, 357, 41, 19, 283, 265]; 135 | 136 | CV.stackBoxBlurShift = 137 | [0, 9, 10, 11, 9, 12, 10, 11, 12, 9, 13, 13, 10, 9, 13, 13]; 138 | 139 | CV.BlurStack = function(){ 140 | this.color = 0; 141 | this.next = null; 142 | }; 143 | 144 | CV.stackBoxBlur = function(imageSrc, imageDst, kernelSize){ 145 | var src = imageSrc.data, dst = imageDst.data, 146 | height = imageSrc.height, width = imageSrc.width, 147 | heightMinus1 = height - 1, widthMinus1 = width - 1, 148 | size = kernelSize + kernelSize + 1, radius = kernelSize + 1, 149 | mult = CV.stackBoxBlurMult[kernelSize], 150 | shift = CV.stackBoxBlurShift[kernelSize], 151 | stack, stackStart, color, sum, pos, start, p, x, y, i; 152 | 153 | stack = stackStart = new CV.BlurStack(); 154 | for (i = 1; i < size; ++ i){ 155 | stack = stack.next = new CV.BlurStack(); 156 | } 157 | stack.next = stackStart; 158 | 159 | pos = 0; 160 | 161 | for (y = 0; y < height; ++ y){ 162 | start = pos; 163 | 164 | color = src[pos]; 165 | sum = radius * color; 166 | 167 | stack = stackStart; 168 | for (i = 0; i < radius; ++ i){ 169 | stack.color = color; 170 | stack = stack.next; 171 | } 172 | for (i = 1; i < radius; ++ i){ 173 | stack.color = src[pos + i]; 174 | sum += stack.color; 175 | stack = stack.next; 176 | } 177 | 178 | stack = stackStart; 179 | for (x = 0; x < width; ++ x){ 180 | dst[pos ++] = (sum * mult) >>> shift; 181 | 182 | p = x + radius; 183 | p = start + (p < widthMinus1? p: widthMinus1); 184 | sum -= stack.color - src[p]; 185 | 186 | stack.color = src[p]; 187 | stack = stack.next; 188 | } 189 | } 190 | 191 | for (x = 0; x < width; ++ x){ 192 | pos = x; 193 | start = pos + width; 194 | 195 | color = dst[pos]; 196 | sum = radius * color; 197 | 198 | stack = stackStart; 199 | for (i = 0; i < radius; ++ i){ 200 | stack.color = color; 201 | stack = stack.next; 202 | } 203 | for (i = 1; i < radius; ++ i){ 204 | stack.color = dst[start]; 205 | sum += stack.color; 206 | stack = stack.next; 207 | 208 | start += width; 209 | } 210 | 211 | stack = stackStart; 212 | for (y = 0; y < height; ++ y){ 213 | dst[pos] = (sum * mult) >>> shift; 214 | 215 | p = y + radius; 216 | p = x + ( (p < heightMinus1? p: heightMinus1) * width ); 217 | sum -= stack.color - dst[p]; 218 | 219 | stack.color = dst[p]; 220 | stack = stack.next; 221 | 222 | pos += width; 223 | } 224 | } 225 | 226 | return imageDst; 227 | }; 228 | 229 | CV.gaussianBlur = function(imageSrc, imageDst, imageMean, kernelSize){ 230 | var kernel = CV.gaussianKernel(kernelSize); 231 | 232 | imageDst.width = imageSrc.width; 233 | imageDst.height = imageSrc.height; 234 | 235 | imageMean.width = imageSrc.width; 236 | imageMean.height = imageSrc.height; 237 | 238 | CV.gaussianBlurFilter(imageSrc, imageMean, kernel, true); 239 | CV.gaussianBlurFilter(imageMean, imageDst, kernel, false); 240 | 241 | return imageDst; 242 | }; 243 | 244 | CV.gaussianBlurFilter = function(imageSrc, imageDst, kernel, horizontal){ 245 | var src = imageSrc.data, dst = imageDst.data, 246 | height = imageSrc.height, width = imageSrc.width, 247 | pos = 0, limit = kernel.length >> 1, 248 | cur, value, i, j, k; 249 | 250 | for (i = 0; i < height; ++ i){ 251 | 252 | for (j = 0; j < width; ++ j){ 253 | value = 0.0; 254 | 255 | for (k = -limit; k <= limit; ++ k){ 256 | 257 | if (horizontal){ 258 | cur = pos + k; 259 | if (j + k < 0){ 260 | cur = pos; 261 | } 262 | else if (j + k >= width){ 263 | cur = pos; 264 | } 265 | }else{ 266 | cur = pos + (k * width); 267 | if (i + k < 0){ 268 | cur = pos; 269 | } 270 | else if (i + k >= height){ 271 | cur = pos; 272 | } 273 | } 274 | 275 | value += kernel[limit + k] * src[cur]; 276 | } 277 | 278 | dst[pos ++] = horizontal? value: (value + 0.5) & 0xff; 279 | } 280 | } 281 | 282 | return imageDst; 283 | }; 284 | 285 | CV.gaussianKernel = function(kernelSize){ 286 | var tab = 287 | [ [1], 288 | [0.25, 0.5, 0.25], 289 | [0.0625, 0.25, 0.375, 0.25, 0.0625], 290 | [0.03125, 0.109375, 0.21875, 0.28125, 0.21875, 0.109375, 0.03125] ], 291 | kernel = [], center, sigma, scale2X, sum, x, i; 292 | 293 | if ( (kernelSize <= 7) && (kernelSize % 2 === 1) ){ 294 | kernel = tab[kernelSize >> 1]; 295 | }else{ 296 | center = (kernelSize - 1.0) * 0.5; 297 | sigma = 0.8 + (0.3 * (center - 1.0) ); 298 | scale2X = -0.5 / (sigma * sigma); 299 | sum = 0.0; 300 | for (i = 0; i < kernelSize; ++ i){ 301 | x = i - center; 302 | sum += kernel[i] = Math.exp(scale2X * x * x); 303 | } 304 | sum = 1 / sum; 305 | for (i = 0; i < kernelSize; ++ i){ 306 | kernel[i] *= sum; 307 | } 308 | } 309 | 310 | return kernel; 311 | }; 312 | 313 | CV.findContours = function(imageSrc, binary){ 314 | var width = imageSrc.width, height = imageSrc.height, contours = [], 315 | src, deltas, pos, pix, nbd, outer, hole, i, j; 316 | 317 | src = CV.binaryBorder(imageSrc, binary); 318 | 319 | deltas = CV.neighborhoodDeltas(width + 2); 320 | 321 | pos = width + 3; 322 | nbd = 1; 323 | 324 | for (i = 0; i < height; ++ i, pos += 2){ 325 | 326 | for (j = 0; j < width; ++ j, ++ pos){ 327 | pix = src[pos]; 328 | 329 | if (0 !== pix){ 330 | outer = hole = false; 331 | 332 | if (1 === pix && 0 === src[pos - 1]){ 333 | outer = true; 334 | } 335 | else if (pix >= 1 && 0 === src[pos + 1]){ 336 | hole = true; 337 | } 338 | 339 | if (outer || hole){ 340 | ++ nbd; 341 | 342 | contours.push( CV.borderFollowing(src, pos, nbd, {x: j, y: i}, hole, deltas) ); 343 | } 344 | } 345 | } 346 | } 347 | 348 | return contours; 349 | }; 350 | 351 | CV.borderFollowing = function(src, pos, nbd, point, hole, deltas){ 352 | var contour = [], pos1, pos3, pos4, s, s_end, s_prev; 353 | 354 | contour.hole = hole; 355 | 356 | s = s_end = hole? 0: 4; 357 | do{ 358 | s = (s - 1) & 7; 359 | pos1 = pos + deltas[s]; 360 | if (src[pos1] !== 0){ 361 | break; 362 | } 363 | }while(s !== s_end); 364 | 365 | if (s === s_end){ 366 | src[pos] = -nbd; 367 | contour.push( {x: point.x, y: point.y} ); 368 | 369 | }else{ 370 | pos3 = pos; 371 | s_prev = s ^ 4; 372 | 373 | while(true){ 374 | s_end = s; 375 | 376 | do{ 377 | pos4 = pos3 + deltas[++ s]; 378 | }while(src[pos4] === 0); 379 | 380 | s &= 7; 381 | 382 | if ( ( (s - 1) >>> 0) < (s_end >>> 0) ){ 383 | src[pos3] = -nbd; 384 | } 385 | else if (src[pos3] === 1){ 386 | src[pos3] = nbd; 387 | } 388 | 389 | contour.push( {x: point.x, y: point.y} ); 390 | 391 | s_prev = s; 392 | 393 | point.x += CV.neighborhood[s][0]; 394 | point.y += CV.neighborhood[s][1]; 395 | 396 | if ( (pos4 === pos) && (pos3 === pos1) ){ 397 | break; 398 | } 399 | 400 | pos3 = pos4; 401 | s = (s + 4) & 7; 402 | } 403 | } 404 | 405 | return contour; 406 | }; 407 | 408 | CV.neighborhood = 409 | [ [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1] ]; 410 | 411 | CV.neighborhoodDeltas = function(width){ 412 | var deltas = [], len = CV.neighborhood.length, i = 0; 413 | 414 | for (; i < len; ++ i){ 415 | deltas[i] = CV.neighborhood[i][0] + (CV.neighborhood[i][1] * width); 416 | } 417 | 418 | return deltas.concat(deltas); 419 | }; 420 | 421 | CV.approxPolyDP = function(contour, epsilon){ 422 | var slice = {start_index: 0, end_index: 0}, 423 | right_slice = {start_index: 0, end_index: 0}, 424 | poly = [], stack = [], len = contour.length, 425 | pt, start_pt, end_pt, dist, max_dist, le_eps, 426 | dx, dy, i, j, k; 427 | 428 | epsilon *= epsilon; 429 | 430 | k = 0; 431 | 432 | for (i = 0; i < 3; ++ i){ 433 | max_dist = 0; 434 | 435 | k = (k + right_slice.start_index) % len; 436 | start_pt = contour[k]; 437 | if (++ k === len) {k = 0;} 438 | 439 | for (j = 1; j < len; ++ j){ 440 | pt = contour[k]; 441 | if (++ k === len) {k = 0;} 442 | 443 | dx = pt.x - start_pt.x; 444 | dy = pt.y - start_pt.y; 445 | dist = dx * dx + dy * dy; 446 | 447 | if (dist > max_dist){ 448 | max_dist = dist; 449 | right_slice.start_index = j; 450 | } 451 | } 452 | } 453 | 454 | if (max_dist <= epsilon){ 455 | poly.push( {x: start_pt.x, y: start_pt.y} ); 456 | 457 | }else{ 458 | slice.start_index = k; 459 | slice.end_index = (right_slice.start_index += slice.start_index); 460 | 461 | right_slice.start_index -= right_slice.start_index >= len? len: 0; 462 | right_slice.end_index = slice.start_index; 463 | if (right_slice.end_index < right_slice.start_index){ 464 | right_slice.end_index += len; 465 | } 466 | 467 | stack.push( {start_index: right_slice.start_index, end_index: right_slice.end_index} ); 468 | stack.push( {start_index: slice.start_index, end_index: slice.end_index} ); 469 | } 470 | 471 | while(stack.length !== 0){ 472 | slice = stack.pop(); 473 | 474 | end_pt = contour[slice.end_index % len]; 475 | start_pt = contour[k = slice.start_index % len]; 476 | if (++ k === len) {k = 0;} 477 | 478 | if (slice.end_index <= slice.start_index + 1){ 479 | le_eps = true; 480 | 481 | }else{ 482 | max_dist = 0; 483 | 484 | dx = end_pt.x - start_pt.x; 485 | dy = end_pt.y - start_pt.y; 486 | 487 | for (i = slice.start_index + 1; i < slice.end_index; ++ i){ 488 | pt = contour[k]; 489 | if (++ k === len) {k = 0;} 490 | 491 | dist = Math.abs( (pt.y - start_pt.y) * dx - (pt.x - start_pt.x) * dy); 492 | 493 | if (dist > max_dist){ 494 | max_dist = dist; 495 | right_slice.start_index = i; 496 | } 497 | } 498 | 499 | le_eps = max_dist * max_dist <= epsilon * (dx * dx + dy * dy); 500 | } 501 | 502 | if (le_eps){ 503 | poly.push( {x: start_pt.x, y: start_pt.y} ); 504 | 505 | }else{ 506 | right_slice.end_index = slice.end_index; 507 | slice.end_index = right_slice.start_index; 508 | 509 | stack.push( {start_index: right_slice.start_index, end_index: right_slice.end_index} ); 510 | stack.push( {start_index: slice.start_index, end_index: slice.end_index} ); 511 | } 512 | } 513 | 514 | return poly; 515 | }; 516 | 517 | CV.warp = function(imageSrc, imageDst, contour, warpSize){ 518 | var src = imageSrc.data, dst = imageDst.data, 519 | width = imageSrc.width, height = imageSrc.height, 520 | pos = 0, 521 | sx1, sx2, dx1, dx2, sy1, sy2, dy1, dy2, p1, p2, p3, p4, 522 | m, r, s, t, u, v, w, x, y, i, j; 523 | 524 | m = CV.getPerspectiveTransform(contour, warpSize - 1); 525 | 526 | r = m[8]; 527 | s = m[2]; 528 | t = m[5]; 529 | 530 | for (i = 0; i < warpSize; ++ i){ 531 | r += m[7]; 532 | s += m[1]; 533 | t += m[4]; 534 | 535 | u = r; 536 | v = s; 537 | w = t; 538 | 539 | for (j = 0; j < warpSize; ++ j){ 540 | u += m[6]; 541 | v += m[0]; 542 | w += m[3]; 543 | 544 | x = v / u; 545 | y = w / u; 546 | 547 | sx1 = x >>> 0; 548 | sx2 = (sx1 === width - 1)? sx1: sx1 + 1; 549 | dx1 = x - sx1; 550 | dx2 = 1.0 - dx1; 551 | 552 | sy1 = y >>> 0; 553 | sy2 = (sy1 === height - 1)? sy1: sy1 + 1; 554 | dy1 = y - sy1; 555 | dy2 = 1.0 - dy1; 556 | 557 | p1 = p2 = sy1 * width; 558 | p3 = p4 = sy2 * width; 559 | 560 | dst[pos ++] = 561 | (dy2 * (dx2 * src[p1 + sx1] + dx1 * src[p2 + sx2]) + 562 | dy1 * (dx2 * src[p3 + sx1] + dx1 * src[p4 + sx2]) ) & 0xff; 563 | 564 | } 565 | } 566 | 567 | imageDst.width = warpSize; 568 | imageDst.height = warpSize; 569 | 570 | return imageDst; 571 | }; 572 | 573 | CV.getPerspectiveTransform = function(src, size){ 574 | var rq = CV.square2quad(src); 575 | 576 | rq[0] /= size; 577 | rq[1] /= size; 578 | rq[3] /= size; 579 | rq[4] /= size; 580 | rq[6] /= size; 581 | rq[7] /= size; 582 | 583 | return rq; 584 | }; 585 | 586 | CV.square2quad = function(src){ 587 | var sq = [], px, py, dx1, dx2, dy1, dy2, den; 588 | 589 | px = src[0].x - src[1].x + src[2].x - src[3].x; 590 | py = src[0].y - src[1].y + src[2].y - src[3].y; 591 | 592 | if (0 === px && 0 === py){ 593 | sq[0] = src[1].x - src[0].x; 594 | sq[1] = src[2].x - src[1].x; 595 | sq[2] = src[0].x; 596 | sq[3] = src[1].y - src[0].y; 597 | sq[4] = src[2].y - src[1].y; 598 | sq[5] = src[0].y; 599 | sq[6] = 0; 600 | sq[7] = 0; 601 | sq[8] = 1; 602 | 603 | }else{ 604 | dx1 = src[1].x - src[2].x; 605 | dx2 = src[3].x - src[2].x; 606 | dy1 = src[1].y - src[2].y; 607 | dy2 = src[3].y - src[2].y; 608 | den = dx1 * dy2 - dx2 * dy1; 609 | 610 | sq[6] = (px * dy2 - dx2 * py) / den; 611 | sq[7] = (dx1 * py - px * dy1) / den; 612 | sq[8] = 1; 613 | sq[0] = src[1].x - src[0].x + sq[6] * src[1].x; 614 | sq[1] = src[3].x - src[0].x + sq[7] * src[3].x; 615 | sq[2] = src[0].x; 616 | sq[3] = src[1].y - src[0].y + sq[6] * src[1].y; 617 | sq[4] = src[3].y - src[0].y + sq[7] * src[3].y; 618 | sq[5] = src[0].y; 619 | } 620 | 621 | return sq; 622 | }; 623 | 624 | CV.isContourConvex = function(contour){ 625 | var orientation = 0, convex = true, 626 | len = contour.length, i = 0, j = 0, 627 | cur_pt, prev_pt, dxdy0, dydx0, dx0, dy0, dx, dy; 628 | 629 | prev_pt = contour[len - 1]; 630 | cur_pt = contour[0]; 631 | 632 | dx0 = cur_pt.x - prev_pt.x; 633 | dy0 = cur_pt.y - prev_pt.y; 634 | 635 | for (; i < len; ++ i){ 636 | if (++ j === len) {j = 0;} 637 | 638 | prev_pt = cur_pt; 639 | cur_pt = contour[j]; 640 | 641 | dx = cur_pt.x - prev_pt.x; 642 | dy = cur_pt.y - prev_pt.y; 643 | dxdy0 = dx * dy0; 644 | dydx0 = dy * dx0; 645 | 646 | orientation |= dydx0 > dxdy0? 1: (dydx0 < dxdy0? 2: 3); 647 | 648 | if (3 === orientation){ 649 | convex = false; 650 | break; 651 | } 652 | 653 | dx0 = dx; 654 | dy0 = dy; 655 | } 656 | 657 | return convex; 658 | }; 659 | 660 | CV.perimeter = function(poly){ 661 | var len = poly.length, i = 0, j = len - 1, 662 | p = 0.0, dx, dy; 663 | 664 | for (; i < len; j = i ++){ 665 | dx = poly[i].x - poly[j].x; 666 | dy = poly[i].y - poly[j].y; 667 | 668 | p += Math.sqrt(dx * dx + dy * dy) ; 669 | } 670 | 671 | return p; 672 | }; 673 | 674 | CV.minEdgeLength = function(poly){ 675 | var len = poly.length, i = 0, j = len - 1, 676 | min = Infinity, d, dx, dy; 677 | 678 | for (; i < len; j = i ++){ 679 | dx = poly[i].x - poly[j].x; 680 | dy = poly[i].y - poly[j].y; 681 | 682 | d = dx * dx + dy * dy; 683 | 684 | if (d < min){ 685 | min = d; 686 | } 687 | } 688 | 689 | return Math.sqrt(min); 690 | }; 691 | 692 | CV.countNonZero = function(imageSrc, square){ 693 | var src = imageSrc.data, height = square.height, width = square.width, 694 | pos = square.x + (square.y * imageSrc.width), 695 | span = imageSrc.width - width, 696 | nz = 0, i, j; 697 | 698 | for (i = 0; i < height; ++ i){ 699 | 700 | for (j = 0; j < width; ++ j){ 701 | 702 | if ( 0 !== src[pos ++] ){ 703 | ++ nz; 704 | } 705 | } 706 | 707 | pos += span; 708 | } 709 | 710 | return nz; 711 | }; 712 | 713 | CV.binaryBorder = function(imageSrc, dst){ 714 | var src = imageSrc.data, height = imageSrc.height, width = imageSrc.width, 715 | posSrc = 0, posDst = 0, i, j; 716 | 717 | for (j = -2; j < width; ++ j){ 718 | dst[posDst ++] = 0; 719 | } 720 | 721 | for (i = 0; i < height; ++ i){ 722 | dst[posDst ++] = 0; 723 | 724 | for (j = 0; j < width; ++ j){ 725 | dst[posDst ++] = (0 === src[posSrc ++]? 0: 1); 726 | } 727 | 728 | dst[posDst ++] = 0; 729 | } 730 | 731 | for (j = -2; j < width; ++ j){ 732 | dst[posDst ++] = 0; 733 | } 734 | 735 | return dst; 736 | }; 737 | -------------------------------------------------------------------------------- /vendor/js-aruco/posit1-patched.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "Iterative Pose Estimation using Coplanar Feature Points" 26 | Denis Oberkampf, Daniel F. DeMenthon, Larry S. Davis 27 | http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/CoplanarPts.pdf 28 | */ 29 | 30 | var POS = POS || {}; 31 | 32 | POS.Posit = function(modelSize, focalLength){ 33 | this.objectPoints = this.buildModel(modelSize); 34 | this.focalLength = focalLength; 35 | 36 | this.objectVectors = []; 37 | this.objectNormal = []; 38 | this.objectMatrix = [[],[],[]]; 39 | 40 | this.init(); 41 | }; 42 | 43 | POS.Posit.prototype.buildModel = function(modelSize){ 44 | var half = modelSize / 2.0; 45 | 46 | return [ 47 | [-half, half, 0.0], 48 | [ half, half, 0.0], 49 | [ half, -half, 0.0], 50 | [-half, -half, 0.0] ]; 51 | }; 52 | 53 | POS.Posit.prototype.init = function(){ 54 | var np = this.objectPoints.length, 55 | vectors = [], n = [], len = 0.0, row = 2, i; 56 | 57 | for (i = 0; i < np; ++ i){ 58 | this.objectVectors[i] = [this.objectPoints[i][0] - this.objectPoints[0][0], 59 | this.objectPoints[i][1] - this.objectPoints[0][1], 60 | this.objectPoints[i][2] - this.objectPoints[0][2]]; 61 | 62 | vectors[i] = [this.objectVectors[i][0], 63 | this.objectVectors[i][1], 64 | this.objectVectors[i][2]]; 65 | } 66 | 67 | while(0.0 === len){ 68 | n[0] = this.objectVectors[1][1] * this.objectVectors[row][2] - 69 | this.objectVectors[1][2] * this.objectVectors[row][1]; 70 | n[1] = this.objectVectors[1][2] * this.objectVectors[row][0] - 71 | this.objectVectors[1][0] * this.objectVectors[row][2]; 72 | n[2] = this.objectVectors[1][0] * this.objectVectors[row][1] - 73 | this.objectVectors[1][1] * this.objectVectors[row][0]; 74 | 75 | len = Math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); 76 | 77 | ++ row; 78 | } 79 | 80 | for (i = 0; i < 3; ++ i){ 81 | this.objectNormal[i] = n[i] / len; 82 | } 83 | 84 | POS.pseudoInverse(vectors, np, this.objectMatrix); 85 | }; 86 | 87 | POS.Posit.prototype.pose = function(imagePoints){ 88 | var posRotation1 = [[],[],[]], posRotation2 = [[],[],[]], posTranslation = [], 89 | rotation1 = [[],[],[]], rotation2 = [[],[],[]], translation1 = [], translation2 = [], 90 | error1, error2, valid1, valid2, i, j; 91 | 92 | this.pos(imagePoints, posRotation1, posRotation2, posTranslation); 93 | 94 | valid1 = this.isValid(posRotation1, posTranslation); 95 | if (valid1){ 96 | error1 = this.iterate(imagePoints, posRotation1, posTranslation, rotation1, translation1); 97 | // console.assert(error1) 98 | }else{ 99 | error1 = {euclidean: -1.0, pixels: -1, maximum: -1.0}; 100 | } 101 | 102 | valid2 = this.isValid(posRotation2, posTranslation); 103 | if (valid2){ 104 | error2 = this.iterate(imagePoints, posRotation2, posTranslation, rotation2, translation2); 105 | // console.assert(error2) 106 | }else{ 107 | error2 = {euclidean: -1.0, pixels: -1, maximum: -1.0}; 108 | } 109 | 110 | for (i = 0; i < 3; ++ i){ 111 | for (j = 0; j < 3; ++ j){ 112 | if (valid1){ 113 | translation1[i] -= rotation1[i][j] * this.objectPoints[0][j]; 114 | } 115 | if (valid2){ 116 | translation2[i] -= rotation2[i][j] * this.objectPoints[0][j]; 117 | } 118 | } 119 | } 120 | 121 | // @jeromeetienne patch 122 | if( error1 === undefined || error2 === undefined ) return null 123 | 124 | return error1.euclidean < error2.euclidean? 125 | new POS.Pose(error1.pixels, rotation1, translation1, error2.pixels, rotation2, translation2): 126 | new POS.Pose(error2.pixels, rotation2, translation2, error1.pixels, rotation1, translation1); 127 | }; 128 | 129 | POS.Posit.prototype.pos = function(imagePoints, rotation1, rotation2, translation){ 130 | var np = this.objectPoints.length, imageVectors = [], 131 | i0 = [], j0 = [], ivec = [], jvec = [], row1 = [], row2 = [], row3 = [], 132 | i0i0, j0j0, i0j0, delta, q, lambda, mu, scale, i, j; 133 | 134 | for (i = 0; i < np; ++ i){ 135 | imageVectors[i] = [imagePoints[i].x - imagePoints[0].x, 136 | imagePoints[i].y - imagePoints[0].y]; 137 | } 138 | 139 | //i0 and j0 140 | for (i = 0; i < 3; ++ i){ 141 | i0[i] = 0.0; 142 | j0[i] = 0.0; 143 | for (j = 0; j < np; ++ j){ 144 | i0[i] += this.objectMatrix[i][j] * imageVectors[j][0]; 145 | j0[i] += this.objectMatrix[i][j] * imageVectors[j][1]; 146 | } 147 | } 148 | 149 | i0i0 = i0[0] * i0[0] + i0[1] * i0[1] + i0[2] * i0[2]; 150 | j0j0 = j0[0] * j0[0] + j0[1] * j0[1] + j0[2] * j0[2]; 151 | i0j0 = i0[0] * j0[0] + i0[1] * j0[1] + i0[2] * j0[2]; 152 | 153 | //Lambda and mu 154 | delta = (j0j0 - i0i0) * (j0j0 - i0i0) + 4.0 * (i0j0 * i0j0); 155 | 156 | if (j0j0 - i0i0 >= 0.0){ 157 | q = (j0j0 - i0i0 + Math.sqrt(delta) ) / 2.0; 158 | }else{ 159 | q = (j0j0 - i0i0 - Math.sqrt(delta) ) / 2.0; 160 | } 161 | 162 | if (q >= 0.0){ 163 | lambda = Math.sqrt(q); 164 | if (0.0 === lambda){ 165 | mu = 0.0; 166 | }else{ 167 | mu = -i0j0 / lambda; 168 | } 169 | }else{ 170 | lambda = Math.sqrt( -(i0j0 * i0j0) / q); 171 | if (0.0 === lambda){ 172 | mu = Math.sqrt(i0i0 - j0j0); 173 | }else{ 174 | mu = -i0j0 / lambda; 175 | } 176 | } 177 | 178 | //First rotation 179 | for (i = 0; i < 3; ++ i){ 180 | ivec[i] = i0[i] + lambda * this.objectNormal[i]; 181 | jvec[i] = j0[i] + mu * this.objectNormal[i]; 182 | } 183 | 184 | scale = Math.sqrt(ivec[0] * ivec[0] + ivec[1] * ivec[1] + ivec[2] * ivec[2]); 185 | 186 | for (i = 0; i < 3; ++ i){ 187 | row1[i] = ivec[i] / scale; 188 | row2[i] = jvec[i] / scale; 189 | } 190 | 191 | row3[0] = row1[1] * row2[2] - row1[2] * row2[1]; 192 | row3[1] = row1[2] * row2[0] - row1[0] * row2[2]; 193 | row3[2] = row1[0] * row2[1] - row1[1] * row2[0]; 194 | 195 | for (i = 0; i < 3; ++ i){ 196 | rotation1[0][i] = row1[i]; 197 | rotation1[1][i] = row2[i]; 198 | rotation1[2][i] = row3[i]; 199 | } 200 | 201 | //Second rotation 202 | for (i = 0; i < 3; ++ i){ 203 | ivec[i] = i0[i] - lambda * this.objectNormal[i]; 204 | jvec[i] = j0[i] - mu * this.objectNormal[i]; 205 | } 206 | 207 | for (i = 0; i < 3; ++ i){ 208 | row1[i] = ivec[i] / scale; 209 | row2[i] = jvec[i] / scale; 210 | } 211 | 212 | row3[0] = row1[1] * row2[2] - row1[2] * row2[1]; 213 | row3[1] = row1[2] * row2[0] - row1[0] * row2[2]; 214 | row3[2] = row1[0] * row2[1] - row1[1] * row2[0]; 215 | 216 | for (i = 0; i < 3; ++ i){ 217 | rotation2[0][i] = row1[i]; 218 | rotation2[1][i] = row2[i]; 219 | rotation2[2][i] = row3[i]; 220 | } 221 | 222 | //Translation 223 | translation[0] = imagePoints[0].x / scale; 224 | translation[1] = imagePoints[0].y / scale; 225 | translation[2] = this.focalLength / scale; 226 | }; 227 | 228 | POS.Posit.prototype.isValid = function(rotation, translation){ 229 | var np = this.objectPoints.length, zmin = Infinity, i = 0, zi; 230 | 231 | for (; i < np; ++ i){ 232 | zi = translation[2] + 233 | (rotation[2][0] * this.objectVectors[i][0] + 234 | rotation[2][1] * this.objectVectors[i][1] + 235 | rotation[2][2] * this.objectVectors[i][2]); 236 | if (zi < zmin){ 237 | zmin = zi; 238 | } 239 | } 240 | 241 | return zmin >= 0.0; 242 | }; 243 | 244 | POS.Posit.prototype.iterate = function(imagePoints, posRotation, posTranslation, rotation, translation){ 245 | var np = this.objectPoints.length, 246 | oldSopImagePoints = [], sopImagePoints = [], 247 | rotation1 = [[],[],[]], rotation2 = [[],[],[]], 248 | translation1 = [], translation2 = [], 249 | converged = false, iteration = 0, 250 | oldImageDifference, imageDifference, factor, 251 | error, error1, error2, delta, i, j; 252 | 253 | for (i = 0; i < np; ++ i){ 254 | oldSopImagePoints[i] = {x: imagePoints[i].x, 255 | y: imagePoints[i].y}; 256 | } 257 | 258 | for (i = 0; i < 3; ++ i){ 259 | for (j = 0; j < 3; ++ j){ 260 | rotation[i][j] = posRotation[i][j]; 261 | } 262 | translation[i] = posTranslation[i]; 263 | } 264 | 265 | for (i = 0; i < np; ++ i){ 266 | factor = 0.0; 267 | for (j = 0; j < 3; ++ j){ 268 | factor += this.objectVectors[i][j] * rotation[2][j] / translation[2]; 269 | } 270 | sopImagePoints[i] = {x: (1.0 + factor) * imagePoints[i].x, 271 | y: (1.0 + factor) * imagePoints[i].y}; 272 | } 273 | 274 | imageDifference = 0.0; 275 | 276 | for (i = 0; i < np; ++ i){ 277 | imageDifference += Math.abs(sopImagePoints[i].x - oldSopImagePoints[i].x); 278 | imageDifference += Math.abs(sopImagePoints[i].y - oldSopImagePoints[i].y); 279 | } 280 | 281 | for (i = 0; i < 3; ++ i){ 282 | translation1[i] = translation[i] - 283 | (rotation[i][0] * this.objectPoints[0][0] + 284 | rotation[i][1] * this.objectPoints[0][1] + 285 | rotation[i][2] * this.objectPoints[0][2]); 286 | } 287 | 288 | error1 = this.error(imagePoints, rotation, translation1); 289 | 290 | //Convergence 291 | converged = (0.0 === error1.pixels) || (imageDifference < 0.01); 292 | 293 | while( iteration ++ < 100 && !converged ){ 294 | 295 | for (i = 0; i < np; ++ i){ 296 | oldSopImagePoints[i].x = sopImagePoints[i].x; 297 | oldSopImagePoints[i].y = sopImagePoints[i].y; 298 | } 299 | 300 | this.pos(sopImagePoints, rotation1, rotation2, translation); 301 | 302 | for (i = 0; i < 3; ++ i){ 303 | translation1[i] = translation[i] - 304 | (rotation1[i][0] * this.objectPoints[0][0] + 305 | rotation1[i][1] * this.objectPoints[0][1] + 306 | rotation1[i][2] * this.objectPoints[0][2]); 307 | 308 | translation2[i] = translation[i] - 309 | (rotation2[i][0] * this.objectPoints[0][0] + 310 | rotation2[i][1] * this.objectPoints[0][1] + 311 | rotation2[i][2] * this.objectPoints[0][2]); 312 | } 313 | 314 | error1 = this.error(imagePoints, rotation1, translation1); 315 | error2 = this.error(imagePoints, rotation2, translation2); 316 | 317 | if ( (error1.euclidean >= 0.0) && (error2.euclidean >= 0.0) ){ 318 | if (error2.euclidean < error1.euclidean){ 319 | error = error2; 320 | for (i = 0; i < 3; ++ i){ 321 | for (j = 0; j < 3; ++ j){ 322 | rotation[i][j] = rotation2[i][j]; 323 | } 324 | } 325 | }else{ 326 | error = error1; 327 | for (i = 0; i < 3; ++ i){ 328 | for (j = 0; j < 3; ++ j){ 329 | rotation[i][j] = rotation1[i][j]; 330 | } 331 | } 332 | } 333 | } 334 | 335 | if ( (error1.euclidean < 0.0) && (error2.euclidean >= 0.0) ){ 336 | error = error2; 337 | for (i = 0; i < 3; ++ i){ 338 | for (j = 0; j < 3; ++ j){ 339 | rotation[i][j] = rotation2[i][j]; 340 | } 341 | } 342 | } 343 | 344 | if ( (error2.euclidean < 0.0) && (error1.euclidean >= 0.0) ){ 345 | error = error1; 346 | for (i = 0; i < 3; ++ i){ 347 | for (j = 0; j < 3; ++ j){ 348 | rotation[i][j] = rotation1[i][j]; 349 | } 350 | } 351 | } 352 | 353 | for (i = 0; i < np; ++ i){ 354 | factor = 0.0; 355 | for (j = 0; j < 3; ++ j){ 356 | factor += this.objectVectors[i][j] * rotation[2][j] / translation[2]; 357 | } 358 | sopImagePoints[i].x = (1.0 + factor) * imagePoints[i].x; 359 | sopImagePoints[i].y = (1.0 + factor) * imagePoints[i].y; 360 | } 361 | 362 | oldImageDifference = imageDifference; 363 | imageDifference = 0.0; 364 | 365 | for (i = 0; i < np; ++ i){ 366 | imageDifference += Math.abs(sopImagePoints[i].x - oldSopImagePoints[i].x); 367 | imageDifference += Math.abs(sopImagePoints[i].y - oldSopImagePoints[i].y); 368 | } 369 | 370 | delta = Math.abs(imageDifference - oldImageDifference); 371 | 372 | converged = (0.0 === error.pixels) || (delta < 0.01); 373 | } 374 | 375 | return error; 376 | }; 377 | 378 | POS.Posit.prototype.error = function(imagePoints, rotation, translation){ 379 | var np = this.objectPoints.length, 380 | move = [], projection = [], errorvec = [], 381 | euclidean = 0.0, pixels = 0.0, maximum = 0.0, 382 | i, j, k; 383 | 384 | if ( !this.isValid(rotation, translation) ){ 385 | return {euclidean: -1.0, pixels: -1, maximum: -1.0}; 386 | } 387 | 388 | for (i = 0; i < np; ++ i){ 389 | move[i] = []; 390 | for (j = 0; j < 3; ++ j){ 391 | move[i][j] = translation[j]; 392 | } 393 | } 394 | 395 | for (i = 0; i < np; ++ i){ 396 | for (j = 0; j < 3; ++ j){ 397 | for (k = 0; k < 3; ++ k){ 398 | move[i][j] += rotation[j][k] * this.objectPoints[i][k]; 399 | } 400 | } 401 | } 402 | 403 | for (i = 0; i < np; ++ i){ 404 | projection[i] = []; 405 | for (j = 0; j < 2; ++ j){ 406 | projection[i][j] = this.focalLength * move[i][j] / move[i][2]; 407 | } 408 | } 409 | 410 | for (i = 0; i < np; ++ i){ 411 | errorvec[i] = [projection[i][0] - imagePoints[i].x, 412 | projection[i][1] - imagePoints[i].y]; 413 | } 414 | 415 | for (i = 0; i < np; ++ i){ 416 | euclidean += Math.sqrt(errorvec[i][0] * errorvec[i][0] + 417 | errorvec[i][1] * errorvec[i][1]); 418 | 419 | pixels += Math.abs( Math.round(projection[i][0]) - Math.round(imagePoints[i].x) ) + 420 | Math.abs( Math.round(projection[i][1]) - Math.round(imagePoints[i].y) ); 421 | 422 | if (Math.abs(errorvec[i][0]) > maximum){ 423 | maximum = Math.abs(errorvec[i][0]); 424 | } 425 | if (Math.abs(errorvec[i][1]) > maximum){ 426 | maximum = Math.abs(errorvec[i][1]); 427 | } 428 | } 429 | 430 | return {euclidean: euclidean / np, pixels: pixels, maximum: maximum}; 431 | }; 432 | 433 | POS.pseudoInverse = function(a, n, b){ 434 | var w = [], v = [[],[],[]], s = [[],[],[]], 435 | wmax = 0.0, cn = 0, 436 | i, j, k; 437 | 438 | SVD.svdcmp(a, n, 3, w, v); 439 | 440 | for (i = 0; i < 3; ++ i){ 441 | if (w[i] > wmax){ 442 | wmax = w[i]; 443 | } 444 | } 445 | 446 | wmax *= 0.01; 447 | 448 | for (i = 0; i < 3; ++ i){ 449 | if (w[i] < wmax){ 450 | w[i] = 0.0; 451 | } 452 | } 453 | 454 | for (j = 0; j < 3; ++ j){ 455 | if (0.0 === w[j]){ 456 | ++ cn; 457 | for (k = j; k < 2; ++ k){ 458 | for (i = 0; i < n; ++ i){ 459 | a[i][k] = a[i][k + 1]; 460 | } 461 | for (i = 0; i < 3; ++ i){ 462 | v[i][k] = v[i][k + 1]; 463 | } 464 | } 465 | } 466 | } 467 | 468 | for (j = 0; j < 2; ++ j){ 469 | if (0.0 === w[j]){ 470 | w[j] = w[j + 1]; 471 | } 472 | } 473 | 474 | for (i = 0; i < 3; ++ i){ 475 | for (j = 0; j < 3 - cn; ++ j){ 476 | s[i][j] = v[i][j] / w[j]; 477 | } 478 | } 479 | 480 | for (i = 0; i < 3; ++ i){ 481 | for (j = 0; j < n; ++ j){ 482 | b[i][j] = 0.0; 483 | for (k = 0; k < 3 - cn; ++ k){ 484 | b[i][j] += s[i][k] * a[j][k]; 485 | } 486 | } 487 | } 488 | }; 489 | 490 | POS.Pose = function(error1, rotation1, translation1, error2, rotation2, translation2){ 491 | this.bestError = error1; 492 | this.bestRotation = rotation1; 493 | this.bestTranslation = translation1; 494 | this.alternativeError = error2; 495 | this.alternativeRotation = rotation2; 496 | this.alternativeTranslation = translation2; 497 | }; 498 | -------------------------------------------------------------------------------- /vendor/js-aruco/posit1.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "Iterative Pose Estimation using Coplanar Feature Points" 26 | Denis Oberkampf, Daniel F. DeMenthon, Larry S. Davis 27 | http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/CoplanarPts.pdf 28 | */ 29 | 30 | var POS = POS || {}; 31 | 32 | POS.Posit = function(modelSize, focalLength){ 33 | this.objectPoints = this.buildModel(modelSize); 34 | this.focalLength = focalLength; 35 | 36 | this.objectVectors = []; 37 | this.objectNormal = []; 38 | this.objectMatrix = [[],[],[]]; 39 | 40 | this.init(); 41 | }; 42 | 43 | POS.Posit.prototype.buildModel = function(modelSize){ 44 | var half = modelSize / 2.0; 45 | 46 | return [ 47 | [-half, half, 0.0], 48 | [ half, half, 0.0], 49 | [ half, -half, 0.0], 50 | [-half, -half, 0.0] ]; 51 | }; 52 | 53 | POS.Posit.prototype.init = function(){ 54 | var np = this.objectPoints.length, 55 | vectors = [], n = [], len = 0.0, row = 2, i; 56 | 57 | for (i = 0; i < np; ++ i){ 58 | this.objectVectors[i] = [this.objectPoints[i][0] - this.objectPoints[0][0], 59 | this.objectPoints[i][1] - this.objectPoints[0][1], 60 | this.objectPoints[i][2] - this.objectPoints[0][2]]; 61 | 62 | vectors[i] = [this.objectVectors[i][0], 63 | this.objectVectors[i][1], 64 | this.objectVectors[i][2]]; 65 | } 66 | 67 | while(0.0 === len){ 68 | n[0] = this.objectVectors[1][1] * this.objectVectors[row][2] - 69 | this.objectVectors[1][2] * this.objectVectors[row][1]; 70 | n[1] = this.objectVectors[1][2] * this.objectVectors[row][0] - 71 | this.objectVectors[1][0] * this.objectVectors[row][2]; 72 | n[2] = this.objectVectors[1][0] * this.objectVectors[row][1] - 73 | this.objectVectors[1][1] * this.objectVectors[row][0]; 74 | 75 | len = Math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); 76 | 77 | ++ row; 78 | } 79 | 80 | for (i = 0; i < 3; ++ i){ 81 | this.objectNormal[i] = n[i] / len; 82 | } 83 | 84 | POS.pseudoInverse(vectors, np, this.objectMatrix); 85 | }; 86 | 87 | POS.Posit.prototype.pose = function(imagePoints){ 88 | var posRotation1 = [[],[],[]], posRotation2 = [[],[],[]], posTranslation = [], 89 | rotation1 = [[],[],[]], rotation2 = [[],[],[]], translation1 = [], translation2 = [], 90 | error1, error2, valid1, valid2, i, j; 91 | 92 | this.pos(imagePoints, posRotation1, posRotation2, posTranslation); 93 | 94 | valid1 = this.isValid(posRotation1, posTranslation); 95 | if (valid1){ 96 | error1 = this.iterate(imagePoints, posRotation1, posTranslation, rotation1, translation1); 97 | }else{ 98 | error1 = {euclidean: -1.0, pixels: -1, maximum: -1.0}; 99 | } 100 | 101 | valid2 = this.isValid(posRotation2, posTranslation); 102 | if (valid2){ 103 | error2 = this.iterate(imagePoints, posRotation2, posTranslation, rotation2, translation2); 104 | }else{ 105 | error2 = {euclidean: -1.0, pixels: -1, maximum: -1.0}; 106 | } 107 | 108 | for (i = 0; i < 3; ++ i){ 109 | for (j = 0; j < 3; ++ j){ 110 | if (valid1){ 111 | translation1[i] -= rotation1[i][j] * this.objectPoints[0][j]; 112 | } 113 | if (valid2){ 114 | translation2[i] -= rotation2[i][j] * this.objectPoints[0][j]; 115 | } 116 | } 117 | } 118 | 119 | return error1.euclidean < error2.euclidean? 120 | new POS.Pose(error1.pixels, rotation1, translation1, error2.pixels, rotation2, translation2): 121 | new POS.Pose(error2.pixels, rotation2, translation2, error1.pixels, rotation1, translation1); 122 | }; 123 | 124 | POS.Posit.prototype.pos = function(imagePoints, rotation1, rotation2, translation){ 125 | var np = this.objectPoints.length, imageVectors = [], 126 | i0 = [], j0 = [], ivec = [], jvec = [], row1 = [], row2 = [], row3 = [], 127 | i0i0, j0j0, i0j0, delta, q, lambda, mu, scale, i, j; 128 | 129 | for (i = 0; i < np; ++ i){ 130 | imageVectors[i] = [imagePoints[i].x - imagePoints[0].x, 131 | imagePoints[i].y - imagePoints[0].y]; 132 | } 133 | 134 | //i0 and j0 135 | for (i = 0; i < 3; ++ i){ 136 | i0[i] = 0.0; 137 | j0[i] = 0.0; 138 | for (j = 0; j < np; ++ j){ 139 | i0[i] += this.objectMatrix[i][j] * imageVectors[j][0]; 140 | j0[i] += this.objectMatrix[i][j] * imageVectors[j][1]; 141 | } 142 | } 143 | 144 | i0i0 = i0[0] * i0[0] + i0[1] * i0[1] + i0[2] * i0[2]; 145 | j0j0 = j0[0] * j0[0] + j0[1] * j0[1] + j0[2] * j0[2]; 146 | i0j0 = i0[0] * j0[0] + i0[1] * j0[1] + i0[2] * j0[2]; 147 | 148 | //Lambda and mu 149 | delta = (j0j0 - i0i0) * (j0j0 - i0i0) + 4.0 * (i0j0 * i0j0); 150 | 151 | if (j0j0 - i0i0 >= 0.0){ 152 | q = (j0j0 - i0i0 + Math.sqrt(delta) ) / 2.0; 153 | }else{ 154 | q = (j0j0 - i0i0 - Math.sqrt(delta) ) / 2.0; 155 | } 156 | 157 | if (q >= 0.0){ 158 | lambda = Math.sqrt(q); 159 | if (0.0 === lambda){ 160 | mu = 0.0; 161 | }else{ 162 | mu = -i0j0 / lambda; 163 | } 164 | }else{ 165 | lambda = Math.sqrt( -(i0j0 * i0j0) / q); 166 | if (0.0 === lambda){ 167 | mu = Math.sqrt(i0i0 - j0j0); 168 | }else{ 169 | mu = -i0j0 / lambda; 170 | } 171 | } 172 | 173 | //First rotation 174 | for (i = 0; i < 3; ++ i){ 175 | ivec[i] = i0[i] + lambda * this.objectNormal[i]; 176 | jvec[i] = j0[i] + mu * this.objectNormal[i]; 177 | } 178 | 179 | scale = Math.sqrt(ivec[0] * ivec[0] + ivec[1] * ivec[1] + ivec[2] * ivec[2]); 180 | 181 | for (i = 0; i < 3; ++ i){ 182 | row1[i] = ivec[i] / scale; 183 | row2[i] = jvec[i] / scale; 184 | } 185 | 186 | row3[0] = row1[1] * row2[2] - row1[2] * row2[1]; 187 | row3[1] = row1[2] * row2[0] - row1[0] * row2[2]; 188 | row3[2] = row1[0] * row2[1] - row1[1] * row2[0]; 189 | 190 | for (i = 0; i < 3; ++ i){ 191 | rotation1[0][i] = row1[i]; 192 | rotation1[1][i] = row2[i]; 193 | rotation1[2][i] = row3[i]; 194 | } 195 | 196 | //Second rotation 197 | for (i = 0; i < 3; ++ i){ 198 | ivec[i] = i0[i] - lambda * this.objectNormal[i]; 199 | jvec[i] = j0[i] - mu * this.objectNormal[i]; 200 | } 201 | 202 | for (i = 0; i < 3; ++ i){ 203 | row1[i] = ivec[i] / scale; 204 | row2[i] = jvec[i] / scale; 205 | } 206 | 207 | row3[0] = row1[1] * row2[2] - row1[2] * row2[1]; 208 | row3[1] = row1[2] * row2[0] - row1[0] * row2[2]; 209 | row3[2] = row1[0] * row2[1] - row1[1] * row2[0]; 210 | 211 | for (i = 0; i < 3; ++ i){ 212 | rotation2[0][i] = row1[i]; 213 | rotation2[1][i] = row2[i]; 214 | rotation2[2][i] = row3[i]; 215 | } 216 | 217 | //Translation 218 | translation[0] = imagePoints[0].x / scale; 219 | translation[1] = imagePoints[0].y / scale; 220 | translation[2] = this.focalLength / scale; 221 | }; 222 | 223 | POS.Posit.prototype.isValid = function(rotation, translation){ 224 | var np = this.objectPoints.length, zmin = Infinity, i = 0, zi; 225 | 226 | for (; i < np; ++ i){ 227 | zi = translation[2] + 228 | (rotation[2][0] * this.objectVectors[i][0] + 229 | rotation[2][1] * this.objectVectors[i][1] + 230 | rotation[2][2] * this.objectVectors[i][2]); 231 | if (zi < zmin){ 232 | zmin = zi; 233 | } 234 | } 235 | 236 | return zmin >= 0.0; 237 | }; 238 | 239 | POS.Posit.prototype.iterate = function(imagePoints, posRotation, posTranslation, rotation, translation){ 240 | var np = this.objectPoints.length, 241 | oldSopImagePoints = [], sopImagePoints = [], 242 | rotation1 = [[],[],[]], rotation2 = [[],[],[]], 243 | translation1 = [], translation2 = [], 244 | converged = false, iteration = 0, 245 | oldImageDifference, imageDifference, factor, 246 | error, error1, error2, delta, i, j; 247 | 248 | for (i = 0; i < np; ++ i){ 249 | oldSopImagePoints[i] = {x: imagePoints[i].x, 250 | y: imagePoints[i].y}; 251 | } 252 | 253 | for (i = 0; i < 3; ++ i){ 254 | for (j = 0; j < 3; ++ j){ 255 | rotation[i][j] = posRotation[i][j]; 256 | } 257 | translation[i] = posTranslation[i]; 258 | } 259 | 260 | for (i = 0; i < np; ++ i){ 261 | factor = 0.0; 262 | for (j = 0; j < 3; ++ j){ 263 | factor += this.objectVectors[i][j] * rotation[2][j] / translation[2]; 264 | } 265 | sopImagePoints[i] = {x: (1.0 + factor) * imagePoints[i].x, 266 | y: (1.0 + factor) * imagePoints[i].y}; 267 | } 268 | 269 | imageDifference = 0.0; 270 | 271 | for (i = 0; i < np; ++ i){ 272 | imageDifference += Math.abs(sopImagePoints[i].x - oldSopImagePoints[i].x); 273 | imageDifference += Math.abs(sopImagePoints[i].y - oldSopImagePoints[i].y); 274 | } 275 | 276 | for (i = 0; i < 3; ++ i){ 277 | translation1[i] = translation[i] - 278 | (rotation[i][0] * this.objectPoints[0][0] + 279 | rotation[i][1] * this.objectPoints[0][1] + 280 | rotation[i][2] * this.objectPoints[0][2]); 281 | } 282 | 283 | error1 = this.error(imagePoints, rotation, translation1); 284 | 285 | //Convergence 286 | converged = (0.0 === error1.pixels) || (imageDifference < 0.01); 287 | 288 | while( iteration ++ < 100 && !converged ){ 289 | 290 | for (i = 0; i < np; ++ i){ 291 | oldSopImagePoints[i].x = sopImagePoints[i].x; 292 | oldSopImagePoints[i].y = sopImagePoints[i].y; 293 | } 294 | 295 | this.pos(sopImagePoints, rotation1, rotation2, translation); 296 | 297 | for (i = 0; i < 3; ++ i){ 298 | translation1[i] = translation[i] - 299 | (rotation1[i][0] * this.objectPoints[0][0] + 300 | rotation1[i][1] * this.objectPoints[0][1] + 301 | rotation1[i][2] * this.objectPoints[0][2]); 302 | 303 | translation2[i] = translation[i] - 304 | (rotation2[i][0] * this.objectPoints[0][0] + 305 | rotation2[i][1] * this.objectPoints[0][1] + 306 | rotation2[i][2] * this.objectPoints[0][2]); 307 | } 308 | 309 | error1 = this.error(imagePoints, rotation1, translation1); 310 | error2 = this.error(imagePoints, rotation2, translation2); 311 | 312 | if ( (error1.euclidean >= 0.0) && (error2.euclidean >= 0.0) ){ 313 | if (error2.euclidean < error1.euclidean){ 314 | error = error2; 315 | for (i = 0; i < 3; ++ i){ 316 | for (j = 0; j < 3; ++ j){ 317 | rotation[i][j] = rotation2[i][j]; 318 | } 319 | } 320 | }else{ 321 | error = error1; 322 | for (i = 0; i < 3; ++ i){ 323 | for (j = 0; j < 3; ++ j){ 324 | rotation[i][j] = rotation1[i][j]; 325 | } 326 | } 327 | } 328 | } 329 | 330 | if ( (error1.euclidean < 0.0) && (error2.euclidean >= 0.0) ){ 331 | error = error2; 332 | for (i = 0; i < 3; ++ i){ 333 | for (j = 0; j < 3; ++ j){ 334 | rotation[i][j] = rotation2[i][j]; 335 | } 336 | } 337 | } 338 | 339 | if ( (error2.euclidean < 0.0) && (error1.euclidean >= 0.0) ){ 340 | error = error1; 341 | for (i = 0; i < 3; ++ i){ 342 | for (j = 0; j < 3; ++ j){ 343 | rotation[i][j] = rotation1[i][j]; 344 | } 345 | } 346 | } 347 | 348 | for (i = 0; i < np; ++ i){ 349 | factor = 0.0; 350 | for (j = 0; j < 3; ++ j){ 351 | factor += this.objectVectors[i][j] * rotation[2][j] / translation[2]; 352 | } 353 | sopImagePoints[i].x = (1.0 + factor) * imagePoints[i].x; 354 | sopImagePoints[i].y = (1.0 + factor) * imagePoints[i].y; 355 | } 356 | 357 | oldImageDifference = imageDifference; 358 | imageDifference = 0.0; 359 | 360 | for (i = 0; i < np; ++ i){ 361 | imageDifference += Math.abs(sopImagePoints[i].x - oldSopImagePoints[i].x); 362 | imageDifference += Math.abs(sopImagePoints[i].y - oldSopImagePoints[i].y); 363 | } 364 | 365 | delta = Math.abs(imageDifference - oldImageDifference); 366 | 367 | converged = (0.0 === error.pixels) || (delta < 0.01); 368 | } 369 | 370 | return error; 371 | }; 372 | 373 | POS.Posit.prototype.error = function(imagePoints, rotation, translation){ 374 | var np = this.objectPoints.length, 375 | move = [], projection = [], errorvec = [], 376 | euclidean = 0.0, pixels = 0.0, maximum = 0.0, 377 | i, j, k; 378 | 379 | if ( !this.isValid(rotation, translation) ){ 380 | return {euclidean: -1.0, pixels: -1, maximum: -1.0}; 381 | } 382 | 383 | for (i = 0; i < np; ++ i){ 384 | move[i] = []; 385 | for (j = 0; j < 3; ++ j){ 386 | move[i][j] = translation[j]; 387 | } 388 | } 389 | 390 | for (i = 0; i < np; ++ i){ 391 | for (j = 0; j < 3; ++ j){ 392 | for (k = 0; k < 3; ++ k){ 393 | move[i][j] += rotation[j][k] * this.objectPoints[i][k]; 394 | } 395 | } 396 | } 397 | 398 | for (i = 0; i < np; ++ i){ 399 | projection[i] = []; 400 | for (j = 0; j < 2; ++ j){ 401 | projection[i][j] = this.focalLength * move[i][j] / move[i][2]; 402 | } 403 | } 404 | 405 | for (i = 0; i < np; ++ i){ 406 | errorvec[i] = [projection[i][0] - imagePoints[i].x, 407 | projection[i][1] - imagePoints[i].y]; 408 | } 409 | 410 | for (i = 0; i < np; ++ i){ 411 | euclidean += Math.sqrt(errorvec[i][0] * errorvec[i][0] + 412 | errorvec[i][1] * errorvec[i][1]); 413 | 414 | pixels += Math.abs( Math.round(projection[i][0]) - Math.round(imagePoints[i].x) ) + 415 | Math.abs( Math.round(projection[i][1]) - Math.round(imagePoints[i].y) ); 416 | 417 | if (Math.abs(errorvec[i][0]) > maximum){ 418 | maximum = Math.abs(errorvec[i][0]); 419 | } 420 | if (Math.abs(errorvec[i][1]) > maximum){ 421 | maximum = Math.abs(errorvec[i][1]); 422 | } 423 | } 424 | 425 | return {euclidean: euclidean / np, pixels: pixels, maximum: maximum}; 426 | }; 427 | 428 | POS.pseudoInverse = function(a, n, b){ 429 | var w = [], v = [[],[],[]], s = [[],[],[]], 430 | wmax = 0.0, cn = 0, 431 | i, j, k; 432 | 433 | SVD.svdcmp(a, n, 3, w, v); 434 | 435 | for (i = 0; i < 3; ++ i){ 436 | if (w[i] > wmax){ 437 | wmax = w[i]; 438 | } 439 | } 440 | 441 | wmax *= 0.01; 442 | 443 | for (i = 0; i < 3; ++ i){ 444 | if (w[i] < wmax){ 445 | w[i] = 0.0; 446 | } 447 | } 448 | 449 | for (j = 0; j < 3; ++ j){ 450 | if (0.0 === w[j]){ 451 | ++ cn; 452 | for (k = j; k < 2; ++ k){ 453 | for (i = 0; i < n; ++ i){ 454 | a[i][k] = a[i][k + 1]; 455 | } 456 | for (i = 0; i < 3; ++ i){ 457 | v[i][k] = v[i][k + 1]; 458 | } 459 | } 460 | } 461 | } 462 | 463 | for (j = 0; j < 2; ++ j){ 464 | if (0.0 === w[j]){ 465 | w[j] = w[j + 1]; 466 | } 467 | } 468 | 469 | for (i = 0; i < 3; ++ i){ 470 | for (j = 0; j < 3 - cn; ++ j){ 471 | s[i][j] = v[i][j] / w[j]; 472 | } 473 | } 474 | 475 | for (i = 0; i < 3; ++ i){ 476 | for (j = 0; j < n; ++ j){ 477 | b[i][j] = 0.0; 478 | for (k = 0; k < 3 - cn; ++ k){ 479 | b[i][j] += s[i][k] * a[j][k]; 480 | } 481 | } 482 | } 483 | }; 484 | 485 | POS.Pose = function(error1, rotation1, translation1, error2, rotation2, translation2){ 486 | this.bestError = error1; 487 | this.bestRotation = rotation1; 488 | this.bestTranslation = translation1; 489 | this.alternativeError = error2; 490 | this.alternativeRotation = rotation2; 491 | this.alternativeTranslation = translation2; 492 | }; 493 | -------------------------------------------------------------------------------- /vendor/js-aruco/posit2.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "3D Pose Estimation" 26 | Andrew Kirillow 27 | http://www.aforgenet.com/articles/posit/ 28 | */ 29 | 30 | var POS = POS || {}; 31 | 32 | POS.Posit = function(modelSize, focalLength){ 33 | this.model = this.buildModel(modelSize); 34 | this.focalLength = focalLength; 35 | 36 | this.init(); 37 | }; 38 | 39 | POS.Posit.prototype.buildModel = function(modelSize){ 40 | var half = modelSize / 2.0; 41 | 42 | return [ 43 | new Vec3(-half, half, 0.0), 44 | new Vec3( half, half, 0.0), 45 | new Vec3( half, -half, 0.0), 46 | new Vec3(-half, -half, 0.0) ]; 47 | }; 48 | 49 | POS.Posit.prototype.init = function(){ 50 | var d = new Vec3(), v = new Mat3(), u; 51 | 52 | this.modelVectors = Mat3.fromRows( 53 | Vec3.sub(this.model[1], this.model[0]), 54 | Vec3.sub(this.model[2], this.model[0]), 55 | Vec3.sub(this.model[3], this.model[0]) ); 56 | 57 | u = Mat3.clone(this.modelVectors); 58 | 59 | SVD.svdcmp(u.m, 3, 3, d.v, v.m); 60 | 61 | this.modelPseudoInverse = Mat3.mult( 62 | Mat3.mult(v, Mat3.fromDiagonal( Vec3.inverse(d) ) ), Mat3.transpose(u) ); 63 | 64 | this.modelNormal = v.column( d.minIndex() ); 65 | }; 66 | 67 | POS.Posit.prototype.pose = function(points){ 68 | var eps = new Vec3(1.0, 1.0, 1.0), 69 | rotation1 = new Mat3(), rotation2 = new Mat3(), 70 | translation1 = new Vec3(), translation2 = new Vec3(), 71 | error1, error2; 72 | 73 | this.pos(points, eps, rotation1, rotation2, translation1, translation2); 74 | 75 | error1 = this.iterate(points, rotation1, translation1); 76 | error2 = this.iterate(points, rotation2, translation2); 77 | 78 | return error1 < error2? 79 | new POS.Pose(error1, rotation1.m, translation1.v, error2, rotation2.m, translation2.v): 80 | new POS.Pose(error2, rotation2.m, translation2.v, error1, rotation1.m, translation1.v); 81 | }; 82 | 83 | POS.Posit.prototype.pos = function(points, eps, rotation1, rotation2, translation1, translation2){ 84 | var xi = new Vec3(points[1].x, points[2].x, points[3].x), 85 | yi = new Vec3(points[1].y, points[2].y, points[3].y), 86 | xs = Vec3.addScalar( Vec3.mult(xi, eps), -points[0].x), 87 | ys = Vec3.addScalar( Vec3.mult(yi, eps), -points[0].y), 88 | i0 = Mat3.multVector(this.modelPseudoInverse, xs), 89 | j0 = Mat3.multVector(this.modelPseudoInverse, ys), 90 | s = j0.square() - i0.square(), 91 | ij = Vec3.dot(i0, j0), 92 | r = 0.0, theta = 0.0, 93 | i, j, k, inorm, jnorm, scale, temp, lambda, mu; 94 | 95 | if (0.0 === s){ 96 | r = Math.sqrt( Math.abs(2.0 * ij) ); 97 | theta = (-Math.PI / 2.0) * (ij < 0.0? -1: (ij > 0.0? 1.0: 0.0) ); 98 | }else{ 99 | r = Math.sqrt( Math.sqrt(s * s + 4.0 * ij * ij) ); 100 | theta = Math.atan(-2.0 * ij / s); 101 | if (s < 0.0){ 102 | theta += Math.PI; 103 | } 104 | theta /= 2.0; 105 | } 106 | 107 | lambda = r * Math.cos(theta); 108 | mu = r * Math.sin(theta); 109 | 110 | //First possible rotation/translation 111 | i = Vec3.add(i0, Vec3.multScalar(this.modelNormal, lambda) ); 112 | j = Vec3.add(j0, Vec3.multScalar(this.modelNormal, mu) ); 113 | inorm = i.normalize(); 114 | jnorm = j.normalize(); 115 | k = Vec3.cross(i, j); 116 | rotation1.copy( Mat3.fromRows(i, j, k) ); 117 | 118 | scale = (inorm + jnorm) / 2.0; 119 | temp = Mat3.multVector(rotation1, this.model[0]); 120 | translation1.v = [ 121 | points[0].x / scale - temp.v[0], 122 | points[0].y / scale - temp.v[1], 123 | this.focalLength / scale]; 124 | 125 | //Second possible rotation/translation 126 | i = Vec3.sub(i0, Vec3.multScalar(this.modelNormal, lambda) ); 127 | j = Vec3.sub(j0, Vec3.multScalar(this.modelNormal, mu) ); 128 | inorm = i.normalize(); 129 | jnorm = j.normalize(); 130 | k = Vec3.cross(i, j); 131 | rotation2.copy( Mat3.fromRows(i, j, k) ); 132 | 133 | scale = (inorm + jnorm) / 2.0; 134 | temp = Mat3.multVector(rotation2, this.model[0]); 135 | translation2.v = [ 136 | points[0].x / scale - temp.v[0], 137 | points[0].y / scale - temp.v[1], 138 | this.focalLength / scale]; 139 | }; 140 | 141 | POS.Posit.prototype.iterate = function(points, rotation, translation){ 142 | var prevError = Infinity, 143 | rotation1 = new Mat3(), rotation2 = new Mat3(), 144 | translation1 = new Vec3(), translation2 = new Vec3(), 145 | i = 0, eps, error, error1, error2; 146 | 147 | for (; i < 100; ++ i){ 148 | eps = Vec3.addScalar( Vec3.multScalar( 149 | Mat3.multVector( this.modelVectors, rotation.row(2) ), 1.0 / translation.v[2]), 1.0); 150 | 151 | this.pos(points, eps, rotation1, rotation2, translation1, translation2); 152 | 153 | error1 = this.getError(points, rotation1, translation1); 154 | error2 = this.getError(points, rotation2, translation2); 155 | 156 | if (error1 < error2){ 157 | rotation.copy(rotation1); 158 | translation.copy(translation1); 159 | error = error1; 160 | }else{ 161 | rotation.copy(rotation2); 162 | translation.copy(translation2); 163 | error = error2; 164 | } 165 | 166 | if ( (error <= 2.0) || (error > prevError) ){ 167 | break; 168 | } 169 | 170 | prevError = error; 171 | } 172 | 173 | return error; 174 | }; 175 | 176 | POS.Posit.prototype.getError = function(points, rotation, translation){ 177 | var v1 = Vec3.add( Mat3.multVector(rotation, this.model[0]), translation), 178 | v2 = Vec3.add( Mat3.multVector(rotation, this.model[1]), translation), 179 | v3 = Vec3.add( Mat3.multVector(rotation, this.model[2]), translation), 180 | v4 = Vec3.add( Mat3.multVector(rotation, this.model[3]), translation), 181 | modeled, ia1, ia2, ia3, ia4, ma1, ma2, ma3, ma4; 182 | 183 | v1 = v1.v; v2 = v2.v; v3 = v3.v; v4 = v4.v; 184 | 185 | v1[0] *= this.focalLength / v1[2]; 186 | v1[1] *= this.focalLength / v1[2]; 187 | v2[0] *= this.focalLength / v2[2]; 188 | v2[1] *= this.focalLength / v2[2]; 189 | v3[0] *= this.focalLength / v3[2]; 190 | v3[1] *= this.focalLength / v3[2]; 191 | v4[0] *= this.focalLength / v4[2]; 192 | v4[1] *= this.focalLength / v4[2]; 193 | 194 | modeled = [ 195 | {x: v1[0], y: v1[1]}, 196 | {x: v2[0], y: v2[1]}, 197 | {x: v3[0], y: v3[1]}, 198 | {x: v4[0], y: v4[1]} 199 | ]; 200 | 201 | ia1 = this.angle( points[0], points[1], points[3] ); 202 | ia2 = this.angle( points[1], points[2], points[0] ); 203 | ia3 = this.angle( points[2], points[3], points[1] ); 204 | ia4 = this.angle( points[3], points[0], points[2] ); 205 | 206 | ma1 = this.angle( modeled[0], modeled[1], modeled[3] ); 207 | ma2 = this.angle( modeled[1], modeled[2], modeled[0] ); 208 | ma3 = this.angle( modeled[2], modeled[3], modeled[1] ); 209 | ma4 = this.angle( modeled[3], modeled[0], modeled[2] ); 210 | 211 | return ( Math.abs(ia1 - ma1) + 212 | Math.abs(ia2 - ma2) + 213 | Math.abs(ia3 - ma3) + 214 | Math.abs(ia4 - ma4) ) / 4.0; 215 | }; 216 | 217 | POS.Posit.prototype.angle = function(a, b, c){ 218 | var x1 = b.x - a.x, y1 = b.y - a.y, 219 | x2 = c.x - a.x, y2 = c.y - a.y; 220 | 221 | return Math.acos( (x1 * x2 + y1 * y2) / 222 | (Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2) ) ) * 180.0 / Math.PI; 223 | }; 224 | 225 | POS.Pose = function(error1, rotation1, translation1, error2, rotation2, translation2){ 226 | this.bestError = error1; 227 | this.bestRotation = rotation1; 228 | this.bestTranslation = translation1; 229 | this.alternativeError = error2; 230 | this.alternativeRotation = rotation2; 231 | this.alternativeTranslation = translation2; 232 | }; 233 | 234 | var Vec3 = function(x, y, z){ 235 | this.v = [x || 0.0, y || 0.0, z || 0.0]; 236 | }; 237 | 238 | Vec3.prototype.copy = function(a){ 239 | var v = this.v; 240 | 241 | a = a.v; 242 | 243 | v[0] = a[0]; 244 | v[1] = a[1]; 245 | v[2] = a[2]; 246 | 247 | return this; 248 | }; 249 | 250 | Vec3.add = function(a, b){ 251 | var vector = new Vec3(), v = vector.v; 252 | 253 | a = a.v; b = b.v; 254 | 255 | v[0] = a[0] + b[0]; 256 | v[1] = a[1] + b[1]; 257 | v[2] = a[2] + b[2]; 258 | 259 | return vector; 260 | }; 261 | 262 | Vec3.sub = function(a, b){ 263 | var vector = new Vec3(), v = vector.v; 264 | 265 | a = a.v; b = b.v; 266 | 267 | v[0] = a[0] - b[0]; 268 | v[1] = a[1] - b[1]; 269 | v[2] = a[2] - b[2]; 270 | 271 | return vector; 272 | }; 273 | 274 | Vec3.mult = function(a, b){ 275 | var vector = new Vec3(), v = vector.v; 276 | 277 | a = a.v; b = b.v; 278 | 279 | v[0] = a[0] * b[0]; 280 | v[1] = a[1] * b[1]; 281 | v[2] = a[2] * b[2]; 282 | 283 | return vector; 284 | }; 285 | 286 | Vec3.addScalar = function(a, b){ 287 | var vector = new Vec3(), v = vector.v; 288 | 289 | a = a.v; 290 | 291 | v[0] = a[0] + b; 292 | v[1] = a[1] + b; 293 | v[2] = a[2] + b; 294 | 295 | return vector; 296 | }; 297 | 298 | Vec3.multScalar = function(a, b){ 299 | var vector = new Vec3(), v = vector.v; 300 | 301 | a = a.v; 302 | 303 | v[0] = a[0] * b; 304 | v[1] = a[1] * b; 305 | v[2] = a[2] * b; 306 | 307 | return vector; 308 | }; 309 | 310 | Vec3.dot = function(a, b){ 311 | a = a.v; b = b.v; 312 | 313 | return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; 314 | }; 315 | 316 | Vec3.cross = function(a, b){ 317 | a = a.v; b = b.v; 318 | 319 | return new Vec3( 320 | a[1] * b[2] - a[2] * b[1], 321 | a[2] * b[0] - a[0] * b[2], 322 | a[0] * b[1] - a[1] * b[0]); 323 | }; 324 | 325 | Vec3.prototype.normalize = function(){ 326 | var v = this.v, 327 | len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); 328 | 329 | if (len > 0.0){ 330 | v[0] /= len; 331 | v[1] /= len; 332 | v[2] /= len; 333 | } 334 | 335 | return len; 336 | }; 337 | 338 | Vec3.inverse = function(a){ 339 | var vector = new Vec3(), v = vector.v; 340 | 341 | a = a.v; 342 | 343 | if (a[0] !== 0.0){ 344 | v[0] = 1.0 / a[0]; 345 | } 346 | if (a[1] !== 0.0){ 347 | v[1] = 1.0 / a[1]; 348 | } 349 | if (a[2] !== 0.0){ 350 | v[2] = 1.0 / a[2]; 351 | } 352 | 353 | return vector; 354 | }; 355 | 356 | Vec3.prototype.square = function(){ 357 | var v = this.v; 358 | 359 | return v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; 360 | }; 361 | 362 | Vec3.prototype.minIndex = function(){ 363 | var v = this.v; 364 | 365 | return v[0] < v[1]? (v[0] < v[2]? 0: 2): (v[1] < v[2]? 1: 2); 366 | }; 367 | 368 | var Mat3 = function(){ 369 | this.m = [ [0.0, 0.0, 0.0], 370 | [0.0, 0.0, 0.0], 371 | [0.0, 0.0, 0.0] ]; 372 | }; 373 | 374 | Mat3.clone = function(a){ 375 | var matrix = new Mat3(), m = matrix.m; 376 | 377 | a = a.m; 378 | 379 | m[0][0] = a[0][0]; 380 | m[0][1] = a[0][1]; 381 | m[0][2] = a[0][2]; 382 | m[1][0] = a[1][0]; 383 | m[1][1] = a[1][1]; 384 | m[1][2] = a[1][2]; 385 | m[2][0] = a[2][0]; 386 | m[2][1] = a[2][1]; 387 | m[2][2] = a[2][2]; 388 | 389 | return matrix; 390 | }; 391 | 392 | Mat3.prototype.copy = function(a){ 393 | var m = this.m; 394 | 395 | a = a.m; 396 | 397 | m[0][0] = a[0][0]; 398 | m[0][1] = a[0][1]; 399 | m[0][2] = a[0][2]; 400 | m[1][0] = a[1][0]; 401 | m[1][1] = a[1][1]; 402 | m[1][2] = a[1][2]; 403 | m[2][0] = a[2][0]; 404 | m[2][1] = a[2][1]; 405 | m[2][2] = a[2][2]; 406 | 407 | return this; 408 | }; 409 | 410 | Mat3.fromRows = function(a, b, c){ 411 | var matrix = new Mat3(), m = matrix.m; 412 | 413 | a = a.v; b = b.v; c = c.v; 414 | 415 | m[0][0] = a[0]; 416 | m[0][1] = a[1]; 417 | m[0][2] = a[2]; 418 | m[1][0] = b[0]; 419 | m[1][1] = b[1]; 420 | m[1][2] = b[2]; 421 | m[2][0] = c[0]; 422 | m[2][1] = c[1]; 423 | m[2][2] = c[2]; 424 | 425 | return matrix; 426 | }; 427 | 428 | Mat3.fromDiagonal = function(a){ 429 | var matrix = new Mat3(), m = matrix.m; 430 | 431 | a = a.v; 432 | 433 | m[0][0] = a[0]; 434 | m[1][1] = a[1]; 435 | m[2][2] = a[2]; 436 | 437 | return matrix; 438 | }; 439 | 440 | Mat3.transpose = function(a){ 441 | var matrix = new Mat3(), m = matrix.m; 442 | 443 | a = a.m; 444 | 445 | m[0][0] = a[0][0]; 446 | m[0][1] = a[1][0]; 447 | m[0][2] = a[2][0]; 448 | m[1][0] = a[0][1]; 449 | m[1][1] = a[1][1]; 450 | m[1][2] = a[2][1]; 451 | m[2][0] = a[0][2]; 452 | m[2][1] = a[1][2]; 453 | m[2][2] = a[2][2]; 454 | 455 | return matrix; 456 | }; 457 | 458 | Mat3.mult = function(a, b){ 459 | var matrix = new Mat3(), m = matrix.m; 460 | 461 | a = a.m; b = b.m; 462 | 463 | m[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0] + a[0][2] * b[2][0]; 464 | m[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1] + a[0][2] * b[2][1]; 465 | m[0][2] = a[0][0] * b[0][2] + a[0][1] * b[1][2] + a[0][2] * b[2][2]; 466 | m[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0] + a[1][2] * b[2][0]; 467 | m[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1] + a[1][2] * b[2][1]; 468 | m[1][2] = a[1][0] * b[0][2] + a[1][1] * b[1][2] + a[1][2] * b[2][2]; 469 | m[2][0] = a[2][0] * b[0][0] + a[2][1] * b[1][0] + a[2][2] * b[2][0]; 470 | m[2][1] = a[2][0] * b[0][1] + a[2][1] * b[1][1] + a[2][2] * b[2][1]; 471 | m[2][2] = a[2][0] * b[0][2] + a[2][1] * b[1][2] + a[2][2] * b[2][2]; 472 | 473 | return matrix; 474 | }; 475 | 476 | Mat3.multVector = function(m, a){ 477 | m = m.m; a = a.v; 478 | 479 | return new Vec3( 480 | m[0][0] * a[0] + m[0][1] * a[1] + m[0][2] * a[2], 481 | m[1][0] * a[0] + m[1][1] * a[1] + m[1][2] * a[2], 482 | m[2][0] * a[0] + m[2][1] * a[1] + m[2][2] * a[2]); 483 | }; 484 | 485 | Mat3.prototype.column = function(index){ 486 | var m = this.m; 487 | 488 | return new Vec3( m[0][index], m[1][index], m[2][index] ); 489 | }; 490 | 491 | Mat3.prototype.row = function(index){ 492 | var m = this.m; 493 | 494 | return new Vec3( m[index][0], m[index][1], m[index][2] ); 495 | }; 496 | -------------------------------------------------------------------------------- /vendor/js-aruco/svd.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012 Juan Mellado 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in 12 | all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | THE SOFTWARE. 21 | */ 22 | 23 | /* 24 | References: 25 | - "Numerical Recipes in C - Second Edition" 26 | http://www.nr.com/ 27 | */ 28 | 29 | var SVD = SVD || {}; 30 | 31 | SVD.svdcmp = function(a, m, n, w, v){ 32 | var flag, i, its, j, jj, k, l, nm, 33 | anorm = 0.0, c, f, g = 0.0, h, s, scale = 0.0, x, y, z, rv1 = []; 34 | 35 | //Householder reduction to bidiagonal form 36 | for (i = 0; i < n; ++ i){ 37 | l = i + 1; 38 | rv1[i] = scale * g; 39 | g = s = scale = 0.0; 40 | if (i < m){ 41 | for (k = i; k < m; ++ k){ 42 | scale += Math.abs( a[k][i] ); 43 | } 44 | if (0.0 !== scale){ 45 | for (k = i; k < m; ++ k){ 46 | a[k][i] /= scale; 47 | s += a[k][i] * a[k][i]; 48 | } 49 | f = a[i][i]; 50 | g = -SVD.sign( Math.sqrt(s), f ); 51 | h = f * g - s; 52 | a[i][i] = f - g; 53 | for (j = l; j < n; ++ j){ 54 | for (s = 0.0, k = i; k < m; ++ k){ 55 | s += a[k][i] * a[k][j]; 56 | } 57 | f = s / h; 58 | for (k = i; k < m; ++ k){ 59 | a[k][j] += f * a[k][i]; 60 | } 61 | } 62 | for (k = i; k < m; ++ k){ 63 | a[k][i] *= scale; 64 | } 65 | } 66 | } 67 | w[i] = scale * g; 68 | g = s = scale = 0.0; 69 | if ( (i < m) && (i !== n - 1) ){ 70 | for (k = l; k < n; ++ k){ 71 | scale += Math.abs( a[i][k] ); 72 | } 73 | if (0.0 !== scale){ 74 | for (k = l; k < n; ++ k){ 75 | a[i][k] /= scale; 76 | s += a[i][k] * a[i][k]; 77 | } 78 | f = a[i][l]; 79 | g = -SVD.sign( Math.sqrt(s), f ); 80 | h = f * g - s; 81 | a[i][l] = f - g; 82 | for (k = l; k < n; ++ k){ 83 | rv1[k] = a[i][k] / h; 84 | } 85 | for (j = l; j < m; ++ j){ 86 | for (s = 0.0, k = l; k < n; ++ k){ 87 | s += a[j][k] * a[i][k]; 88 | } 89 | for (k = l; k < n; ++ k){ 90 | a[j][k] += s * rv1[k]; 91 | } 92 | } 93 | for (k = l; k < n; ++ k){ 94 | a[i][k] *= scale; 95 | } 96 | } 97 | } 98 | anorm = Math.max(anorm, ( Math.abs( w[i] ) + Math.abs( rv1[i] ) ) ); 99 | } 100 | 101 | //Acumulation of right-hand transformation 102 | for (i = n - 1; i >= 0; -- i){ 103 | if (i < n - 1){ 104 | if (0.0 !== g){ 105 | for (j = l; j < n; ++ j){ 106 | v[j][i] = ( a[i][j] / a[i][l] ) / g; 107 | } 108 | for (j = l; j < n; ++ j){ 109 | for (s = 0.0, k = l; k < n; ++ k){ 110 | s += a[i][k] * v[k][j]; 111 | } 112 | for (k = l; k < n; ++ k){ 113 | v[k][j] += s * v[k][i]; 114 | } 115 | } 116 | } 117 | for (j = l; j < n; ++ j){ 118 | v[i][j] = v[j][i] = 0.0; 119 | } 120 | } 121 | v[i][i] = 1.0; 122 | g = rv1[i]; 123 | l = i; 124 | } 125 | 126 | //Acumulation of left-hand transformation 127 | for (i = Math.min(n, m) - 1; i >= 0; -- i){ 128 | l = i + 1; 129 | g = w[i]; 130 | for (j = l; j < n; ++ j){ 131 | a[i][j] = 0.0; 132 | } 133 | if (0.0 !== g){ 134 | g = 1.0 / g; 135 | for (j = l; j < n; ++ j){ 136 | for (s = 0.0, k = l; k < m; ++ k){ 137 | s += a[k][i] * a[k][j]; 138 | } 139 | f = (s / a[i][i]) * g; 140 | for (k = i; k < m; ++ k){ 141 | a[k][j] += f * a[k][i]; 142 | } 143 | } 144 | for (j = i; j < m; ++ j){ 145 | a[j][i] *= g; 146 | } 147 | }else{ 148 | for (j = i; j < m; ++ j){ 149 | a[j][i] = 0.0; 150 | } 151 | } 152 | ++ a[i][i]; 153 | } 154 | 155 | //Diagonalization of the bidiagonal form 156 | for (k = n - 1; k >= 0; -- k){ 157 | for (its = 1; its <= 30; ++ its){ 158 | flag = true; 159 | for (l = k; l >= 0; -- l){ 160 | nm = l - 1; 161 | if ( Math.abs( rv1[l] ) + anorm === anorm ){ 162 | flag = false; 163 | break; 164 | } 165 | if ( Math.abs( w[nm] ) + anorm === anorm ){ 166 | break; 167 | } 168 | } 169 | if (flag){ 170 | c = 0.0; 171 | s = 1.0; 172 | for (i = l; i <= k; ++ i){ 173 | f = s * rv1[i]; 174 | if ( Math.abs(f) + anorm === anorm ){ 175 | break; 176 | } 177 | g = w[i]; 178 | h = SVD.pythag(f, g); 179 | w[i] = h; 180 | h = 1.0 / h; 181 | c = g * h; 182 | s = -f * h; 183 | for (j = 1; j <= m; ++ j){ 184 | y = a[j][nm]; 185 | z = a[j][i]; 186 | a[j][nm] = y * c + z * s; 187 | a[j][i] = z * c - y * s; 188 | } 189 | } 190 | } 191 | 192 | //Convergence 193 | z = w[k]; 194 | if (l === k){ 195 | if (z < 0.0){ 196 | w[k] = -z; 197 | for (j = 0; j < n; ++ j){ 198 | v[j][k] = -v[j][k]; 199 | } 200 | } 201 | break; 202 | } 203 | 204 | if (30 === its){ 205 | return false; 206 | } 207 | 208 | //Shift from bottom 2-by-2 minor 209 | x = w[l]; 210 | nm = k - 1; 211 | y = w[nm]; 212 | g = rv1[nm]; 213 | h = rv1[k]; 214 | f = ( (y - z) * (y + z) + (g - h) * (g + h) ) / (2.0 * h * y); 215 | g = SVD.pythag( f, 1.0 ); 216 | f = ( (x - z) * (x + z) + h * ( (y / (f + SVD.sign(g, f) ) ) - h) ) / x; 217 | 218 | //Next QR transformation 219 | c = s = 1.0; 220 | for (j = l; j <= nm; ++ j){ 221 | i = j + 1; 222 | g = rv1[i]; 223 | y = w[i]; 224 | h = s * g; 225 | g = c * g; 226 | z = SVD.pythag(f, h); 227 | rv1[j] = z; 228 | c = f / z; 229 | s = h / z; 230 | f = x * c + g * s; 231 | g = g * c - x * s; 232 | h = y * s; 233 | y *= c; 234 | for (jj = 0; jj < n; ++ jj){ 235 | x = v[jj][j]; 236 | z = v[jj][i]; 237 | v[jj][j] = x * c + z * s; 238 | v[jj][i] = z * c - x * s; 239 | } 240 | z = SVD.pythag(f, h); 241 | w[j] = z; 242 | if (0.0 !== z){ 243 | z = 1.0 / z; 244 | c = f * z; 245 | s = h * z; 246 | } 247 | f = c * g + s * y; 248 | x = c * y - s * g; 249 | for (jj = 0; jj < m; ++ jj){ 250 | y = a[jj][j]; 251 | z = a[jj][i]; 252 | a[jj][j] = y * c + z * s; 253 | a[jj][i] = z * c - y * s; 254 | } 255 | } 256 | rv1[l] = 0.0; 257 | rv1[k] = f; 258 | w[k] = x; 259 | } 260 | } 261 | 262 | return true; 263 | }; 264 | 265 | SVD.pythag = function(a, b){ 266 | var at = Math.abs(a), bt = Math.abs(b), ct; 267 | 268 | if (at > bt){ 269 | ct = bt / at; 270 | return at * Math.sqrt(1.0 + ct * ct); 271 | } 272 | 273 | if (0.0 === bt){ 274 | return 0.0; 275 | } 276 | 277 | ct = at / bt; 278 | return bt * Math.sqrt(1.0 + ct * ct); 279 | }; 280 | 281 | SVD.sign = function(a, b){ 282 | return b >= 0.0? Math.abs(a): -Math.abs(a); 283 | }; 284 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path'); 2 | module.exports = { 3 | entry: './src/index.js', 4 | output: { 5 | filename: 'bundle.js', 6 | path: './dist' 7 | }, 8 | module: { 9 | rules: [ 10 | { 11 | test: /\.(js|jsx)$/, 12 | exclude: path.resolve(__dirname, "node_modules"), 13 | use: [ 14 | { 15 | loader: 'babel-loader', 16 | options: { 17 | presets: ['es2015'], 18 | }, 19 | }, 20 | ], 21 | }, 22 | ], 23 | }, 24 | }; 25 | --------------------------------------------------------------------------------