language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadertoy-basic.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadertoy-bleepy-blocks.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadertoy-prep.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-directional-light-shadow-acne.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(-1.4, 14, 12); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -65,7 +62,6 @@ } planeGeo.computeVertexNormals(); - const planeMat = new THREE.MeshPhongMaterial({ map: texture, flatShading: true, @@ -214,7 +210,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2); {
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-directional-light-with-camera-gui.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -177,7 +174,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); {
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-directional-light-with-camera-helper.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -134,7 +131,7 @@ }; onChange(); - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-directional-light.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -131,7 +128,7 @@ }; onChange(); - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-fake.html
@@ -20,11 +20,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-point-light.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -161,7 +158,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); gui.add(light, 'distance', 0, 40).onChange(updateCamera);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-spot-light-with-camera-gui.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -172,7 +169,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); gui.add(light, 'distance', 0, 40).onChange(updateCamera);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-shadows-spot-light-with-shadow-radius.html
@@ -20,13 +20,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -41,7 +38,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 10, 20); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -173,7 +170,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); gui.add(light, 'distance', 0, 40).onChange(updateCamera);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-textured-cube-6-textures.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-textured-cube-adjust.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -91,7 +88,7 @@ texture.needsUpdate = true; } - const gui = new dat.GUI(); + const gui = new GUI(); gui.add(new StringToNumberHelper(texture, 'wrapS'), 'value', wrapModes) .name('texture.wrapS') .onChange(updateTexture);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-textured-cube-wait-for-all-textures.html
@@ -44,11 +44,8 @@ <div class="progress"><div class="progressbar"></div></div> </div> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-textured-cube-wait-for-texture.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-textured-cube.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-tips-preservedrawingbuffer.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-tips-screenshot-bad.html
@@ -36,11 +36,8 @@ <canvas id="c"></canvas> <button id="screenshot" type="button">Save...</button> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-tips-screenshot-good.html
@@ -36,11 +36,8 @@ <canvas id="c"></canvas> <button id="screenshot" type="button">Save...</button> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-tips-tabindex.html
@@ -36,8 +36,8 @@ </div> </div> </body> -<script> -'use strict'; +<script type="module"> + document.querySelectorAll('canvas').forEach((canvas) => { const ctx = canvas.getContext('2d');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-tips-transparent-canvas.html
@@ -46,11 +46,8 @@ <h1>Cubes-R-Us!</h1> </div> </div> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency-doubleside-hack.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -37,7 +34,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.z = 4; - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency-doubleside.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -37,7 +34,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.z = 4; - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency-intersecting-planes-alphatest.html
@@ -19,13 +19,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script src="../3rdparty/dat.gui.min.js"></script> -<script> -'use strict'; - -/* global THREE, dat */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; +import { GUI } from '../3rdparty/dat.gui.module.js'; function main() { const canvas = document.querySelector('#c'); @@ -38,7 +35,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0.5, 1, 0.5); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update(); @@ -106,7 +103,7 @@ } } - const gui = new dat.GUI(); + const gui = new GUI(); gui.add(new AllMaterialPropertyGUIHelper('alphaTest', scene), 'value', 0, 1) .name('alphaTest') .onChange(requestRenderIfNotRequested);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency-intersecting-planes-fixed.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -37,7 +34,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0.5, 1, 0.5); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency-intersecting-planes.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -37,7 +34,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0.5, 1, 0.5); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-transparency.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -37,7 +34,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.z = 4; - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 0, 0); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-voxel-geometry-culled-faces-ui.html
@@ -70,12 +70,9 @@ </div> </div> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; class VoxelWorld { constructor(options) { @@ -353,7 +350,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-voxel-geometry-culled-faces-with-textures.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; class VoxelWorld { constructor(options) { @@ -203,7 +200,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2); controls.update(); @@ -220,7 +217,6 @@ addLight(-1, 2, 4); addLight( 1, -1, -2); - const loader = new THREE.TextureLoader(); const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render); texture.magFilter = THREE.NearestFilter;
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-voxel-geometry-culled-faces.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; class VoxelWorld { constructor(cellSize) { @@ -186,7 +183,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-voxel-geometry-merged.html
@@ -19,13 +19,10 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/utils/BufferGeometryUtils.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {BufferGeometryUtils} from './resources/threejs/r108/examples/jsm/utils/BufferGeometryUtils.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -40,7 +37,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(cellSize / 2, 60, cellSize); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(cellSize / 2, 60, cellSize / 2); controls.update(); @@ -70,7 +67,7 @@ } } - const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries( + const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( geometries, false); const material = new THREE.MeshPhongMaterial({color: 'green'}); const mesh = new THREE.Mesh(mergedGeometry, material);
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-voxel-geometry-separate-cubes.html
@@ -19,12 +19,9 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -39,7 +36,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3); - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2); controls.update();
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-basic-vr-optional.html
@@ -28,13 +28,10 @@ <a href="?" id="nonvr">Use Non-VR Mode</a> </div> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script src="resources/threejs/r108/js/controls/OrbitControls.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; +import {OrbitControls} from './resources/threejs/r108/examples/jsm/controls/OrbitControls.js'; function main() { const canvas = document.querySelector('#c'); @@ -50,12 +47,12 @@ const allowvr = params.get('allowvr') === 'true'; if (allowvr) { renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); document.querySelector('#vr').style.display = 'none'; } else { // no VR, add some controls camera.position.y = 1.6; - const controls = new THREE.OrbitControls(camera, canvas); + const controls = new OrbitControls(camera, canvas); controls.target.set(0, 1.6, -2); controls.update(); document.querySelector('#nonvr').style.display = 'none';
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-basic-w-background.html
@@ -19,18 +19,15 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-basic.html
@@ -19,18 +19,15 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-look-to-select-selector.html
@@ -19,11 +19,8 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; function main() { const canvas = document.querySelector('#c');
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-look-to-select-w-cursor.html
@@ -19,18 +19,15 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-look-to-select.html
@@ -19,18 +19,15 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-point-to-select-w-move.html
@@ -19,19 +19,16 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script src="resources/threejs/r108/js/utils/SceneUtils.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; +import {SceneUtils} from './resources/threejs/r108/examples/jsm/utils/SceneUtils.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default @@ -189,8 +186,8 @@ object: selectedObject, parent: selectedObject.parent, }); - THREE.SceneUtils.detach(selectedObject, selectedObject.parent, scene); - THREE.SceneUtils.attach(selectedObject, scene, controller); + SceneUtils.detach(selectedObject, selectedObject.parent, scene); + SceneUtils.attach(selectedObject, scene, controller); } }); @@ -199,8 +196,8 @@ const selection = controllerToSelection.get(controller); if (selection) { controllerToSelection.delete(controller); - THREE.SceneUtils.detach(selection.object, controller, scene); - THREE.SceneUtils.attach(selection.object, scene, selection.parent); + SceneUtils.detach(selection.object, controller, scene); + SceneUtils.attach(selection.object, scene, selection.parent); } });
true
Other
mrdoob
three.js
d2fd74e7b551b049b48e30bf191926aae87291fa.json
use modules in all examples
threejs/threejs-webvr-point-to-select.html
@@ -19,18 +19,15 @@ <body> <canvas id="c"></canvas> </body> -<script src="resources/threejs/r108/three.min.js"></script> -<script src="resources/threejs/r108/js/vr/WebVR.js"></script> -<script> -'use strict'; - -/* global THREE */ +<script type="module"> +import * as THREE from './resources/threejs/r108/build/three.module.js'; +import {WEBVR} from './resources/threejs/r108/examples/jsm/vr/WebVR.js'; function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({canvas}); renderer.vr.enabled = true; - document.body.appendChild(THREE.WEBVR.createButton(renderer)); + document.body.appendChild(WEBVR.createButton(renderer)); const fov = 75; const aspect = 2; // the canvas default
true
Other
mrdoob
three.js
53471122b49e92f301656c7b6274af224e61866c.json
add dat.gui module
3rdparty/dat.gui.module.js
@@ -0,0 +1,2523 @@ +/** + * dat-gui JavaScript Controller Library + * http://code.google.com/p/dat-gui + * + * Copyright 2011 Data Arts Team, Google Creative Lab + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + */ + +function ___$insertStyle(css) { + if (!css) { + return; + } + if (typeof window === 'undefined') { + return; + } + + var style = document.createElement('style'); + + style.setAttribute('type', 'text/css'); + style.innerHTML = css; + document.head.appendChild(style); + + return css; +} + +function colorToString (color, forceCSSHex) { + var colorFormat = color.__state.conversionName.toString(); + var r = Math.round(color.r); + var g = Math.round(color.g); + var b = Math.round(color.b); + var a = color.a; + var h = Math.round(color.h); + var s = color.s.toFixed(1); + var v = color.v.toFixed(1); + if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') { + var str = color.hex.toString(16); + while (str.length < 6) { + str = '0' + str; + } + return '#' + str; + } else if (colorFormat === 'CSS_RGB') { + return 'rgb(' + r + ',' + g + ',' + b + ')'; + } else if (colorFormat === 'CSS_RGBA') { + return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; + } else if (colorFormat === 'HEX') { + return '0x' + color.hex.toString(16); + } else if (colorFormat === 'RGB_ARRAY') { + return '[' + r + ',' + g + ',' + b + ']'; + } else if (colorFormat === 'RGBA_ARRAY') { + return '[' + r + ',' + g + ',' + b + ',' + a + ']'; + } else if (colorFormat === 'RGB_OBJ') { + return '{r:' + r + ',g:' + g + ',b:' + b + '}'; + } else if (colorFormat === 'RGBA_OBJ') { + return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}'; + } else if (colorFormat === 'HSV_OBJ') { + return '{h:' + h + ',s:' + s + ',v:' + v + '}'; + } else if (colorFormat === 'HSVA_OBJ') { + return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}'; + } + return 'unknown format'; +} + +var ARR_EACH = Array.prototype.forEach; +var ARR_SLICE = Array.prototype.slice; +var Common = { + BREAK: {}, + extend: function extend(target) { + this.each(ARR_SLICE.call(arguments, 1), function (obj) { + var keys = this.isObject(obj) ? Object.keys(obj) : []; + keys.forEach(function (key) { + if (!this.isUndefined(obj[key])) { + target[key] = obj[key]; + } + }.bind(this)); + }, this); + return target; + }, + defaults: function defaults(target) { + this.each(ARR_SLICE.call(arguments, 1), function (obj) { + var keys = this.isObject(obj) ? Object.keys(obj) : []; + keys.forEach(function (key) { + if (this.isUndefined(target[key])) { + target[key] = obj[key]; + } + }.bind(this)); + }, this); + return target; + }, + compose: function compose() { + var toCall = ARR_SLICE.call(arguments); + return function () { + var args = ARR_SLICE.call(arguments); + for (var i = toCall.length - 1; i >= 0; i--) { + args = [toCall[i].apply(this, args)]; + } + return args[0]; + }; + }, + each: function each(obj, itr, scope) { + if (!obj) { + return; + } + if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) { + obj.forEach(itr, scope); + } else if (obj.length === obj.length + 0) { + var key = void 0; + var l = void 0; + for (key = 0, l = obj.length; key < l; key++) { + if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) { + return; + } + } + } else { + for (var _key in obj) { + if (itr.call(scope, obj[_key], _key) === this.BREAK) { + return; + } + } + } + }, + defer: function defer(fnc) { + setTimeout(fnc, 0); + }, + debounce: function debounce(func, threshold, callImmediately) { + var timeout = void 0; + return function () { + var obj = this; + var args = arguments; + function delayed() { + timeout = null; + if (!callImmediately) func.apply(obj, args); + } + var callNow = callImmediately || !timeout; + clearTimeout(timeout); + timeout = setTimeout(delayed, threshold); + if (callNow) { + func.apply(obj, args); + } + }; + }, + toArray: function toArray(obj) { + if (obj.toArray) return obj.toArray(); + return ARR_SLICE.call(obj); + }, + isUndefined: function isUndefined(obj) { + return obj === undefined; + }, + isNull: function isNull(obj) { + return obj === null; + }, + isNaN: function (_isNaN) { + function isNaN(_x) { + return _isNaN.apply(this, arguments); + } + isNaN.toString = function () { + return _isNaN.toString(); + }; + return isNaN; + }(function (obj) { + return isNaN(obj); + }), + isArray: Array.isArray || function (obj) { + return obj.constructor === Array; + }, + isObject: function isObject(obj) { + return obj === Object(obj); + }, + isNumber: function isNumber(obj) { + return obj === obj + 0; + }, + isString: function isString(obj) { + return obj === obj + ''; + }, + isBoolean: function isBoolean(obj) { + return obj === false || obj === true; + }, + isFunction: function isFunction(obj) { + return Object.prototype.toString.call(obj) === '[object Function]'; + } +}; + +var INTERPRETATIONS = [ +{ + litmus: Common.isString, + conversions: { + THREE_CHAR_HEX: { + read: function read(original) { + var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i); + if (test === null) { + return false; + } + return { + space: 'HEX', + hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0) + }; + }, + write: colorToString + }, + SIX_CHAR_HEX: { + read: function read(original) { + var test = original.match(/^#([A-F0-9]{6})$/i); + if (test === null) { + return false; + } + return { + space: 'HEX', + hex: parseInt('0x' + test[1].toString(), 0) + }; + }, + write: colorToString + }, + CSS_RGB: { + read: function read(original) { + var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/); + if (test === null) { + return false; + } + return { + space: 'RGB', + r: parseFloat(test[1]), + g: parseFloat(test[2]), + b: parseFloat(test[3]) + }; + }, + write: colorToString + }, + CSS_RGBA: { + read: function read(original) { + var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/); + if (test === null) { + return false; + } + return { + space: 'RGB', + r: parseFloat(test[1]), + g: parseFloat(test[2]), + b: parseFloat(test[3]), + a: parseFloat(test[4]) + }; + }, + write: colorToString + } + } +}, +{ + litmus: Common.isNumber, + conversions: { + HEX: { + read: function read(original) { + return { + space: 'HEX', + hex: original, + conversionName: 'HEX' + }; + }, + write: function write(color) { + return color.hex; + } + } + } +}, +{ + litmus: Common.isArray, + conversions: { + RGB_ARRAY: { + read: function read(original) { + if (original.length !== 3) { + return false; + } + return { + space: 'RGB', + r: original[0], + g: original[1], + b: original[2] + }; + }, + write: function write(color) { + return [color.r, color.g, color.b]; + } + }, + RGBA_ARRAY: { + read: function read(original) { + if (original.length !== 4) return false; + return { + space: 'RGB', + r: original[0], + g: original[1], + b: original[2], + a: original[3] + }; + }, + write: function write(color) { + return [color.r, color.g, color.b, color.a]; + } + } + } +}, +{ + litmus: Common.isObject, + conversions: { + RGBA_OBJ: { + read: function read(original) { + if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) { + return { + space: 'RGB', + r: original.r, + g: original.g, + b: original.b, + a: original.a + }; + } + return false; + }, + write: function write(color) { + return { + r: color.r, + g: color.g, + b: color.b, + a: color.a + }; + } + }, + RGB_OBJ: { + read: function read(original) { + if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) { + return { + space: 'RGB', + r: original.r, + g: original.g, + b: original.b + }; + } + return false; + }, + write: function write(color) { + return { + r: color.r, + g: color.g, + b: color.b + }; + } + }, + HSVA_OBJ: { + read: function read(original) { + if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) { + return { + space: 'HSV', + h: original.h, + s: original.s, + v: original.v, + a: original.a + }; + } + return false; + }, + write: function write(color) { + return { + h: color.h, + s: color.s, + v: color.v, + a: color.a + }; + } + }, + HSV_OBJ: { + read: function read(original) { + if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) { + return { + space: 'HSV', + h: original.h, + s: original.s, + v: original.v + }; + } + return false; + }, + write: function write(color) { + return { + h: color.h, + s: color.s, + v: color.v + }; + } + } + } +}]; +var result = void 0; +var toReturn = void 0; +var interpret = function interpret() { + toReturn = false; + var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0]; + Common.each(INTERPRETATIONS, function (family) { + if (family.litmus(original)) { + Common.each(family.conversions, function (conversion, conversionName) { + result = conversion.read(original); + if (toReturn === false && result !== false) { + toReturn = result; + result.conversionName = conversionName; + result.conversion = conversion; + return Common.BREAK; + } + }); + return Common.BREAK; + } + }); + return toReturn; +}; + +var tmpComponent = void 0; +var ColorMath = { + hsv_to_rgb: function hsv_to_rgb(h, s, v) { + var hi = Math.floor(h / 60) % 6; + var f = h / 60 - Math.floor(h / 60); + var p = v * (1.0 - s); + var q = v * (1.0 - f * s); + var t = v * (1.0 - (1.0 - f) * s); + var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi]; + return { + r: c[0] * 255, + g: c[1] * 255, + b: c[2] * 255 + }; + }, + rgb_to_hsv: function rgb_to_hsv(r, g, b) { + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h = void 0; + var s = void 0; + if (max !== 0) { + s = delta / max; + } else { + return { + h: NaN, + s: 0, + v: 0 + }; + } + if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else { + h = 4 + (r - g) / delta; + } + h /= 6; + if (h < 0) { + h += 1; + } + return { + h: h * 360, + s: s, + v: max / 255 + }; + }, + rgb_to_hex: function rgb_to_hex(r, g, b) { + var hex = this.hex_with_component(0, 2, r); + hex = this.hex_with_component(hex, 1, g); + hex = this.hex_with_component(hex, 0, b); + return hex; + }, + component_from_hex: function component_from_hex(hex, componentIndex) { + return hex >> componentIndex * 8 & 0xFF; + }, + hex_with_component: function hex_with_component(hex, componentIndex, value) { + return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent); + } +}; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; +} : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; +}; + + + + + + + + + + + +var classCallCheck = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; + +var createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps); + if (staticProps) defineProperties(Constructor, staticProps); + return Constructor; + }; +}(); + + + + + + + +var get = function get(object, property, receiver) { + if (object === null) object = Function.prototype; + var desc = Object.getOwnPropertyDescriptor(object, property); + + if (desc === undefined) { + var parent = Object.getPrototypeOf(object); + + if (parent === null) { + return undefined; + } else { + return get(parent, property, receiver); + } + } else if ("value" in desc) { + return desc.value; + } else { + var getter = desc.get; + + if (getter === undefined) { + return undefined; + } + + return getter.call(receiver); + } +}; + +var inherits = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; +}; + + + + + + + + + + + +var possibleConstructorReturn = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && (typeof call === "object" || typeof call === "function") ? call : self; +}; + +var Color = function () { + function Color() { + classCallCheck(this, Color); + this.__state = interpret.apply(this, arguments); + if (this.__state === false) { + throw new Error('Failed to interpret color arguments'); + } + this.__state.a = this.__state.a || 1; + } + createClass(Color, [{ + key: 'toString', + value: function toString() { + return colorToString(this); + } + }, { + key: 'toHexString', + value: function toHexString() { + return colorToString(this, true); + } + }, { + key: 'toOriginal', + value: function toOriginal() { + return this.__state.conversion.write(this); + } + }]); + return Color; +}(); +function defineRGBComponent(target, component, componentHexIndex) { + Object.defineProperty(target, component, { + get: function get$$1() { + if (this.__state.space === 'RGB') { + return this.__state[component]; + } + Color.recalculateRGB(this, component, componentHexIndex); + return this.__state[component]; + }, + set: function set$$1(v) { + if (this.__state.space !== 'RGB') { + Color.recalculateRGB(this, component, componentHexIndex); + this.__state.space = 'RGB'; + } + this.__state[component] = v; + } + }); +} +function defineHSVComponent(target, component) { + Object.defineProperty(target, component, { + get: function get$$1() { + if (this.__state.space === 'HSV') { + return this.__state[component]; + } + Color.recalculateHSV(this); + return this.__state[component]; + }, + set: function set$$1(v) { + if (this.__state.space !== 'HSV') { + Color.recalculateHSV(this); + this.__state.space = 'HSV'; + } + this.__state[component] = v; + } + }); +} +Color.recalculateRGB = function (color, component, componentHexIndex) { + if (color.__state.space === 'HEX') { + color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex); + } else if (color.__state.space === 'HSV') { + Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v)); + } else { + throw new Error('Corrupted color state'); + } +}; +Color.recalculateHSV = function (color) { + var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b); + Common.extend(color.__state, { + s: result.s, + v: result.v + }); + if (!Common.isNaN(result.h)) { + color.__state.h = result.h; + } else if (Common.isUndefined(color.__state.h)) { + color.__state.h = 0; + } +}; +Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a']; +defineRGBComponent(Color.prototype, 'r', 2); +defineRGBComponent(Color.prototype, 'g', 1); +defineRGBComponent(Color.prototype, 'b', 0); +defineHSVComponent(Color.prototype, 'h'); +defineHSVComponent(Color.prototype, 's'); +defineHSVComponent(Color.prototype, 'v'); +Object.defineProperty(Color.prototype, 'a', { + get: function get$$1() { + return this.__state.a; + }, + set: function set$$1(v) { + this.__state.a = v; + } +}); +Object.defineProperty(Color.prototype, 'hex', { + get: function get$$1() { + if (!this.__state.space !== 'HEX') { + this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b); + } + return this.__state.hex; + }, + set: function set$$1(v) { + this.__state.space = 'HEX'; + this.__state.hex = v; + } +}); + +var Controller = function () { + function Controller(object, property) { + classCallCheck(this, Controller); + this.initialValue = object[property]; + this.domElement = document.createElement('div'); + this.object = object; + this.property = property; + this.__onChange = undefined; + this.__onFinishChange = undefined; + } + createClass(Controller, [{ + key: 'onChange', + value: function onChange(fnc) { + this.__onChange = fnc; + return this; + } + }, { + key: 'onFinishChange', + value: function onFinishChange(fnc) { + this.__onFinishChange = fnc; + return this; + } + }, { + key: 'setValue', + value: function setValue(newValue) { + this.object[this.property] = newValue; + if (this.__onChange) { + this.__onChange.call(this, newValue); + } + this.updateDisplay(); + return this; + } + }, { + key: 'getValue', + value: function getValue() { + return this.object[this.property]; + } + }, { + key: 'updateDisplay', + value: function updateDisplay() { + return this; + } + }, { + key: 'isModified', + value: function isModified() { + return this.initialValue !== this.getValue(); + } + }]); + return Controller; +}(); + +var EVENT_MAP = { + HTMLEvents: ['change'], + MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'], + KeyboardEvents: ['keydown'] +}; +var EVENT_MAP_INV = {}; +Common.each(EVENT_MAP, function (v, k) { + Common.each(v, function (e) { + EVENT_MAP_INV[e] = k; + }); +}); +var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/; +function cssValueToPixels(val) { + if (val === '0' || Common.isUndefined(val)) { + return 0; + } + var match = val.match(CSS_VALUE_PIXELS); + if (!Common.isNull(match)) { + return parseFloat(match[1]); + } + return 0; +} +var dom = { + makeSelectable: function makeSelectable(elem, selectable) { + if (elem === undefined || elem.style === undefined) return; + elem.onselectstart = selectable ? function () { + return false; + } : function () {}; + elem.style.MozUserSelect = selectable ? 'auto' : 'none'; + elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none'; + elem.unselectable = selectable ? 'on' : 'off'; + }, + makeFullscreen: function makeFullscreen(elem, hor, vert) { + var vertical = vert; + var horizontal = hor; + if (Common.isUndefined(horizontal)) { + horizontal = true; + } + if (Common.isUndefined(vertical)) { + vertical = true; + } + elem.style.position = 'absolute'; + if (horizontal) { + elem.style.left = 0; + elem.style.right = 0; + } + if (vertical) { + elem.style.top = 0; + elem.style.bottom = 0; + } + }, + fakeEvent: function fakeEvent(elem, eventType, pars, aux) { + var params = pars || {}; + var className = EVENT_MAP_INV[eventType]; + if (!className) { + throw new Error('Event type ' + eventType + ' not supported.'); + } + var evt = document.createEvent(className); + switch (className) { + case 'MouseEvents': + { + var clientX = params.x || params.clientX || 0; + var clientY = params.y || params.clientY || 0; + evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, + 0, + clientX, + clientY, + false, false, false, false, 0, null); + break; + } + case 'KeyboardEvents': + { + var init = evt.initKeyboardEvent || evt.initKeyEvent; + Common.defaults(params, { + cancelable: true, + ctrlKey: false, + altKey: false, + shiftKey: false, + metaKey: false, + keyCode: undefined, + charCode: undefined + }); + init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode); + break; + } + default: + { + evt.initEvent(eventType, params.bubbles || false, params.cancelable || true); + break; + } + } + Common.defaults(evt, aux); + elem.dispatchEvent(evt); + }, + bind: function bind(elem, event, func, newBool) { + var bool = newBool || false; + if (elem.addEventListener) { + elem.addEventListener(event, func, bool); + } else if (elem.attachEvent) { + elem.attachEvent('on' + event, func); + } + return dom; + }, + unbind: function unbind(elem, event, func, newBool) { + var bool = newBool || false; + if (elem.removeEventListener) { + elem.removeEventListener(event, func, bool); + } else if (elem.detachEvent) { + elem.detachEvent('on' + event, func); + } + return dom; + }, + addClass: function addClass(elem, className) { + if (elem.className === undefined) { + elem.className = className; + } else if (elem.className !== className) { + var classes = elem.className.split(/ +/); + if (classes.indexOf(className) === -1) { + classes.push(className); + elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, ''); + } + } + return dom; + }, + removeClass: function removeClass(elem, className) { + if (className) { + if (elem.className === className) { + elem.removeAttribute('class'); + } else { + var classes = elem.className.split(/ +/); + var index = classes.indexOf(className); + if (index !== -1) { + classes.splice(index, 1); + elem.className = classes.join(' '); + } + } + } else { + elem.className = undefined; + } + return dom; + }, + hasClass: function hasClass(elem, className) { + return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false; + }, + getWidth: function getWidth(elem) { + var style = getComputedStyle(elem); + return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width); + }, + getHeight: function getHeight(elem) { + var style = getComputedStyle(elem); + return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height); + }, + getOffset: function getOffset(el) { + var elem = el; + var offset = { left: 0, top: 0 }; + if (elem.offsetParent) { + do { + offset.left += elem.offsetLeft; + offset.top += elem.offsetTop; + elem = elem.offsetParent; + } while (elem); + } + return offset; + }, + isActive: function isActive(elem) { + return elem === document.activeElement && (elem.type || elem.href); + } +}; + +var BooleanController = function (_Controller) { + inherits(BooleanController, _Controller); + function BooleanController(object, property) { + classCallCheck(this, BooleanController); + var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property)); + var _this = _this2; + _this2.__prev = _this2.getValue(); + _this2.__checkbox = document.createElement('input'); + _this2.__checkbox.setAttribute('type', 'checkbox'); + function onChange() { + _this.setValue(!_this.__prev); + } + dom.bind(_this2.__checkbox, 'change', onChange, false); + _this2.domElement.appendChild(_this2.__checkbox); + _this2.updateDisplay(); + return _this2; + } + createClass(BooleanController, [{ + key: 'setValue', + value: function setValue(v) { + var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v); + if (this.__onFinishChange) { + this.__onFinishChange.call(this, this.getValue()); + } + this.__prev = this.getValue(); + return toReturn; + } + }, { + key: 'updateDisplay', + value: function updateDisplay() { + if (this.getValue() === true) { + this.__checkbox.setAttribute('checked', 'checked'); + this.__checkbox.checked = true; + this.__prev = true; + } else { + this.__checkbox.checked = false; + this.__prev = false; + } + return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this); + } + }]); + return BooleanController; +}(Controller); + +var OptionController = function (_Controller) { + inherits(OptionController, _Controller); + function OptionController(object, property, opts) { + classCallCheck(this, OptionController); + var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property)); + var options = opts; + var _this = _this2; + _this2.__select = document.createElement('select'); + if (Common.isArray(options)) { + var map = {}; + Common.each(options, function (element) { + map[element] = element; + }); + options = map; + } + Common.each(options, function (value, key) { + var opt = document.createElement('option'); + opt.innerHTML = key; + opt.setAttribute('value', value); + _this.__select.appendChild(opt); + }); + _this2.updateDisplay(); + dom.bind(_this2.__select, 'change', function () { + var desiredValue = this.options[this.selectedIndex].value; + _this.setValue(desiredValue); + }); + _this2.domElement.appendChild(_this2.__select); + return _this2; + } + createClass(OptionController, [{ + key: 'setValue', + value: function setValue(v) { + var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v); + if (this.__onFinishChange) { + this.__onFinishChange.call(this, this.getValue()); + } + return toReturn; + } + }, { + key: 'updateDisplay', + value: function updateDisplay() { + if (dom.isActive(this.__select)) return this; + this.__select.value = this.getValue(); + return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this); + } + }]); + return OptionController; +}(Controller); + +var StringController = function (_Controller) { + inherits(StringController, _Controller); + function StringController(object, property) { + classCallCheck(this, StringController); + var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property)); + var _this = _this2; + function onChange() { + _this.setValue(_this.__input.value); + } + function onBlur() { + if (_this.__onFinishChange) { + _this.__onFinishChange.call(_this, _this.getValue()); + } + } + _this2.__input = document.createElement('input'); + _this2.__input.setAttribute('type', 'text'); + dom.bind(_this2.__input, 'keyup', onChange); + dom.bind(_this2.__input, 'change', onChange); + dom.bind(_this2.__input, 'blur', onBlur); + dom.bind(_this2.__input, 'keydown', function (e) { + if (e.keyCode === 13) { + this.blur(); + } + }); + _this2.updateDisplay(); + _this2.domElement.appendChild(_this2.__input); + return _this2; + } + createClass(StringController, [{ + key: 'updateDisplay', + value: function updateDisplay() { + if (!dom.isActive(this.__input)) { + this.__input.value = this.getValue(); + } + return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this); + } + }]); + return StringController; +}(Controller); + +function numDecimals(x) { + var _x = x.toString(); + if (_x.indexOf('.') > -1) { + return _x.length - _x.indexOf('.') - 1; + } + return 0; +} +var NumberController = function (_Controller) { + inherits(NumberController, _Controller); + function NumberController(object, property, params) { + classCallCheck(this, NumberController); + var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property)); + var _params = params || {}; + _this.__min = _params.min; + _this.__max = _params.max; + _this.__step = _params.step; + if (Common.isUndefined(_this.__step)) { + if (_this.initialValue === 0) { + _this.__impliedStep = 1; + } else { + _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10; + } + } else { + _this.__impliedStep = _this.__step; + } + _this.__precision = numDecimals(_this.__impliedStep); + return _this; + } + createClass(NumberController, [{ + key: 'setValue', + value: function setValue(v) { + var _v = v; + if (this.__min !== undefined && _v < this.__min) { + _v = this.__min; + } else if (this.__max !== undefined && _v > this.__max) { + _v = this.__max; + } + if (this.__step !== undefined && _v % this.__step !== 0) { + _v = Math.round(_v / this.__step) * this.__step; + } + return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v); + } + }, { + key: 'min', + value: function min(minValue) { + this.__min = minValue; + return this; + } + }, { + key: 'max', + value: function max(maxValue) { + this.__max = maxValue; + return this; + } + }, { + key: 'step', + value: function step(stepValue) { + this.__step = stepValue; + this.__impliedStep = stepValue; + this.__precision = numDecimals(stepValue); + return this; + } + }]); + return NumberController; +}(Controller); + +function roundToDecimal(value, decimals) { + var tenTo = Math.pow(10, decimals); + return Math.round(value * tenTo) / tenTo; +} +var NumberControllerBox = function (_NumberController) { + inherits(NumberControllerBox, _NumberController); + function NumberControllerBox(object, property, params) { + classCallCheck(this, NumberControllerBox); + var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params)); + _this2.__truncationSuspended = false; + var _this = _this2; + var prevY = void 0; + function onChange() { + var attempted = parseFloat(_this.__input.value); + if (!Common.isNaN(attempted)) { + _this.setValue(attempted); + } + } + function onFinish() { + if (_this.__onFinishChange) { + _this.__onFinishChange.call(_this, _this.getValue()); + } + } + function onBlur() { + onFinish(); + } + function onMouseDrag(e) { + var diff = prevY - e.clientY; + _this.setValue(_this.getValue() + diff * _this.__impliedStep); + prevY = e.clientY; + } + function onMouseUp() { + dom.unbind(window, 'mousemove', onMouseDrag); + dom.unbind(window, 'mouseup', onMouseUp); + onFinish(); + } + function onMouseDown(e) { + dom.bind(window, 'mousemove', onMouseDrag); + dom.bind(window, 'mouseup', onMouseUp); + prevY = e.clientY; + } + _this2.__input = document.createElement('input'); + _this2.__input.setAttribute('type', 'text'); + dom.bind(_this2.__input, 'change', onChange); + dom.bind(_this2.__input, 'blur', onBlur); + dom.bind(_this2.__input, 'mousedown', onMouseDown); + dom.bind(_this2.__input, 'keydown', function (e) { + if (e.keyCode === 13) { + _this.__truncationSuspended = true; + this.blur(); + _this.__truncationSuspended = false; + onFinish(); + } + }); + _this2.updateDisplay(); + _this2.domElement.appendChild(_this2.__input); + return _this2; + } + createClass(NumberControllerBox, [{ + key: 'updateDisplay', + value: function updateDisplay() { + this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision); + return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this); + } + }]); + return NumberControllerBox; +}(NumberController); + +function map(v, i1, i2, o1, o2) { + return o1 + (o2 - o1) * ((v - i1) / (i2 - i1)); +} +var NumberControllerSlider = function (_NumberController) { + inherits(NumberControllerSlider, _NumberController); + function NumberControllerSlider(object, property, min, max, step) { + classCallCheck(this, NumberControllerSlider); + var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, { min: min, max: max, step: step })); + var _this = _this2; + _this2.__background = document.createElement('div'); + _this2.__foreground = document.createElement('div'); + dom.bind(_this2.__background, 'mousedown', onMouseDown); + dom.bind(_this2.__background, 'touchstart', onTouchStart); + dom.addClass(_this2.__background, 'slider'); + dom.addClass(_this2.__foreground, 'slider-fg'); + function onMouseDown(e) { + document.activeElement.blur(); + dom.bind(window, 'mousemove', onMouseDrag); + dom.bind(window, 'mouseup', onMouseUp); + onMouseDrag(e); + } + function onMouseDrag(e) { + e.preventDefault(); + var bgRect = _this.__background.getBoundingClientRect(); + _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max)); + return false; + } + function onMouseUp() { + dom.unbind(window, 'mousemove', onMouseDrag); + dom.unbind(window, 'mouseup', onMouseUp); + if (_this.__onFinishChange) { + _this.__onFinishChange.call(_this, _this.getValue()); + } + } + function onTouchStart(e) { + if (e.touches.length !== 1) { + return; + } + dom.bind(window, 'touchmove', onTouchMove); + dom.bind(window, 'touchend', onTouchEnd); + onTouchMove(e); + } + function onTouchMove(e) { + var clientX = e.touches[0].clientX; + var bgRect = _this.__background.getBoundingClientRect(); + _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max)); + } + function onTouchEnd() { + dom.unbind(window, 'touchmove', onTouchMove); + dom.unbind(window, 'touchend', onTouchEnd); + if (_this.__onFinishChange) { + _this.__onFinishChange.call(_this, _this.getValue()); + } + } + _this2.updateDisplay(); + _this2.__background.appendChild(_this2.__foreground); + _this2.domElement.appendChild(_this2.__background); + return _this2; + } + createClass(NumberControllerSlider, [{ + key: 'updateDisplay', + value: function updateDisplay() { + var pct = (this.getValue() - this.__min) / (this.__max - this.__min); + this.__foreground.style.width = pct * 100 + '%'; + return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this); + } + }]); + return NumberControllerSlider; +}(NumberController); + +var FunctionController = function (_Controller) { + inherits(FunctionController, _Controller); + function FunctionController(object, property, text) { + classCallCheck(this, FunctionController); + var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property)); + var _this = _this2; + _this2.__button = document.createElement('div'); + _this2.__button.innerHTML = text === undefined ? 'Fire' : text; + dom.bind(_this2.__button, 'click', function (e) { + e.preventDefault(); + _this.fire(); + return false; + }); + dom.addClass(_this2.__button, 'button'); + _this2.domElement.appendChild(_this2.__button); + return _this2; + } + createClass(FunctionController, [{ + key: 'fire', + value: function fire() { + if (this.__onChange) { + this.__onChange.call(this); + } + this.getValue().call(this.object); + if (this.__onFinishChange) { + this.__onFinishChange.call(this, this.getValue()); + } + } + }]); + return FunctionController; +}(Controller); + +var ColorController = function (_Controller) { + inherits(ColorController, _Controller); + function ColorController(object, property) { + classCallCheck(this, ColorController); + var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property)); + _this2.__color = new Color(_this2.getValue()); + _this2.__temp = new Color(0); + var _this = _this2; + _this2.domElement = document.createElement('div'); + dom.makeSelectable(_this2.domElement, false); + _this2.__selector = document.createElement('div'); + _this2.__selector.className = 'selector'; + _this2.__saturation_field = document.createElement('div'); + _this2.__saturation_field.className = 'saturation-field'; + _this2.__field_knob = document.createElement('div'); + _this2.__field_knob.className = 'field-knob'; + _this2.__field_knob_border = '2px solid '; + _this2.__hue_knob = document.createElement('div'); + _this2.__hue_knob.className = 'hue-knob'; + _this2.__hue_field = document.createElement('div'); + _this2.__hue_field.className = 'hue-field'; + _this2.__input = document.createElement('input'); + _this2.__input.type = 'text'; + _this2.__input_textShadow = '0 1px 1px '; + dom.bind(_this2.__input, 'keydown', function (e) { + if (e.keyCode === 13) { + onBlur.call(this); + } + }); + dom.bind(_this2.__input, 'blur', onBlur); + dom.bind(_this2.__selector, 'mousedown', function () { + dom.addClass(this, 'drag').bind(window, 'mouseup', function () { + dom.removeClass(_this.__selector, 'drag'); + }); + }); + dom.bind(_this2.__selector, 'touchstart', function () { + dom.addClass(this, 'drag').bind(window, 'touchend', function () { + dom.removeClass(_this.__selector, 'drag'); + }); + }); + var valueField = document.createElement('div'); + Common.extend(_this2.__selector.style, { + width: '122px', + height: '102px', + padding: '3px', + backgroundColor: '#222', + boxShadow: '0px 1px 3px rgba(0,0,0,0.3)' + }); + Common.extend(_this2.__field_knob.style, { + position: 'absolute', + width: '12px', + height: '12px', + border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'), + boxShadow: '0px 1px 3px rgba(0,0,0,0.5)', + borderRadius: '12px', + zIndex: 1 + }); + Common.extend(_this2.__hue_knob.style, { + position: 'absolute', + width: '15px', + height: '2px', + borderRight: '4px solid #fff', + zIndex: 1 + }); + Common.extend(_this2.__saturation_field.style, { + width: '100px', + height: '100px', + border: '1px solid #555', + marginRight: '3px', + display: 'inline-block', + cursor: 'pointer' + }); + Common.extend(valueField.style, { + width: '100%', + height: '100%', + background: 'none' + }); + linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000'); + Common.extend(_this2.__hue_field.style, { + width: '15px', + height: '100px', + border: '1px solid #555', + cursor: 'ns-resize', + position: 'absolute', + top: '3px', + right: '3px' + }); + hueGradient(_this2.__hue_field); + Common.extend(_this2.__input.style, { + outline: 'none', + textAlign: 'center', + color: '#fff', + border: 0, + fontWeight: 'bold', + textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)' + }); + dom.bind(_this2.__saturation_field, 'mousedown', fieldDown); + dom.bind(_this2.__saturation_field, 'touchstart', fieldDown); + dom.bind(_this2.__field_knob, 'mousedown', fieldDown); + dom.bind(_this2.__field_knob, 'touchstart', fieldDown); + dom.bind(_this2.__hue_field, 'mousedown', fieldDownH); + dom.bind(_this2.__hue_field, 'touchstart', fieldDownH); + function fieldDown(e) { + setSV(e); + dom.bind(window, 'mousemove', setSV); + dom.bind(window, 'touchmove', setSV); + dom.bind(window, 'mouseup', fieldUpSV); + dom.bind(window, 'touchend', fieldUpSV); + } + function fieldDownH(e) { + setH(e); + dom.bind(window, 'mousemove', setH); + dom.bind(window, 'touchmove', setH); + dom.bind(window, 'mouseup', fieldUpH); + dom.bind(window, 'touchend', fieldUpH); + } + function fieldUpSV() { + dom.unbind(window, 'mousemove', setSV); + dom.unbind(window, 'touchmove', setSV); + dom.unbind(window, 'mouseup', fieldUpSV); + dom.unbind(window, 'touchend', fieldUpSV); + onFinish(); + } + function fieldUpH() { + dom.unbind(window, 'mousemove', setH); + dom.unbind(window, 'touchmove', setH); + dom.unbind(window, 'mouseup', fieldUpH); + dom.unbind(window, 'touchend', fieldUpH); + onFinish(); + } + function onBlur() { + var i = interpret(this.value); + if (i !== false) { + _this.__color.__state = i; + _this.setValue(_this.__color.toOriginal()); + } else { + this.value = _this.__color.toString(); + } + } + function onFinish() { + if (_this.__onFinishChange) { + _this.__onFinishChange.call(_this, _this.__color.toOriginal()); + } + } + _this2.__saturation_field.appendChild(valueField); + _this2.__selector.appendChild(_this2.__field_knob); + _this2.__selector.appendChild(_this2.__saturation_field); + _this2.__selector.appendChild(_this2.__hue_field); + _this2.__hue_field.appendChild(_this2.__hue_knob); + _this2.domElement.appendChild(_this2.__input); + _this2.domElement.appendChild(_this2.__selector); + _this2.updateDisplay(); + function setSV(e) { + if (e.type.indexOf('touch') === -1) { + e.preventDefault(); + } + var fieldRect = _this.__saturation_field.getBoundingClientRect(); + var _ref = e.touches && e.touches[0] || e, + clientX = _ref.clientX, + clientY = _ref.clientY; + var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left); + var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top); + if (v > 1) { + v = 1; + } else if (v < 0) { + v = 0; + } + if (s > 1) { + s = 1; + } else if (s < 0) { + s = 0; + } + _this.__color.v = v; + _this.__color.s = s; + _this.setValue(_this.__color.toOriginal()); + return false; + } + function setH(e) { + if (e.type.indexOf('touch') === -1) { + e.preventDefault(); + } + var fieldRect = _this.__hue_field.getBoundingClientRect(); + var _ref2 = e.touches && e.touches[0] || e, + clientY = _ref2.clientY; + var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top); + if (h > 1) { + h = 1; + } else if (h < 0) { + h = 0; + } + _this.__color.h = h * 360; + _this.setValue(_this.__color.toOriginal()); + return false; + } + return _this2; + } + createClass(ColorController, [{ + key: 'updateDisplay', + value: function updateDisplay() { + var i = interpret(this.getValue()); + if (i !== false) { + var mismatch = false; + Common.each(Color.COMPONENTS, function (component) { + if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) { + mismatch = true; + return {}; + } + }, this); + if (mismatch) { + Common.extend(this.__color.__state, i); + } + } + Common.extend(this.__temp.__state, this.__color.__state); + this.__temp.a = 1; + var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0; + var _flip = 255 - flip; + Common.extend(this.__field_knob.style, { + marginLeft: 100 * this.__color.s - 7 + 'px', + marginTop: 100 * (1 - this.__color.v) - 7 + 'px', + backgroundColor: this.__temp.toHexString(), + border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')' + }); + this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'; + this.__temp.s = 1; + this.__temp.v = 1; + linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString()); + this.__input.value = this.__color.toString(); + Common.extend(this.__input.style, { + backgroundColor: this.__color.toHexString(), + color: 'rgb(' + flip + ',' + flip + ',' + flip + ')', + textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)' + }); + } + }]); + return ColorController; +}(Controller); +var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', '']; +function linearGradient(elem, x, a, b) { + elem.style.background = ''; + Common.each(vendors, function (vendor) { + elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); '; + }); +} +function hueGradient(elem) { + elem.style.background = ''; + elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'; + elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; + elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; + elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; + elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; +} + +var css = { + load: function load(url, indoc) { + var doc = indoc || document; + var link = doc.createElement('link'); + link.type = 'text/css'; + link.rel = 'stylesheet'; + link.href = url; + doc.getElementsByTagName('head')[0].appendChild(link); + }, + inject: function inject(cssContent, indoc) { + var doc = indoc || document; + var injected = document.createElement('style'); + injected.type = 'text/css'; + injected.innerHTML = cssContent; + var head = doc.getElementsByTagName('head')[0]; + try { + head.appendChild(injected); + } catch (e) { + } + } +}; + +var saveDialogContents = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>"; + +var ControllerFactory = function ControllerFactory(object, property) { + var initialValue = object[property]; + if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) { + return new OptionController(object, property, arguments[2]); + } + if (Common.isNumber(initialValue)) { + if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) { + if (Common.isNumber(arguments[4])) { + return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]); + } + return new NumberControllerSlider(object, property, arguments[2], arguments[3]); + } + if (Common.isNumber(arguments[4])) { + return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3], step: arguments[4] }); + } + return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] }); + } + if (Common.isString(initialValue)) { + return new StringController(object, property); + } + if (Common.isFunction(initialValue)) { + return new FunctionController(object, property, ''); + } + if (Common.isBoolean(initialValue)) { + return new BooleanController(object, property); + } + return null; +}; + +function requestAnimationFrame(callback) { + setTimeout(callback, 1000 / 60); +} +var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame; + +var CenteredDiv = function () { + function CenteredDiv() { + classCallCheck(this, CenteredDiv); + this.backgroundElement = document.createElement('div'); + Common.extend(this.backgroundElement.style, { + backgroundColor: 'rgba(0,0,0,0.8)', + top: 0, + left: 0, + display: 'none', + zIndex: '1000', + opacity: 0, + WebkitTransition: 'opacity 0.2s linear', + transition: 'opacity 0.2s linear' + }); + dom.makeFullscreen(this.backgroundElement); + this.backgroundElement.style.position = 'fixed'; + this.domElement = document.createElement('div'); + Common.extend(this.domElement.style, { + position: 'fixed', + display: 'none', + zIndex: '1001', + opacity: 0, + WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear', + transition: 'transform 0.2s ease-out, opacity 0.2s linear' + }); + document.body.appendChild(this.backgroundElement); + document.body.appendChild(this.domElement); + var _this = this; + dom.bind(this.backgroundElement, 'click', function () { + _this.hide(); + }); + } + createClass(CenteredDiv, [{ + key: 'show', + value: function show() { + var _this = this; + this.backgroundElement.style.display = 'block'; + this.domElement.style.display = 'block'; + this.domElement.style.opacity = 0; + this.domElement.style.webkitTransform = 'scale(1.1)'; + this.layout(); + Common.defer(function () { + _this.backgroundElement.style.opacity = 1; + _this.domElement.style.opacity = 1; + _this.domElement.style.webkitTransform = 'scale(1)'; + }); + } + }, { + key: 'hide', + value: function hide() { + var _this = this; + var hide = function hide() { + _this.domElement.style.display = 'none'; + _this.backgroundElement.style.display = 'none'; + dom.unbind(_this.domElement, 'webkitTransitionEnd', hide); + dom.unbind(_this.domElement, 'transitionend', hide); + dom.unbind(_this.domElement, 'oTransitionEnd', hide); + }; + dom.bind(this.domElement, 'webkitTransitionEnd', hide); + dom.bind(this.domElement, 'transitionend', hide); + dom.bind(this.domElement, 'oTransitionEnd', hide); + this.backgroundElement.style.opacity = 0; + this.domElement.style.opacity = 0; + this.domElement.style.webkitTransform = 'scale(1.1)'; + } + }, { + key: 'layout', + value: function layout() { + this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px'; + this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px'; + } + }]); + return CenteredDiv; +}(); + +var styleSheet = ___$insertStyle(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n"); + +css.inject(styleSheet); +var CSS_NAMESPACE = 'dg'; +var HIDE_KEY_CODE = 72; +var CLOSE_BUTTON_HEIGHT = 20; +var DEFAULT_DEFAULT_PRESET_NAME = 'Default'; +var SUPPORTS_LOCAL_STORAGE = function () { + try { + return !!window.localStorage; + } catch (e) { + return false; + } +}(); +var SAVE_DIALOGUE = void 0; +var autoPlaceVirgin = true; +var autoPlaceContainer = void 0; +var hide = false; +var hideableGuis = []; +var GUI = function GUI(pars) { + var _this = this; + var params = pars || {}; + this.domElement = document.createElement('div'); + this.__ul = document.createElement('ul'); + this.domElement.appendChild(this.__ul); + dom.addClass(this.domElement, CSS_NAMESPACE); + this.__folders = {}; + this.__controllers = []; + this.__rememberedObjects = []; + this.__rememberedObjectIndecesToControllers = []; + this.__listening = []; + params = Common.defaults(params, { + closeOnTop: false, + autoPlace: true, + width: GUI.DEFAULT_WIDTH + }); + params = Common.defaults(params, { + resizable: params.autoPlace, + hideable: params.autoPlace + }); + if (!Common.isUndefined(params.load)) { + if (params.preset) { + params.load.preset = params.preset; + } + } else { + params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME }; + } + if (Common.isUndefined(params.parent) && params.hideable) { + hideableGuis.push(this); + } + params.resizable = Common.isUndefined(params.parent) && params.resizable; + if (params.autoPlace && Common.isUndefined(params.scrollable)) { + params.scrollable = true; + } + var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true'; + var saveToLocalStorage = void 0; + var titleRow = void 0; + Object.defineProperties(this, + { + parent: { + get: function get$$1() { + return params.parent; + } + }, + scrollable: { + get: function get$$1() { + return params.scrollable; + } + }, + autoPlace: { + get: function get$$1() { + return params.autoPlace; + } + }, + closeOnTop: { + get: function get$$1() { + return params.closeOnTop; + } + }, + preset: { + get: function get$$1() { + if (_this.parent) { + return _this.getRoot().preset; + } + return params.load.preset; + }, + set: function set$$1(v) { + if (_this.parent) { + _this.getRoot().preset = v; + } else { + params.load.preset = v; + } + setPresetSelectIndex(this); + _this.revert(); + } + }, + width: { + get: function get$$1() { + return params.width; + }, + set: function set$$1(v) { + params.width = v; + setWidth(_this, v); + } + }, + name: { + get: function get$$1() { + return params.name; + }, + set: function set$$1(v) { + params.name = v; + if (titleRow) { + titleRow.innerHTML = params.name; + } + } + }, + closed: { + get: function get$$1() { + return params.closed; + }, + set: function set$$1(v) { + params.closed = v; + if (params.closed) { + dom.addClass(_this.__ul, GUI.CLASS_CLOSED); + } else { + dom.removeClass(_this.__ul, GUI.CLASS_CLOSED); + } + this.onResize(); + if (_this.__closeButton) { + _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED; + } + } + }, + load: { + get: function get$$1() { + return params.load; + } + }, + useLocalStorage: { + get: function get$$1() { + return useLocalStorage; + }, + set: function set$$1(bool) { + if (SUPPORTS_LOCAL_STORAGE) { + useLocalStorage = bool; + if (bool) { + dom.bind(window, 'unload', saveToLocalStorage); + } else { + dom.unbind(window, 'unload', saveToLocalStorage); + } + localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool); + } + } + } + }); + if (Common.isUndefined(params.parent)) { + this.closed = params.closed || false; + dom.addClass(this.domElement, GUI.CLASS_MAIN); + dom.makeSelectable(this.domElement, false); + if (SUPPORTS_LOCAL_STORAGE) { + if (useLocalStorage) { + _this.useLocalStorage = true; + var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui')); + if (savedGui) { + params.load = JSON.parse(savedGui); + } + } + } + this.__closeButton = document.createElement('div'); + this.__closeButton.innerHTML = GUI.TEXT_CLOSED; + dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON); + if (params.closeOnTop) { + dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP); + this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]); + } else { + dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM); + this.domElement.appendChild(this.__closeButton); + } + dom.bind(this.__closeButton, 'click', function () { + _this.closed = !_this.closed; + }); + } else { + if (params.closed === undefined) { + params.closed = true; + } + var titleRowName = document.createTextNode(params.name); + dom.addClass(titleRowName, 'controller-name'); + titleRow = addRow(_this, titleRowName); + var onClickTitle = function onClickTitle(e) { + e.preventDefault(); + _this.closed = !_this.closed; + return false; + }; + dom.addClass(this.__ul, GUI.CLASS_CLOSED); + dom.addClass(titleRow, 'title'); + dom.bind(titleRow, 'click', onClickTitle); + if (!params.closed) { + this.closed = false; + } + } + if (params.autoPlace) { + if (Common.isUndefined(params.parent)) { + if (autoPlaceVirgin) { + autoPlaceContainer = document.createElement('div'); + dom.addClass(autoPlaceContainer, CSS_NAMESPACE); + dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER); + document.body.appendChild(autoPlaceContainer); + autoPlaceVirgin = false; + } + autoPlaceContainer.appendChild(this.domElement); + dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE); + } + if (!this.parent) { + setWidth(_this, params.width); + } + } + this.__resizeHandler = function () { + _this.onResizeDebounced(); + }; + dom.bind(window, 'resize', this.__resizeHandler); + dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler); + dom.bind(this.__ul, 'transitionend', this.__resizeHandler); + dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler); + this.onResize(); + if (params.resizable) { + addResizeHandle(this); + } + saveToLocalStorage = function saveToLocalStorage() { + if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') { + localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject())); + } + }; + this.saveToLocalStorageIfPossible = saveToLocalStorage; + function resetWidth() { + var root = _this.getRoot(); + root.width += 1; + Common.defer(function () { + root.width -= 1; + }); + } + if (!params.parent) { + resetWidth(); + } +}; +GUI.toggleHide = function () { + hide = !hide; + Common.each(hideableGuis, function (gui) { + gui.domElement.style.display = hide ? 'none' : ''; + }); +}; +GUI.CLASS_AUTO_PLACE = 'a'; +GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac'; +GUI.CLASS_MAIN = 'main'; +GUI.CLASS_CONTROLLER_ROW = 'cr'; +GUI.CLASS_TOO_TALL = 'taller-than-window'; +GUI.CLASS_CLOSED = 'closed'; +GUI.CLASS_CLOSE_BUTTON = 'close-button'; +GUI.CLASS_CLOSE_TOP = 'close-top'; +GUI.CLASS_CLOSE_BOTTOM = 'close-bottom'; +GUI.CLASS_DRAG = 'drag'; +GUI.DEFAULT_WIDTH = 245; +GUI.TEXT_CLOSED = 'Close Controls'; +GUI.TEXT_OPEN = 'Open Controls'; +GUI._keydownHandler = function (e) { + if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) { + GUI.toggleHide(); + } +}; +dom.bind(window, 'keydown', GUI._keydownHandler, false); +Common.extend(GUI.prototype, +{ + add: function add(object, property) { + return _add(this, object, property, { + factoryArgs: Array.prototype.slice.call(arguments, 2) + }); + }, + addColor: function addColor(object, property) { + return _add(this, object, property, { + color: true + }); + }, + remove: function remove(controller) { + this.__ul.removeChild(controller.__li); + this.__controllers.splice(this.__controllers.indexOf(controller), 1); + var _this = this; + Common.defer(function () { + _this.onResize(); + }); + }, + destroy: function destroy() { + if (this.parent) { + throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.'); + } + if (this.autoPlace) { + autoPlaceContainer.removeChild(this.domElement); + } + var _this = this; + Common.each(this.__folders, function (subfolder) { + _this.removeFolder(subfolder); + }); + dom.unbind(window, 'keydown', GUI._keydownHandler, false); + removeListeners(this); + }, + addFolder: function addFolder(name) { + if (this.__folders[name] !== undefined) { + throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"'); + } + var newGuiParams = { name: name, parent: this }; + newGuiParams.autoPlace = this.autoPlace; + if (this.load && + this.load.folders && + this.load.folders[name]) { + newGuiParams.closed = this.load.folders[name].closed; + newGuiParams.load = this.load.folders[name]; + } + var gui = new GUI(newGuiParams); + this.__folders[name] = gui; + var li = addRow(this, gui.domElement); + dom.addClass(li, 'folder'); + return gui; + }, + removeFolder: function removeFolder(folder) { + this.__ul.removeChild(folder.domElement.parentElement); + delete this.__folders[folder.name]; + if (this.load && + this.load.folders && + this.load.folders[folder.name]) { + delete this.load.folders[folder.name]; + } + removeListeners(folder); + var _this = this; + Common.each(folder.__folders, function (subfolder) { + folder.removeFolder(subfolder); + }); + Common.defer(function () { + _this.onResize(); + }); + }, + open: function open() { + this.closed = false; + }, + close: function close() { + this.closed = true; + }, + hide: function hide() { + this.domElement.style.display = 'none'; + }, + show: function show() { + this.domElement.style.display = ''; + }, + onResize: function onResize() { + var root = this.getRoot(); + if (root.scrollable) { + var top = dom.getOffset(root.__ul).top; + var h = 0; + Common.each(root.__ul.childNodes, function (node) { + if (!(root.autoPlace && node === root.__save_row)) { + h += dom.getHeight(node); + } + }); + if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) { + dom.addClass(root.domElement, GUI.CLASS_TOO_TALL); + root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px'; + } else { + dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL); + root.__ul.style.height = 'auto'; + } + } + if (root.__resize_handle) { + Common.defer(function () { + root.__resize_handle.style.height = root.__ul.offsetHeight + 'px'; + }); + } + if (root.__closeButton) { + root.__closeButton.style.width = root.width + 'px'; + } + }, + onResizeDebounced: Common.debounce(function () { + this.onResize(); + }, 50), + remember: function remember() { + if (Common.isUndefined(SAVE_DIALOGUE)) { + SAVE_DIALOGUE = new CenteredDiv(); + SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents; + } + if (this.parent) { + throw new Error('You can only call remember on a top level GUI.'); + } + var _this = this; + Common.each(Array.prototype.slice.call(arguments), function (object) { + if (_this.__rememberedObjects.length === 0) { + addSaveMenu(_this); + } + if (_this.__rememberedObjects.indexOf(object) === -1) { + _this.__rememberedObjects.push(object); + } + }); + if (this.autoPlace) { + setWidth(this, this.width); + } + }, + getRoot: function getRoot() { + var gui = this; + while (gui.parent) { + gui = gui.parent; + } + return gui; + }, + getSaveObject: function getSaveObject() { + var toReturn = this.load; + toReturn.closed = this.closed; + if (this.__rememberedObjects.length > 0) { + toReturn.preset = this.preset; + if (!toReturn.remembered) { + toReturn.remembered = {}; + } + toReturn.remembered[this.preset] = getCurrentPreset(this); + } + toReturn.folders = {}; + Common.each(this.__folders, function (element, key) { + toReturn.folders[key] = element.getSaveObject(); + }); + return toReturn; + }, + save: function save() { + if (!this.load.remembered) { + this.load.remembered = {}; + } + this.load.remembered[this.preset] = getCurrentPreset(this); + markPresetModified(this, false); + this.saveToLocalStorageIfPossible(); + }, + saveAs: function saveAs(presetName) { + if (!this.load.remembered) { + this.load.remembered = {}; + this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true); + } + this.load.remembered[presetName] = getCurrentPreset(this); + this.preset = presetName; + addPresetOption(this, presetName, true); + this.saveToLocalStorageIfPossible(); + }, + revert: function revert(gui) { + Common.each(this.__controllers, function (controller) { + if (!this.getRoot().load.remembered) { + controller.setValue(controller.initialValue); + } else { + recallSavedValue(gui || this.getRoot(), controller); + } + if (controller.__onFinishChange) { + controller.__onFinishChange.call(controller, controller.getValue()); + } + }, this); + Common.each(this.__folders, function (folder) { + folder.revert(folder); + }); + if (!gui) { + markPresetModified(this.getRoot(), false); + } + }, + listen: function listen(controller) { + var init = this.__listening.length === 0; + this.__listening.push(controller); + if (init) { + updateDisplays(this.__listening); + } + }, + updateDisplay: function updateDisplay() { + Common.each(this.__controllers, function (controller) { + controller.updateDisplay(); + }); + Common.each(this.__folders, function (folder) { + folder.updateDisplay(); + }); + } +}); +function addRow(gui, newDom, liBefore) { + var li = document.createElement('li'); + if (newDom) { + li.appendChild(newDom); + } + if (liBefore) { + gui.__ul.insertBefore(li, liBefore); + } else { + gui.__ul.appendChild(li); + } + gui.onResize(); + return li; +} +function removeListeners(gui) { + dom.unbind(window, 'resize', gui.__resizeHandler); + if (gui.saveToLocalStorageIfPossible) { + dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible); + } +} +function markPresetModified(gui, modified) { + var opt = gui.__preset_select[gui.__preset_select.selectedIndex]; + if (modified) { + opt.innerHTML = opt.value + '*'; + } else { + opt.innerHTML = opt.value; + } +} +function augmentController(gui, li, controller) { + controller.__li = li; + controller.__gui = gui; + Common.extend(controller, { + options: function options(_options) { + if (arguments.length > 1) { + var nextSibling = controller.__li.nextElementSibling; + controller.remove(); + return _add(gui, controller.object, controller.property, { + before: nextSibling, + factoryArgs: [Common.toArray(arguments)] + }); + } + if (Common.isArray(_options) || Common.isObject(_options)) { + var _nextSibling = controller.__li.nextElementSibling; + controller.remove(); + return _add(gui, controller.object, controller.property, { + before: _nextSibling, + factoryArgs: [_options] + }); + } + }, + name: function name(_name) { + controller.__li.firstElementChild.firstElementChild.innerHTML = _name; + return controller; + }, + listen: function listen() { + controller.__gui.listen(controller); + return controller; + }, + remove: function remove() { + controller.__gui.remove(controller); + return controller; + } + }); + if (controller instanceof NumberControllerSlider) { + var box = new NumberControllerBox(controller.object, controller.property, { min: controller.__min, max: controller.__max, step: controller.__step }); + Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) { + var pc = controller[method]; + var pb = box[method]; + controller[method] = box[method] = function () { + var args = Array.prototype.slice.call(arguments); + pb.apply(box, args); + return pc.apply(controller, args); + }; + }); + dom.addClass(li, 'has-slider'); + controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild); + } else if (controller instanceof NumberControllerBox) { + var r = function r(returned) { + if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) { + var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML; + var wasListening = controller.__gui.__listening.indexOf(controller) > -1; + controller.remove(); + var newController = _add(gui, controller.object, controller.property, { + before: controller.__li.nextElementSibling, + factoryArgs: [controller.__min, controller.__max, controller.__step] + }); + newController.name(oldName); + if (wasListening) newController.listen(); + return newController; + } + return returned; + }; + controller.min = Common.compose(r, controller.min); + controller.max = Common.compose(r, controller.max); + } else if (controller instanceof BooleanController) { + dom.bind(li, 'click', function () { + dom.fakeEvent(controller.__checkbox, 'click'); + }); + dom.bind(controller.__checkbox, 'click', function (e) { + e.stopPropagation(); + }); + } else if (controller instanceof FunctionController) { + dom.bind(li, 'click', function () { + dom.fakeEvent(controller.__button, 'click'); + }); + dom.bind(li, 'mouseover', function () { + dom.addClass(controller.__button, 'hover'); + }); + dom.bind(li, 'mouseout', function () { + dom.removeClass(controller.__button, 'hover'); + }); + } else if (controller instanceof ColorController) { + dom.addClass(li, 'color'); + controller.updateDisplay = Common.compose(function (val) { + li.style.borderLeftColor = controller.__color.toString(); + return val; + }, controller.updateDisplay); + controller.updateDisplay(); + } + controller.setValue = Common.compose(function (val) { + if (gui.getRoot().__preset_select && controller.isModified()) { + markPresetModified(gui.getRoot(), true); + } + return val; + }, controller.setValue); +} +function recallSavedValue(gui, controller) { + var root = gui.getRoot(); + var matchedIndex = root.__rememberedObjects.indexOf(controller.object); + if (matchedIndex !== -1) { + var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex]; + if (controllerMap === undefined) { + controllerMap = {}; + root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap; + } + controllerMap[controller.property] = controller; + if (root.load && root.load.remembered) { + var presetMap = root.load.remembered; + var preset = void 0; + if (presetMap[gui.preset]) { + preset = presetMap[gui.preset]; + } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) { + preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME]; + } else { + return; + } + if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) { + var value = preset[matchedIndex][controller.property]; + controller.initialValue = value; + controller.setValue(value); + } + } + } +} +function _add(gui, object, property, params) { + if (object[property] === undefined) { + throw new Error('Object "' + object + '" has no property "' + property + '"'); + } + var controller = void 0; + if (params.color) { + controller = new ColorController(object, property); + } else { + var factoryArgs = [object, property].concat(params.factoryArgs); + controller = ControllerFactory.apply(gui, factoryArgs); + } + if (params.before instanceof Controller) { + params.before = params.before.__li; + } + recallSavedValue(gui, controller); + dom.addClass(controller.domElement, 'c'); + var name = document.createElement('span'); + dom.addClass(name, 'property-name'); + name.innerHTML = controller.property; + var container = document.createElement('div'); + container.appendChild(name); + container.appendChild(controller.domElement); + var li = addRow(gui, container, params.before); + dom.addClass(li, GUI.CLASS_CONTROLLER_ROW); + if (controller instanceof ColorController) { + dom.addClass(li, 'color'); + } else { + dom.addClass(li, _typeof(controller.getValue())); + } + augmentController(gui, li, controller); + gui.__controllers.push(controller); + return controller; +} +function getLocalStorageHash(gui, key) { + return document.location.href + '.' + key; +} +function addPresetOption(gui, name, setSelected) { + var opt = document.createElement('option'); + opt.innerHTML = name; + opt.value = name; + gui.__preset_select.appendChild(opt); + if (setSelected) { + gui.__preset_select.selectedIndex = gui.__preset_select.length - 1; + } +} +function showHideExplain(gui, explain) { + explain.style.display = gui.useLocalStorage ? 'block' : 'none'; +} +function addSaveMenu(gui) { + var div = gui.__save_row = document.createElement('li'); + dom.addClass(gui.domElement, 'has-save'); + gui.__ul.insertBefore(div, gui.__ul.firstChild); + dom.addClass(div, 'save-row'); + var gears = document.createElement('span'); + gears.innerHTML = '&nbsp;'; + dom.addClass(gears, 'button gears'); + var button = document.createElement('span'); + button.innerHTML = 'Save'; + dom.addClass(button, 'button'); + dom.addClass(button, 'save'); + var button2 = document.createElement('span'); + button2.innerHTML = 'New'; + dom.addClass(button2, 'button'); + dom.addClass(button2, 'save-as'); + var button3 = document.createElement('span'); + button3.innerHTML = 'Revert'; + dom.addClass(button3, 'button'); + dom.addClass(button3, 'revert'); + var select = gui.__preset_select = document.createElement('select'); + if (gui.load && gui.load.remembered) { + Common.each(gui.load.remembered, function (value, key) { + addPresetOption(gui, key, key === gui.preset); + }); + } else { + addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false); + } + dom.bind(select, 'change', function () { + for (var index = 0; index < gui.__preset_select.length; index++) { + gui.__preset_select[index].innerHTML = gui.__preset_select[index].value; + } + gui.preset = this.value; + }); + div.appendChild(select); + div.appendChild(gears); + div.appendChild(button); + div.appendChild(button2); + div.appendChild(button3); + if (SUPPORTS_LOCAL_STORAGE) { + var explain = document.getElementById('dg-local-explain'); + var localStorageCheckBox = document.getElementById('dg-local-storage'); + var saveLocally = document.getElementById('dg-save-locally'); + saveLocally.style.display = 'block'; + if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') { + localStorageCheckBox.setAttribute('checked', 'checked'); + } + showHideExplain(gui, explain); + dom.bind(localStorageCheckBox, 'change', function () { + gui.useLocalStorage = !gui.useLocalStorage; + showHideExplain(gui, explain); + }); + } + var newConstructorTextArea = document.getElementById('dg-new-constructor'); + dom.bind(newConstructorTextArea, 'keydown', function (e) { + if (e.metaKey && (e.which === 67 || e.keyCode === 67)) { + SAVE_DIALOGUE.hide(); + } + }); + dom.bind(gears, 'click', function () { + newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2); + SAVE_DIALOGUE.show(); + newConstructorTextArea.focus(); + newConstructorTextArea.select(); + }); + dom.bind(button, 'click', function () { + gui.save(); + }); + dom.bind(button2, 'click', function () { + var presetName = prompt('Enter a new preset name.'); + if (presetName) { + gui.saveAs(presetName); + } + }); + dom.bind(button3, 'click', function () { + gui.revert(); + }); +} +function addResizeHandle(gui) { + var pmouseX = void 0; + gui.__resize_handle = document.createElement('div'); + Common.extend(gui.__resize_handle.style, { + width: '6px', + marginLeft: '-3px', + height: '200px', + cursor: 'ew-resize', + position: 'absolute' + }); + function drag(e) { + e.preventDefault(); + gui.width += pmouseX - e.clientX; + gui.onResize(); + pmouseX = e.clientX; + return false; + } + function dragStop() { + dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG); + dom.unbind(window, 'mousemove', drag); + dom.unbind(window, 'mouseup', dragStop); + } + function dragStart(e) { + e.preventDefault(); + pmouseX = e.clientX; + dom.addClass(gui.__closeButton, GUI.CLASS_DRAG); + dom.bind(window, 'mousemove', drag); + dom.bind(window, 'mouseup', dragStop); + return false; + } + dom.bind(gui.__resize_handle, 'mousedown', dragStart); + dom.bind(gui.__closeButton, 'mousedown', dragStart); + gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild); +} +function setWidth(gui, w) { + gui.domElement.style.width = w + 'px'; + if (gui.__save_row && gui.autoPlace) { + gui.__save_row.style.width = w + 'px'; + } + if (gui.__closeButton) { + gui.__closeButton.style.width = w + 'px'; + } +} +function getCurrentPreset(gui, useInitialValues) { + var toReturn = {}; + Common.each(gui.__rememberedObjects, function (val, index) { + var savedValues = {}; + var controllerMap = gui.__rememberedObjectIndecesToControllers[index]; + Common.each(controllerMap, function (controller, property) { + savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue(); + }); + toReturn[index] = savedValues; + }); + return toReturn; +} +function setPresetSelectIndex(gui) { + for (var index = 0; index < gui.__preset_select.length; index++) { + if (gui.__preset_select[index].value === gui.preset) { + gui.__preset_select.selectedIndex = index; + } + } +} +function updateDisplays(controllerArray) { + if (controllerArray.length !== 0) { + requestAnimationFrame$1.call(window, function () { + updateDisplays(controllerArray); + }); + } + Common.each(controllerArray, function (c) { + c.updateDisplay(); + }); +} + +var color = { + Color: Color, + math: ColorMath, + interpret: interpret +}; +var controllers = { + Controller: Controller, + BooleanController: BooleanController, + OptionController: OptionController, + StringController: StringController, + NumberController: NumberController, + NumberControllerBox: NumberControllerBox, + NumberControllerSlider: NumberControllerSlider, + FunctionController: FunctionController, + ColorController: ColorController +}; +var dom$1 = { dom: dom }; +var gui = { GUI: GUI }; +var GUI$1 = GUI; +var index = { + color: color, + controllers: controllers, + dom: dom$1, + gui: gui, + GUI: GUI$1 +}; + +export { color, controllers, dom$1 as dom, gui, GUI$1 as GUI }; +export default index; +//# sourceMappingURL=dat.gui.module.js.map
false
Other
mrdoob
three.js
c3978af0c81fd3eb574f9b19511177bd63685c0e.json
copy jsm to correct folder
Gruntfile.js
@@ -185,8 +185,9 @@ module.exports = function(grunt) { files: [ { expand: true, cwd: `${threePath}/build/`, src: 'three.js', dest: `${basePath}/`, }, { expand: true, cwd: `${threePath}/build/`, src: 'three.min.js', dest: `${basePath}/`, }, + { expand: true, cwd: `${threePath}/build/`, src: 'three.module.js', dest: `${basePath}/`, }, { expand: true, cwd: `${threePath}/examples/js/`, src: '**', dest: `${basePath}/js/`, }, - { expand: true, cwd: `${threePath}/examples/jsm/`, src: '**', dest: `${basePath}/js/`, }, + { expand: true, cwd: `${threePath}/examples/jsm/`, src: '**', dest: `${basePath}/jsm/`, }, ], }, },
false
Other
mrdoob
three.js
aa2db5e656e377ff0157ab21154246149267847c.json
copy jsm folder when getting new three.js
Gruntfile.js
@@ -186,6 +186,7 @@ module.exports = function(grunt) { { expand: true, cwd: `${threePath}/build/`, src: 'three.js', dest: `${basePath}/`, }, { expand: true, cwd: `${threePath}/build/`, src: 'three.min.js', dest: `${basePath}/`, }, { expand: true, cwd: `${threePath}/examples/js/`, src: '**', dest: `${basePath}/js/`, }, + { expand: true, cwd: `${threePath}/examples/jsm/`, src: '**', dest: `${basePath}/js/`, }, ], }, },
false
Other
mrdoob
three.js
2ffa100f9a36924d721c8b8095b0a1b6c622b79b.json
use https for baseURL
Gruntfile.js
@@ -124,7 +124,7 @@ module.exports = function(grunt) { const buildSettings = { outDir: 'out', - baseUrl: 'http://threejsfundamentals.org', + baseUrl: 'https://threejsfundamentals.org', rootFolder: 'threejs', lessonGrep: 'threejs*.md', siteName: 'ThreeJSFundamentals',
false
Other
mrdoob
three.js
273871385e5651212d69ac8a3c06f43b9414fa11.json
convert ambient to class
src/lights/AmbientLight.js
@@ -1,20 +1,17 @@ import { Light } from './Light.js'; -function AmbientLight( color, intensity ) { +class AmbientLight extends Light { - Light.call( this, color, intensity ); + constructor( color, intensity ) { - this.type = 'AmbientLight'; + super( color, intensity ); -} - -AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { + this.type = 'AmbientLight'; + Object.defineProperty( this, 'isAmbientLight', { value: true } ); - constructor: AmbientLight, + } - isAmbientLight: true - -} ); +} export { AmbientLight };
false
Other
mrdoob
three.js
93f47339e1e53ed5a6a09c5bbcd0afbfb50a62a8.json
Convert selected color to linear
examples/webgl_materials_matcap.html
@@ -25,7 +25,7 @@ var mesh, renderer, scene, camera; var API = { - color: 0xffffff, + color: 0xffffff, // sRGB exposure: 1.0 }; @@ -80,7 +80,7 @@ mesh.material = new THREE.MeshMatcapMaterial( { - color: API.color, + color: new THREE.Color().setHex( API.color ).convertSRGBToLinear(), matcap: matcap, normalMap: normalmap @@ -97,14 +97,16 @@ .listen() .onChange( function () { - mesh.material.color.set( API.color ); render(); + mesh.material.color.set( API.color ).convertSRGBToLinear(); + render(); } ); gui.add( API, 'exposure', 0, 2 ) .onChange( function () { - renderer.toneMappingExposure = API.exposure; render(); + renderer.toneMappingExposure = API.exposure; + render(); } );
false
Other
mrdoob
three.js
97557b6a9ee0f906612dac0b3a779d47bb96fca9.json
Fix enum in the switch case (#23540)
examples/webgl_lines_fat.html
@@ -230,14 +230,14 @@ switch ( val ) { - case '0': + case 0: line.visible = true; line1.visible = false; break; - case '1': + case 1: line.visible = false; line1.visible = true; @@ -285,7 +285,7 @@ switch ( val ) { - case '0': + case 0: matLine.dashSize = 2; matLine.gapSize = 1; @@ -294,7 +294,7 @@ break; - case '1': + case 1: matLine.dashSize = 1; matLine.gapSize = 1; @@ -303,7 +303,7 @@ break; - case '2': + case 2: matLine.dashSize = 1; matLine.gapSize = 2;
true
Other
mrdoob
three.js
97557b6a9ee0f906612dac0b3a779d47bb96fca9.json
Fix enum in the switch case (#23540)
examples/webgl_lines_fat_wireframe.html
@@ -191,14 +191,14 @@ switch ( val ) { - case '0': + case 0: wireframe.visible = true; wireframe1.visible = false; break; - case '1': + case 1: wireframe.visible = false; wireframe1.visible = true; @@ -240,7 +240,7 @@ switch ( val ) { - case '0': + case 0: matLine.dashSize = 2; matLine.gapSize = 1; @@ -249,7 +249,7 @@ break; - case '1': + case 1: matLine.dashSize = 1; matLine.gapSize = 1; @@ -258,7 +258,7 @@ break; - case '2': + case 2: matLine.dashSize = 1; matLine.gapSize = 2;
true
Other
mrdoob
three.js
6ccadd1000e5b4ef6c5d6657ef859a4745cf946b.json
Add type conversions in ShaderNode (#23544) * Add type conversions to float, int, and color * update code style Co-authored-by: sunag <jcdeconto@igalia.com>
examples/jsm/renderers/nodes/ShaderNode.js
@@ -195,18 +195,36 @@ export const nodeObject = ( val ) => { export const float = ( val ) => { + if ( val?.isNode === true ) { + + return nodeObject( new ConvertNode( val, 'float' ) ); + + } + return nodeObject( new FloatNode( val ).setConst( true ) ); }; export const int = ( val ) => { + if ( val?.isNode === true ) { + + return nodeObject( new ConvertNode( val, 'int' ) ); + + } + return nodeObject( new IntNode( val ).setConst( true ) ); }; export const color = ( ...params ) => { + if ( params[ 0 ]?.isNode === true ) { + + return nodeObject( new ConvertNode( params[0], 'color' ) ); + + } + return nodeObject( new ColorNode( new Color( ...params ) ).setConst( true ) ); };
false
Other
mrdoob
three.js
31df72c8b528a8ef28c94fa926c843f789f3c0e5.json
Add more functions to the ShaderNode (#23539) * Update ShaderNode.js * Add remainder operator * Add xor * Update OperatorNode.getNodeType * Fix % operator
examples/jsm/renderers/nodes/ShaderNode.js
@@ -5,6 +5,7 @@ import VarNode from './core/VarNode.js'; // inputs import ColorNode from './inputs/ColorNode.js'; import FloatNode from './inputs/FloatNode.js'; +import IntNode from './inputs/IntNode.js'; import Vector2Node from './inputs/Vector2Node.js'; import Vector3Node from './inputs/Vector3Node.js'; import Vector4Node from './inputs/Vector4Node.js'; @@ -198,6 +199,12 @@ export const float = ( val ) => { }; +export const int = ( val ) => { + + return nodeObject( new IntNode( val ).setConst( true ) ); + +}; + export const color = ( ...params ) => { return nodeObject( new ColorNode( new Color( ...params ) ).setConst( true ) ); @@ -294,11 +301,21 @@ export const add = ShaderNodeProxy( OperatorNode, '+' ); export const sub = ShaderNodeProxy( OperatorNode, '-' ); export const mul = ShaderNodeProxy( OperatorNode, '*' ); export const div = ShaderNodeProxy( OperatorNode, '/' ); +export const remainder = ShaderNodeProxy( OperatorNode, '%' ); export const equal = ShaderNodeProxy( OperatorNode, '==' ); export const assign = ShaderNodeProxy( OperatorNode, '=' ); +export const lessThan = ShaderNodeProxy( OperatorNode, '<' ); export const greaterThan = ShaderNodeProxy( OperatorNode, '>' ); export const lessThanEqual = ShaderNodeProxy( OperatorNode, '<=' ); +export const greaterThanEqual = ShaderNodeProxy( OperatorNode, '>=' ); export const and = ShaderNodeProxy( OperatorNode, '&&' ); +export const or = ShaderNodeProxy( OperatorNode, '||' ); +export const xor = ShaderNodeProxy( OperatorNode, '^^' ); +export const bitAnd = ShaderNodeProxy( OperatorNode, '&' ); +export const bitOr = ShaderNodeProxy( OperatorNode, '|' ); +export const bitXor = ShaderNodeProxy( OperatorNode, '^' ); +export const shiftLeft = ShaderNodeProxy( OperatorNode, '<<' ); +export const shiftRight = ShaderNodeProxy( OperatorNode, '>>' ); export const element = ShaderNodeProxy( ArrayElementNode );
true
Other
mrdoob
three.js
31df72c8b528a8ef28c94fa926c843f789f3c0e5.json
Add more functions to the ShaderNode (#23539) * Update ShaderNode.js * Add remainder operator * Add xor * Update OperatorNode.getNodeType * Fix % operator
examples/jsm/renderers/nodes/math/OperatorNode.js
@@ -41,15 +41,19 @@ class OperatorNode extends TempNode { return 'void'; - } else if ( op === '=' ) { + } else if ( op === '=' || op === '%' ) { return typeA; - } else if ( op === '==' || op === '&&' ) { + } else if ( op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) { + + return 'int'; + + } else if ( op === '==' || op === '&&' || op === '||' || op === '^^' ) { return 'bool'; - } else if ( op === '<=' || op === '>' ) { + } else if ( op === '<=' || op === '>=' || op === '<' || op === '>' ) { const length = builder.getTypeLength( output );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/core/Object3D.tests.js
@@ -12,6 +12,7 @@ import { w, eps } from '../math/Constants.tests.js'; +import { EventDispatcher } from '../../../../src/core/EventDispatcher.js'; const matrixEquals4 = ( a, b ) => { @@ -54,10 +55,12 @@ export default QUnit.module( 'Core', () => { }; // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { - - assert.ok( false, 'everything\'s gonna be alright' ); + QUnit.test( 'Extending', ( assert ) => { + var object = new Object3D(); + + assert.strictEqual( object instanceof EventDispatcher, true, 'Object3D extends from EventDispatcher' ); + } ); // INSTANCING
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Bone.tests.js
@@ -1,15 +1,18 @@ /* global QUnit */ -// import { Bone } from '../../../../src/objects/Bone.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Bone } from '../../../../src/objects/Bone.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'Bone', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var bone = new Bone(); + + assert.strictEqual( bone instanceof Object3D, true, 'Bone extends from Object3D' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Group.tests.js
@@ -1,15 +1,18 @@ /* global QUnit */ -// import { Group } from '../../../../src/objects/Group.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Group } from '../../../../src/objects/Group.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'Group', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var group = new Group(); + + assert.strictEqual( group instanceof Object3D, true, 'Group extends from Object3D' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Line.tests.js
@@ -1,15 +1,18 @@ /* global QUnit */ -// import { Line } from '../../../../src/objects/Line.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Line } from '../../../../src/objects/Line.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'Line', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var line = new Line(); + + assert.strictEqual( line instanceof Object3D, true, 'Line extends from Object3D' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/LineLoop.tests.js
@@ -1,16 +1,21 @@ /* global QUnit */ -// import { LineLoop } from '../../../../src/objects/LineLoop.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Line } from '../../../../src/objects/Line.js'; +import { LineLoop } from '../../../../src/objects/LineLoop.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'LineLoop', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { - - assert.ok( false, 'everything\'s gonna be alright' ); + QUnit.test( 'Extending', ( assert ) => { + var lineLoop = new LineLoop(); + + assert.strictEqual( lineLoop instanceof Object3D, true, 'LineLoop extends from Object3D' ); + assert.strictEqual( lineLoop instanceof Line, true, 'LineLoop extends from Line' ); + } ); // INSTANCING
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/LineSegments.tests.js
@@ -1,15 +1,20 @@ /* global QUnit */ -// import { LineSegments } from '../../../../src/objects/LineSegments.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Line } from '../../../../src/objects/Line.js'; +import { LineSegments } from '../../../../src/objects/LineSegments.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'LineSegments', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var lineSegments = new LineSegments(); + + assert.strictEqual( lineSegments instanceof Object3D, true, 'LineSegments extends from Object3D' ); + assert.strictEqual( lineSegments instanceof Line, true, 'LineSegments extends from Line' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Mesh.tests.js
@@ -1,5 +1,6 @@ /* global QUnit */ +import { Object3D } from '../../../../src/core/Object3D.js'; import { Mesh } from '../../../../src/objects/Mesh.js'; import { Raycaster } from '../../../../src/core/Raycaster.js'; import { PlaneGeometry } from '../../../../src/geometries/PlaneGeometry.js'; @@ -12,9 +13,11 @@ export default QUnit.module( 'Objects', () => { QUnit.module( 'Mesh', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var mesh = new Mesh(); + + assert.strictEqual( mesh instanceof Object3D, true, 'Mesh extends from Object3D' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Points.tests.js
@@ -1,15 +1,18 @@ /* global QUnit */ -// import { Points } from '../../../../src/objects/Points.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Points } from '../../../../src/objects/Points.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'Points', () => { // INHERITANCE - QUnit.todo( 'isPoints', ( assert ) => { + QUnit.test( 'isPoints', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var points = new Points(); + + assert.strictEqual( points instanceof Object3D, true, 'Points extends from Object3D' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/SkinnedMesh.tests.js
@@ -1,15 +1,20 @@ /* global QUnit */ -// import { SkinnedMesh } from '../../../../src/objects/SkinnedMesh.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Mesh } from '../../../../src/objects/Mesh.js'; +import { SkinnedMesh } from '../../../../src/objects/SkinnedMesh.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'SkinnedMesh', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var skinnedMesh = new SkinnedMesh(); + + assert.strictEqual( skinnedMesh instanceof Object3D, true, 'SkinnedMesh extends from Object3D' ); + assert.strictEqual( skinnedMesh instanceof Mesh, true, 'SkinnedMesh extends from Mesh' ); } );
true
Other
mrdoob
three.js
ddbfd26da0c87badf632f85bc2c4b0a88d9da8c2.json
implement tests (#25009)
test/unit/src/objects/Sprite.tests.js
@@ -1,15 +1,18 @@ /* global QUnit */ -// import { Sprite } from '../../../../src/objects/Sprite.js'; +import { Object3D } from '../../../../src/core/Object3D.js'; +import { Sprite } from '../../../../src/objects/Sprite.js'; export default QUnit.module( 'Objects', () => { QUnit.module( 'Sprite', () => { // INHERITANCE - QUnit.todo( 'Extending', ( assert ) => { + QUnit.test( 'Extending', ( assert ) => { - assert.ok( false, 'everything\'s gonna be alright' ); + var sprite = new Sprite(); + + assert.strictEqual( sprite instanceof Object3D, true, 'Sprite extends from Object3D' ); } );
true
Other
mrdoob
three.js
2bc5ae9acfd0e8a6436bef40e8466f43a32090fb.json
Fix code error in load-gltf.html (#24976)
manual/en/load-gltf.html
@@ -271,7 +271,7 @@ <h1>Loading a .GLTF File</h1> - cars = root.getObjectByName('Cars'); + const loadedCars = root.getObjectByName('Cars'); + const fixes = [ -+ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI +* .5], }, ++ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, + { prefix: 'CAR_03', rot: [0, Math.PI, 0], }, + { prefix: 'Car_04', rot: [0, Math.PI, 0], }, + ]; @@ -707,4 +707,4 @@ <h1>Loading a .GLTF File</h1> -</body></html> \ No newline at end of file +</body></html>
true
Other
mrdoob
three.js
2bc5ae9acfd0e8a6436bef40e8466f43a32090fb.json
Fix code error in load-gltf.html (#24976)
manual/ja/load-gltf.html
@@ -249,7 +249,7 @@ <h1>でGLFTファイルを読み込む</h1> - cars = root.getObjectByName('Cars'); + const loadedCars = root.getObjectByName('Cars'); + const fixes = [ -+ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI +* .5], }, ++ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, + { prefix: 'CAR_03', rot: [0, Math.PI, 0], }, + { prefix: 'Car_04', rot: [0, Math.PI, 0], }, + ]; @@ -643,4 +643,4 @@ <h1>でGLFTファイルを読み込む</h1> -</body></html> \ No newline at end of file +</body></html>
true
Other
mrdoob
three.js
2bc5ae9acfd0e8a6436bef40e8466f43a32090fb.json
Fix code error in load-gltf.html (#24976)
manual/ko/load-gltf.html
@@ -262,7 +262,7 @@ <h1>에서 .GLTF 파일 불러오기</h1> - cars = root.getObjectByName('Cars'); + const loadedCars = root.getObjectByName('Cars'); + const fixes = [ -+ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI +* .5], }, ++ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, + { prefix: 'CAR_03', rot: [0, Math.PI, 0], }, + { prefix: 'Car_04', rot: [0, Math.PI, 0], }, + ]; @@ -674,4 +674,4 @@ <h1>에서 .GLTF 파일 불러오기</h1> -</body></html> \ No newline at end of file +</body></html>
true
Other
mrdoob
three.js
2bc5ae9acfd0e8a6436bef40e8466f43a32090fb.json
Fix code error in load-gltf.html (#24976)
manual/zh/load-gltf.html
@@ -262,7 +262,7 @@ <h1>加载 .gltf 文件</h1> - cars = root.getObjectByName('Cars'); + const loadedCars = root.getObjectByName('Cars'); + const fixes = [ -+ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI +* .5], }, ++ { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, + { prefix: 'CAR_03', rot: [0, Math.PI, 0], }, + { prefix: 'Car_04', rot: [0, Math.PI, 0], }, + ];
true
Other
mrdoob
three.js
268aa2d46f9ca88f0d57621e59c1128f6c0241a5.json
Remove outdated code (#24977)
examples/jsm/shaders/MMDToonShader.js
@@ -45,8 +45,6 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in Geometric #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong - -#define Material_LightProbeLOD( material ) (0) `; const mmd_toon_matcap_fragment = /* glsl */`
true
Other
mrdoob
three.js
268aa2d46f9ca88f0d57621e59c1128f6c0241a5.json
Remove outdated code (#24977)
src/renderers/shaders/ShaderChunk/lights_fragment_begin.glsl.js
@@ -5,7 +5,6 @@ export default /* glsl */` * * Instructions for use: * - Ensure that both RE_Direct, RE_IndirectDiffuse and RE_IndirectSpecular are defined - * - If you have defined an RE_IndirectSpecular, you need to also provide a Material_LightProbeLOD. <---- ??? * - Create a material parameter that is to be passed as the third parameter to your lighting functions. * * TODO:
true
Other
mrdoob
three.js
268aa2d46f9ca88f0d57621e59c1128f6c0241a5.json
Remove outdated code (#24977)
src/renderers/shaders/ShaderChunk/lights_lambert_pars_fragment.glsl.js
@@ -25,6 +25,4 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricCon #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert - -#define Material_LightProbeLOD( material ) (0) `;
true
Other
mrdoob
three.js
268aa2d46f9ca88f0d57621e59c1128f6c0241a5.json
Remove outdated code (#24977)
src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl.js
@@ -29,6 +29,4 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in Geometric #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong - -#define Material_LightProbeLOD( material ) (0) `;
true
Other
mrdoob
three.js
268aa2d46f9ca88f0d57621e59c1128f6c0241a5.json
Remove outdated code (#24977)
src/renderers/shaders/ShaderChunk/lights_toon_pars_fragment.glsl.js
@@ -23,6 +23,4 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContex #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon - -#define Material_LightProbeLOD( material ) (0) `;
true
Other
mrdoob
three.js
dbbde82cd84be119c28f588e259bc19518ace55a.json
Set default to working color space (#24965)
src/math/Color.js
@@ -1,6 +1,6 @@ import { clamp, euclideanModulo, lerp } from './MathUtils.js'; import { ColorManagement, SRGBToLinear, LinearToSRGB } from './ColorManagement.js'; -import { SRGBColorSpace, LinearSRGBColorSpace } from '../constants.js'; +import { SRGBColorSpace } from '../constants.js'; const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, @@ -117,7 +117,7 @@ class Color { } - setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) { + setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) { this.r = r; this.g = g; @@ -129,7 +129,7 @@ class Color { } - setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) { + setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) { // h,s,l ranges are in 0.0 - 1.0 h = euclideanModulo( h, 1 ); @@ -369,7 +369,7 @@ class Color { } - getHSL( target, colorSpace = LinearSRGBColorSpace ) { + getHSL( target, colorSpace = ColorManagement.workingColorSpace ) { // h,s,l ranges are in 0.0 - 1.0 @@ -414,7 +414,7 @@ class Color { } - getRGB( target, colorSpace = LinearSRGBColorSpace ) { + getRGB( target, colorSpace = ColorManagement.workingColorSpace ) { ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
false
Other
mrdoob
three.js
727ef10fdfd3c3710248f1567f291d925a589b64.json
Remove outdated comment (#24966)
src/renderers/webgl/WebGLLights.js
@@ -333,10 +333,6 @@ function WebGLLights( extensions, capabilities ) { const uniforms = cache.get( light ); - // (a) intensity is the total visible light emitted - //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); - - // (b) intensity is the brightness of the light uniforms.color.copy( color ).multiplyScalar( intensity ); uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
false
Other
mrdoob
three.js
f974f3d9c1c9f1650ef272726af718fc3bdd759c.json
Update OrbitControls documentation (#24951) after having a hard time searching for a good value to start fine-tuning the dumping factor I found that the default value is 0.05, I was using way higher numbers. Hope this value in the documentation saves people time
docs/examples/en/controls/OrbitControls.html
@@ -96,6 +96,7 @@ <h3> <p> The damping inertia used if [page:.enableDamping] is set to true.<br> Note that for this to work, you must call [page:.update] () in your animation loop. + Default is 0.05. </p> <h3>[property:HTMLDOMElement domElement]</h3>
false
Other
mrdoob
three.js
735d376fc58a3b78d58fdb8dacd47bd6fd4b2d69.json
Update JSFiddle links in issue template (#24944)
.github/ISSUE_TEMPLATE/bug_report.md
@@ -28,8 +28,8 @@ Steps to reproduce the behavior: ***Live example*** -* [jsfiddle-latest-release](https://jsfiddle.net/hbfpj2wv/2/) -* [jsfiddle-dev](https://jsfiddle.net/086yzvgc/) +* [jsfiddle-latest-release](https://jsfiddle.net/g3atw6k5/) +* [jsfiddle-dev](https://jsfiddle.net/eL7gqyhd/) **Expected behavior**
false
Other
mrdoob
three.js
2f77862098bad45d095e99d2863dddd1ec94d559.json
fix .repeatWrapping() (#24922)
examples/jsm/renderers/webgpu/nodes/WebGPUNodeBuilder.js
@@ -78,9 +78,9 @@ fn threejs_mod( x : f32, y : f32 ) -> f32 { } ` ), repeatWrapping: new CodeNode( ` -fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<i32> ) -> vec2<i32> { +fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> { - let uvScaled = vec2<i32>( uv * vec2<f32>( dimension ) ); + let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) ); return ( ( uvScaled % dimension ) + dimension ) % dimension;
false
Other
mrdoob
three.js
6671e7c4b7544207bc4e6c7bc9fcf5fc88bbb4e6.json
Clarify range of attenuationDistance (#24917)
docs/api/en/materials/MeshPhysicalMaterial.html
@@ -90,7 +90,7 @@ <h3>[property:Color attenuationColor]</h3> <h3>[property:Float attenuationDistance]</h3> <p> - Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space. Default is `Infinity`. + Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space units, and must be greater than zero. Default is `Infinity`. </p> <h3>[property:Float clearcoat]</h3>
true
Other
mrdoob
three.js
6671e7c4b7544207bc4e6c7bc9fcf5fc88bbb4e6.json
Clarify range of attenuationDistance (#24917)
docs/api/it/materials/MeshPhysicalMaterial.html
@@ -94,6 +94,7 @@ <h3>[property:Float attenuationDistance]</h3> <p> Densità del mezzo, data come distanza media percorsa dalla luce nel mezzo prima di interagire con una particella. Il valore è indicato nello spazio del mondo. Il valore predefinito è `0`. + Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space units, and must be greater than zero. Default is `Infinity`. </p> <h3>[property:Float clearcoat]</h3>
true
Other
mrdoob
three.js
6671e7c4b7544207bc4e6c7bc9fcf5fc88bbb4e6.json
Clarify range of attenuationDistance (#24917)
docs/api/zh/materials/MeshPhysicalMaterial.html
@@ -81,7 +81,7 @@ <h3>[property:Color attenuationColor]</h3> <h3>[property:Float attenuationDistance]</h3> <p> - Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space. Default is *0*. + Density of the medium given as the average distance that light travels in the medium before interacting with a particle. The value is given in world space units, and must be greater than zero. Default is `Infinity`. </p> <h3>[property:Float clearcoat]</h3>
true
Other
mrdoob
three.js
542343752ea588f46370cff9cc20278a102cdf7e.json
add missing example
threejs/lessons/threejs-post-processing-3dlut.md
@@ -486,6 +486,9 @@ Note that Adobe LUTs are not designed for online usage. They are large files. Yo The sample below is just a modification of the code above. We only draw the background picture, no glTF file. That picture is the an identity lut image created from the script above. We then use the effect to apply whatever LUT file is loaded so the result is the image we'd need to reproduce the LUT file as a PNG. -<script src="resources/threejs-post-processing-3dlut.js"></script> +{{{example url="../threejs-postprocessing-adobe-lut-to-png-converter.html" }}} One thing completely skipped is how the shader itself works. Hopefully we can cover a little more GLSL in the future. For now, if you're curious, you can follow the links in the [post processing article](threejs-post-processing.html) as well as maybe [take a look at this video](https://www.youtube.com/watch?v=rfQ8rKGTVlg#t=24m30s). + +<script src="resources/threejs-post-processing-3dlut.js"></script> +
false
Other
mrdoob
three.js
8ef676c18f0805b6868c6b44623f35bcd1811870.json
add continuous build
Gruntfile.js
@@ -15,6 +15,11 @@ module.exports = function(grunt) { return !s_ignoreRE.test(filename); } + const s_isMdRE = /\.md$/i; + function mdsOnly(filename) { + return s_isMdRE.test(filename); + } + function notFolder(filename) { return !fs.statSync(filename).isDirectory(); } @@ -58,6 +63,11 @@ module.exports = function(grunt) { clean: [ 'out/**/*', ], + buildlesson: { + main: { + files: [], + }, + }, watch: { main: { files: [ @@ -69,6 +79,15 @@ module.exports = function(grunt) { spawn: false, }, }, + lessons: { + files: [ + 'threejs/lessons/**/threejs*.md', + ], + tasks: ['buildlesson'], + options: { + spawn: false, + }, + }, }, }); @@ -80,25 +99,51 @@ module.exports = function(grunt) { dest: 'out/', }; })); + grunt.config('buildlesson.main.files', Object.keys(changedFiles).filter(mdsOnly).map((file) => { + return { + src: file, + }; + })); changedFiles = {}; }, 200); grunt.event.on('watch', function(action, filepath) { changedFiles[filepath] = action; onChange(); }); + const buildSettings = { + outDir: 'out', + baseUrl: 'http://threejsfundamentals.org', + rootFolder: 'threejs', + lessonGrep: 'threejs*.md', + siteName: 'ThreeJSFundamentals', + siteThumbnail: 'threejsfundamentals.jpg', // in rootFolder/lessons/resources + templatePath: 'build/templates', + }; + + // just the hackiest way to get this working. + grunt.registerMultiTask('buildlesson', 'build a lesson', function() { + const filenames = new Set(); + this.files.forEach((files) => { + files.src.forEach((filename) => { + filenames.add(filename); + }); + }); + const buildStuff = require('./build/js/build'); + const settings = Object.assign({}, buildSettings, { + filenames, + }); + const finish = this.async(); + buildStuff(settings).then(function() { + finish(); + }).done(); + }); + grunt.registerTask('buildlessons', function() { const buildStuff = require('./build/js/build'); const finish = this.async(); - buildStuff({ - outDir: 'out', - baseUrl: 'http://threejsfundamentals.org', - rootFolder: 'threejs', - lessonGrep: 'threejs*.md', - siteName: 'ThreeJSFundamentals', - siteThumbnail: 'threejsfundamentals.jpg', // in rootFolder/lessons/resources - }).then(function() { - finish(); + buildStuff(buildSettings).then(function() { + finish(); }).done(); });
true
Other
mrdoob
three.js
8ef676c18f0805b6868c6b44623f35bcd1811870.json
add continuous build
build/js/build.js
@@ -11,6 +11,8 @@ if (parseInt((/^v(\d+)\./).exec(process.version)[1]) < requiredNodeVersion) { module.exports = function(settings) { // wrapper in case we're in module_context mode +const hackyProcessSelectFiles = settings.filenames !== undefined; + const cache = new (require('inmemfilecache'))(); const Feed = require('feed').Feed; const fs = require('fs'); @@ -201,6 +203,11 @@ function slashify(s) { } function articleFilter(f) { + if (hackyProcessSelectFiles) { + if (!settings.filenames.has(f)) { + return false; + } + } return !process.env['ARTICLE_FILTER'] || f.indexOf(process.env['ARTICLE_FILTER']) >= 0; } @@ -537,6 +544,10 @@ const Builder = function(outBaseDir, options) { }); } + if (hackyProcessSelectFiles) { + return Promise.resolve(); + } + // generate place holders for non-translated files const missing = g_origArticles.filter(name => articlesFilenames.indexOf(name) < 0); missing.forEach(name => { @@ -704,6 +715,18 @@ const Builder = function(outBaseDir, options) { table_of_contents: '', templateOptions: '', }); + + { + const filename = path.join(settings.outDir, 'link-check.html'); + const html = ` + <html> + <body> + ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')} + </body> + </html> + `; + writeFileIfChanged(filename, html); + } }; @@ -766,16 +789,14 @@ langs = langs.concat(readdirs(`${settings.rootFolder}/lessons`) b.preProcess(langs); -{ - const filename = path.join(settings.outDir, 'link-check.html'); - const html = ` - <html> - <body> - ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')} - </body> - </html> - `; - writeFileIfChanged(filename, html); +if (hackyProcessSelectFiles) { + const langsInFilenames = new Set(); + [...settings.filenames].forEach((filename) => { + const m = /lessons\/(\w{2}|\w{5})\//.exec(filename); + const lang = m ? m[1] : 'en'; + langsInFilenames.add(lang); + }); + langs = langs.filter(lang => langsInFilenames.has(lang.lang)); } const tasks = langs.map(function(lang) { @@ -787,9 +808,12 @@ const tasks = langs.map(function(lang) { return tasks.reduce(function(cur, next) { return cur.then(next); }, Promise.resolve()).then(function() { - b.writeGlobalFiles(); - cache.clear(); + if (!hackyProcessSelectFiles) { + b.writeGlobalFiles(langs); + } return numErrors ? Promise.reject(new Error(`${numErrors} errors`)) : Promise.resolve(); +}).finally(() => { + cache.clear(); }); };
true
Other
mrdoob
three.js
84d6c7f553ca60e0ca8591364974f4e92d838a24.json
add watch for simple copy
Gruntfile.js
@@ -58,6 +58,33 @@ module.exports = function(grunt) { clean: [ 'out/**/*', ], + watch: { + main: { + files: [ + 'threejs/**', + '3rdparty/**', + ], + tasks: ['copy'], + options: { + spawn: false, + }, + }, + }, + }); + + let changedFiles = {}; + const onChange = grunt.util._.debounce(function() { + grunt.config('copy.main.files', Object.keys(changedFiles).filter(noMds).map((file) => { + return { + src: file, + dest: 'out/', + }; + })); + changedFiles = {}; + }, 200); + grunt.event.on('watch', function(action, filepath) { + changedFiles[filepath] = action; + onChange(); }); grunt.registerTask('buildlessons', function() {
false
Other
mrdoob
three.js
385f0240ba53cf2981b7da5c045dc85aac6f2114.json
require node 11
build/js/build.js
@@ -4,6 +4,11 @@ 'use strict'; +const requiredNodeVersion = 11; +if (parseInt((/^v(\d+)\./).exec(process.version)[1]) < requiredNodeVersion) { + throw Error(`requires at least node: ${requiredNodeVersion}`); +} + module.exports = function(settings) { // wrapper in case we're in module_context mode const cache = new (require('inmemfilecache'))();
false
Other
mrdoob
three.js
d2ac2e90f489528d9e6e0a62a5ebd17d75b69586.json
use node 11
.travis.yml
@@ -1,6 +1,6 @@ language: node_js node_js: - - "8.4" + - "11" script: - npm run build env:
false
Other
mrdoob
three.js
5877f6b0408d3a3b186b13c985e0e52494a022cc.json
use new build that fixes md links and checks them
Gruntfile.js
@@ -64,6 +64,7 @@ module.exports = function(grunt) { const buildStuff = require('./build/js/build'); const finish = this.async(); buildStuff({ + outDir: 'out', baseUrl: 'http://threejsfundamentals.org', rootFolder: 'threejs', lessonGrep: 'threejs*.md',
true
Other
mrdoob
three.js
5877f6b0408d3a3b186b13c985e0e52494a022cc.json
use new build that fixes md links and checks them
build/js/build.js
@@ -1,4 +1,7 @@ -/* global module require */ +/* global module require process */ +/* eslint no-undef: "error" */ +/* eslint no-console: "off" */ + 'use strict'; module.exports = function(settings) { // wrapper in case we're in module_context mode @@ -19,6 +22,12 @@ const url = require('url'); //process.title = 'build'; +let numErrors = 0; +function error(...args) { + ++numErrors; + console.error(...args); +} + const executeP = Promise.denodeify(utils.execute); marked.setOptions({ @@ -186,6 +195,10 @@ function slashify(s) { return s.replace(/\\/g, '/'); } +function articleFilter(f) { + return !process.env['ARTICLE_FILTER'] || f.indexOf(process.env['ARTICLE_FILTER']) >= 0; +} + const Builder = function(outBaseDir, options) { const g_articlesByLang = {}; @@ -196,7 +209,11 @@ const Builder = function(outBaseDir, options) { const g_origPath = options.origPath; // This are the english articles. - const g_origArticles = glob.sync(path.join(g_origPath, '*.md')).map(a => path.basename(a)).filter(a => a !== 'index.md'); + const g_origArticles = glob. + sync(path.join(g_origPath, '*.md')) + .map(a => path.basename(a)) + .filter(a => a !== 'index.md') + .filter(articleFilter); const extractHeader = (function() { const headerRE = /([A-Z0-9_-]+): (.*?)$/i; @@ -268,18 +285,114 @@ const Builder = function(outBaseDir, options) { return content; } + function isSameDomain(url, pageUrl) { + const fdq1 = new URL(pageUrl); + const fdq2 = new URL(url, pageUrl); + return fdq1.origin === fdq2.origin; + } + + function getUrlPath(url) { + // yes, this is a hack + const q = url.indexOf('?'); + return q >= 0 ? url.substring(0, q) : url; + } + + // Try top fix relative links. This *should* only + // happen in translations + const iframeLinkRE = /(<iframe[\s\S]*?\s+src=")(.*?)(")/g; + const imgLinkRE = /(<img[\s\S]*?\s+src=")(.*?)(")/g; + const aLinkRE = /(<a[\s\S]*?\s+href=")(.*?)(")/g; + const mdLinkRE = /(\[[\s\S]*?\]\()(.*?)(\))/g; + const handlebarLinkRE = /({{{.*?\s+url=")(.*?)(")/g; + const linkREs = [ + iframeLinkRE, + imgLinkRE, + aLinkRE, + mdLinkRE, + handlebarLinkRE, + ]; + function hackRelLinks(content, pageUrl) { + // console.log('---> pageUrl:', pageUrl); + function fixRelLink(m, prefix, url, suffix) { + if (isSameDomain(url, pageUrl)) { + // a link that starts with "../" should be "../../" if it's in a translation + // a link that starts with "resources" should be "../resources" if it's in a translation + if (url.startsWith('../') || + url.startsWith('resources')) { + // console.log(' url:', url); + return `${prefix}../${url}${suffix}`; + } + } + return m; + } + + return content + .replace(imgLinkRE, fixRelLink) + .replace(aLinkRE, fixRelLink) + .replace(iframeLinkRE, fixRelLink); + } + + /** + * Get all the local urls based on a regex that has <prefix><url><suffix> + */ + function getUrls(regex, str) { + const links = new Set(); + let m; + do { + m = regex.exec(str); + if (m && m[2][0] !== '#' && isSameDomain(m[2], 'http://example.com/a/b/c/d')) { + links.add(getUrlPath(m[2])); + } + } while (m); + return links; + } + + /** + * Get all the local links in content + */ + function getLinks(content) { + return new Set(linkREs.map(re => [...getUrls(re, content)]).flat()); + } + + function fixUrls(regex, content, origLinks) { + return content.replace(regex, (m, prefix, url, suffix) => { + const q = url.indexOf('?'); + const urlPath = q >= 0 ? url.substring(0, q) : url; + const urlQuery = q >= 0 ? url.substring(q) : ''; + if (!origLinks.has(urlPath) && + isSameDomain(urlPath, 'https://foo.com/a/b/c/d.html') && + !(/\/..\/^/.test(urlPath)) && // hacky test for link to main page. Example /webgl/lessons/ja/ + urlPath[0] !== '#') { // test for same page anchor -- bad test :( + for (const origLink of origLinks) { + if (urlPath.endsWith(origLink)) { + const newUrl = `${origLink}${urlQuery}`; + console.log(' fixing:', url, 'to', newUrl); + return `${prefix}${newUrl}${suffix}`; + } + } + error('could not fix:', url); + } + return m; + }); + } + const applyTemplateToContent = function(templatePath, contentFileName, outFileName, opt_extra, data) { // Call prep's Content which parses the HTML. This helps us find missing tags // should probably call something else. //Convert(md_content) + const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length); + const pageUrl = `${settings.baseUrl}${relativeOutName}`; const metaData = data.headers; const content = data.content; //console.log(JSON.stringify(metaData, undefined, ' ')); const info = extractHandlebars(content); let html = marked(info.content); + // HACK! :-( + if (opt_extra && opt_extra.home && opt_extra.home.length > 1) { + html = hackRelLinks(html, pageUrl); + } html = insertHandlebars(info, html); html = replaceParams(html, [opt_extra, g_langInfo]); - const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length); const pathRE = new RegExp(`^\\/${settings.rootFolder}\\/lessons\\/$`); const langs = Object.keys(g_langDB).map((name) => { const lang = g_langDB[name]; @@ -300,7 +413,7 @@ const Builder = function(outBaseDir, options) { metaData['toc'] = opt_extra.toc; metaData['templateOptions'] = opt_extra.templateOptions; metaData['langInfo'] = g_langInfo; - metaData['url'] = `${settings.baseUrl}${relativeOutName}`; + metaData['url'] = pageUrl; metaData['relUrl'] = relativeOutName; metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`; const basename = path.basename(contentFileName, '.md'); @@ -325,7 +438,10 @@ const Builder = function(outBaseDir, options) { }; const applyTemplateToFiles = function(templatePath, filesSpec, extra) { - const files = glob.sync(filesSpec).sort(); + const files = glob + .sync(filesSpec) + .sort() + .filter(articleFilter); files.forEach(function(fileName) { const ext = path.extname(fileName); const baseName = fileName.substr(0, fileName.length - ext.length); @@ -354,10 +470,10 @@ const Builder = function(outBaseDir, options) { }; const getLanguageSelection = function(lang) { - const lessons = lang.lessons || (`${settings.rootFolder}/lessons/${lang.lang}`); + const lessons = lang.lessons; const langInfo = hanson.parse(fs.readFileSync(path.join(lessons, 'langinfo.hanson'), {encoding: 'utf8'})); langInfo.langCode = langInfo.langCode || lang.lang; - langInfo.home = lang.home || ('/' + lessons + '/'); + langInfo.home = lang.home; g_langDB[lang.lang] = { lang: lang.lang, language: langInfo.language, @@ -372,18 +488,51 @@ const Builder = function(outBaseDir, options) { this.process = function(options) { console.log('Processing Lang: ' + options.lang); // eslint-disable-line - options.lessons = options.lessons || (`${settings.rootFolder}/lessons/${options.lang}`); - options.toc = options.toc || (`${settings.rootFolder}/lessons/${options.lang}/toc.html`); - options.template = options.template || 'build/templates/lesson.template'; - options.examplePath = options.examplePath === undefined ? `/${settings.rootFolder}/lessons/` : options.examplePath; - g_articles = []; g_langInfo = g_langDB[options.lang].langInfo; applyTemplateToFiles(options.template, path.join(options.lessons, settings.lessonGrep), options); - // generate place holders for non-translated files const articlesFilenames = g_articles.map(a => path.basename(a.src_file_name)); + + // should do this first was easier to add here + if (options.lang !== 'en') { + const existing = g_origArticles.filter(name => articlesFilenames.indexOf(name) >= 0); + existing.forEach((name) => { + const origMdFilename = path.join(g_origPath, name); + const transMdFilename = path.join(g_origPath, options.lang, name); + const origLinks = getLinks(loadMD(origMdFilename).content); + const transLinks = getLinks(loadMD(transMdFilename).content); + + if (process.env['ARTICLE_VERBOSE']) { + console.log('---[', transMdFilename, ']---'); + console.log('origLinks: ---\n ', [...origLinks].join('\n ')); + console.log('transLinks: ---\n ', [...transLinks].join('\n ')); + } + + let show = true; + transLinks.forEach((link) => { + if (!origLinks.has(link)) { + if (show) { + show = false; + error('---[', transMdFilename, ']---'); + } + error(' link:[', link, '] not found in English file'); + } + }); + + if (!show && process.env['ARTICLE_FIX']) { + // there was an error, try to auto-fix + let fixedMd = fs.readFileSync(transMdFilename, {encoding: 'utf8'}); + linkREs.forEach((re) => { + fixedMd = fixUrls(re, fixedMd, origLinks); + }); + fs.writeFileSync(transMdFilename, fixedMd); + } + }); + } + + // generate place holders for non-translated files const missing = g_origArticles.filter(name => articlesFilenames.indexOf(name) < 0); missing.forEach(name => { const ext = path.extname(name); @@ -512,10 +661,10 @@ const Builder = function(outBaseDir, options) { }); return Promise.resolve(); }, function(err) { - console.error('ERROR!:'); // eslint-disable-line - console.error(err); // eslint-disable-line + error('ERROR!:'); + error(err); if (err.stack) { - console.error(err.stack); // eslint-disable-line + error(err.stack); // eslint-disable-line } throw new Error(err.toString()); }); @@ -555,7 +704,7 @@ const Builder = function(outBaseDir, options) { }; -const b = new Builder('out', { +const b = new Builder(settings.outDir, { origPath: `${settings.rootFolder}/lessons`, // english articles }); @@ -581,8 +730,16 @@ const isLangFolder = function(dirname) { const pathToLang = function(filename) { + const lang = path.basename(filename); + const lessonBase = `${settings.rootFolder}/lessons`; + const lessons = `${lessonBase}/${lang}`; return { - lang: path.basename(filename), + lang, + toc: `${settings.rootFolder}/lessons/${lang}/toc.html`, + lessons: `${lessonBase}/${lang}`, + template: 'build/templates/lesson.template', + examplePath: `/${lessonBase}/`, + home: `/${lessons}/`, }; }; @@ -604,6 +761,18 @@ langs = langs.concat(readdirs(`${settings.rootFolder}/lessons`) b.preProcess(langs); +{ + const filename = path.join(settings.outDir, 'link-check.html'); + const html = ` + <html> + <body> + ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')} + </body> + </html> + `; + writeFileIfChanged(filename, html); +} + const tasks = langs.map(function(lang) { return function() { return b.process(lang); @@ -615,7 +784,7 @@ return tasks.reduce(function(cur, next) { }, Promise.resolve()).then(function() { b.writeGlobalFiles(); cache.clear(); - return Promise.resolve(); + return numErrors ? Promise.reject(new Error(`${numErrors} errors`)) : Promise.resolve(); }); };
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-cameras.md
@@ -44,7 +44,7 @@ To do that we'll make a `MinMaxGUIHelper` for the `near` and `far` settings so ` is always greater than `near`. It will have `min` and `max` properties that dat.GUI will adjust. When adjusted they'll set the 2 properties we specify. -```javascript +```js class MinMaxGUIHelper { constructor(obj, minProp, maxProp, minDif) { this.obj = obj; @@ -71,7 +71,7 @@ class MinMaxGUIHelper { Now we can setup our GUI like this -```javascript +```js function updateCamera() { camera.updateProjectionMatrix(); } @@ -133,7 +133,7 @@ the canvas Then in our code we'll add a `CameraHelper`. A `CameraHelper` draws the frustum for a `Camera` -```javascript +```js const cameraHelper = new THREE.CameraHelper(camera); ... @@ -143,15 +143,15 @@ scene.add(cameraHelper); Now let's look up the 2 view elements. -```javascript +```js const view1Elem = document.querySelector('#view1'); const view2Elem = document.querySelector('#view2'); ``` And we'll set our existing `OrbitControls` to respond to the first view element only. -```javascript +```js -const controls = new THREE.OrbitControls(camera, canvas); +const controls = new THREE.OrbitControls(camera, view1Elem); ``` @@ -160,7 +160,7 @@ Let's make a second `PerspectiveCamera` and a second `OrbitControls`. The second `OrbitControls` is tied to the second camera and gets input from the second view element. -``` +```js const camera2 = new THREE.PerspectiveCamera( 60, // fov 2, // aspect @@ -182,7 +182,7 @@ Here is a function that given an element will compute the rectangle of that element that overlaps the canvas. It will then set the scissor and viewport to that rectangle and return the aspect for that size. -```javascript +```js function setScissorForElement(elem) { const canvasRect = canvas.getBoundingClientRect(); const elemRect = elem.getBoundingClientRect(); @@ -207,7 +207,7 @@ function setScissorForElement(elem) { And now we can use that function to draw the scene twice in our `render` function -```javascript +```js function render() { - if (resizeRendererToDisplaySize(renderer)) { @@ -270,7 +270,7 @@ second view to dark blue just to make it easier to distinguish the two views. We can also remove our `updateCamera` code since we're updating everything in the `render` function. -```javascript +```js -function updateCamera() { - camera.updateProjectionMatrix(); -} @@ -311,7 +311,7 @@ and slowly expand as they approach `far`. Starting with the top example, let's change the code to insert 20 spheres in a row. -```javascript +```js { const sphereRadius = 3; const sphereWidthDivisions = 32; @@ -330,7 +330,7 @@ row. and let's set `near` to 0.00001 -```javascript +```js const fov = 45; const aspect = 2; // the canvas default -const near = 0.1; @@ -341,7 +341,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); We also need to tweak the GUI code a little to allow 0.00001 if the value is edited -```javascript +```js -gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); +gui.add(minMaxGUIHelper, 'min', 0.00001, 50, 0.00001).name('near').onChange(updateCamera); ``` @@ -361,7 +361,7 @@ One solution is to tell three.js use to a different method to compute which pixels are in front and which are behind. We can do that by enabling `logarithmicDepthBuffer` when we create the `WebGLRenderer` -```javascript +```js -const renderer = new THREE.WebGLRenderer({canvas: canvas}); +const renderer = new THREE.WebGLRenderer({ + canvas: canvas, @@ -404,7 +404,7 @@ in the first view. First let's setup an `OrthographicCamera`. -```javascript +```js const left = -1; const right = 1; const top = 1; @@ -422,7 +422,7 @@ to make it easy to adjust how many units are actually shown by the camera. Let's add a GUI setting for `zoom` -```javascript +```js const gui = new dat.GUI(); +gui.add(camera, 'zoom', 0.01, 1, 0.01).listen(); ``` @@ -434,7 +434,7 @@ a mouse will zoom via the `OrbitControls`. Last we just need to change the part that renders the left side to update the `OrthographicCamera`. -```javascript +```js { const aspect = setScissorForElement(view1Elem); @@ -465,7 +465,7 @@ one unit in the camera you could do something like To put the origin at the center and have 1 pixel = 1 three.js unit something like -```javascript +```js camera.left = -canvas.width / 2; camera.right = canvas.width / 2; camera.top = canvas.heigth / 2; @@ -478,7 +478,7 @@ camera.zoom = 1; Or if we wanted the origin to be in the top left just like a 2D canvas we could use this -```javascript +```js camera.left = 0; camera.right = canvas.width; camera.top = 0; @@ -492,7 +492,7 @@ In which case the top left corner would be 0,0 just like a 2D canvas Let's try it! First let's set the camera up -```javascript +```js const left = 0; const right = 300; // default canvas size const top = 0; @@ -507,7 +507,7 @@ Then let's load 6 textures and make 6 planes, one for each texture. We'll parent each plane to a `THREE.Object3D` to make it easy to offset the plane so it's center appears to be at it's top left corner. -```javascript +```js const loader = new THREE.TextureLoader(); const textures = [ loader.load('resources/images/flower-1.jpg'), @@ -538,7 +538,7 @@ const planes = textures.map((texture) => { and we need to update the camera if the size of the canvas changes. -```javascript +```js function render() { if (resizeRendererToDisplaySize(renderer)) { @@ -553,7 +553,7 @@ function render() { `planes` is an array of `THREE.Mesh`, one for each plane. Let's move them around based on the time. -```javascript +```js function render(time) { time *= 0.001; // convert to seconds;
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-debugging-javascript.md
@@ -75,14 +75,14 @@ Then pick "Disable Cache (while DevTools is open)". Inside all devtools is a *console*. It shows warnings and error messages. You can print your own info to the console with with `console.log` as in -``` +```js console.log(someObject.position.x, someObject.position.y, someObject.position.z); ``` Even cooler, if you log an object you can inspect it. For example if we log the root scene object from [the gLTF article](threejs-load-gltf.html) -``` +```js { const gltfLoader = new THREE.GLTFLoader(); gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { @@ -105,7 +105,7 @@ and put data in them. The most obvious way is to make some HTML elements -``` +```html <canvas id="c"></canvas> +<div id="debug"> + <div>x:<span id="x"></span></div> @@ -117,7 +117,7 @@ The most obvious way is to make some HTML elements Style them so they stay on top of the canvas. (assuming your canvas fills the page) -``` +```html <style> #debug { position: absolute; @@ -133,7 +133,7 @@ fills the page) And then looking the elements up and setting their content. -``` +```js // at init time const xElem = document.querySelector('#x'); const yElem = document.querySelector('#y'); @@ -158,7 +158,7 @@ than making an element per piece of data above. For example let's change the HTML from above to just this -``` +```html <canvas id="c"></canvas> <div id="debug"> <pre></pre> @@ -167,7 +167,7 @@ For example let's change the HTML from above to just this And let's make simple class to manage this *clear back buffer*. -``` +```js class ClearingLogger { constructor(elem) { this.elem = elem; @@ -188,7 +188,7 @@ one of the examples from the article on [making things responsive](threejs-respo Here's the code that adds a new `Mesh` everytime we click the mouse -``` +```js const geometry = new THREE.SphereBufferGeometry(); const material = new THREE.MeshBasicMaterial({color: 'red'}); @@ -218,7 +218,7 @@ canvas.addEventListener('click', createThing); And here's the code that moves the meshes we created, logs them, and removes them when their timer has run out -``` +```js const logger = new ClearingLogger(document.querySelector('#debug pre')); let then = 0; @@ -275,7 +275,7 @@ the debug stuff only shows up if we put `?debug=true` in the URL. First we need some code to parse the query string -``` +```js /** * Returns the query parameters as a key/value object. * Example: If the query parameters are @@ -303,7 +303,7 @@ function getQuery() { Then we might make the debug element not show by default -``` +```html <canvas id="c"></canvas> +<div id="debug" style="display: none;"> <pre></pre> @@ -313,7 +313,7 @@ Then we might make the debug element not show by default Then in the code we read the params and choose to unhide the debug info if and only if `?debug=true` is passed in -``` +```js const query = getQuery(); const debug = query.debug === 'true'; const logger = debug @@ -326,7 +326,7 @@ if (debug) { We also made a `DummyLogger` that does nothing and chose to use it if `?debug=true` has not been passed in. -``` +```js class DummyLogger { log() {} render() {} @@ -377,7 +377,7 @@ As an example when I first started making the path for the [article about loadin I then used that curve to move the cars like this -``` +```js curve.getPointAt(zeroToOnePointOnCurve, car.position); ``` @@ -415,7 +415,7 @@ THREE.js to step through the code and see what is going on. I see this pattern often -``` +```js function render() { requestAnimationFrame(render); @@ -429,7 +429,7 @@ requestAnimationFrame(render); I'd suggest that putting the call to `requestAnimationFrame` at the bottom as in -``` +```js function render() { // -- do stuff --
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-fog.md
@@ -21,7 +21,7 @@ There's also `FogExp2` which grows expotentially with distance from the camera. To use either type of fog you create one and and assign it to the scene as in -``` +```js const scene = new THREE.Scene(); { const color = 0xFFFFFF; // white @@ -33,7 +33,7 @@ const scene = new THREE.Scene(); or for `FogExp2` it would be -``` +```js const scene = new THREE.Scene(); { const color = 0xFFFFFF; @@ -67,7 +67,7 @@ The background color is set using the [`scene.background`](Scene.background) property. To pick a background color you attach a `THREE.Color` to it. For example -``` +```js scene.background = new THREE.Color('#F00'); // red ``` @@ -86,7 +86,7 @@ Here is one of our previous examples with fog added. The only addition is right after setting up the scene we add the fog and set the scene's backgound color -``` +```js const scene = new THREE.Scene(); +{ @@ -114,7 +114,7 @@ the fog's `near` and `far` properties but it's invalid to have can manipulate a `near` and `far` property but we'll make sure `near` is less than or equal to `far` and `far` is greater than or equal `near`. -``` +```js // We use this class to pass to dat.gui // so when it manipulates near or far // near is never > far and far is never < near @@ -141,7 +141,7 @@ class FogGUIHelper { We can then add it like this -``` +```js { const near = 1; const far = 2; @@ -176,7 +176,7 @@ dat.GUI is only manipulating a single value. Fortunately `THREE.Color` as a [`getHexString`](Color.getHexString) method we get use to easily get such a string, we just have to prepend a '#' to the front. -``` +```js // We use this class to pass to dat.gui // so when it manipulates near or far // near is never > far and far is never < near @@ -213,7 +213,7 @@ class FogGUIHelper { We then call `gui.addColor` to add a color UI for our helper's virutal property. -``` +```js { const near = 1; const far = 2;
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-fundamentals.md
@@ -29,7 +29,7 @@ so let's start with "Hello Cube!" The first thing we need is a `<canvas>` tag so -``` +```html <body> <canvas id="c"></canvas> </body> @@ -38,7 +38,7 @@ The first thing we need is a `<canvas>` tag so Three.js will draw into that canvas so we need to look it up and pass it to three.js. -``` +```html <script> 'use strict'; @@ -69,7 +69,7 @@ that uses WebGL to render 3D to the canvas. Next up we need a camera. -``` +```js const fov = 75; const aspect = 2; // the canvas default const near = 0.1; @@ -106,7 +106,7 @@ The camera defaults to looking down the -Z axis with +Y up. We'll put our cube at the origin so we need to move the camera back a litte from the origin in order to see anything. -``` +```js camera.position.z = 2; ``` @@ -125,15 +125,15 @@ Next we make a `Scene`. A `Scene` in three.js is the root of a form of scene gra Anything you want three.js to draw needs to be added to the scene. We'll cover more details of [how scenes work in a future article](threejs-scenegraph.html). -``` +```js const scene = new THREE.Scene(); ``` Next up we create a `BoxGeometry` which contains the data for a box. Almost anything we want to display in Three.js needs geometry which defines the vertices that make up our 3D object. -``` +```js const boxWidth = 1; const boxHeight = 1; const boxDepth = 1; @@ -143,7 +143,7 @@ const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); We then create a basic material and set its color. Colors can be specified using standard CSS style 6 digit hex color values. -``` +```js const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); ``` @@ -153,20 +153,20 @@ the object, shiny or flat, what color, what texture(s) to apply. Etc.) as well as the position, orientation, and scale of that object in the scene. -``` +```js const cube = new THREE.Mesh(geometry, material); ``` And finally we add that mesh to the scene -``` +```js scene.add(cube); ``` We can then render the scene by calling the renderer's render function and passing it the scene and the camera -``` +```js renderer.render(scene, camera); ``` @@ -184,7 +184,7 @@ it clear it's being drawn in 3D. To animate it we'll render inside a render loop Here's our loop -``` +```js function render(time) { time *= 0.001; // convert time to seconds @@ -225,7 +225,7 @@ so let's add a light. There are many kinds of lights in three.js which we'll go over in a future article. For now let's create a directional light. -``` +```js { const color = 0xFFFFFF; const intensity = 1; @@ -243,7 +243,7 @@ toward the origin. We also need to change the material. The `MeshBasicMaterial` is not affected by lights. Let's change it to a `MeshPhongMaterial` which is affected by lights. -``` +```js -const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); // greenish blue +const material = new THREE.MeshPhongMaterial({color: 0x44aa88}); // greenish blue ``` @@ -264,7 +264,7 @@ with the specified color. Then it creates a mesh using the specified geometry and adds it to the scene and sets its X position. -``` +```js function makeInstance(geometry, color, x) { const material = new THREE.MeshPhongMaterial({color}); @@ -280,7 +280,7 @@ function makeInstance(geometry, color, x) { Then we'll call it 3 times with 3 different colors and X positions saving the `Mesh` instances in an array. -``` +```js const cubes = [ makeInstance(geometry, 0x44aa88, 0), makeInstance(geometry, 0x8844aa, -2), @@ -291,7 +291,7 @@ const cubes = [ Finally we'll spin all 3 cubes in our render function. We compute a slightly different rotation for each one. -``` +```js function render(time) { time *= 0.001; // convert time to seconds
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-lights.md
@@ -13,7 +13,7 @@ Starting with one of our previous samples let's update the camera. We'll set the field of view to 45 degrees, the far plane to 100 units, and we'll move the camera 10 units up and 20 units back from the origin -```javascript +```js *const fov = 45; const aspect = 2; // the canvas default const near = 0.1; @@ -27,15 +27,15 @@ or *orbit* the camera around some point. The `OrbitControls` are an optional feature of three.js so first we need to include them in our page -```javascript +```html <script src="resources/threejs/r98/three.min.js"></script> +<script src="resources/threejs/r98/js/controls/OrbitControls.js"></script> ``` Then we can use them. We pass the `OrbitControls` a camera to control and the DOM element to use to get input events -```javascript +```js const controls = new THREE.OrbitControls(camera, canvas); controls.target.set(0, 5, 0); controls.update(); @@ -62,7 +62,7 @@ texture is a 2x2 pixel checkerboard, by repeating and setting the repeat to half the size of the plane each check on the checkerboard will be exactly 1 unit large; -```javascript +```js const planeSize = 40; const loader = new THREE.TextureLoader(); @@ -78,7 +78,7 @@ We then make a plane geometry, a material for the plane, and mesh to insert it in the scene. Planes default to being in the XY plane but the ground is in the XZ plane so we rotate it. -```javascript +```js const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize); const planeMat = new THREE.MeshPhongMaterial({ map: texture, @@ -91,7 +91,7 @@ scene.add(mesh); Let's add a cube and a sphere so we have 3 things to light including the plane -```javascript +```js { const cubeSize = 4; const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize); @@ -118,7 +118,7 @@ Now that we have a scene to light up let's add lights! First let's make an `AmbientLight` -```javascript +```js const color = 0xFFFFFF; const intensity = 1; const light = new THREE.AmbientLight(color, intensity); @@ -136,7 +136,7 @@ color. Here's the helper: -```javascript +```js class ColorGUIHelper { constructor(object, prop) { this.object = object; @@ -153,7 +153,7 @@ class ColorGUIHelper { And here's our code setting up dat.GUI -```javascript +```js const gui = new dat.GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); @@ -187,7 +187,7 @@ the surface of the object is pointing down. Here's the new code -```javascript +```js -const color = 0xFFFFFF; +const skyColor = 0xB1E1FF; // light blue +const groundColor = 0xB97A20; // brownish orange @@ -199,7 +199,7 @@ scene.add(light); Let's also update the dat.GUI code to edit both colors -```javascript +```js const gui = new dat.GUI(); -gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); +gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('skyColor'); @@ -222,7 +222,7 @@ other light or a substitute for an `AmbientLight`. Let's switch the code to a `DirectionalLight`. A `DirectionalLight` is often used to represent the sun. -```javascript +```js const color = 0xFFFFFF; const intensity = 1; const light = new THREE.DirectionalLight(color, intensity); @@ -239,7 +239,7 @@ in the direction of its target. Let's make it so we can move the target by adding it to our GUI. -```javascript +```js const gui = new dat.GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); @@ -257,7 +257,7 @@ invisible parts of a scene. In this case we'll use the the light, and a line from the light to the target. We just pass it the light and add itd add it to the scene. -```javascript +```js const helper = new THREE.DirectionalLightHelper(light); scene.add(helper); ``` @@ -267,7 +267,7 @@ of the light and the target. To do this we'll make a function that given a `Vector3` will adjust its `x`, `y`, and `z` properties using `dat.GUI`. -```javascript +```js function makeXYZGUI(gui, vector3, name, onChangeFn) { const folder = gui.addFolder(name); folder.add(vector3, 'x', -10, 10).onChange(onChangeFn); @@ -285,7 +285,7 @@ get called anytime dat.GUI updates a value. Then we can use that for both the light's position and the target's position like this -```javascript +```js +function updateLight{ + light.target.updateMatrixWorld(); + helper.update(); @@ -315,7 +315,7 @@ shooting out parallel rays of light. A `PointLight` is a light that sits at a point and shoots light in all directions from that point. Let's change the code. -```javascript +```js const color = 0xFFFFFF; const intensity = 1; -const light = new THREE.DirectionalLight(color, intensity); @@ -328,15 +328,15 @@ scene.add(light); Let's also switch to a `PointLightHelper` -```javascript +```js -const helper = new THREE.DirectionalLightHelper(light); +const helper = new THREE.PointLightHelper(light); scene.add(helper); ``` and as there is no target the `onChange` function can be simpler. -```javascript +```js function updateLight{ - light.target.updateMatrixWorld(); helper.update(); @@ -356,7 +356,7 @@ units away from the light. Let's setup the GUI so we can adjust the distance. -```javascript +```js const gui = new dat.GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 2, 0.01); @@ -386,7 +386,7 @@ open toward the target. Modifying our `DirectionalLight` with helper from above -```javascript +```js const color = 0xFFFFFF; const intensity = 1; -const light = new THREE.DirectionalLight(color, intensity); @@ -404,7 +404,7 @@ property in radians. We'll use our `DegRadHelper` from the [texture artcle](threejs-textures.html) to present a UI in degrees. -```javascript +```js gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight); ``` @@ -415,7 +415,7 @@ inner code is the same size (0 = no difference) from the outer cone. When the outer cone. When `penumbra` is .5 then the light fades starting from 50% between the center of the outer cone. -```javascript +```js gui.add(light, 'penumbra', 0, 1, 0.01); ``` @@ -437,7 +437,7 @@ fluorescent light or maybe a frosted sky light in a ceiling. The `RectAreaLight` only works with the `MeshStandardMaterai` and the `MeshPhysicalMaterial` so let's change all our materials to `MeshStandardMaterial` -```javascript +```js ... const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize); @@ -484,7 +484,7 @@ be sure to remember to include the extra data. Now we can create the light -```javascript +```js const color = 0xFFFFFF; *const intensity = 5; +const width = 12; @@ -504,7 +504,7 @@ One thing to notice is that unlike the `DirectionalLight` and the `SpotLight` th Let's also adjust the GUI. We'll make it so we can rotate the light and adjust its `width` and `height` -```javascript +```js const gui = new dat.GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'intensity', 0, 10, 0.01); @@ -536,15 +536,15 @@ Let's test that. First we'll turn on physically correct lights -```javascript +```js const renderer = new THREE.WebGLRenderer({canvas: canvas}); +renderer.physicallyCorrectLights = true; ``` Then we'll set the `power` to 800 lumens, the `decay` to 2, and the `distance` to `Infinity`. -```javascript +```js const color = 0xFFFFFF; const intensity = 1; const light = new THREE.PointLight(color, intensity); @@ -555,7 +555,7 @@ light.distance = Infinity; and we'll add gui so we can change the `power` and `decay` -```javascript +```js const gui = new dat.GUI(); gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color'); gui.add(light, 'decay', 0, 4, 0.01);
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-load-gltf.md
@@ -69,7 +69,7 @@ for loading .OBJ and replaced it with code for loading .GLTF The old .OBJ code was -``` +```js const objLoader = new THREE.OBJLoader2(); objLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', null, (materials) => { materials.Material.side = THREE.DoubleSide; @@ -84,7 +84,7 @@ objLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', null, (materia The new .GLTF code is -``` +```js { const gltfLoader = new THREE.GLTFLoader(); const url = 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf'; @@ -99,7 +99,7 @@ I kept the auto framing code as before We also need to include the `GLTFLoader` and we can get rid of the `OBJLoader2`. -``` +```html -<script src="resources/threejs/r98/js/loaders/LoaderSupport.js"></script> -<script src="resources/threejs/r98/js/loaders/OBJLoader2.js"></script> -<script src="resources/threejs/r98/js/loaders/MTLLoader.js"></script> @@ -121,7 +121,7 @@ console. Here's the code to print out the scenegraph. -``` +```js function dumpObject(obj, lines = [], isLast = true, prefix = '') { const localPrefix = isLast ? '└─' : '├─'; lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`); @@ -137,7 +137,7 @@ function dumpObject(obj, lines = [], isLast = true, prefix = '') { And I just called it right after loading the scene. -``` +```js const gltfLoader = new THREE.GLTFLoader(); gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { const root = gltf.scene; @@ -147,7 +147,7 @@ gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.glt [Running that](.../threejs-load-gltf-dump-scenegraph.html) I got this listing -``` +```text OSG_Scene [Scene] └─RootNode_(gltf_orientation_matrix) [Object3D] └─RootNode_(model_correction_matrix) [Object3D] @@ -191,7 +191,7 @@ OSG_Scene [Scene] From that we can see all the cars happen to be under parent called `"Cars"` -``` +```text * ├─Cars [Object3D] │ ├─CAR_03_1 [Object3D] │ │ └─CAR_03_1_World_ap_0 [Mesh] @@ -207,7 +207,7 @@ all the children of the "Cars" node around their Y axis I looked up the "Cars" node after loading the scene and saved the result. -``` +```js +let cars; { const gltfLoader = new THREE.GLTFLoader(); @@ -220,7 +220,7 @@ and saved the result. Then in the `render` function we can just set the rotation of each child of `cars` -``` +```js +function render(time) { + time *= 0.001; // convert to seconds @@ -267,7 +267,7 @@ Each type of car will work with the same adjustments. I wrote this code to go through each car, parent it to a new `Object3D`, parent that new `Object3D` to the scene, and apply some per car *type* settings to fix its orientation, and add the new `Object3D` a `cars` array. -``` +```js -let cars; +const cars = []; { @@ -320,7 +320,7 @@ Fortunately I was able to select just my path and export .OBJ checking "write nu Opening the .OBJ file I was able to get a list of points which I formated into this -``` +```js const controlPoints = [ [1.118281, 5.115846, -3.681386], [3.948875, 5.115846, -3.641834], @@ -367,7 +367,7 @@ This will give us a curve like this Here's the code to make the curve -``` +```js let curve; let curveObject; { @@ -426,7 +426,7 @@ the lines made by connecting those 250 points. Running [the example](../threejs-load-gltf-car-path.html) I didn't see the curve. To make it visible made it ignore the depth test and render last -``` +```js curveObject = new THREE.Line(geometry, material); + material.depthTest = false; + curveObject.renderOrder = 1; @@ -461,7 +461,7 @@ is less of an issue. Going back to the function we wrote above to dump the scene graph, let's dump the position, rotation, and scale of each node. -``` +```js +function dumpVec3(v3, precision = 3) { + return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`; +} @@ -487,7 +487,7 @@ function dumpObject(obj, lines, isLast = true, prefix = '') { And the result from [running it](.../threejs-load-gltf-dump-scenegraph-extra.html) -``` +```text OSG_Scene [Scene] │ pos: 0.000, 0.000, 0.000 │ rot: 0.000, 0.000, 0.000 @@ -531,7 +531,7 @@ all the major nodes and removed any transformations. All these nodes at the top -``` +```text OSG_Scene [Scene] │ pos: 0.000, 0.000, 0.000 │ rot: 0.000, 0.000, 0.000 @@ -568,7 +568,7 @@ Here's what I ended up with. First I adjusted the position of the curve and after I found values that seemd to work. I then hid it. -``` +```js { const points = curve.getPoints(250); const geometry = new THREE.BufferGeometry().setFromPoints(points); @@ -588,7 +588,7 @@ a position from 0 to 1 along the curve and compute a point in world space using the `curveObject` to transform the point. We then pick another point slightly further down the curve. We set the car's orientation using `lookAt` and put the car at the mid point between the 2 points. -``` +```js // create 2 Vector3s we can use for path calculations const carPosition = new THREE.Vector3(); const carTarget = new THREE.Vector3(); @@ -630,7 +630,7 @@ and when I ran it I found out for each type of car, their height above their ori are not consistently set and so I needed to offset each one a little. -``` +```js const loadedCars = root.getObjectByName('Cars'); const fixes = [ - { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], }, @@ -669,7 +669,7 @@ into our latest code. Then, after loading, we need to turn on shadows on all the objects. -``` +```js { const gltfLoader = new THREE.GLTFLoader(); gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => { @@ -687,7 +687,7 @@ Then, after loading, we need to turn on shadows on all the objects. I then spent nearly 4 hours trying to figure out why the shadow helpers were not working. It was because I forgot to enable shadows with -``` +```js renderer.shadowMap.enabled = true; ``` @@ -697,7 +697,7 @@ I then adjusted the values until our `DirectionLight`'s shadow camera had a frustum that covered the entire scene. These are the settings I ended up with. -``` +```js { const color = 0xFFFFFF; const intensity = 1; @@ -724,7 +724,7 @@ I ended up with. and I set the background color to light blue. -``` +```js const scene = new THREE.Scene(); -scene.background = new THREE.Color('black'); +scene.background = new THREE.Color('#DEFEFF');
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-load-obj.md
@@ -44,7 +44,7 @@ that were being added to the scene. From that the first thing we need to do is include the `OBJLoader2` loader in our scene. The `OBJLoader2` also needs the `LoadingSupport.js` file so let's add both. -``` +```html <script src="resources/threejs/r98/js/loaders/LoadingSupport.js"></script> <script src="resources/threejs/r98/js/loaders/OBJLoader2.js"></script> ``` @@ -53,7 +53,7 @@ Then to load the .OBJ file we create an instance of `OBJLoader2`, pass it the URL of our .OBJ file, and pass in a callback that adds the loaded model to our scene. -``` +```js { const objLoader = new THREE.OBJLoader2(); objLoader.load('resources/models/windmill/windmill.obj', (event) => { @@ -82,7 +82,7 @@ Sometimes .OBJ files come with a .MTL file that defines materials. In our case the exporter also created a .MTL file. .MTL format is plain ASCII so it's easy to look at. Looking at it here -``` +```mtl # Blender MTL File: 'windmill_001.blend' # Material Count: 2 @@ -143,7 +143,7 @@ Now that we have the textures available we can load the .MTL file. First we need to include the `MTLLoader` -``` +```html <script src="resources/threejs/r98/three.min.js"></script> <script src="resources/threejs/r98/js/controls/OrbitControls.js"></script> <script src="resources/threejs/r98/js/loaders/LoaderSupport.js"></script> @@ -153,7 +153,7 @@ First we need to include the `MTLLoader` Then we first load the .MTL file. When it's finished loading we set the just loaded materials on to the `OBJLoader2` itself and then load the .OBJ file. -``` +```js { + const objLoader = new THREE.OBJLoader2(); + objLoader.loadMtl('resources/models/windmill/windmill.mtl', null, (materials) => { @@ -235,7 +235,7 @@ the surface. Looking at [the source for the MTLLoader](https://github.com/mrdoob/three.js/blob/1a560a3426e24bbfc9ca1f5fb0dfb4c727d59046/examples/js/loaders/MTLLoader.js#L432) it expects the keyword `norm` for normal maps so let's edit the .MTL file -``` +```mtl # Blender MTL File: 'windmill_001.blend' # Material Count: 2 @@ -280,7 +280,7 @@ Searching the net I found this [CC-BY-NC](https://creativecommons.org/licenses/b It had a .OBJ version already available. Let's load it up (note I removed the .MTL loader for now) -``` +```js - objLoader.load('resources/models/windmill/windmill.obj', ... + objLoader.load('resources/models/windmill-2/windmill.obj', ... ``` @@ -294,7 +294,7 @@ camera automatically. First off we can ask THREE.js to compute a box that contains the scene we just loaded and ask for its size and center -``` +```js objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { const root = event.detail.loaderRootNode; scene.add(root); @@ -308,7 +308,7 @@ objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { Looking in [the JavaScript console](threejs-debugging.html) I see -``` +```js size 2123.6499788469982 center p {x: -0.00006103515625, y: 770.0909731090069, z: -3.313507080078125} ``` @@ -347,15 +347,15 @@ given we know the field of view for the frustum and we know the size of the box Based on that diagram the formula for computing distance is -``` +```js distance = halfSizeToFitOnScreen / tangent(halfFovY) ``` Let's translate that to code. First let's make a function that will compute `distance` and then move the camera that `distance` units from the center of the box. We'll then point the camera at the `center` of the box. -``` +```js function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) { const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5; const halfFovY = THREE.Math.degToRad(camera.fov * .5); @@ -386,7 +386,7 @@ and used that as `sizeToFitOnScreen` then the math would make the box fit perfec the frustum. We want a little extra space above and below so we'll pass in a slightly larger size. -``` +```js { const objLoader = new THREE.OBJLoader2(); objLoader.load('resources/models/windmill_2/windmill.obj', (event) => { @@ -431,7 +431,7 @@ the camera is from the center. All we need to do to do that is zero out the `y` of the vector from the box to the camera. Then, when we normalize that vector it will become a vector parallel to the XZ plane. In otherwords parallel to the ground. -``` +```js -// compute a unit vector that points in the direction the camera is now -// from the center of the box -const direction = (new THREE.Vector3()).subVectors(camera.position, boxCenter).normalize(); @@ -453,7 +453,7 @@ Since the windmill is over 2000 units big let's change the size of the ground pl something more fitting. We also need to adjust the repeat otherwise our checkerboard will be so fine we won't even be able to see it unless we zoom way way in. -``` +```js -const planeSize = 40; +const planeSize = 4000; @@ -474,7 +474,7 @@ and now we can see this windmill Let's add the materials back. Like before there is a .MTL file that references some textures but looking at the files I quickly see an issue. -``` +```shell $ ls -l windmill -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj @@ -507,7 +507,7 @@ Loading the files up they were each 2048x2048. That seemed like a waste to me bu course it depends on your use case. I made them each 1024x1024 and saved them at a 50% quality setting in Photoshop. Getting a file listing -``` +```shell $ ls -l ../threejsfundamentals.org/threejs/resources/models/windmill -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj @@ -522,7 +522,7 @@ with this compression so be sure to consult with them to discuss the tradeoffs. Now, to use the .MTL file we need to edit it to reference the .JPG files instead of the .TGA files. Fortunately it's a simple text file so it's easy to edit -``` +```mtl newmtl blinn1SG Ka 0.10 0.10 0.10 @@ -550,7 +550,7 @@ illum 2 Now that the .MTL file points to some reasonable size textures we need to load it so we'll just do like we did above, first load the materials and then set them on the `OBJLoader2` -``` +```js { + const objLoader = new THREE.OBJLoader2(); + objLoader.loadMtl('resources/models/windmill_2/windmill-fixed.mtl', null, (materials) => { @@ -584,7 +584,7 @@ Issue #1: The three `MTLLoader` creates materials that multiply the material's d That's a useful feature but looking a the .MTL file above the line -``` +```mtl Kd 0.00 0.00 0.00 ``` @@ -593,7 +593,7 @@ did not multiply the diffuse texture map by the diffuse color. That's why it wor To fix this we can change the line to -``` +```mtl Kd 1.00 1.00 1.00 ``` @@ -608,7 +608,7 @@ needs a specular color set. Like above we can fix that by editing the .MTL file like this. -``` +```mtl -Ks 0.00 0.00 0.00 +Ks 1.00 1.00 1.00 ``` @@ -617,7 +617,7 @@ Issue #3: The `windmill_normal.jpg` is a normal map not a bump map. Just like above we just need to edit the .MTL file -``` +```mtl -map_bump windmill_normal.jpg -bump windmill_normal.jpg +norm windmill_normal.jpg
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-materials.md
@@ -14,7 +14,7 @@ accomplish. There are 2 ways to set most material properties. One at creation time which we've seen before. -``` +```js const material = new THREE.MeshPhongMaterial({ color: 0xFF0000, // red (can also use a CSS color string here) flatShading: true, @@ -23,15 +23,15 @@ const material = new THREE.MeshPhongMaterial({ The other is after creation -``` +```js const material = new THREE.MeshPhongMaterial(); material.color.setHSL(0, 1, .5); // red material.flatShading = true; ``` note that properties of type `THREE.Color` have multiple ways to be set. -``` +```js material.color.set(0x00FFFF); // same as CSS's #RRGGBB style material.color.set(cssString); // any CSS color, eg 'purple', '#F32', // 'rgb(255, 127, 64)', @@ -43,7 +43,7 @@ material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 And at creation time you can pass either a hex number or a CSS string -``` +```js const m1 = new THREE.MeshBasicMaterial({color: 0xFF0000}); // red const m2 = new THREE.MeshBasicMaterial({color: 'red'}); // red const m3 = new THREE.MeshBasicMaterial({color: '#F00'}); // red
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-multiple-scenes.md
@@ -35,7 +35,7 @@ issues for the same reasons. Let's start with a simple example with just 2 scenes. First we'll make the HTML -``` +```html <canvas id="c"></canvas> <p> <span id="box" class="diagram left"></span> @@ -51,7 +51,7 @@ make the HTML Then we can setup the CSS maybe something like this -``` +```css #c { position: fixed; left: 0; @@ -83,7 +83,7 @@ We set the canvsas to fill the screen and we set its `z-index` to Now we'll make 2 scenes each with a light and a camera. To one scene we'll add a cube and to another a diamond. -``` +```js function makeScene(elem) { const scene = new THREE.Scene(); @@ -142,7 +142,7 @@ only if the element is on the screen. We can tell THREE.js to only render to part of the canvas by turning on the *scissor* test with `Renderer.setScissorTest` and then setting both the scissor and the viewport with `Renderer.setViewport` and `Renderer.setScissor`. -``` +```js function rendenerSceneInfo(sceneInfo) { const {scene, camera, elem} = sceneInfo; @@ -173,7 +173,7 @@ function rendenerSceneInfo(sceneInfo) { And then our render function will just first clear the screen and then render each scene. -``` +```js function render(time) { time *= 0.001; @@ -208,7 +208,7 @@ drawn into the canvas will lag behind the rest of the page. If we give each area a border -``` +```css .diagram { display: inline-block; width: 5em; @@ -219,7 +219,7 @@ If we give each area a border And we set the background of each scene -``` +```js const scene = new THREE.Scene(); +scene.background = new THREE.Color('red'); ``` @@ -230,7 +230,7 @@ And if we <a href="../threejs-multiple-scenes-v2.html" target="_blank">quickly s We can switch to a different method which has a different tradeoff. We'll switch the canvas's CSS from `position: fixed` to `position: absolute`. -``` +```css #c { - position: fixed; + position: absolute; @@ -240,14 +240,14 @@ Then we'll set the canvas's transform to move it so the top of the canvas is at the top of whatever part the page is currently scrolled to. -``` +```js function render(time) { ... const transform = `translateY(${window.scrollY}px)`; renderer.domElement.style.transform = transform; -``` +```js `position: fixed` kept the canvas from scrolling at all while the rest of the page scrolled over it. `position: absolute` will let the canvas scroll with the rest of the page which means whatever we draw will stick with the page as it scrolls even if we're too slow to render. When we finally get a chance to render then we move the canvas so it matches where the page has been scrolled and then we re-render. This means only the edges of the window will show some un-rendered bits for a moment but <a href="../threejs-multiple-scenes-v2.html" target="_blank">the stuff in the middle of the page should match up</a> and not slide. Here's a view of the results of the new method slowed down 10x. @@ -262,7 +262,7 @@ We could make it so the main render function, the one managing the canvas, just Here's the main render function -``` +```js const sceneElements = []; function addScene(elem, fn) { sceneElements.push({elem, fn}); @@ -310,7 +310,7 @@ It checks if the element is on screen. If it is it calls `fn` and passes it the Now the setup code for each scene just adds itself to the list of scenes -``` +```js { const elem = document.querySelector('#box'); const {scene, camera} = makeScene(); @@ -356,7 +356,7 @@ With that we no longer needed `sceneInfo1` and `sceneInfo2` and the code that wa One last even more generic thing we can do is use HTML [dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset). This is a way to add your own data to an HTML element. Instead of using `id="..."` we'll use `data-diagram="..."` like this -``` +```html <canvas id="c"></canvas> <p> - <span id="box" class="diagram left"></span> @@ -374,7 +374,7 @@ One last even more generic thing we can do is use HTML [dataset](https://develop We can them change the CSS selector to select for that -``` +```css -.diagram +*[data-diagram] { display: inline-block; @@ -385,7 +385,7 @@ We can them change the CSS selector to select for that We'll change the scene setup code to just be a map of names to *scene initialization functions* that return a *scene render function*. -``` +```js const sceneInitFunctionsByName = { 'box': () => { const {scene, camera} = makeScene(); @@ -423,7 +423,7 @@ const sceneInitFunctionsByName = { And to init we can just use `querySelectorAll` to find all the diagrams and call the corresponding init function for that diagram. -``` +```js document.querySelectorAll('[data-diagram]').forEach((elem) => { const sceneName = elem.dataset.diagram; const sceneInitFunction = sceneInitFunctionsByName[sceneName]; @@ -440,13 +440,13 @@ No change to the visuals but the code is even more generic. Adding interactively, for example a `TrackballControls` is just as easy. First we add the script for the control. -``` +```html <script src="resources/threejs/r98/js/controls/TrackballControls.js"></script> ``` And then we can add a `TrackballControls` to each scene passing in the element associated with that scene. -``` +```js -function makeScene() { +function makeScene(elem) { const scene = new THREE.Scene(); @@ -482,7 +482,7 @@ You'll notice we added the camera to the scene and the light to the camera. This We need up update those controls in our render functions -``` +```js const sceneInitFunctionsByName = { - 'box': () => { - const {scene, camera} = makeScene();
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-picking.md
@@ -18,7 +18,7 @@ A few changes We'll parent the camera to another object so we can spin that other object and the camera will move around the scene just like a selfie stick. -``` +```js *const fov = 60; const aspect = 2; // the canvas default const near = 0.1; @@ -38,21 +38,21 @@ const scene = new THREE.Scene(); and in the `render` function we'll spin the camera pole. -``` +```js cameraPole.rotation.y = time * .1; ``` Also let's put the light on the camera so the light moves with it. -``` +```js -scene.add(light); +camera.add(light); ``` Let's generate 100 cubes with random colors in random positions, orientations, and scales. -``` +```js const boxWidth = 1; const boxHeight = 1; const boxDepth = 1; @@ -89,7 +89,7 @@ And finally let's pick. Let's make a simple class to manage the picking -``` +```js class PickHelper { constructor() { this.raycaster = new THREE.Raycaster(); @@ -124,7 +124,7 @@ You can see we create a `RayCaster` and then we can call the `pick` function to Of course we could call this function only when the user pressed the mouse *down* which is probaby usually what you want but for this example we'll pick every frame whatever is under the mouse. To do this we first need to track where the mouse is -``` +```js const pickPosition = {x: 0, y: 0}; clearPickPosition(); @@ -153,7 +153,7 @@ Notice we're recording a normalized mouse position. Reguardless of the size of t While we're at it lets support mobile as well -``` +```js window.addEventListener('touchstart', (event) => { // prevent the window from scrolling event.preventDefault(); @@ -169,7 +169,7 @@ window.addEventListener('touchend', clearPickPosition); And finally in our `render` function we call call the `PickHelper`'s `pick` function. -``` +```js +const pickHelper = new PickHelper(); function render(time) { @@ -219,7 +219,7 @@ As an example let's apply this texture to the cubes. We'll just make these changes -``` +```js +const loader = new THREE.TextureLoader(); +const texture = loader.load('resources/images/frame.png'); @@ -261,7 +261,7 @@ To do this type of picking in THREE.js at the moment requires we create 2 scenes So, first create a second scene and make sure it clears to black. -``` +```js const scene = new THREE.Scene(); scene.background = new THREE.Color('white'); const pickingScene = new THREE.Scene(); @@ -270,7 +270,7 @@ pickingScene.background = new THREE.Color(0); Then, for each cube we place in the main scene we make a corresponding "picking cube" at the same position as the original cube, put it in the `pickingScene`, and set it's material to something that will draw the object's id as its color. Also we keep a map of ids to objects so when we look up an id later we can map it back to its corresponding object. -``` +```js const idToObject = {}; +const numObjects = 100; for (let i = 0; i < numObjects; ++i) { @@ -315,7 +315,7 @@ Note that abusing the `MeshPhongMaterial` might not be the best solution as it w Because we're picking from pixels instead of ray casting we can change the code that sets the pick position to just use pixels. -``` +```js function setPickPosition(event) { - pickPosition.x = (event.clientX / canvas.clientWidth ) * 2 - 1; - pickPosition.y = (event.clientY / canvas.clientHeight) * -2 + 1; // note we flip Y @@ -326,7 +326,7 @@ function setPickPosition(event) { Then let's change the `PickHelper` into a `GPUPickHelper`. It will use a `WebGLRenderTarget` like we covered the [article on render targets](threejs-rendertargets.html). Our render target here is only a single pixel in size, 1x1. -``` +```js -class PickHelper { +class GPUPickHelper { constructor() { @@ -397,14 +397,14 @@ Then let's change the `PickHelper` into a `GPUPickHelper`. It will use a `WebGLR Then we just need to use it -``` +```js -const pickHelper = new PickHelper(); +const pickHelper = new GPUPickHelper(); ``` and pass it the `pickScene` instead of the `scene`. -``` +```js - pickHelper.pick(pickPosition, scene, camera, time); + pickHelper.pick(pickPosition, pickScene, camera, time); ```
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-prerequisites.md
@@ -29,7 +29,7 @@ Lots of 20yr old pages use HTML like That style is deprecated. Put your scripts at the bottom of the page. -``` +```html <html> <head> ... @@ -62,7 +62,7 @@ Put `'use strict';` at the top of every JavaScript file. It will help prevent lo ## Know how closures work -``` +```js function a(v) { const foo = v; return function() { @@ -123,7 +123,7 @@ the time. Use `let` in those cases where the value changes. This will help avoid As one example you can iterate over all the key/value pairs of an object with -``` +```js for (const [key, value] of Object.entries(someObject)) { console.log(key, value); } @@ -153,7 +153,7 @@ new code old code -``` +```js const width = 300; const height = 150; const obj = { @@ -167,7 +167,7 @@ old code new code -``` +```js const width = 300; const height = 150; const obj = { @@ -183,7 +183,7 @@ new code The spread operator has a ton of uses. Example -``` +```js function log(className, ...args) { const elem = document.createElement('div'); elem.className = className; @@ -194,7 +194,7 @@ The spread operator has a ton of uses. Example Another example -``` +```js const position = [1, 2, 3]; somemesh.position.set(...position); ``` @@ -216,15 +216,15 @@ of ES5 makes them much easier than pre ES5. This is especially useful with callbacks and promises. -``` +```js loader.load((texture) => { // use textrue }); ``` Arrow functions bind `this`. They are a shortcut for -``` +```js (function(args) {/* code */}).bind(this)) ``` @@ -245,7 +245,7 @@ Template literals are strings using backticks instead of quotes. Template literals have basically 2 features. One is they can be multi-line -``` +```js const foo = `this is a @@ -259,7 +259,7 @@ const bar = "this\nis\na\ntemplate\nliteral"; The other is that you can pop out of string mode and insert snippets of JavaScript using `${javascript-expression}`. This is the template part. Example: -``` +```js const r = 192; const g = 255; const b = 64; @@ -268,14 +268,14 @@ const rgbCSSColor = `rgb(${r},${g},${b})`; or -``` +```js const color = [192, 255, 64]; const rgbCSSColor = `rgb(${color.join(',')})`; ``` or -``` +```js const aWidth = 10; const bWidth = 20; someElement.style.width = `${aWidth + bWidth}px`;
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-primitives.md
@@ -80,7 +80,7 @@ with the [examples from the previous article](threejs-responsive.html). Near the top let's set a background color -``` +```js const scene = new THREE.Scene(); +scene.background = new THREE.Color(0xAAAAAA); ``` @@ -90,7 +90,7 @@ This tells three.js to clear to lightish gray. The camera needs to change position so that we can see all the objects. -``` +```js -const fov = 75; +const fov = 40; const aspect = 2; // the canvas default @@ -105,7 +105,7 @@ const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); Let's add a function, `addObject`, that takes an x, y position and an `Object3D` and adds the object to the scene. -``` +```js const objects = []; const spread = 15; @@ -132,7 +132,7 @@ as `luminance` goes from 0.0 to 0.5 the color will go from black to `hue`. From 0.5 to 1.0 the color will go from `hue` to white. -``` +```js function createMaterial() { const material = new THREE.MeshPhongMaterial({ side: THREE.DoubleSide, @@ -169,7 +169,7 @@ we pass a geometry and it creates a random colored material via `createMaterial` and adds it to the scene via `addObject`. -``` +```js function addSolidGeometry(x, y, geometry) { const mesh = new THREE.Mesh(geometry, createMaterial()); addObject(x, y, mesh); @@ -179,7 +179,7 @@ function addSolidGeometry(x, y, geometry) { Now we can use this for the majority of the primitives we create. For example creating a box -``` +```js { const width = 8; const height = 8; @@ -204,7 +204,7 @@ and a callback. The callback is called after the font loads. In the callback we create the geometry and call `addObject` to add it the scene. -``` +```js { const loader = new THREE.FontLoader(); loader.load('resources/threejs/fonts/helvetiker_regular.typeface.json', (font) => { @@ -263,7 +263,7 @@ The other exceptions are the 2 line based examples for `EdgesGeometry` and `WireframeGeometry`. Instead of calling `addSolidGeometry` they call `addLineGeomtry` which looks like this -``` +```js function addLineGeometry(x, y, geometry) { const material = new THREE.LineBasicMaterial({color: 0x000000}); const mesh = new THREE.LineSegments(geometry, material);
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-rendertargets.md
@@ -8,15 +8,15 @@ Let's make a simple example. We'll start with an example from [the article on re Rendering to a render target just almost exactly the same as normal rendering. First we create a `WebGLRenderTarget`. -``` +```js const rtWidth = 512; const rtHeight = 512; const renderTarget = new THREE.WebGLRenderTarget(rtWidth, rtHeight); ``` Then we need a `Camera` and a `Scene` -``` +```js const rtFov = 75; const rtAspect = rtWidth / rtHeight; const rtNear = 0.1; @@ -32,7 +32,7 @@ Notice we set the aspect to the aspect for the render target, not the canvas. We fill the scene with stuff. In this case we're using the light and the 3 cubes [from the previous article](threejs-responsive.html). -``` +```js { const color = 0xFFFFFF; const intensity = 1; @@ -69,7 +69,7 @@ We just need to add stuff to render. Let's add a cube that uses the render target's texture. -``` +```js const material = new THREE.MeshPhongMaterial({ map: renderTarget.texture, }); @@ -79,7 +79,7 @@ scene.add(cube); Now at render time first we render the render target scene to the render target. -``` +```js function render(time) { time *= 0.001; @@ -95,12 +95,11 @@ function render(time) { // draw render target scene to render target renderer.render(rtScene, rtCamera, renderTarget); - ``` Then we render the scene with the single cube that is using the render target's texture to the canvas. -``` +```js // rotate the cube in the scene cube.rotation.x = time; cube.rotation.y = time * 1.1;
true
Other
mrdoob
three.js
b6b702c50b236fee662c30c9e79c570861270d2d.json
add language tags to code blocks
threejs/lessons/threejs-responsive.md
@@ -18,7 +18,7 @@ in the middle of a document is another example. The last sample we had used a plain canvas with no css and no size -``` +```html <canvas id="c"></canvas> ``` @@ -29,7 +29,7 @@ of something is to use CSS. Let's make the canvas fill the page by adding CSS -``` +```html <style> html, body { margin: 0; @@ -82,7 +82,7 @@ display size. We can do that by looking at the canvas's We'll update our render loop like this -``` +```js function render(time) { time *= 0.001; @@ -111,7 +111,7 @@ number of pixels in the canvas itself. This is no different than an image. For example we might have a 128x64 pixel image and using css we might display as 400x200 pixels. -``` +```html <img src="some128x64image.jpg" style="width:400px; height:200px"> ``` @@ -124,7 +124,7 @@ attributes. Let's write a function that checks if the renderer's canvas is not already the size it is being displayed as and if so set its size. -``` +```js function resizeRendererToDisplaySize(renderer) { const canvas = renderer.domElement; const width = canvas.clientWidth; @@ -152,7 +152,7 @@ Note that our function returns true if the canvas was resized. We can use this to check if there are other things we should update. Let's modify our render loop to use the new function -``` +```js function render(time) { time *= 0.001; @@ -237,7 +237,7 @@ you passed in. The other way is to do it yourself when you resize the canvas. -``` +```js function resizeRendererToDisplaySize(renderer) { const canvas = renderer.domElement; const pixelRatio = window.devicePixelRatio;
true