├── LICENSE ├── README.md ├── demo ├── model.js └── textures.js ├── index.html ├── libs ├── OrbitControls.js └── three.min.js └── src └── ModelViewer.js /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Valentin Berlier 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 | # json-model-viewer 2 | 3 | A 3d model viewer for minecraft json models. Requires [three.js](https://github.com/mrdoob/three.js/) and [OrbitControls](https://github.com/mrdoob/three.js/blob/master/examples/js/controls/OrbitControls.js). 4 | 5 | **:warning: Warning :warning:** 6 | 7 | This project is getting pretty old. I'm considering rewriting it but that'll take some time, so come back later! 8 | 9 | ## Basic usage 10 | 11 | ```javascript 12 | 13 | var viewer = new ModelViewer(document.body) 14 | 15 | window.addEventListener('resize', viewer.resize) 16 | 17 | // "json", "textureName" and "dataURL" must be provided from somewhere else 18 | var model = new JsonModel('myModel', json, [{name: textureName, texture: dataURL}]) 19 | 20 | viewer.load(model) 21 | ``` 22 | 23 | ### ModelViewer(element) 24 | 25 | Use `new ModelViewer(element)` to create a new viewer. `element` must be a DOM element and will be used to hold the viewer. The size of the element will determine the size of the viewer. 26 | 27 | #### Methods 28 | 29 | Method | Description 30 | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- 31 | `.load(model)` | Loads a model in the viewer. `model` must be a `JsonModel` object. 32 | `.get(name)` | Returns the model with the name `name`. 33 | `.getAll()` | Returns an Array with all the loaded models. 34 | `.remove(name)` | Removes the model with the name `name`. 35 | `.removeAll()` | Removes all the loaded models. 36 | `.hide(name)` | Sets the `visible` property to `false` for the model with the name `name`. 37 | `.hideAll()` | Sets the `visible` property to `false` for all the loaded models. 38 | `.show(name)` | Sets the `visible` property to `true` for the model with the name `name`. 39 | `.showAll()` | Sets the `visible` property to `true` for all the loaded models. 40 | `.lookAt(name)` | Moves the camera toward the model with the name `name`. 41 | `.showGrid()` | Displays the floor grid. 42 | `.hideGrid()` | Hides the floor grid. 43 | `.setGridColor(color)` | Sets the grid color. `color` must be a number, usually written in hexadecimal (i.e. red: `0xff0000`). 44 | `.resize()` | Updates the size and the aspect ratio of the viewer. Usualy bound to the `resize` event of the `window` if the viewer takes the whole page. 45 | `.reset()` | Resets the camera. 46 | 47 | ### JsonModel(name, json, textures, clipUVs) 48 | 49 | Use `new JsonModel(name, json, textures)` to create a group of [three.js meshs](http://threejs.org/docs/index.html#Reference/Objects/Mesh) from any minecraft json model. `name` must be a unique identifier and `json` a JSON string that contains a minecraft json model. `textures` must be an Array formatted as followed: 50 | 51 | ```javascript 52 | [{name: 'texture1', texture: dataURL1}, {name: 'texture2', texture: dataURL2}, ...] 53 | ``` 54 | 55 | All textures referenced in the json model must be passed in parameter with the correct name. 56 | 57 | For instance, if the `textures` property of a model looks like this: 58 | 59 | ```javascript 60 | { 61 | "textures": { 62 | "0": "blocks/dirt", 63 | "1": "blocks/stone" 64 | }, 65 | "elements": [ 66 | ... 67 | ] 68 | } 69 | ``` 70 | 71 | The `textures` Array will contain two textures, the `dirt` texture and the `stone` texture: 72 | 73 | ```javascript 74 | var textures = [ 75 | {name: 'dirt', texture: dirtTextureDataURL}, 76 | {name: 'stone', texture: stoneTextureDataURL} 77 | ] 78 | var model = new JsonModel('myModel', json, textures) 79 | ``` 80 | 81 | The `name` property must match the texture's file name, regardless of the folder in which it is. This means that `folderA/myTexture` and `folderB/myTexture` will both use the texture named `myTexture`, even if the original textures are not the same. 82 | 83 | The `texture` property must be the image dataURL of the corresponding texture. 84 | 85 | The constructor can also take an optional argument. `clipUVs` is set to true by default, and will clip invalid uvs on the fly. If set to false, the constructor will throw an error if it encounters uv coordinates outside of the valid 0-16 range. 86 | 87 | #### Animated textures 88 | 89 | If the texture is an animated texture, the .mcmeta file must be provided as well. For instance, if a model has only one animated texture, the `textures` Array will look like this: 90 | 91 | ```javascript 92 | var textures = [{name: 'animatedTexture', texture: textureDataURL, mcmeta: textureMcmeta}] 93 | ``` 94 | 95 | The `mcmeta` property must be a JSON string that contains the content of the mcmeta file of the texture. 96 | 97 | Note that the viewer doesn't support frame interpolation. 98 | 99 | #### Methods 100 | 101 | `JsonModel` objects inherit from `THREE.Object3D`, see the [three.js documentation](http://threejs.org/docs/index.html#Reference/Core/Object3D) for more information. 102 | 103 | Method | Description 104 | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 105 | `.getCenter()` | Returns the center of the model's bounding box as a `THREE.Vector3` object. 106 | `.applyDisplay(option)` | Applies a transformation specified in the `display` section of the model. The `option` parameter can be `thirdperson_righthand` or `thirdperson`, `thirdperson_lefthand`, `firstperson_righthand` or `firstperson`, `firstperson_lefthand`, `gui`, `head`, `ground`, `fixed` and `block`. 107 | 108 | --- 109 | 110 | License - [MIT](https://github.com/vberlier/json-model-viewer/blob/master/LICENSE) 111 | -------------------------------------------------------------------------------- /demo/model.js: -------------------------------------------------------------------------------- 1 | var json = 2 | '{"textures":{"particle":"blocks/cake_side","bottom":"blocks/cake_bottom","top":"blocks/cake_top","side":"blocks/cake_side"},"elements":[{"from":[1,0,1],"to":[15,8,15],"faces":{"down":{"texture":"#bottom","uv":[1,1,15,15],"cullface":"down"},"up":{"texture":"#top","uv":[1,1,15,15]},"north":{"texture":"#side","uv":[1,8,15,16]},"south":{"texture":"#side","uv":[1,8,15,16]},"west":{"texture":"#side","uv":[1,8,15,16]},"east":{"texture":"#side","uv":[1,8,15,16]}}}]}' 3 | -------------------------------------------------------------------------------- /demo/textures.js: -------------------------------------------------------------------------------- 1 | var textures = [ 2 | {name: 'cake_bottom', texture: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAV0lEQVR42mNgoAZYHqzwnxyMYsCOWPX/MBofRlaLYQC6IbjYeA3AZSM2cZK9gO4inC4gxiDaeAE9lEnyAjFRSJYXyI5GXF7Bm5BITZEEvUBSSqQoM1ECAHvFqyQXkgWpAAAAAElFTkSuQmCC'}, 3 | {name: 'cake_side', texture: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAYUlEQVR42mNgGAWjAAoOHTr0//79+yRhkB4UA169fE0SxmoAiIa5hhAfwwAQXh6sAMbE8uEGTPeUgkuuj1CGs/HxQXpQDABJ7IhVB2MQmxAfwwCYJDIG2YRLDMMAcjBILwCrtTHpCEHg4gAAAABJRU5ErkJggg=='}, 4 | {name: 'cake_top', texture: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAjklEQVR42q2T3QnAIAyEXcQx3H+KPPvanyFaIkTO9LQWKwTBcl+8Mw3hjyUiV875U6mmAvTg2M+5irHsqnkAkO474vcuYEupdvBdFYpnFFDEDoBCtMoBRMS8cwB09pYsk1cLfjdLFh5m1AeQEFlGwxtYDmw+hs+I72xl12Y25ybR5TAGsCHqVANY/plW1g14oK4NJ6IuzwAAAABJRU5ErkJggg=='} 5 | ] 6 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 284 | 285 | Minecraft json model viewer 286 | 287 | 288 | 289 | 290 |
291 | 292 | 293 | 294 |
295 | 296 | 297 | 372 | 373 | 433 | 434 | 435 | 436 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 544 | 545 | 546 | 579 | 580 | 581 | 582 | -------------------------------------------------------------------------------- /libs/OrbitControls.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author qiao / https://github.com/qiao 3 | * @author mrdoob / http://mrdoob.com 4 | * @author alteredq / http://alteredqualia.com/ 5 | * @author WestLangley / http://github.com/WestLangley 6 | * @author erich666 / http://erichaines.com 7 | */ 8 | 9 | // This set of controls performs orbiting, dollying (zooming), and panning. 10 | // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). 11 | // 12 | // Orbit - left mouse / touch: one finger move 13 | // Zoom - middle mouse, or mousewheel / touch: two finger spread or squish 14 | // Pan - right mouse, or arrow keys / touch: three finter swipe 15 | 16 | THREE.OrbitControls = function ( object, domElement ) { 17 | 18 | this.object = object; 19 | 20 | this.domElement = ( domElement !== undefined ) ? domElement : document; 21 | 22 | // Set to false to disable this control 23 | this.enabled = true; 24 | 25 | // "target" sets the location of focus, where the object orbits around 26 | this.target = new THREE.Vector3(); 27 | 28 | // How far you can dolly in and out ( PerspectiveCamera only ) 29 | this.minDistance = 0; 30 | this.maxDistance = Infinity; 31 | 32 | // How far you can zoom in and out ( OrthographicCamera only ) 33 | this.minZoom = 0; 34 | this.maxZoom = Infinity; 35 | 36 | // How far you can orbit vertically, upper and lower limits. 37 | // Range is 0 to Math.PI radians. 38 | this.minPolarAngle = 0; // radians 39 | this.maxPolarAngle = Math.PI; // radians 40 | 41 | // How far you can orbit horizontally, upper and lower limits. 42 | // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ]. 43 | this.minAzimuthAngle = - Infinity; // radians 44 | this.maxAzimuthAngle = Infinity; // radians 45 | 46 | // Set to true to enable damping (inertia) 47 | // If damping is enabled, you must call controls.update() in your animation loop 48 | this.enableDamping = false; 49 | this.dampingFactor = 0.25; 50 | 51 | // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. 52 | // Set to false to disable zooming 53 | this.enableZoom = true; 54 | this.zoomSpeed = 1.0; 55 | 56 | // Set to false to disable rotating 57 | this.enableRotate = true; 58 | this.rotateSpeed = 1.0; 59 | 60 | // Set to false to disable panning 61 | this.enablePan = true; 62 | this.keyPanSpeed = 7.0; // pixels moved per arrow key push 63 | 64 | // Set to true to automatically rotate around the target 65 | // If auto-rotate is enabled, you must call controls.update() in your animation loop 66 | this.autoRotate = false; 67 | this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 68 | 69 | // Set to false to disable use of the keys 70 | this.enableKeys = true; 71 | 72 | // The four arrow keys 73 | this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; 74 | 75 | // Mouse buttons 76 | this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; 77 | 78 | // for reset 79 | this.target0 = this.target.clone(); 80 | this.position0 = this.object.position.clone(); 81 | this.zoom0 = this.object.zoom; 82 | 83 | // 84 | // public methods 85 | // 86 | 87 | this.getPolarAngle = function () { 88 | 89 | return spherical.phi; 90 | 91 | }; 92 | 93 | this.getAzimuthalAngle = function () { 94 | 95 | return spherical.theta; 96 | 97 | }; 98 | 99 | this.reset = function () { 100 | 101 | scope.target.copy( scope.target0 ); 102 | scope.object.position.copy( scope.position0 ); 103 | scope.object.zoom = scope.zoom0; 104 | 105 | scope.object.updateProjectionMatrix(); 106 | scope.dispatchEvent( changeEvent ); 107 | 108 | scope.update(); 109 | 110 | state = STATE.NONE; 111 | 112 | }; 113 | 114 | // this method is exposed, but perhaps it would be better if we can make it private... 115 | this.update = function() { 116 | 117 | var offset = new THREE.Vector3(); 118 | 119 | // so camera.up is the orbit axis 120 | var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); 121 | var quatInverse = quat.clone().inverse(); 122 | 123 | var lastPosition = new THREE.Vector3(); 124 | var lastQuaternion = new THREE.Quaternion(); 125 | 126 | return function () { 127 | 128 | var position = scope.object.position; 129 | 130 | offset.copy( position ).sub( scope.target ); 131 | 132 | // rotate offset to "y-axis-is-up" space 133 | offset.applyQuaternion( quat ); 134 | 135 | // angle from z-axis around y-axis 136 | spherical.setFromVector3( offset ); 137 | 138 | if ( scope.autoRotate && state === STATE.NONE ) { 139 | 140 | rotateLeft( getAutoRotationAngle() ); 141 | 142 | } 143 | 144 | spherical.theta += sphericalDelta.theta; 145 | spherical.phi += sphericalDelta.phi; 146 | 147 | // restrict theta to be between desired limits 148 | spherical.theta = Math.max( scope.minAzimuthAngle, Math.min( scope.maxAzimuthAngle, spherical.theta ) ); 149 | 150 | // restrict phi to be between desired limits 151 | spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) ); 152 | 153 | spherical.makeSafe(); 154 | 155 | 156 | spherical.radius *= scale; 157 | 158 | // restrict radius to be between desired limits 159 | spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) ); 160 | 161 | // move target to panned location 162 | scope.target.add( panOffset ); 163 | 164 | offset.setFromSpherical( spherical ); 165 | 166 | // rotate offset back to "camera-up-vector-is-up" space 167 | offset.applyQuaternion( quatInverse ); 168 | 169 | position.copy( scope.target ).add( offset ); 170 | 171 | scope.object.lookAt( scope.target ); 172 | 173 | if ( scope.enableDamping === true ) { 174 | 175 | sphericalDelta.theta *= ( 1 - scope.dampingFactor ); 176 | sphericalDelta.phi *= ( 1 - scope.dampingFactor ); 177 | 178 | } else { 179 | 180 | sphericalDelta.set( 0, 0, 0 ); 181 | 182 | } 183 | 184 | scale = 1; 185 | panOffset.set( 0, 0, 0 ); 186 | 187 | // update condition is: 188 | // min(camera displacement, camera rotation in radians)^2 > EPS 189 | // using small-angle approximation cos(x/2) = 1 - x^2 / 8 190 | 191 | if ( zoomChanged || 192 | lastPosition.distanceToSquared( scope.object.position ) > EPS || 193 | 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) { 194 | 195 | scope.dispatchEvent( changeEvent ); 196 | 197 | lastPosition.copy( scope.object.position ); 198 | lastQuaternion.copy( scope.object.quaternion ); 199 | zoomChanged = false; 200 | 201 | return true; 202 | 203 | } 204 | 205 | return false; 206 | 207 | }; 208 | 209 | }(); 210 | 211 | this.dispose = function() { 212 | 213 | scope.domElement.removeEventListener( 'contextmenu', onContextMenu, false ); 214 | scope.domElement.removeEventListener( 'mousedown', onMouseDown, false ); 215 | scope.domElement.removeEventListener( 'mousewheel', onMouseWheel, false ); 216 | scope.domElement.removeEventListener( 'MozMousePixelScroll', onMouseWheel, false ); // firefox 217 | 218 | scope.domElement.removeEventListener( 'touchstart', onTouchStart, false ); 219 | scope.domElement.removeEventListener( 'touchend', onTouchEnd, false ); 220 | scope.domElement.removeEventListener( 'touchmove', onTouchMove, false ); 221 | 222 | document.removeEventListener( 'mousemove', onMouseMove, false ); 223 | document.removeEventListener( 'mouseup', onMouseUp, false ); 224 | document.removeEventListener( 'mouseout', onMouseUp, false ); 225 | 226 | window.removeEventListener( 'keydown', onKeyDown, false ); 227 | 228 | //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? 229 | 230 | }; 231 | 232 | // 233 | // internals 234 | // 235 | 236 | var scope = this; 237 | 238 | var changeEvent = { type: 'change' }; 239 | var startEvent = { type: 'start' }; 240 | var endEvent = { type: 'end' }; 241 | 242 | var STATE = { NONE : - 1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; 243 | 244 | var state = STATE.NONE; 245 | 246 | var EPS = 0.000001; 247 | 248 | // current position in spherical coordinates 249 | var spherical = new THREE.Spherical(); 250 | var sphericalDelta = new THREE.Spherical(); 251 | 252 | var scale = 1; 253 | var panOffset = new THREE.Vector3(); 254 | var zoomChanged = false; 255 | 256 | var rotateStart = new THREE.Vector2(); 257 | var rotateEnd = new THREE.Vector2(); 258 | var rotateDelta = new THREE.Vector2(); 259 | 260 | var panStart = new THREE.Vector2(); 261 | var panEnd = new THREE.Vector2(); 262 | var panDelta = new THREE.Vector2(); 263 | 264 | var dollyStart = new THREE.Vector2(); 265 | var dollyEnd = new THREE.Vector2(); 266 | var dollyDelta = new THREE.Vector2(); 267 | 268 | function getAutoRotationAngle() { 269 | 270 | return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; 271 | 272 | } 273 | 274 | function getZoomScale() { 275 | 276 | return Math.pow( 0.95, scope.zoomSpeed ); 277 | 278 | } 279 | 280 | function rotateLeft( angle ) { 281 | 282 | sphericalDelta.theta -= angle; 283 | 284 | } 285 | 286 | function rotateUp( angle ) { 287 | 288 | sphericalDelta.phi -= angle; 289 | 290 | } 291 | 292 | var panLeft = function() { 293 | 294 | var v = new THREE.Vector3(); 295 | 296 | return function panLeft( distance, objectMatrix ) { 297 | 298 | v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix 299 | v.multiplyScalar( - distance ); 300 | 301 | panOffset.add( v ); 302 | 303 | }; 304 | 305 | }(); 306 | 307 | var panUp = function() { 308 | 309 | var v = new THREE.Vector3(); 310 | 311 | return function panUp( distance, objectMatrix ) { 312 | 313 | v.setFromMatrixColumn( objectMatrix, 1 ); // get Y column of objectMatrix 314 | v.multiplyScalar( distance ); 315 | 316 | panOffset.add( v ); 317 | 318 | }; 319 | 320 | }(); 321 | 322 | // deltaX and deltaY are in pixels; right and down are positive 323 | var pan = function() { 324 | 325 | var offset = new THREE.Vector3(); 326 | 327 | return function( deltaX, deltaY ) { 328 | 329 | var element = scope.domElement === document ? scope.domElement.body : scope.domElement; 330 | 331 | if ( scope.object instanceof THREE.PerspectiveCamera ) { 332 | 333 | // perspective 334 | var position = scope.object.position; 335 | offset.copy( position ).sub( scope.target ); 336 | var targetDistance = offset.length(); 337 | 338 | // half of the fov is center to top of screen 339 | targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); 340 | 341 | // we actually don't use screenWidth, since perspective camera is fixed to screen height 342 | panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); 343 | panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix ); 344 | 345 | } else if ( scope.object instanceof THREE.OrthographicCamera ) { 346 | 347 | // orthographic 348 | panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); 349 | panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix ); 350 | 351 | } else { 352 | 353 | // camera neither orthographic nor perspective 354 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); 355 | scope.enablePan = false; 356 | 357 | } 358 | 359 | }; 360 | 361 | }(); 362 | 363 | function dollyIn( dollyScale ) { 364 | 365 | if ( scope.object instanceof THREE.PerspectiveCamera ) { 366 | 367 | scale /= dollyScale; 368 | 369 | } else if ( scope.object instanceof THREE.OrthographicCamera ) { 370 | 371 | scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) ); 372 | scope.object.updateProjectionMatrix(); 373 | zoomChanged = true; 374 | 375 | } else { 376 | 377 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); 378 | scope.enableZoom = false; 379 | 380 | } 381 | 382 | } 383 | 384 | function dollyOut( dollyScale ) { 385 | 386 | if ( scope.object instanceof THREE.PerspectiveCamera ) { 387 | 388 | scale *= dollyScale; 389 | 390 | } else if ( scope.object instanceof THREE.OrthographicCamera ) { 391 | 392 | scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) ); 393 | scope.object.updateProjectionMatrix(); 394 | zoomChanged = true; 395 | 396 | } else { 397 | 398 | console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); 399 | scope.enableZoom = false; 400 | 401 | } 402 | 403 | } 404 | 405 | // 406 | // event callbacks - update the object state 407 | // 408 | 409 | function handleMouseDownRotate( event ) { 410 | 411 | //console.log( 'handleMouseDownRotate' ); 412 | 413 | rotateStart.set( event.clientX, event.clientY ); 414 | 415 | } 416 | 417 | function handleMouseDownDolly( event ) { 418 | 419 | //console.log( 'handleMouseDownDolly' ); 420 | 421 | dollyStart.set( event.clientX, event.clientY ); 422 | 423 | } 424 | 425 | function handleMouseDownPan( event ) { 426 | 427 | //console.log( 'handleMouseDownPan' ); 428 | 429 | panStart.set( event.clientX, event.clientY ); 430 | 431 | } 432 | 433 | function handleMouseMoveRotate( event ) { 434 | 435 | //console.log( 'handleMouseMoveRotate' ); 436 | 437 | rotateEnd.set( event.clientX, event.clientY ); 438 | rotateDelta.subVectors( rotateEnd, rotateStart ); 439 | 440 | var element = scope.domElement === document ? scope.domElement.body : scope.domElement; 441 | 442 | // rotating across whole screen goes 360 degrees around 443 | rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); 444 | 445 | // rotating up and down along whole screen attempts to go 360, but limited to 180 446 | rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); 447 | 448 | rotateStart.copy( rotateEnd ); 449 | 450 | scope.update(); 451 | 452 | } 453 | 454 | function handleMouseMoveDolly( event ) { 455 | 456 | //console.log( 'handleMouseMoveDolly' ); 457 | 458 | dollyEnd.set( event.clientX, event.clientY ); 459 | 460 | dollyDelta.subVectors( dollyEnd, dollyStart ); 461 | 462 | if ( dollyDelta.y > 0 ) { 463 | 464 | dollyIn( getZoomScale() ); 465 | 466 | } else if ( dollyDelta.y < 0 ) { 467 | 468 | dollyOut( getZoomScale() ); 469 | 470 | } 471 | 472 | dollyStart.copy( dollyEnd ); 473 | 474 | scope.update(); 475 | 476 | } 477 | 478 | function handleMouseMovePan( event ) { 479 | 480 | //console.log( 'handleMouseMovePan' ); 481 | 482 | panEnd.set( event.clientX, event.clientY ); 483 | 484 | panDelta.subVectors( panEnd, panStart ); 485 | 486 | pan( panDelta.x, panDelta.y ); 487 | 488 | panStart.copy( panEnd ); 489 | 490 | scope.update(); 491 | 492 | } 493 | 494 | function handleMouseUp( event ) { 495 | 496 | //console.log( 'handleMouseUp' ); 497 | 498 | } 499 | 500 | function handleMouseWheel( event ) { 501 | 502 | //console.log( 'handleMouseWheel' ); 503 | 504 | var delta = 0; 505 | 506 | if ( event.wheelDelta !== undefined ) { 507 | 508 | // WebKit / Opera / Explorer 9 509 | 510 | delta = event.wheelDelta; 511 | 512 | } else if ( event.detail !== undefined ) { 513 | 514 | // Firefox 515 | 516 | delta = - event.detail; 517 | 518 | } 519 | 520 | if ( delta > 0 ) { 521 | 522 | dollyOut( getZoomScale() ); 523 | 524 | } else if ( delta < 0 ) { 525 | 526 | dollyIn( getZoomScale() ); 527 | 528 | } 529 | 530 | scope.update(); 531 | 532 | } 533 | 534 | function handleKeyDown( event ) { 535 | 536 | //console.log( 'handleKeyDown' ); 537 | 538 | switch ( event.keyCode ) { 539 | 540 | case scope.keys.UP: 541 | pan( 0, scope.keyPanSpeed ); 542 | scope.update(); 543 | break; 544 | 545 | case scope.keys.BOTTOM: 546 | pan( 0, - scope.keyPanSpeed ); 547 | scope.update(); 548 | break; 549 | 550 | case scope.keys.LEFT: 551 | pan( scope.keyPanSpeed, 0 ); 552 | scope.update(); 553 | break; 554 | 555 | case scope.keys.RIGHT: 556 | pan( - scope.keyPanSpeed, 0 ); 557 | scope.update(); 558 | break; 559 | 560 | } 561 | 562 | } 563 | 564 | function handleTouchStartRotate( event ) { 565 | 566 | //console.log( 'handleTouchStartRotate' ); 567 | 568 | rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 569 | 570 | } 571 | 572 | function handleTouchStartDolly( event ) { 573 | 574 | //console.log( 'handleTouchStartDolly' ); 575 | 576 | var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 577 | var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 578 | 579 | var distance = Math.sqrt( dx * dx + dy * dy ); 580 | 581 | dollyStart.set( 0, distance ); 582 | 583 | } 584 | 585 | function handleTouchStartPan( event ) { 586 | 587 | //console.log( 'handleTouchStartPan' ); 588 | 589 | panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 590 | 591 | } 592 | 593 | function handleTouchMoveRotate( event ) { 594 | 595 | //console.log( 'handleTouchMoveRotate' ); 596 | 597 | rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 598 | rotateDelta.subVectors( rotateEnd, rotateStart ); 599 | 600 | var element = scope.domElement === document ? scope.domElement.body : scope.domElement; 601 | 602 | // rotating across whole screen goes 360 degrees around 603 | rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); 604 | 605 | // rotating up and down along whole screen attempts to go 360, but limited to 180 606 | rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); 607 | 608 | rotateStart.copy( rotateEnd ); 609 | 610 | scope.update(); 611 | 612 | } 613 | 614 | function handleTouchMoveDolly( event ) { 615 | 616 | //console.log( 'handleTouchMoveDolly' ); 617 | 618 | var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; 619 | var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; 620 | 621 | var distance = Math.sqrt( dx * dx + dy * dy ); 622 | 623 | dollyEnd.set( 0, distance ); 624 | 625 | dollyDelta.subVectors( dollyEnd, dollyStart ); 626 | 627 | if ( dollyDelta.y > 0 ) { 628 | 629 | dollyOut( getZoomScale() ); 630 | 631 | } else if ( dollyDelta.y < 0 ) { 632 | 633 | dollyIn( getZoomScale() ); 634 | 635 | } 636 | 637 | dollyStart.copy( dollyEnd ); 638 | 639 | scope.update(); 640 | 641 | } 642 | 643 | function handleTouchMovePan( event ) { 644 | 645 | //console.log( 'handleTouchMovePan' ); 646 | 647 | panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); 648 | 649 | panDelta.subVectors( panEnd, panStart ); 650 | 651 | pan( panDelta.x, panDelta.y ); 652 | 653 | panStart.copy( panEnd ); 654 | 655 | scope.update(); 656 | 657 | } 658 | 659 | function handleTouchEnd( event ) { 660 | 661 | //console.log( 'handleTouchEnd' ); 662 | 663 | } 664 | 665 | // 666 | // event handlers - FSM: listen for events and reset state 667 | // 668 | 669 | function onMouseDown( event ) { 670 | 671 | if ( scope.enabled === false ) return; 672 | 673 | event.preventDefault(); 674 | 675 | if ( event.button === scope.mouseButtons.ORBIT ) { 676 | 677 | if ( scope.enableRotate === false ) return; 678 | 679 | handleMouseDownRotate( event ); 680 | 681 | state = STATE.ROTATE; 682 | 683 | } else if ( event.button === scope.mouseButtons.ZOOM ) { 684 | 685 | if ( scope.enableZoom === false ) return; 686 | 687 | handleMouseDownDolly( event ); 688 | 689 | state = STATE.DOLLY; 690 | 691 | } else if ( event.button === scope.mouseButtons.PAN ) { 692 | 693 | if ( scope.enablePan === false ) return; 694 | 695 | handleMouseDownPan( event ); 696 | 697 | state = STATE.PAN; 698 | 699 | } 700 | 701 | if ( state !== STATE.NONE ) { 702 | 703 | document.addEventListener( 'mousemove', onMouseMove, false ); 704 | document.addEventListener( 'mouseup', onMouseUp, false ); 705 | document.addEventListener( 'mouseout', onMouseUp, false ); 706 | 707 | scope.dispatchEvent( startEvent ); 708 | 709 | } 710 | 711 | } 712 | 713 | function onMouseMove( event ) { 714 | 715 | if ( scope.enabled === false ) return; 716 | 717 | event.preventDefault(); 718 | 719 | if ( state === STATE.ROTATE ) { 720 | 721 | if ( scope.enableRotate === false ) return; 722 | 723 | handleMouseMoveRotate( event ); 724 | 725 | } else if ( state === STATE.DOLLY ) { 726 | 727 | if ( scope.enableZoom === false ) return; 728 | 729 | handleMouseMoveDolly( event ); 730 | 731 | } else if ( state === STATE.PAN ) { 732 | 733 | if ( scope.enablePan === false ) return; 734 | 735 | handleMouseMovePan( event ); 736 | 737 | } 738 | 739 | } 740 | 741 | function onMouseUp( event ) { 742 | 743 | if ( scope.enabled === false ) return; 744 | 745 | handleMouseUp( event ); 746 | 747 | document.removeEventListener( 'mousemove', onMouseMove, false ); 748 | document.removeEventListener( 'mouseup', onMouseUp, false ); 749 | document.removeEventListener( 'mouseout', onMouseUp, false ); 750 | 751 | scope.dispatchEvent( endEvent ); 752 | 753 | state = STATE.NONE; 754 | 755 | } 756 | 757 | function onMouseWheel( event ) { 758 | 759 | if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return; 760 | 761 | event.preventDefault(); 762 | event.stopPropagation(); 763 | 764 | handleMouseWheel( event ); 765 | 766 | scope.dispatchEvent( startEvent ); // not sure why these are here... 767 | scope.dispatchEvent( endEvent ); 768 | 769 | } 770 | 771 | function onKeyDown( event ) { 772 | 773 | if ( scope.enabled === false || scope.enableKeys === false || scope.enablePan === false ) return; 774 | 775 | handleKeyDown( event ); 776 | 777 | } 778 | 779 | function onTouchStart( event ) { 780 | 781 | if ( scope.enabled === false ) return; 782 | 783 | switch ( event.touches.length ) { 784 | 785 | case 1: // one-fingered touch: rotate 786 | 787 | if ( scope.enableRotate === false ) return; 788 | 789 | handleTouchStartRotate( event ); 790 | 791 | state = STATE.TOUCH_ROTATE; 792 | 793 | break; 794 | 795 | case 2: // two-fingered touch: dolly 796 | 797 | if ( scope.enableZoom === false ) return; 798 | 799 | handleTouchStartDolly( event ); 800 | 801 | state = STATE.TOUCH_DOLLY; 802 | 803 | break; 804 | 805 | case 3: // three-fingered touch: pan 806 | 807 | if ( scope.enablePan === false ) return; 808 | 809 | handleTouchStartPan( event ); 810 | 811 | state = STATE.TOUCH_PAN; 812 | 813 | break; 814 | 815 | default: 816 | 817 | state = STATE.NONE; 818 | 819 | } 820 | 821 | if ( state !== STATE.NONE ) { 822 | 823 | scope.dispatchEvent( startEvent ); 824 | 825 | } 826 | 827 | } 828 | 829 | function onTouchMove( event ) { 830 | 831 | if ( scope.enabled === false ) return; 832 | 833 | event.preventDefault(); 834 | event.stopPropagation(); 835 | 836 | switch ( event.touches.length ) { 837 | 838 | case 1: // one-fingered touch: rotate 839 | 840 | if ( scope.enableRotate === false ) return; 841 | if ( state !== STATE.TOUCH_ROTATE ) return; // is this needed?... 842 | 843 | handleTouchMoveRotate( event ); 844 | 845 | break; 846 | 847 | case 2: // two-fingered touch: dolly 848 | 849 | if ( scope.enableZoom === false ) return; 850 | if ( state !== STATE.TOUCH_DOLLY ) return; // is this needed?... 851 | 852 | handleTouchMoveDolly( event ); 853 | 854 | break; 855 | 856 | case 3: // three-fingered touch: pan 857 | 858 | if ( scope.enablePan === false ) return; 859 | if ( state !== STATE.TOUCH_PAN ) return; // is this needed?... 860 | 861 | handleTouchMovePan( event ); 862 | 863 | break; 864 | 865 | default: 866 | 867 | state = STATE.NONE; 868 | 869 | } 870 | 871 | } 872 | 873 | function onTouchEnd( event ) { 874 | 875 | if ( scope.enabled === false ) return; 876 | 877 | handleTouchEnd( event ); 878 | 879 | scope.dispatchEvent( endEvent ); 880 | 881 | state = STATE.NONE; 882 | 883 | } 884 | 885 | function onContextMenu( event ) { 886 | 887 | event.preventDefault(); 888 | 889 | } 890 | 891 | // 892 | 893 | scope.domElement.addEventListener( 'contextmenu', onContextMenu, false ); 894 | 895 | scope.domElement.addEventListener( 'mousedown', onMouseDown, false ); 896 | scope.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); 897 | scope.domElement.addEventListener( 'MozMousePixelScroll', onMouseWheel, false ); // firefox 898 | 899 | scope.domElement.addEventListener( 'touchstart', onTouchStart, false ); 900 | scope.domElement.addEventListener( 'touchend', onTouchEnd, false ); 901 | scope.domElement.addEventListener( 'touchmove', onTouchMove, false ); 902 | 903 | window.addEventListener( 'keydown', onKeyDown, false ); 904 | 905 | // force an update at start 906 | 907 | this.update(); 908 | 909 | }; 910 | 911 | THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); 912 | THREE.OrbitControls.prototype.constructor = THREE.OrbitControls; 913 | 914 | Object.defineProperties( THREE.OrbitControls.prototype, { 915 | 916 | center: { 917 | 918 | get: function () { 919 | 920 | console.warn( 'THREE.OrbitControls: .center has been renamed to .target' ); 921 | return this.target; 922 | 923 | } 924 | 925 | }, 926 | 927 | // backward compatibility 928 | 929 | noZoom: { 930 | 931 | get: function () { 932 | 933 | console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' ); 934 | return ! this.enableZoom; 935 | 936 | }, 937 | 938 | set: function ( value ) { 939 | 940 | console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' ); 941 | this.enableZoom = ! value; 942 | 943 | } 944 | 945 | }, 946 | 947 | noRotate: { 948 | 949 | get: function () { 950 | 951 | console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' ); 952 | return ! this.enableRotate; 953 | 954 | }, 955 | 956 | set: function ( value ) { 957 | 958 | console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' ); 959 | this.enableRotate = ! value; 960 | 961 | } 962 | 963 | }, 964 | 965 | noPan: { 966 | 967 | get: function () { 968 | 969 | console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' ); 970 | return ! this.enablePan; 971 | 972 | }, 973 | 974 | set: function ( value ) { 975 | 976 | console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' ); 977 | this.enablePan = ! value; 978 | 979 | } 980 | 981 | }, 982 | 983 | noKeys: { 984 | 985 | get: function () { 986 | 987 | console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' ); 988 | return ! this.enableKeys; 989 | 990 | }, 991 | 992 | set: function ( value ) { 993 | 994 | console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' ); 995 | this.enableKeys = ! value; 996 | 997 | } 998 | 999 | }, 1000 | 1001 | staticMoving : { 1002 | 1003 | get: function () { 1004 | 1005 | console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' ); 1006 | return ! this.enableDamping; 1007 | 1008 | }, 1009 | 1010 | set: function ( value ) { 1011 | 1012 | console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' ); 1013 | this.enableDamping = ! value; 1014 | 1015 | } 1016 | 1017 | }, 1018 | 1019 | dynamicDampingFactor : { 1020 | 1021 | get: function () { 1022 | 1023 | console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' ); 1024 | return this.dampingFactor; 1025 | 1026 | }, 1027 | 1028 | set: function ( value ) { 1029 | 1030 | console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' ); 1031 | this.dampingFactor = value; 1032 | 1033 | } 1034 | 1035 | } 1036 | 1037 | } ); -------------------------------------------------------------------------------- /src/ModelViewer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Fizzy / https://github.com/fizzy81 3 | */ 4 | 5 | 6 | /** 7 | * ModelViewer 8 | *****************************/ 9 | 10 | function ModelViewer(container) { 11 | 12 | 13 | // container 14 | 15 | this.container = container 16 | 17 | 18 | // element 19 | 20 | this.element = document.createElement('div') 21 | this.element.setAttribute('style', 'position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: auto; height: auto; overflow: hidden;') 22 | 23 | this.container.appendChild(this.element) 24 | 25 | // get element dimensions 26 | var rect = this.element.getBoundingClientRect() 27 | 28 | 29 | // camera 30 | 31 | this.camera = new THREE.PerspectiveCamera(60, rect.width / rect.height, 1, 1000) 32 | this.camera.position.x = 16 33 | this.camera.position.y = 16 34 | this.camera.position.z = 32 35 | 36 | 37 | // scene 38 | 39 | this.scene = new THREE.Scene() 40 | 41 | 42 | // lights 43 | 44 | var light 45 | 46 | light = new THREE.AmbientLight(0xffffff, 0.97) 47 | this.scene.add(light) 48 | 49 | light = new THREE.DirectionalLight(0xffffff, 0.1) 50 | light.position.set(4, 10, 6) 51 | this.scene.add(light) 52 | 53 | 54 | // renderer 55 | 56 | this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }) 57 | this.renderer.setSize(rect.width, rect.height) 58 | 59 | 60 | // controls 61 | 62 | this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement) 63 | this.controls.enableDamping = true 64 | this.controls.dampingFactor = 0.2 65 | this.controls.zoomSpeed = 1.4 66 | this.controls.rotateSpeed = 0.6 67 | this.controls.enableKeys = false 68 | 69 | 70 | // append viewer 71 | 72 | this.element.appendChild(this.renderer.domElement) 73 | 74 | 75 | // view methods 76 | 77 | var self = this 78 | 79 | 80 | // draw 81 | 82 | this.draw = function() { 83 | 84 | self.renderer.render(self.scene, self.camera) 85 | 86 | } 87 | 88 | 89 | // animate 90 | 91 | this.animate = function() { 92 | 93 | window.requestAnimationFrame(self.animate) 94 | self.controls.update() 95 | 96 | self.draw() 97 | 98 | } 99 | 100 | 101 | // resize 102 | 103 | this.resize = function() { 104 | 105 | var rect = self.element.getBoundingClientRect() 106 | 107 | self.camera.aspect = rect.width / rect.height 108 | self.camera.updateProjectionMatrix() 109 | 110 | self.renderer.setSize(rect.width, rect.height) 111 | 112 | } 113 | 114 | 115 | // models 116 | 117 | this.models = {} 118 | 119 | 120 | // model methods 121 | 122 | var self = this 123 | 124 | 125 | // load 126 | 127 | this.load = function(model) { 128 | 129 | var name = model.modelName 130 | 131 | if (Object.keys(self.models).indexOf(name) >= 0) 132 | throw new Error('Model "' + name + '" is already loaded.') 133 | 134 | self.scene.add(model) 135 | self.models[name] = model 136 | 137 | return self 138 | 139 | } 140 | 141 | 142 | // get 143 | 144 | this.get = function(name) { 145 | 146 | if (!(Object.keys(self.models).indexOf(name) >= 0)) 147 | throw new Error('Model "' + name + '" is not loaded.') 148 | 149 | return self.models[name] 150 | 151 | } 152 | 153 | 154 | // getAll 155 | 156 | this.getAll = function() { 157 | 158 | return Object.keys(self.models).map(function(name) {return self.models[name]}) 159 | 160 | } 161 | 162 | 163 | // remove 164 | 165 | this.remove = function(name) { 166 | 167 | if (!(Object.keys(self.models).indexOf(name) >= 0)) 168 | throw new Error('Model "' + name + '" is not loaded.') 169 | 170 | delete self.models[name] 171 | 172 | for (var i = 0; i < self.scene.children.length; i++) { 173 | var child = self.scene.children[i] 174 | if (child instanceof JsonModel && child.modelName == name) { 175 | child.animationLoop = false 176 | self.scene.remove(child) 177 | break 178 | } 179 | } 180 | 181 | return self 182 | 183 | } 184 | 185 | 186 | // removeAll 187 | 188 | this.removeAll = function() { 189 | 190 | for (var i = self.scene.children.length - 1; i >= 0; i--) { 191 | var child = self.scene.children[i] 192 | if (child instanceof JsonModel) { 193 | child.animationLoop = false 194 | self.scene.remove(child) 195 | } 196 | } 197 | 198 | self.models = {} 199 | 200 | return self 201 | 202 | } 203 | 204 | 205 | // hide 206 | 207 | this.hide = function(name) { 208 | 209 | if (!(Object.keys(self.models).indexOf(name) >= 0)) 210 | throw new Error('Model "' + name + '" is not loaded.') 211 | 212 | self.models[name].visible = false 213 | self.draw() 214 | 215 | } 216 | 217 | 218 | // hideAll 219 | 220 | this.hideAll = function() { 221 | 222 | Object.keys(self.models).forEach(function(name) { 223 | self.models[name].visible = false 224 | }) 225 | 226 | return self 227 | 228 | } 229 | 230 | 231 | // show 232 | 233 | this.show = function(name) { 234 | 235 | if (!(Object.keys(self.models).indexOf(name) >= 0)) 236 | throw new Error('Model "' + name + '" is not loaded.') 237 | 238 | self.models[name].visible = true 239 | self.draw() 240 | 241 | } 242 | 243 | 244 | // showAll 245 | 246 | this.showAll = function() { 247 | 248 | Object.keys(self.models).forEach(function(name) { 249 | self.models[name].visible = true 250 | }) 251 | 252 | return self 253 | 254 | } 255 | 256 | 257 | // reset 258 | 259 | this.reset = function() { 260 | 261 | self.controls.reset() 262 | 263 | } 264 | 265 | 266 | // lookAt 267 | 268 | this.lookAt = function(name) { 269 | 270 | var model = self.get(name) 271 | self.controls.target = model.getCenter() 272 | 273 | 274 | } 275 | 276 | 277 | // create grid 278 | 279 | var gridGeometry = new THREE.Geometry() 280 | var gridMaterial = new THREE.LineBasicMaterial({color: 0xafafaf}) 281 | 282 | for (var i = -8; i <= 8; i++) { 283 | 284 | gridGeometry.vertices.push(new THREE.Vector3(-8, -8, i)) 285 | gridGeometry.vertices.push(new THREE.Vector3(8, -8, i)) 286 | 287 | gridGeometry.vertices.push(new THREE.Vector3(i, -8, -8)) 288 | gridGeometry.vertices.push(new THREE.Vector3(i, -8, 8)) 289 | 290 | } 291 | 292 | // arrow 293 | 294 | gridGeometry.vertices.push(new THREE.Vector3(-1, -8, 9)) 295 | gridGeometry.vertices.push(new THREE.Vector3(1, -8, 9)) 296 | 297 | gridGeometry.vertices.push(new THREE.Vector3(1, -8, 9)) 298 | gridGeometry.vertices.push(new THREE.Vector3(0, -8, 10)) 299 | 300 | gridGeometry.vertices.push(new THREE.Vector3(0, -8, 10)) 301 | gridGeometry.vertices.push(new THREE.Vector3(-1, -8, 9)) 302 | 303 | var grid = new THREE.LineSegments(gridGeometry, gridMaterial) 304 | grid.visible = true 305 | 306 | this.scene.add(grid) 307 | this.grid = grid 308 | 309 | 310 | // grid methods 311 | 312 | var self = this 313 | 314 | 315 | // showGrid 316 | 317 | this.showGrid = function() { 318 | 319 | self.grid.visible = true 320 | 321 | } 322 | 323 | 324 | // hideGrid 325 | 326 | this.hideGrid = function() { 327 | 328 | self.grid.visible = false 329 | 330 | } 331 | 332 | 333 | // setGridColor 334 | 335 | this.setGridColor = function(color) { 336 | 337 | self.grid.material.color = new THREE.Color(color) 338 | 339 | } 340 | 341 | 342 | this.animate() 343 | 344 | 345 | } 346 | 347 | 348 | 349 | /** 350 | * JsonModel 351 | *****************************/ 352 | 353 | function JsonModel(name, rawModel, texturesReference, clipUVs) { 354 | 355 | 356 | // set default clip value to true 357 | 358 | if (clipUVs === undefined) { 359 | clipUVs = true 360 | } 361 | 362 | 363 | // parent constructor 364 | 365 | THREE.Object3D.call(this) 366 | 367 | 368 | // set modelName 369 | 370 | this.modelName = name 371 | 372 | 373 | // track animation 374 | 375 | this.animationLoop = true 376 | 377 | 378 | // parse model or throw an error if parsing fails 379 | 380 | try { 381 | var model = JSON.parse(rawModel) 382 | } catch (e) { 383 | throw new Error('Couldn\'t parse json model. ' + e.message + '.') 384 | } 385 | 386 | 387 | // get textures and handle animated textures 388 | 389 | var textures = {} 390 | var references = [] 391 | 392 | var animated = [] 393 | var animations = [] 394 | 395 | if (model.hasOwnProperty('textures')) { 396 | 397 | Object.keys(model.textures).forEach(function(key, index) { 398 | 399 | // get texture reference value 400 | var temp = model.textures[key].split('/') 401 | var textureName = temp[temp.length - 1] 402 | 403 | // look for this value in the textures passed in parameter 404 | var reference 405 | for (var i = 0; i < texturesReference.length; i++) { 406 | reference = texturesReference[i] 407 | if (reference.name == textureName) { 408 | break 409 | } 410 | } 411 | 412 | // register the texture or throw an error if the name wasn't in the textures passed in parameter 413 | if (reference.name == textureName) { 414 | 415 | references.push(key) 416 | 417 | // handle animated textures 418 | if (reference.hasOwnProperty('mcmeta')) { 419 | 420 | // parse mcmeta 421 | try { 422 | var mcmeta = JSON.parse(reference.mcmeta) 423 | } catch (e) { 424 | throw new Error('Couldn\'t parse mcmeta for texture "' + textureName + '". ' + e.message + '.') 425 | } 426 | 427 | // check property 428 | if (!mcmeta.hasOwnProperty('animation')) 429 | throw new Error('Couldn\'t find the "animation" property in mcmeta for texture "' + textureName + '"') 430 | 431 | // image buffer to access width and height from dataURL 432 | var imageBuffer = new Image() 433 | imageBuffer.src = reference.texture 434 | 435 | var width = imageBuffer.width 436 | var height = imageBuffer.height 437 | 438 | // check if dimensions are valid 439 | if (height % width != 0) 440 | throw new Error('Image dimensions are invalid for texture "' + textureName + '".') 441 | 442 | // get frames from mcmeta or generate them 443 | var frames = [] 444 | 445 | if (mcmeta.animation.hasOwnProperty('frames')) { 446 | frames = mcmeta.animation.frames 447 | } else { 448 | for (var k = 0; k < height/width; k++) { 449 | frames.push(k) 450 | } 451 | } 452 | 453 | // default value for frametime 454 | var frametime = mcmeta.animation.frametime || 1 455 | 456 | // uniform animation frames 457 | var animation = [] 458 | 459 | for (var i = 0; i < frames.length; i++) { 460 | frame = frames[i] 461 | if (typeof frame == 'number') { 462 | animation.push({index: frame, time:frametime}) 463 | } else { 464 | if (!frame.hasOwnProperty('index')) 465 | throw new Error('Invalid animation frame at index "' + i + '" in mcmeta for texture "' + textureName + '".') 466 | animation.push({index: frame.index, time: frame.time || frametime}) 467 | } 468 | } 469 | 470 | // number of vertical frames 471 | var numberOfImages = height/width 472 | 473 | // register animation 474 | animations.push({height: numberOfImages, frames: animation, currentFrame: 0}) 475 | animated.push(references.length - 1) 476 | 477 | // split frames 478 | var images = [] 479 | 480 | for (var i = 0; i < height/width; i++) { 481 | 482 | // workspace 483 | var canvas = document.createElement('canvas') 484 | canvas.width = width 485 | canvas.height = width 486 | 487 | var ctx = canvas.getContext('2d') 488 | ctx.drawImage(imageBuffer, 0, -i*width) 489 | 490 | images.push(canvas.toDataURL('image/png')) 491 | 492 | } 493 | 494 | // register textures 495 | textures[key] = images 496 | 497 | } else { 498 | 499 | // register texture 500 | textures[key] = reference.texture 501 | 502 | } 503 | 504 | } else { 505 | 506 | throw new Error('Couldn\'t find matching texture for texture reference "' + textureName + '".') 507 | 508 | } 509 | 510 | }) 511 | 512 | } else { 513 | 514 | throw new Error('Couldn\'t find "textures" property.') 515 | 516 | } 517 | 518 | 519 | // access this.animationLoop 520 | 521 | var self = this 522 | 523 | 524 | // generate material 525 | 526 | var materials = [] 527 | 528 | // final material is made of several different materials, one for each texture 529 | references.forEach(function(ref, index) { 530 | 531 | // if animated texture, get the first frame 532 | var image = textures[ref] instanceof Array ? textures[ref][0] : textures[ref] 533 | 534 | // create three js texture from image 535 | var loader = new THREE.TextureLoader() 536 | var texture = loader.load(image) 537 | 538 | // sharp pixels and smooth edges 539 | texture.magFilter = THREE.NearestFilter 540 | texture.minFilter = THREE.LinearFilter 541 | 542 | // map texture to material, keep transparency and fix transparent z-fighting 543 | var mat = new THREE.MeshLambertMaterial({map: texture, transparent: true, alphaTest: 0.5}) 544 | 545 | materials.push(mat) 546 | 547 | // if animated texture 548 | if (textures[ref] instanceof Array) { 549 | 550 | // get texture array and animation frames 551 | var images = textures[ref] 552 | var animation = animations[animated.indexOf(index)] 553 | 554 | // keep scope 555 | ;(function(material, images, animation) { 556 | 557 | // recursively called with a setTimeout 558 | var animateTexture = function() { 559 | 560 | var frame = animation.frames[animation.currentFrame] 561 | 562 | // Prevent crashing with big animated textures 563 | try { 564 | material.map.image.src = images[frame.index] 565 | animation.currentFrame = animation.currentFrame < animation.frames.length - 1 ? animation.currentFrame + 1 : 0 566 | } catch (e) { 567 | console.log(e.message) 568 | } 569 | 570 | window.setTimeout(function() { 571 | if (self.animationLoop) 572 | window.requestAnimationFrame(animateTexture) 573 | }, frame.time*50) // multiplied by the length of a minecraft game tick (50ms) 574 | 575 | } 576 | 577 | // initialize recursion 578 | window.requestAnimationFrame(animateTexture) 579 | 580 | })(mat, images, animation) 581 | 582 | } 583 | 584 | }) 585 | 586 | // extra transparent material for hidden faces 587 | var transparentMaterial = new THREE.MeshBasicMaterial({transparent: true, opacity: 0, alphaTest: 0.5}) 588 | 589 | materials.push(transparentMaterial) 590 | 591 | // big material list from all the other materials 592 | var material = new THREE.MeshFaceMaterial(materials) 593 | 594 | 595 | // create geometry 596 | 597 | // get elements or throw an error if the "elements" property can't be found 598 | 599 | var elements 600 | 601 | if (model.hasOwnProperty('elements')) { 602 | elements = model.elements 603 | } else { 604 | throw new Error('Couldn\'t find "elements" property') 605 | } 606 | 607 | 608 | // generate mesh 609 | 610 | var group = new THREE.Group() 611 | 612 | elements.forEach(function(element, index) { 613 | 614 | 615 | // check properties 616 | 617 | if (!element.hasOwnProperty('from')) 618 | throw new Error('Couldn\'t find "from" property for element "' + index + '".') 619 | if (!(element['from'].length == 3)) 620 | throw new Error('"from" property for element "' + index + '" is invalid.') 621 | 622 | if (!element.hasOwnProperty('to')) 623 | throw new Error('Couldn\'t find "to" property for element "' + index + '".') 624 | if (!(element['to'].length == 3)) 625 | throw new Error('"to" property for element "' + index + '" is invalid.') 626 | 627 | for (var i = 0; i < 3; i++) { 628 | var f = element['from'][i] 629 | var t = element['to'][i] 630 | if (typeof f != 'number' || f < -16) 631 | throw new Error('"from" property for element "' + index + '" is invalid (got "' + f + '" for coordinate "' + ['x', 'y', 'z'][i] + '").') 632 | if (typeof t != 'number' || t > 32) 633 | throw new Error('"to" property for element "' + index + '" is invalid (got "' + t + '" for coordinate "' + ['x', 'y', 'z'][i] + '").') 634 | if (t - f < 0) 635 | throw new Error('"from" property is bigger than "to" property for coordinate "' + ['x', 'y', 'z'][i] + '" in element "' + index + '".') 636 | } 637 | 638 | 639 | // get dimensions and origin 640 | 641 | var width = element['to'][0] - element['from'][0] 642 | var height = element['to'][1] - element['from'][1] 643 | var length = element['to'][2] - element['from'][2] 644 | 645 | var origin = { 646 | x: (element['to'][0] + element['from'][0]) / 2 - 8, 647 | y: (element['to'][1] + element['from'][1]) / 2 - 8, 648 | z: (element['to'][2] + element['from'][2]) / 2 - 8 649 | } 650 | 651 | 652 | // create geometry 653 | 654 | var fix = 0.001 // if a value happens to be 0, the geometry becomes a plane and will have 4 vertices instead of 12. 655 | 656 | var geometry = new THREE.BoxGeometry(width + fix, height + fix, length + fix) 657 | geometry.faceVertexUvs[0] = [] 658 | 659 | 660 | // assign materials 661 | 662 | if (element.hasOwnProperty('faces')) { 663 | 664 | var faces = ['east', 'west', 'up', 'down', 'south', 'north'] 665 | 666 | for (var i = 0; i < 6; i++) { 667 | 668 | var face = faces[i] 669 | 670 | if (element.faces.hasOwnProperty(face)) { 671 | 672 | 673 | // check properties 674 | 675 | if (!element.faces[face].hasOwnProperty('texture')) 676 | throw new Error('Couldn\'t find "texture" property for "' + face + '" face in element "' + index + '".') 677 | if (!element.faces[face].hasOwnProperty('uv')) 678 | throw new Error('Couldn\'t find "uv" property for "' + face + '" face in element "' + index + '".') 679 | if (element.faces[face].uv.length != 4) 680 | throw new Error('The "uv" property for "' + face + '" face in element "' + index + '" is invalid (got "' + element.faces[face].uv + '").') 681 | 682 | 683 | // get texture index 684 | 685 | var ref = element.faces[face].texture 686 | var textureIndex = references.indexOf(ref[0] == '#' ? ref.substring(1) : ref) 687 | 688 | 689 | // check if texture has been registered 690 | 691 | if (textureIndex < 0) 692 | throw new Error('The "texture" property for "' + face + '" face in element "' + index + '" is invalid (got "' + ref + '").') 693 | 694 | geometry.faces[i*2].materialIndex = textureIndex 695 | geometry.faces[i*2+1].materialIndex = textureIndex 696 | 697 | 698 | // uv map 699 | 700 | var uv = element.faces[face].uv 701 | 702 | 703 | // check 704 | 705 | if (clipUVs) { 706 | uv.forEach(function(e, pos) {if (typeof e != 'number') throw new Error('The "uv" property for "' + face + '" face in element "' + index + '" is invalid (got "' + e + '" at index "' + pos + '").')}) 707 | uv.map(function(e) { 708 | if (e + 0.00001 < 0) { 709 | return 0 710 | } else if (e - 0.00001 > 16) { 711 | return 16 712 | } else { 713 | return e 714 | } 715 | }) 716 | } else { 717 | uv.forEach(function(e, pos) {if (typeof e != 'number' || e + 0.00001 < 0 || e - 0.00001 > 16) throw new Error('The "uv" property for "' + face + '" face in element "' + index + '" is invalid (got "' + e + '" at index "' + pos + '").')}) 718 | } 719 | 720 | uv = uv.map(function(e) {return e/16}) 721 | 722 | // fix edges 723 | uv[0] += 0.0005 724 | uv[1] += 0.0005 725 | uv[2] -= 0.0005 726 | uv[3] -= 0.0005 727 | 728 | var map = [ 729 | new THREE.Vector2(uv[0], 1-uv[1]), 730 | new THREE.Vector2(uv[0], 1-uv[3]), 731 | new THREE.Vector2(uv[2], 1-uv[3]), 732 | new THREE.Vector2(uv[2], 1-uv[1]) 733 | ] 734 | 735 | if (element.faces[face].hasOwnProperty('rotation')) { 736 | 737 | var amount = element.faces[face].rotation 738 | 739 | // check property 740 | 741 | if (!([0, 90, 180, 270].indexOf(amount) >= 0)) 742 | throw new Error('The "rotation" property for "' + face + '" face in element "' + index + '" is invalid (got "' + amount + '").') 743 | 744 | // rotate map 745 | 746 | for (var j = 0; j < amount/90; j++) { 747 | map = [map[1], map[2], map[3], map[0]] 748 | } 749 | 750 | } 751 | 752 | geometry.faceVertexUvs[0][i*2] = [map[0], map[1], map[3]] 753 | geometry.faceVertexUvs[0][i*2+1] = [map[1], map[2], map[3]] 754 | 755 | 756 | } else { 757 | 758 | // transparent material 759 | 760 | geometry.faces[i*2].materialIndex = references.length 761 | geometry.faces[i*2+1].materialIndex = references.length 762 | 763 | var map = [ 764 | new THREE.Vector2(0, 0), 765 | new THREE.Vector2(1, 0), 766 | new THREE.Vector2(1, 1), 767 | new THREE.Vector2(0, 1) 768 | ] 769 | 770 | geometry.faceVertexUvs[0][i*2] = [map[0], map[1], map[3]] 771 | geometry.faceVertexUvs[0][i*2+1] = [map[1], map[2], map[3]] 772 | 773 | } 774 | 775 | } 776 | 777 | } 778 | 779 | 780 | // create mesh 781 | 782 | var mesh = new THREE.Mesh(geometry, material) 783 | mesh.position.x = origin.x 784 | mesh.position.y = origin.y 785 | mesh.position.z = origin.z 786 | 787 | 788 | // rotate if "rotation" property is defined 789 | 790 | if (element.hasOwnProperty('rotation')) { 791 | 792 | 793 | // check properties 794 | 795 | if (!element.rotation.hasOwnProperty('origin')) 796 | throw new Error('Couldn\'t find "origin" property in "rotation" for element "' + index + '".') 797 | if (!(element.rotation.origin.length == 3)) 798 | throw new Error('"origin" property in "rotation" for element "' + index + '" is invalid.') 799 | 800 | if (!element.rotation.hasOwnProperty('axis')) 801 | throw new Error('Couldn\'t find "axis" property in "rotation" for element "' + index + '".') 802 | if (!((['x', 'y', 'z']).indexOf(element.rotation.axis) >= 0)) 803 | throw new Error('"axis" property in "rotation" for element "' + index + '" is invalid.') 804 | 805 | if (!element.rotation.hasOwnProperty('angle')) 806 | throw new Error('Couldn\'t find "angle" property in "rotation" for element "' + index + '".') 807 | if (!(([45, 22.5, 0, -22.5, -45]).indexOf(element.rotation.angle) >= 0)) 808 | throw new Error('"angle" property in "rotation" for element "' + index + '" is invalid.') 809 | 810 | 811 | // get origin, axis and angle 812 | 813 | var rotationOrigin = { 814 | x: element.rotation.origin[0] - 8, 815 | y: element.rotation.origin[1] - 8, 816 | z: element.rotation.origin[2] - 8 817 | } 818 | 819 | var axis = element.rotation.axis 820 | var angle = element.rotation.angle 821 | 822 | 823 | // create pivot 824 | 825 | var pivot = new THREE.Group() 826 | pivot.position.x = rotationOrigin.x 827 | pivot.position.y = rotationOrigin.y 828 | pivot.position.z = rotationOrigin.z 829 | 830 | pivot.add(mesh) 831 | 832 | 833 | // adjust mesh coordinates 834 | 835 | mesh.position.x -= rotationOrigin.x 836 | mesh.position.y -= rotationOrigin.y 837 | mesh.position.z -= rotationOrigin.z 838 | 839 | 840 | // rotate pivot 841 | 842 | if (axis == 'x') 843 | pivot.rotateX(angle * Math.PI/180) 844 | else if (axis == 'y') 845 | pivot.rotateY(angle * Math.PI/180) 846 | else if (axis == 'z') 847 | pivot.rotateZ(angle * Math.PI/180) 848 | 849 | 850 | // add pivot 851 | 852 | group.add(pivot) 853 | 854 | } else { 855 | 856 | var pivot = new THREE.Group() 857 | pivot.add(mesh) 858 | 859 | 860 | // add pivot 861 | 862 | group.add(pivot) 863 | 864 | } 865 | 866 | 867 | }) 868 | 869 | 870 | // add group 871 | 872 | this.add(group) 873 | 874 | 875 | // register display options 876 | 877 | var keys = ['thirdperson_righthand', 'thirdperson_lefthand', 'firstperson_righthand', 'firstperson_lefthand', 'gui', 'head', 'ground', 'fixed'] 878 | 879 | this.displayOptions = {} 880 | 881 | for (var i = 0; i < keys.length; i++) { 882 | this.displayOptions[keys[i]] = {rotation: [0, 0, 0], translation: [0, 0, 0], scale: [1, 1, 1]} 883 | } 884 | 885 | this.displayOptions.firstperson = this.displayOptions.firstperson_righthand 886 | this.displayOptions.thirdperson = this.displayOptions.thirdperson_righthand 887 | 888 | if (model.hasOwnProperty('display')) { 889 | 890 | var display = model.display 891 | 892 | for (var option in display) { 893 | if (this.displayOptions.hasOwnProperty(option)) { 894 | 895 | var fields = display[option] 896 | 897 | for (var name in fields) { 898 | if (this.displayOptions[option].hasOwnProperty(name)) { 899 | 900 | var field = fields[name] 901 | 902 | // check value 903 | if (field.length != 3 || typeof field[0] != 'number' || typeof field[1] != 'number' || typeof field[2] != 'number') 904 | throw new Error('"' + name + '" property is invalid for display option "' + option + '".') 905 | 906 | this.displayOptions[option][name] = field 907 | 908 | } 909 | } 910 | 911 | } 912 | } 913 | 914 | } 915 | 916 | 917 | // methods 918 | 919 | var self = this 920 | 921 | 922 | // getCenter 923 | 924 | this.getCenter = function() { 925 | 926 | var group = self.children[0] 927 | 928 | 929 | // compute absolute bounding box 930 | 931 | var box = { 932 | minx: 0, miny: 0, minz: 0, 933 | maxx: 0, maxy: 0, maxz: 0 934 | } 935 | 936 | for (var i = 0; i < group.children.length; i++) { 937 | 938 | var pivot = group.children[i] 939 | var mesh = pivot.children[0] 940 | 941 | for (var j = 0; j < mesh.geometry.vertices.length; j++) { 942 | 943 | // convert vertex coordinates to world coordinates 944 | 945 | var vertex = mesh.geometry.vertices[j].clone() 946 | var abs = mesh.localToWorld(vertex) 947 | 948 | // update bounding box 949 | 950 | if (abs.x < box.minx) box.minx = abs.x 951 | if (abs.y < box.miny) box.miny = abs.y 952 | if (abs.z < box.minz) box.minz = abs.z 953 | 954 | if (abs.x > box.maxx) box.maxx = abs.x 955 | if (abs.y > box.maxy) box.maxy = abs.y 956 | if (abs.z > box.maxz) box.maxz = abs.z 957 | 958 | } 959 | 960 | } 961 | 962 | // return the center of the bounding box 963 | 964 | return new THREE.Vector3( 965 | (box.minx + box.maxx) / 2, 966 | (box.miny + box.maxy) / 2, 967 | (box.minz + box.maxz) / 2 968 | ) 969 | 970 | } 971 | 972 | 973 | // applyDisplay 974 | 975 | this.applyDisplay = function(option) { 976 | 977 | var group = self.children[0] 978 | 979 | if (option == 'block') { 980 | 981 | // reset transformations 982 | group.rotation.set(0, 0, 0) 983 | group.position.set(0, 0, 0) 984 | group.scale.set(1, 1, 1) 985 | 986 | } else { 987 | 988 | if (!self.displayOptions.hasOwnProperty(option)) 989 | throw new Error('Display option is invalid.') 990 | 991 | var options = self.displayOptions[option] 992 | 993 | var rot = options.rotation 994 | var pos = options.translation 995 | var scale = options.scale 996 | 997 | // apply transformations 998 | group.rotation.set(rot[0] * Math.PI/180, rot[1] * Math.PI/180, rot[2] * Math.PI/180) 999 | group.position.set(pos[0], pos[1], pos[2]) 1000 | group.scale.set(scale[0] == 0 ? 0.00001 : scale[0], scale[1] == 0 ? 0.00001 : scale[1], scale[2] == 0 ? 0.00001 : scale[2]) 1001 | 1002 | } 1003 | 1004 | } 1005 | 1006 | 1007 | } 1008 | 1009 | JsonModel.prototype = Object.create(THREE.Object3D.prototype) 1010 | JsonModel.prototype.constructor = JsonModel 1011 | --------------------------------------------------------------------------------