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
bb3b4900cdefbcac7de9fccb845e48d8e1459d3d.json
add package to package.json
test/package.json
@@ -13,6 +13,7 @@ "pixelmatch": "^5.2.0", "puppeteer": "3.1.0", "qunit": "^2.10.0", + "rimraf": "^3.0.2", "serve-handler": "^6.1.2" }, "license": "MIT"
false
Other
mrdoob
three.js
9288ff08e5691f8439d59df9c350543101cbc164.json
remove symbolic link in node_modules
test/package.json
@@ -4,7 +4,7 @@ "description": "This package hiding test dependincies from main repo because puppeteer is pretty big.", "scripts": { "dev": "rollup -c rollup.unit.config.js -w -m inline", - "unit": "rollup -c rollup.unit.config.js && cd unit/build && \"../../qunit\" -r failonlyreporter three.source.unit.js" + "unit": "rollup -c rollup.unit.config.js && rimraf node_modules/three && qunit -r failonlyreporter unit/build/three.source.unit.js" }, "devDependencies": { "failonlyreporter": "^1.0.0",
false
Other
mrdoob
three.js
a4bc463fb42f694bdd031fbe6d8e77907aa11e14.json
add build folder also
test/package.json
@@ -4,7 +4,7 @@ "description": "This package hiding test dependincies from main repo because puppeteer is pretty big.", "scripts": { "dev": "rollup -c rollup.unit.config.js -w -m inline", - "unit": "rollup -c rollup.unit.config.js && cd unit && ..\\qunit -r failonlyreporter build\\three.source.unit.js" + "unit": "rollup -c rollup.unit.config.js && cd unit\\build && ..\\..\\qunit -r failonlyreporter three.source.unit.js" }, "devDependencies": { "failonlyreporter": "^1.0.0",
false
Other
mrdoob
three.js
e198fe78048cfeb296ef2f5756ac00c4c5e09430.json
Add documentation of hemisphereLightProbe
docs/api/en/lights/HemisphereLightProbe.html
@@ -0,0 +1,46 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <base href="../../../" /> + <script src="list.js"></script> + <script src="page.js"></script> + <link type="text/css" rel="stylesheet" href="page.css" /> + </head> + <body> + [page:Object3D] &rarr; [page:Light] &rarr; [page:LightProbe] + + <h1>[name]</h1> + + <p class="desc"> + Light probes are an alternative way of adding light to a 3D scene. HemisphereLightProbe is the light estimation data + of a single hemisphere light in the scene. For more information about light probes, go to [page:LightProbe]. + </p> + + <h2>Constructor</h2> + + <h3>[name]( [param:Color skyColor], [param:Color groundColor], [param:Float intensity] )</h3> + <p> + [page:Color skyColor] - (optional) An instance of Color, string representing a color or a number representing a color.<br /> + [page:Color groundColor] - (optional) An instance of Color, string representing a color or a number representing a color.<br /> + [page:Float intensity] - (optional) Numeric value of the light probe's intensity. Default is 1.<br /><br /> + + Creates a new [name]. + </p> + + <h2>Properties</h2> + <p> + See the base [page:LightProbe LightProbe] class for common properties. + </p> + + <h2>Methods</h2> + <p> + See the base [page:LightProbe LightProbe] class for common methods. + </p> + <h2>Source</h2> + + <p> + [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js] + </p> + </body> +</html>
true
Other
mrdoob
three.js
e198fe78048cfeb296ef2f5756ac00c4c5e09430.json
Add documentation of hemisphereLightProbe
docs/api/zh/lights/HemisphereLightProbe.html
@@ -0,0 +1,46 @@ +<!DOCTYPE html> +<html lang="zh"> + <head> + <meta charset="utf-8" /> + <base href="../../../" /> + <script src="list.js"></script> + <script src="page.js"></script> + <link type="text/css" rel="stylesheet" href="page.css" /> + </head> + <body> + [page:Object3D] &rarr; [page:Light] &rarr; [page:LightProbe] + + <h1>[name]</h1> + + <p class="desc"> + Light probes are an alternative way of adding light to a 3D scene. HemisphereLightProbe is the light estimation data + of a single hemisphere light in the scene. For more information about light probes, go to [page:LightProbe]. + </p> + + <h2>Constructor</h2> + + <h3>[name]( [param:Color skyColor], [param:Color groundColor], [param:Float intensity] )</h3> + <p> + [page:Color skyColor] - (optional) An instance of Color, string representing a color or a number representing a color.<br /> + [page:Color groundColor] - (optional) An instance of Color, string representing a color or a number representing a color.<br /> + [page:Float intensity] - (optional) Numeric value of the light probe's intensity. Default is 1.<br /><br /> + + Creates a new [name]. + </p> + + <h2>Properties</h2> + <p> + See the base [page:LightProbe LightProbe] class for common properties. + </p> + + <h2>Methods</h2> + <p> + See the base [page:LightProbe LightProbe] class for common methods. + </p> + <h2>Source</h2> + + <p> + [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js] + </p> + </body> +</html>
true
Other
mrdoob
three.js
e198fe78048cfeb296ef2f5756ac00c4c5e09430.json
Add documentation of hemisphereLightProbe
docs/list.js
@@ -204,6 +204,7 @@ var list = { "AmbientLightProbe": "api/en/lights/AmbientLightProbe", "DirectionalLight": "api/en/lights/DirectionalLight", "HemisphereLight": "api/en/lights/HemisphereLight", + "HemisphereLightProbe": "api/en/lights/HemisphereLightProbe", "Light": "api/en/lights/Light", "LightProbe": "api/en/lights/LightProbe", "PointLight": "api/en/lights/PointLight", @@ -664,6 +665,7 @@ var list = { "AmbientLightProbe": "api/zh/lights/AmbientLightProbe", "DirectionalLight": "api/zh/lights/DirectionalLight", "HemisphereLight": "api/zh/lights/HemisphereLight", + "HemisphereLightProbe": "api/zh/lights/HemisphereLightProbe", "Light": "api/zh/lights/Light", "LightProbe": "api/zh/lights/LightProbe", "PointLight": "api/zh/lights/PointLight",
true
Other
mrdoob
three.js
bbc05ad6538e7014c81008d766f1b742b2cdfdbc.json
add suggestion from mrdoob
examples/webgl_animation_cloth.html
@@ -42,10 +42,11 @@ // http://cg.alexandra.dk/tag/spring-mass-system/ // Real-time Cloth Animation http://www.darwin3d.com/gamedev/articles/col0599.pdf - var params = {}; - params[ "Enable wind" ] = true; - params[ "Show ball" ] = false; - params[ "Toggle pins" ] = togglePins; + var params = { + enableWind: true, + showBall: false, + togglePins: togglePins + }; var DAMPING = 0.03; var DRAG = 1 - DAMPING; @@ -272,7 +273,7 @@ // Aerodynamics forces - if ( params[ "Enable wind" ] ) { + if ( params.enableWind ) { var indx; var normal = new THREE.Vector3(); @@ -322,7 +323,7 @@ ballPosition.z = - Math.sin( now / 600 ) * 90; //+ 40; ballPosition.x = Math.cos( now / 400 ) * 70; - if ( params[ "Show ball" ] ) { + if ( params.showBall ) { sphere.visible = true; @@ -580,25 +581,22 @@ // var gui = new GUI(); - gui.add( params, 'Enable wind' ); - gui.add( params, 'Show ball' ); - gui.add( params, 'Toggle pins' ); - + gui.add( params, 'enableWind' ).name( 'Enable wind' ); + gui.add( params, 'showBall' ).name( 'Show ball' ); + gui.add( params, 'togglePins' ).name( 'Toggle pins' ); // if ( typeof TESTING !== 'undefined' ) { - for ( var i = 0; i < 50; i ++ ) { - - simulate( 500 - 10 * i ); - - } + for ( var i = 0; i < 50; i ++ ) { + simulate( 500 - 10 * i ); + } - } + } -} + } // @@ -646,4 +644,4 @@ </script> </body> -</html> +</html> \ No newline at end of file
false
Other
mrdoob
three.js
23054b4e69f65a324fa5efc2ddf9e28733bf3e02.json
Allow the factory to cache controllers Noticed that there was a significant delay in controllers reappearing after jumping into and out of a system menu, which was primarily caused by re-parsing the glTF assets. This change makes it much smoother. Also includes a few bug fixes.
examples/jsm/webxr/XRControllerModelFactory.js
@@ -11,15 +11,15 @@ import { SphereGeometry, } from "../../../build/three.module.js"; -import { GLTFLoader } from '../loaders/GLTFLoader.js' +import { GLTFLoader } from '../loaders/GLTFLoader.js'; import { Constants as MotionControllerConstants, fetchProfile, MotionController -} from '../libs/motion-controllers.module.js' +} from '../libs/motion-controllers.module.js'; -const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@0.2.0/dist/profiles' +const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@0.2.0/dist/profiles'; function XRControllerModel( ) { @@ -182,12 +182,37 @@ function findNodes( motionController, scene ) { }); } +function addAssetSceneToControllerModel( controllerModel, scene ) { + // Find the nodes needed for animation and cache them on the motionController. + findNodes( controllerModel.motionController, scene ); + + // Apply any environment map that the mesh already has set. + if ( controllerModel.envMap ) { + + scene.traverse(( child ) => { + + if ( child.isMesh ) { + + child.material.envMap = controllerModel.envMap; + child.material.needsUpdate = true; + + } + + }); + + } + + // Add the glTF scene to the controllerModel. + controllerModel.add( scene ); +} + var XRControllerModelFactory = ( function () { function XRControllerModelFactory( gltfLoader = null ) { this.gltfLoader = gltfLoader; this.path = DEFAULT_PROFILES_PATH; + this._assetCache = {}; // If a GLTFLoader wasn't supplied to the constructor create a new one. if ( !this.gltfLoader ) { @@ -204,19 +229,15 @@ var XRControllerModelFactory = ( function () { createControllerModel: function ( controller ) { - if ( !this.gltfLoader ) { - - throw new Error(`GLTFLoader not set.`); - - } - const controllerModel = new XRControllerModel(); let scene = null; controller.addEventListener( 'connected', ( event ) => { const xrInputSource = event.data; + if (xrInputSource.targetRayMode !== 'tracked-pointer' ) return; + fetchProfile(xrInputSource, this.path).then(({ profile, assetPath }) => { controllerModel.motionController = new MotionController( @@ -225,40 +246,39 @@ var XRControllerModelFactory = ( function () { assetPath ); - this.gltfLoader.setPath(''); - this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => { + let cachedAsset = this._assetCache[controllerModel.motionController.assetUrl]; + if (cachedAsset) { - scene = asset.scene; + scene = cachedAsset.scene.clone(); - // Find the nodes needed for animation and cache them on the motionController. - findNodes( controllerModel.motionController, scene ); + addAssetSceneToControllerModel(controllerModel, scene); - // Apply any environment map that the mesh already has set. - if ( controllerModel.envMap ) { + } else { - scene.traverse(( child ) => { + if ( !this.gltfLoader ) { - if ( child.isMesh ) { + throw new Error(`GLTFLoader not set.`); - child.material.envMap = controllerModel.envMap; - child.material.needsUpdate = true; + } - } + this.gltfLoader.setPath(''); + this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => { - }); + this._assetCache[controllerModel.motionController.assetUrl] = asset; - } + scene = asset.scene.clone(); + + addAssetSceneToControllerModel(controllerModel, scene); - // Add the glTF scene to the controllerModel. - controllerModel.add( scene ); + }, + null, + () => { - }, - null, - () => { + throw new Error(`Asset ${motionController.assetUrl} missing or malformed.`); - throw new Error(`Asset ${motionController.assetUrl} missing or malformed.`); + }); - }); + } }).catch((err) => {
false
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/jsm/libs/motion-controllers.module.js
@@ -0,0 +1,397 @@ +/** + * @webxr-input-profiles/motion-controllers 0.2.0 https://github.com/immersive-web/webxr-input-profiles + */ + +const Constants = { + Handedness: Object.freeze({ + NONE: 'none', + LEFT: 'left', + RIGHT: 'right' + }), + + ComponentState: Object.freeze({ + DEFAULT: 'default', + TOUCHED: 'touched', + PRESSED: 'pressed' + }), + + ComponentProperty: Object.freeze({ + BUTTON: 'button', + X_AXIS: 'xAxis', + Y_AXIS: 'yAxis', + STATE: 'state' + }), + + ComponentType: Object.freeze({ + TRIGGER: 'trigger', + SQUEEZE: 'squeeze', + TOUCHPAD: 'touchpad', + THUMBSTICK: 'thumbstick', + BUTTON: 'button' + }), + + ButtonTouchThreshold: 0.05, + + AxisTouchThreshold: 0.1, + + VisualResponseProperty: Object.freeze({ + TRANSFORM: 'transform', + VISIBILITY: 'visibility' + }) +}; + +/** + * @description Static helper function to fetch a JSON file and turn it into a JS object + * @param {string} path - Path to JSON file to be fetched + */ +async function fetchJsonFile(path) { + const response = await fetch(path); + if (!response.ok) { + throw new Error(response.statusText); + } else { + return response.json(); + } +} + +async function fetchProfilesList(basePath) { + if (!basePath) { + throw new Error('No basePath supplied'); + } + + const profileListFileName = 'profilesList.json'; + const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`); + return profilesList; +} + +async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) { + if (!xrInputSource) { + throw new Error('No xrInputSource supplied'); + } + + if (!basePath) { + throw new Error('No basePath supplied'); + } + + // Get the list of profiles + const supportedProfilesList = await fetchProfilesList(basePath); + + // Find the relative path to the first requested profile that is recognized + let match; + xrInputSource.profiles.some((profileId) => { + const supportedProfile = supportedProfilesList[profileId]; + if (supportedProfile) { + match = { + profileId, + profilePath: `${basePath}/${supportedProfile.path}`, + deprecated: !!supportedProfile.deprecated + }; + } + return !!match; + }); + + if (!match) { + if (!defaultProfile) { + throw new Error('No matching profile name found'); + } + + const supportedProfile = supportedProfilesList[defaultProfile]; + if (!supportedProfile) { + throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`); + } + + match = { + profileId: defaultProfile, + profilePath: `${basePath}/${supportedProfile.path}`, + deprecated: !!supportedProfile.deprecated + }; + } + + const profile = await fetchJsonFile(match.profilePath); + + let assetPath; + if (getAssetPath) { + let layout; + if (xrInputSource.handedness === 'any') { + layout = profile.layouts[Object.keys(profile.layouts)[0]]; + } else { + layout = profile.layouts[xrInputSource.handedness]; + } + if (!layout) { + throw new Error( + `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}` + ); + } + + if (layout.assetPath) { + assetPath = match.profilePath.replace('profile.json', layout.assetPath); + } + } + + return { profile, assetPath }; +} + +/** @constant {Object} */ +const defaultComponentValues = { + xAxis: 0, + yAxis: 0, + button: 0, + state: Constants.ComponentState.DEFAULT +}; + +/** + * @description Converts an X, Y coordinate from the range -1 to 1 (as reported by the Gamepad + * API) to the range 0 to 1 (for interpolation). Also caps the X, Y values to be bounded within + * a circle. This ensures that thumbsticks are not animated outside the bounds of their physical + * range of motion and touchpads do not report touch locations off their physical bounds. + * @param {number} x The original x coordinate in the range -1 to 1 + * @param {number} y The original y coordinate in the range -1 to 1 + */ +function normalizeAxes(x = 0, y = 0) { + let xAxis = x; + let yAxis = y; + + // Determine if the point is outside the bounds of the circle + // and, if so, place it on the edge of the circle + const hypotenuse = Math.sqrt((x * x) + (y * y)); + if (hypotenuse > 1) { + const theta = Math.atan2(y, x); + xAxis = Math.cos(theta); + yAxis = Math.sin(theta); + } + + // Scale and move the circle so values are in the interpolation range. The circle's origin moves + // from (0, 0) to (0.5, 0.5). The circle's radius scales from 1 to be 0.5. + const result = { + normalizedXAxis: (xAxis * 0.5) + 0.5, + normalizedYAxis: (yAxis * 0.5) + 0.5 + }; + return result; +} + +/** + * Contains the description of how the 3D model should visually respond to a specific user input. + * This is accomplished by initializing the object with the name of a node in the 3D model and + * property that need to be modified in response to user input, the name of the nodes representing + * the allowable range of motion, and the name of the input which triggers the change. In response + * to the named input changing, this object computes the appropriate weighting to use for + * interpolating between the range of motion nodes. + */ +class VisualResponse { + constructor(visualResponseDescription) { + this.componentProperty = visualResponseDescription.componentProperty; + this.states = visualResponseDescription.states; + this.valueNodeName = visualResponseDescription.valueNodeName; + this.valueNodeProperty = visualResponseDescription.valueNodeProperty; + + if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) { + this.minNodeName = visualResponseDescription.minNodeName; + this.maxNodeName = visualResponseDescription.maxNodeName; + } + + // Initializes the response's current value based on default data + this.value = 0; + this.updateFromComponent(defaultComponentValues); + } + + /** + * Computes the visual response's interpolation weight based on component state + * @param {Object} componentValues - The component from which to update + * @param {number} xAxis - The reported X axis value of the component + * @param {number} yAxis - The reported Y axis value of the component + * @param {number} button - The reported value of the component's button + * @param {string} state - The component's active state + */ + updateFromComponent({ + xAxis, yAxis, button, state + }) { + const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis); + switch (this.componentProperty) { + case Constants.ComponentProperty.X_AXIS: + this.value = (this.states.includes(state)) ? normalizedXAxis : 0.5; + break; + case Constants.ComponentProperty.Y_AXIS: + this.value = (this.states.includes(state)) ? normalizedYAxis : 0.5; + break; + case Constants.ComponentProperty.BUTTON: + this.value = (this.states.includes(state)) ? button : 0; + break; + case Constants.ComponentProperty.STATE: + if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) { + this.value = (this.states.includes(state)); + } else { + this.value = this.states.includes(state) ? 1.0 : 0.0; + } + break; + default: + throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`); + } + } +} + +class Component { + /** + * @param {Object} componentId - Id of the component + * @param {Object} componentDescription - Description of the component to be created + */ + constructor(componentId, componentDescription) { + if (!componentId + || !componentDescription + || !componentDescription.visualResponses + || !componentDescription.gamepadIndices + || Object.keys(componentDescription.gamepadIndices).length === 0) { + throw new Error('Invalid arguments supplied'); + } + + this.id = componentId; + this.type = componentDescription.type; + this.rootNodeName = componentDescription.rootNodeName; + this.touchPointNodeName = componentDescription.touchPointNodeName; + + // Build all the visual responses for this component + this.visualResponses = {}; + Object.keys(componentDescription.visualResponses).forEach((responseName) => { + const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]); + this.visualResponses[responseName] = visualResponse; + }); + + // Set default values + this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices); + + this.values = { + state: Constants.ComponentState.DEFAULT, + button: (this.gamepadIndices.button !== undefined) ? 0 : undefined, + xAxis: (this.gamepadIndices.xAxis !== undefined) ? 0 : undefined, + yAxis: (this.gamepadIndices.yAxis !== undefined) ? 0 : undefined + }; + } + + get data() { + const data = { id: this.id, ...this.values }; + return data; + } + + /** + * @description Poll for updated data based on current gamepad state + * @param {Object} gamepad - The gamepad object from which the component data should be polled + */ + updateFromGamepad(gamepad) { + // Set the state to default before processing other data sources + this.values.state = Constants.ComponentState.DEFAULT; + + // Get and normalize button + if (this.gamepadIndices.button !== undefined + && gamepad.buttons.length > this.gamepadIndices.button) { + const gamepadButton = gamepad.buttons[this.gamepadIndices.button]; + this.values.button = gamepadButton.value; + this.values.button = (this.values.button < 0) ? 0 : this.values.button; + this.values.button = (this.values.button > 1) ? 1 : this.values.button; + + // Set the state based on the button + if (gamepadButton.pressed || this.values.button === 1) { + this.values.state = Constants.ComponentState.PRESSED; + } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) { + this.values.state = Constants.ComponentState.TOUCHED; + } + } + + // Get and normalize x axis value + if (this.gamepadIndices.xAxis !== undefined + && gamepad.axes.length > this.gamepadIndices.xAxis) { + this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis]; + this.values.xAxis = (this.values.xAxis < -1) ? -1 : this.values.xAxis; + this.values.xAxis = (this.values.xAxis > 1) ? 1 : this.values.xAxis; + + // If the state is still default, check if the xAxis makes it touched + if (this.values.state === Constants.ComponentState.DEFAULT + && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) { + this.values.state = Constants.ComponentState.TOUCHED; + } + } + + // Get and normalize Y axis value + if (this.gamepadIndices.yAxis !== undefined + && gamepad.axes.length > this.gamepadIndices.yAxis) { + this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis]; + this.values.yAxis = (this.values.yAxis < -1) ? -1 : this.values.yAxis; + this.values.yAxis = (this.values.yAxis > 1) ? 1 : this.values.yAxis; + + // If the state is still default, check if the yAxis makes it touched + if (this.values.state === Constants.ComponentState.DEFAULT + && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) { + this.values.state = Constants.ComponentState.TOUCHED; + } + } + + // Update the visual response weights based on the current component data + Object.values(this.visualResponses).forEach((visualResponse) => { + visualResponse.updateFromComponent(this.values); + }); + } +} + +/** + * @description Builds a motion controller with components and visual responses based on the + * supplied profile description. Data is polled from the xrInputSource's gamepad. + * @author Nell Waliczek / https://github.com/NellWaliczek +*/ +class MotionController { + /** + * @param {Object} xrInputSource - The XRInputSource to build the MotionController around + * @param {Object} profile - The best matched profile description for the supplied xrInputSource + * @param {Object} assetUrl + */ + constructor(xrInputSource, profile, assetUrl) { + if (!xrInputSource) { + throw new Error('No xrInputSource supplied'); + } + + if (!profile) { + throw new Error('No profile supplied'); + } + + this.xrInputSource = xrInputSource; + this.assetUrl = assetUrl; + this.id = profile.profileId; + + // Build child components as described in the profile description + this.layoutDescription = profile.layouts[xrInputSource.handedness]; + this.components = {}; + Object.keys(this.layoutDescription.components).forEach((componentId) => { + const componentDescription = this.layoutDescription.components[componentId]; + this.components[componentId] = new Component(componentId, componentDescription); + }); + + // Initialize components based on current gamepad state + this.updateFromGamepad(); + } + + get gripSpace() { + return this.xrInputSource.gripSpace; + } + + get targetRaySpace() { + return this.xrInputSource.targetRaySpace; + } + + /** + * @description Returns a subset of component data for simplified debugging + */ + get data() { + const data = []; + Object.values(this.components).forEach((component) => { + data.push(component.data); + }); + return data; + } + + /** + * @description Poll for updated data based on current gamepad state + */ + updateFromGamepad() { + Object.values(this.components).forEach((component) => { + component.updateFromGamepad(this.xrInputSource.gamepad); + }); + } +} + +export { Constants, MotionController, fetchProfile, fetchProfilesList };
true
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/jsm/webxr/XRControllerModelFactory.d.ts
@@ -14,11 +14,10 @@ export class XRControllerModel extends Object3D { setEnvironmentMap( envMap: Texture ): XRControllerModel; } -export class XRControllerModelLoader { +export class XRControllerModelFactory { constructor( gltfLoader?: GLTFLoader ); gltfLoader: GLTFLoader | null; path: string; - setGLTFLoader( gltfLoader: GLTFLoader ): XRControllerModelLoader; - getControllerModel( controller: Group ): XRControllerModel; + createControllerModel( controller: Group ): XRControllerModel; }
true
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/jsm/webxr/XRControllerModelFactory.js
@@ -11,13 +11,15 @@ import { SphereGeometry, } from "../../../build/three.module.js"; +import { GLTFLoader } from '../loaders/GLTFLoader.js' + import { Constants as MotionControllerConstants, fetchProfile, MotionController -} from 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/motion-controllers@0.1.0/dist/motion-controllers.module.js' +} from '../libs/motion-controllers.module.js' -const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@0.1.0/dist/profiles' +const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@0.2.0/dist/profiles' function XRControllerModel( ) { @@ -180,27 +182,27 @@ function findNodes( motionController, scene ) { }); } -var XRControllerModelLoader = ( function () { +var XRControllerModelFactory = ( function () { - function XRControllerModelLoader( gltfLoader ) { + function XRControllerModelFactory( gltfLoader = null ) { this.gltfLoader = gltfLoader; this.path = DEFAULT_PROFILES_PATH; - } + // If a GLTFLoader wasn't supplied to the constructor create a new one. + if ( !this.gltfLoader ) { - XRControllerModelLoader.prototype = { + this.gltfLoader = new GLTFLoader(); - constructor: XRControllerModelLoader, + } - setGLTFLoader: function ( gltfLoader ) { + } - this.gltfLoader = gltfLoader; - return this; + XRControllerModelFactory.prototype = { - }, + constructor: XRControllerModelFactory, - getControllerModel: function ( controller ) { + createControllerModel: function ( controller ) { if ( !this.gltfLoader ) { @@ -279,8 +281,8 @@ var XRControllerModelLoader = ( function () { }; - return XRControllerModelLoader; + return XRControllerModelFactory; } )(); -export { XRControllerModelLoader }; +export { XRControllerModelFactory };
true
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/webxr_vr_ballshooter.html
@@ -20,6 +20,7 @@ import { BoxLineGeometry } from './jsm/geometries/BoxLineGeometry.js'; import { VRButton } from './jsm/webxr/VRButton.js'; + import { XRControllerModelFactory } from './jsm/webxr/XRControllerModelFactory.js'; var camera, scene, renderer; var controller1, controller2; @@ -51,8 +52,10 @@ room.geometry.translate( 0, 3, 0 ); scene.add( room ); - var light = new THREE.HemisphereLight( 0xffffff, 0x444444 ); - light.position.set( 1, 1, 1 ); + scene.add( new THREE.HemisphereLight( 0x606060, 0x404040 ) ); + + var light = new THREE.DirectionalLight( 0xffffff ); + light.position.set( 1, 1, 1 ).normalize(); scene.add( light ); var geometry = new THREE.IcosahedronBufferGeometry( radius, 2 ); @@ -130,6 +133,14 @@ } ); scene.add( controller2 ); + // The XRControllerModelFactory will automatically fetch controller models + // that match what the user is holding as closely as possible. + + var controllerModelFactory = new XRControllerModelFactory(); + + controller1.add( controllerModelFactory.createControllerModel( controller1 ) ); + controller2.add( controllerModelFactory.createControllerModel( controller2 ) ); + // window.addEventListener( 'resize', onWindowResize, false );
true
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/webxr_vr_cubes.html
@@ -20,6 +20,7 @@ import { BoxLineGeometry } from './jsm/geometries/BoxLineGeometry.js'; import { VRButton } from './jsm/webxr/VRButton.js'; + import { XRControllerModelFactory } from './jsm/webxr/XRControllerModelFactory.js'; var clock = new THREE.Clock(); @@ -122,6 +123,10 @@ } ); scene.add( controller ); + var controllerModelFactory = new XRControllerModelFactory(); + + controller.add( controllerModelFactory.createControllerModel( controller ) ); + window.addEventListener( 'resize', onWindowResize, false ); //
true
Other
mrdoob
three.js
fca61b053d5ccb7d8779abc4e91cf74c7587ea4a.json
Update XRControllerModelFactory based on feedback Also assed it to three existing examples. Skipped paint/sculpt because they already had simple controller visualizations.
examples/webxr_vr_dragging.html
@@ -19,6 +19,7 @@ import * as THREE from '../build/three.module.js'; import { OrbitControls } from './jsm/controls/OrbitControls.js'; import { VRButton } from './jsm/webxr/VRButton.js'; + import { XRControllerModelFactory } from './jsm/webxr/XRControllerModelFactory.js'; var container; var camera, scene, renderer; @@ -133,6 +134,11 @@ controller2.addEventListener( 'selectend', onSelectEnd ); scene.add( controller2 ); + var controllerModelFactory = new XRControllerModelFactory(); + + controller1.add( controllerModelFactory.createControllerModel( controller1 ) ); + controller2.add( controllerModelFactory.createControllerModel( controller2 ) ); + // var geometry = new THREE.BufferGeometry().setFromPoints( [ new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, - 1 ) ] );
true
Other
mrdoob
three.js
40c35590800745bf1650f1876fdcff844cad6492.json
remove envMap flipping for CUBE_UV textures
examples/webgl_materials_envmaps_parallax.html
@@ -105,8 +105,7 @@ #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); - vec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 ); + vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); #else @@ -172,8 +171,7 @@ #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); - vec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness ); + vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); #elif defined( ENVMAP_TYPE_EQUIREC )
true
Other
mrdoob
three.js
40c35590800745bf1650f1876fdcff844cad6492.json
remove envMap flipping for CUBE_UV textures
src/renderers/shaders/ShaderChunk/envmap_fragment.glsl.js
@@ -40,7 +40,7 @@ export default /* glsl */` #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 envColor = textureCubeUV( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ), 0.0 ); + vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 ); #elif defined( ENVMAP_TYPE_EQUIREC )
true
Other
mrdoob
three.js
40c35590800745bf1650f1876fdcff844cad6492.json
remove envMap flipping for CUBE_UV textures
src/renderers/shaders/ShaderChunk/envmap_physical_pars_fragment.glsl.js
@@ -31,8 +31,7 @@ export default /* glsl */` #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz ); - vec4 envMapColor = textureCubeUV( envMap, queryVec, 1.0 ); + vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 ); #else @@ -94,8 +93,7 @@ export default /* glsl */` #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz ); - vec4 envMapColor = textureCubeUV( envMap, queryReflectVec, roughness ); + vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness ); #elif defined( ENVMAP_TYPE_EQUIREC )
true
Other
mrdoob
three.js
5dc078a9d60be4811a36d1408f5d8cab3737e383.json
fix NormalNode context
examples/jsm/nodes/accessors/NormalNode.js
@@ -29,6 +29,20 @@ NormalNode.prototype.getShared = function () { }; +NormalNode.prototype.build = function ( builder, output, uuid, ns ) { + + var contextNormal = builder.context[ this.scope + 'Normal' ]; + + if ( contextNormal ) { + + return contextNormal.build( builder, output, uuid, ns ); + + } + + return TempNode.prototype.build.call( this, builder, output, uuid ); + +} + NormalNode.prototype.generate = function ( builder, output ) { var result;
true
Other
mrdoob
three.js
5dc078a9d60be4811a36d1408f5d8cab3737e383.json
fix NormalNode context
examples/jsm/nodes/accessors/ReflectNode.js
@@ -54,7 +54,7 @@ ReflectNode.prototype.generate = function ( builder, output ) { case ReflectNode.VECTOR: - var viewNormalNode = builder.context.viewNormal || new NormalNode( NormalNode.VIEW ); + var viewNormalNode = new NormalNode( NormalNode.VIEW ); var roughnessNode = builder.context.roughness; var viewNormal = viewNormalNode.build( builder, 'v3' );
true
Other
mrdoob
three.js
5dc078a9d60be4811a36d1408f5d8cab3737e383.json
fix NormalNode context
examples/jsm/nodes/materials/nodes/StandardNode.js
@@ -135,6 +135,7 @@ StandardNode.prototype.build = function ( builder ) { roughness: specularRoughness, bias: new SpecularMIPLevelNode( specularRoughness ), viewNormal: new ExpressionNode( 'normal', 'v3' ), + worldNormal: new ExpressionNode( 'inverseTransformDirection( geometry.normal, viewMatrix )', 'v3' ), gamma: true }; @@ -146,6 +147,7 @@ StandardNode.prototype.build = function ( builder ) { roughness: clearcoatRoughness, bias: new SpecularMIPLevelNode( clearcoatRoughness ), viewNormal: new ExpressionNode( 'clearcoatNormal', 'v3' ), + worldNormal: new ExpressionNode( 'inverseTransformDirection( geometry.clearcoatNormal, viewMatrix )', 'v3' ), gamma: true };
true
Other
mrdoob
three.js
5dc078a9d60be4811a36d1408f5d8cab3737e383.json
fix NormalNode context
examples/jsm/nodes/misc/TextureCubeUVNode.js
@@ -84,11 +84,14 @@ TextureCubeUVNode.Nodes = ( function () { var bilinearCubeUV = new FunctionNode( `TextureCubeUVData bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) { + float face = getFace(direction); float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0); mipInt = max(mipInt, cubeUV_minMipLevel); float faceSize = exp2(mipInt); + float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize); + vec2 uv = getUV(direction, face) * (faceSize - 1.0); vec2 f = fract(uv); uv += 0.5 - f; @@ -103,6 +106,7 @@ TextureCubeUVNode.Nodes = ( function () { uv.y += filterInt * 2.0 * cubeUV_minTileSize; uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize); uv *= texelSize; + vec4 tl = texture2D(envMap, uv); uv.x += texelSize; vec4 tr = texture2D(envMap, uv);
true
Other
mrdoob
three.js
a7c3713d7532dbf305f9923185e457101f6a7cec.json
update default values
examples/jsm/nodes/materials/nodes/StandardNode.js
@@ -17,11 +17,9 @@ function StandardNode() { Node.call( this ); - this.color = new ColorNode( 0xEEEEEE ); - this.roughness = new FloatNode( 0.5 ); - this.metalness = new FloatNode( 0.5 ); - - this.energyPreservation = true; + this.color = new ColorNode( 0xFFFFFF ); + this.roughness = new FloatNode( 1 ); + this.metalness = new FloatNode( 0 ); }
false
Other
mrdoob
three.js
b98a3a3044a3efc84c833bd0c4cb90b0f491576e.json
Open the helper folder by default
examples/webgl_shadowmap_csm.html
@@ -235,6 +235,8 @@ helperFolder.add( params, 'updateHelper' ).name( 'update' ); + helperFolder.open(); + window.addEventListener( 'resize', function () { camera.aspect = window.innerWidth / window.innerHeight;
false
Other
mrdoob
three.js
92f0693914f3202a37aef1699d7cae7f01031dc5.json
Remove unused variables
examples/jsm/csm/CSM.js
@@ -8,11 +8,6 @@ import { DirectionalLight, MathUtils, ShaderChunk, - LineBasicMaterial, - Object3D, - BufferGeometry, - BufferAttribute, - Line, Matrix4, Box3 } from '../../../build/three.module.js'; @@ -21,9 +16,7 @@ import Shader from './Shader.js'; const _cameraToLightMatrix = new Matrix4(); const _lightSpaceFrustum = new Frustum(); -const _frustum = new Frustum(); const _center = new Vector3(); -const _size = new Vector3(); const _bbox = new Box3(); const _uniformArray = []; const _logArray = [];
false
Other
mrdoob
three.js
a4dabf4afc26fab16587f6482d2db848200a3972.json
Remove helper from CSM.js
examples/jsm/csm/CSM.js
@@ -333,68 +333,6 @@ export default class CSM { } - helper( cameraMatrix ) { - - let geometry, vertices; - const material = new LineBasicMaterial( { color: 0xffffff } ); - const object = new Object3D(); - - for ( let i = 0; i < this.frustums.length; i ++ ) { - - this.frustums[ i ].toSpace( cameraMatrix, _frustum ); - - geometry = new BufferGeometry(); - vertices = []; - - - for ( let i = 0; i < 5; i ++ ) { - - const point = _frustum.vertices.near[ i === 4 ? 0 : i ]; - vertices.push( point.x, point.y, point.z ); - - } - - geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) ); - - object.add( new Line( geometry, material ) ); - - geometry = new BufferGeometry(); - vertices = []; - - for ( let i = 0; i < 5; i ++ ) { - - const point = _frustum.vertices.far[ i === 4 ? 0 : i ]; - vertices.push( point.x, point.y, point.z ); - - } - - geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) ); - - object.add( new Line( geometry, material ) ); - - for ( let i = 0; i < 4; i ++ ) { - - geometry = new BufferGeometry(); - vertices = []; - - const near = _frustum.vertices.near[ i ]; - const far = _frustum.vertices.far[ i ]; - - vertices.push( near.x, near.y, near.z ); - vertices.push( far.x, far.y, far.z ); - - geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) ); - - object.add( new Line( geometry, material ) ); - - } - - } - - return object; - - } - remove() { for ( let i = 0; i < this.lights.length; i ++ ) {
false
Other
mrdoob
three.js
16217975112392ec4d14d681b96322e23dfa07f4.json
Use CSMHelper in the scene
examples/webgl_shadowmap_csm.html
@@ -21,8 +21,9 @@ import { OrbitControls } from './jsm/controls/OrbitControls.js'; import { GUI } from './jsm/libs/dat.gui.module.js'; import * as CSM from './jsm/csm/CSM.js'; + import { CSMHelper } from './jsm/csm/CSMHelper.js'; - var renderer, scene, camera, orthoCamera, controls, csm; + var renderer, scene, camera, orthoCamera, controls, csm, csmHelper; var params = { orthographic: false, @@ -35,10 +36,10 @@ margin: 100, lightFar: 5000, lightNear: 1, - helper: function () { + autoUpdateHelper: true, + updateHelper: function () { - var helper = csm.helper( camera.matrix ); - scene.add( helper ); + csmHelper.update(); } }; @@ -93,6 +94,9 @@ camera: camera } ); + csmHelper = new CSMHelper( csm ); + scene.add( csmHelper ); + var floorMaterial = new THREE.MeshPhongMaterial( { color: '#252a34' } ); csm.setupMaterial( floorMaterial ); @@ -204,8 +208,32 @@ } ); - gui.add( params, 'helper' ).name( 'add frustum helper' ); + const helperFolder = gui.addFolder( 'helper' ); + + helperFolder.add( csmHelper, 'visible' ); + + helperFolder.add( csmHelper, 'displayFrustum' ).onChange( function () { + + csmHelper.updateVisibility(); + + } ); + + helperFolder.add( csmHelper, 'displayPlanes' ).onChange( function () { + + csmHelper.updateVisibility(); + + } ); + + helperFolder.add( csmHelper, 'displayShadowBounds' ).onChange( function () { + + csmHelper.updateVisibility(); + + } ); + + helperFolder.add( params, 'autoUpdateHelper' ).name( 'auto update' ); + helperFolder.add( params, 'updateHelper' ).name( 'update' ); + window.addEventListener( 'resize', function () { camera.aspect = window.innerWidth / window.innerHeight; @@ -231,10 +259,20 @@ updateOrthoCamera(); csm.updateFrustums(); + if ( params.autoUpdateHelper ) { + + csmHelper.update(); + + } renderer.render( scene, orthoCamera ); } else { + if ( params.autoUpdateHelper ) { + + csmHelper.update(); + + } renderer.render( scene, camera ); }
false
Other
mrdoob
three.js
1f08ad1f824b1e521a3bf40c5a398aa66321e792.json
Add visibility toggle
examples/jsm/csm/CSMHelper.js
@@ -1,11 +1,26 @@ -import { Group, Mesh, LineSegments, BufferGeometry, LineBasicMaterial, Box3Helper, Box3, PlaneBufferGeometry, MeshBasicMaterial, BufferAttribute, DoubleSide } from '../../../build/three.module.js'; +import { + Group, + Mesh, + LineSegments, + BufferGeometry, + LineBasicMaterial, + Box3Helper, + Box3, + PlaneBufferGeometry, + MeshBasicMaterial, + BufferAttribute, + DoubleSide +} from '../../../build/three.module.js'; class CSMHelper extends Group { constructor( csm ) { super(); this.csm = csm; + this.displayFrustum = true; + this.displayPlanes = true; + this.displayShadowBounds = true; const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); const positions = new Float32Array( 24 ); @@ -22,6 +37,32 @@ class CSMHelper extends Group { } + updateVisibility() { + + const displayFrustum = this.displayFrustum; + const displayPlanes = this.displayPlanes; + const displayShadowBounds = this.displayShadowBounds; + + const frustumLines = this.frustumLines; + const cascadeLines = this.cascadeLines; + const cascadePlanes = this.cascadePlanes; + const shadowLines = this.shadowLines; + for ( let i = 0, l = cascadeLines.length; i < l; i ++ ) { + + const cascadeLine = cascadeLines[ i ]; + const cascadePlane = cascadePlanes[ i ]; + const shadowLineGroup = shadowLines[ i ]; + + cascadeLine.visible = displayFrustum; + cascadePlane.visible = displayFrustum && displayPlanes; + shadowLineGroup.visible = displayShadowBounds; + + } + + frustumLines.visible = displayFrustum; + + } + update() { const csm = this.csm;
false
Other
mrdoob
three.js
7118eec85cfa39602dd4b33db87f6f42214bca9c.json
Update light frustums
examples/jsm/csm/CSMHelper.js
@@ -1,4 +1,4 @@ -import { Group, Mesh, LineSegments, BufferGeometry, LineBasicMaterial, Box3Helper, Box3, PlaneBufferGeometry, MeshBasicMaterial, BufferAttribute } from '../../../build/three.module.js'; +import { Group, Mesh, LineSegments, BufferGeometry, LineBasicMaterial, Box3Helper, Box3, PlaneBufferGeometry, MeshBasicMaterial, BufferAttribute, DoubleSide } from '../../../build/three.module.js'; class CSMHelper extends Group { @@ -37,6 +37,11 @@ class CSMHelper extends Group { const cascadePlanes = this.cascadePlanes; const shadowLines = this.shadowLines; + this.position.copy( camera.position ); + this.quaternion.copy( camera.quaternion ); + this.scale.copy( camera.scale ); + this.updateMatrixWorld( true ); + while( cascadeLines.length > cascades ) { this.remove( cascadeLines.pop() ); @@ -48,7 +53,8 @@ class CSMHelper extends Group { while( cascadeLines.length < cascades ) { const cascadeLine = new Box3Helper( new Box3(), 0xffffff ); - const cascadePlane = new Mesh( new PlaneBufferGeometry(), new MeshBasicMaterial( { transparent: true, opacity: 0.1, depthWrite: false } ) ); + const planeMat = new MeshBasicMaterial( { transparent: true, opacity: 0.1, depthWrite: false, side: DoubleSide } ); + const cascadePlane = new Mesh( new PlaneBufferGeometry(), planeMat ); const shadowLineGroup = new Group(); const shadowLine = new Box3Helper( new Box3(), 0xffff00 ); shadowLineGroup.add( shadowLine ); @@ -85,12 +91,14 @@ class CSMHelper extends Group { cascadePlane.scale.z = 1e-4; this.remove( shadowLineGroup ); - shadowCam.matrixWorld.decompose( shadowLineGroup.position, shadowLineGroup.quaternion, shadowLineGroup.scale ); - shadowCam.updateMatrixWorld( true ); + shadowLineGroup.position.copy( shadowCam.position ); + shadowLineGroup.quaternion.copy( shadowCam.quaternion ); + shadowLineGroup.scale.copy( shadowCam.scale ); + shadowLineGroup.updateMatrixWorld( true ); this.attach( shadowLineGroup ); - shadowLine.box.min.set( shadowCam.bottom, shadowCam.left, shadowCam.near ); - shadowLine.box.max.set( shadowCam.top, shadowCam.right, shadowCam.far ); + shadowLine.box.min.set( shadowCam.bottom, shadowCam.left, - shadowCam.far ); + shadowLine.box.max.set( shadowCam.top, shadowCam.right, - shadowCam.near ); } @@ -107,10 +115,6 @@ class CSMHelper extends Group { frustumLinePositions.setXYZ( 7, nearVerts[ 1 ].x, nearVerts[ 1 ].y, nearVerts[ 1 ].z ); frustumLinePositions.needsUpdate = true; - this.position.copy( camera.position ); - this.quaternion.copy( camera.quaternion ); - this.scale.copy( camera.scale ); - } }
false
Other
mrdoob
three.js
933f7f0c6b64975795a770f63134f6f049841ae6.json
use farthest verts on frustum
examples/jsm/csm/CSM.js
@@ -170,15 +170,29 @@ export default class CSM { _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, cameraMatrix ); frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum ); - const farTopRight = _lightSpaceFrustum.vertices.far[ 0 ]; - const nearBotLeft = _lightSpaceFrustum.vertices.near[ 2 ]; - let squaredBBWidth = farTopRight.distanceTo( nearBotLeft ); + // Get the two points that represent that furthest points on the frustum assuming + // that's either the diagonal across the far plane or the diagonal across the whole + // frustum itself. + const nearVerts = _lightSpaceFrustum.vertices.near; + const farVerts = _lightSpaceFrustum.vertices.far; + const point1 = farVerts[ 0 ]; + let point2; + if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) { + point2 = farVerts[ 2 ]; + + } else { + + point2 = nearVerts[ 2 ]; + + } + + let squaredBBWidth = point1.distanceTo( point2 ); _bbox.makeEmpty(); for ( let j = 0; j < 4; j ++ ) { - _bbox.expandByPoint( _lightSpaceFrustum.vertices.near[ j ] ); - _bbox.expandByPoint( _lightSpaceFrustum.vertices.far[ j ] ); + _bbox.expandByPoint( nearVerts[ j ] ); + _bbox.expandByPoint( farVerts[ j ] ); }
false
Other
mrdoob
three.js
d527e1b7e4b420c0aef99e161934795f6ac4d50f.json
Use the frustum diagonal
examples/jsm/csm/CSM.js
@@ -182,7 +182,7 @@ export default class CSM { _bbox.getCenter( _center ); _center.z = _bbox.max.z + this.lightMargin; - let squaredBBWidth = _lightSpaceFrustum.vertices.far[ 0 ].distanceTo( _lightSpaceFrustum.vertices.far[ 2 ] ); + let squaredBBWidth = _lightSpaceFrustum.vertices.far[ 0 ].distanceTo( _lightSpaceFrustum.vertices.near[ 2 ] ); if ( this.fade ) { // expand the shadow extents by the fade margin if fade is enabled. @@ -198,7 +198,6 @@ export default class CSM { const texelSize = squaredBBWidth / this.shadowMapSize; _center.x = Math.floor( _center.x / texelSize ) * texelSize; _center.y = Math.floor( _center.y / texelSize ) * texelSize; - _center.z = Math.floor( _center.z / texelSize ) * texelSize; _center.applyMatrix4( light.shadow.camera.matrixWorld ); light.shadow.camera.left = - squaredBBWidth / 2;
false
Other
mrdoob
three.js
6c687f4c8f0a8b7e6d46d3cea68502e0e5a0eb10.json
Fix pixel swimming
examples/jsm/csm/CSM.js
@@ -181,9 +181,8 @@ export default class CSM { _bbox.getSize( _size ); _bbox.getCenter( _center ); _center.z = _bbox.max.z + this.lightMargin; - _center.applyMatrix4( light.shadow.camera.matrixWorld ); - let squaredBBWidth = Math.max( _size.x, _size.y ); + let squaredBBWidth = _lightSpaceFrustum.vertices.far[ 0 ].distanceTo( _lightSpaceFrustum.vertices.far[ 2 ] ); if ( this.fade ) { // expand the shadow extents by the fade margin if fade is enabled. @@ -196,6 +195,12 @@ export default class CSM { } + const texelSize = squaredBBWidth / this.shadowMapSize; + _center.x = Math.floor( _center.x / texelSize ) * texelSize; + _center.y = Math.floor( _center.y / texelSize ) * texelSize; + _center.z = Math.floor( _center.z / texelSize ) * texelSize; + _center.applyMatrix4( light.shadow.camera.matrixWorld ); + light.shadow.camera.left = - squaredBBWidth / 2; light.shadow.camera.right = squaredBBWidth / 2; light.shadow.camera.top = squaredBBWidth / 2;
false
Other
mrdoob
three.js
973e03e84c3415f78975dd1aeaf9d188e8106470.json
Update csm frustums when resizing window
examples/webgl_shadowmap_csm.html
@@ -212,6 +212,7 @@ camera.updateProjectionMatrix(); updateOrthoCamera(); + csm.updateFrustums(); renderer.setSize( window.innerWidth, window.innerHeight );
false
Other
mrdoob
three.js
9a768ede0ea7311653576d758dc75de03208eb7b.json
Reuse variables in shader
examples/jsm/csm/Shader.js
@@ -102,15 +102,15 @@ IncidentLight directLight; directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - bool shouldFadeLastCascade = i == CSM_CASCADES - 1 && linearDepth > ( csmx + csmy ) / 2.0; + bool shouldFadeLastCascade = i == CSM_CASCADES - 1 && linearDepth > cascadeCenter; directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); } ReflectedLight prevLight = reflectedLight; RE_Direct( directLight, geometry, material, reflectedLight ); - bool shouldBlend = i != CSM_CASCADES - 1 || i == CSM_CASCADES - 1 && linearDepth < ( csmx + csmy ) / 2.0; + bool shouldBlend = i != CSM_CASCADES - 1 || i == CSM_CASCADES - 1 && linearDepth < cascadeCenter; float blendRatio = shouldBlend ? ratio : 1.0; reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );
false
Other
mrdoob
three.js
05a1ac5eb12a17ef0a1761165f8a02b16a47b890.json
Use nearest cascade edge to compute fade
examples/jsm/csm/Shader.js
@@ -84,10 +84,15 @@ IncidentLight directLight; directionalLight = directionalLights[ i ]; getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight ); - float margin = 0.25 * pow( linearDepth, 2.0 ); - float csmx = CSM_cascades[ i ].x - margin / 2.0; - float csmy = CSM_cascades[ i ].y + margin / 2.0; - if( i < NUM_DIR_LIGHT_SHADOWS && linearDepth >= csmx && ( linearDepth < csmy || i == CSM_CASCADES - 1 ) ) { + // NOTE: Depth gets larger away from the camera. + // cascade.x is closer, cascade.y is further + vec2 cascade = CSM_cascades[ i ]; + float cascadeCenter = ( cascade.x + cascade.y ) / 2.0; + float closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; + float margin = 0.25 * pow( closestEdge, 2.0 ); + float csmx = cascade.x - margin / 2.0; + float csmy = cascade.y + margin / 2.0; + if( i < NUM_DIR_LIGHT_SHADOWS && linearDepth >= csmx && ( linearDepth < csmy || i == CSM_CASCADES - 1 ) ) { float dist = min( linearDepth - csmx, csmy - linearDepth ); float ratio = clamp( dist / margin, 0.0, 1.0 );
false
Other
mrdoob
three.js
4e6aee44be75545be6da49daa394f5b204365cb5.json
Update CSM example
examples/webgl_shadowmap_csm.html
@@ -140,7 +140,7 @@ gui.add( params, 'fade' ).onChange( function ( value ) { csm.fade = value; - csm.updateUniforms(); + csm.updateFrustums(); } );
false
Other
mrdoob
three.js
31e4409b4c396292e9c48a83e33d6ef0617ebae6.json
remove extra line
examples/jsm/csm/CSM.js
@@ -400,7 +400,6 @@ export default class CSM { delete shader.uniforms.cameraNear; delete shader.uniforms.shadowFar; - material.needsUpdate = true; } );
false
Other
mrdoob
three.js
b0436ca155722717d7e9888f2b22e7ed313ae875.json
Add a dispose function
examples/jsm/csm/CSM.js
@@ -386,4 +386,26 @@ export default class CSM { } + dispose() { + + const shaders = this.shaders; + shaders.forEach( function ( shader, material ) { + + delete material.onBeforeCompile; + delete material.defines.USE_CSM; + delete material.defines.CSM_CASCADES; + delete material.defines.CSM_FADE; + + delete shader.uniforms.CSM_cascades; + delete shader.uniforms.cameraNear; + delete shader.uniforms.shadowFar; + + + material.needsUpdate = true; + + } ); + shaders.clear(); + + } + }
false
Other
mrdoob
three.js
35101131b7cbc66b1ed377597a27c49a4051c0a1.json
Fix stale values in before compile
examples/jsm/csm/CSM.js
@@ -235,16 +235,16 @@ export default class CSM { } const breaksVec2 = []; - this.getExtendedBreaks( breaksVec2 ); - - const far = Math.min( this.camera.far, this.maxFar ); + const self = this; const shaders = this.shaders; - const camera = this.camera; material.onBeforeCompile = function ( shader ) { + const far = Math.min( self.camera.far, self.maxFar ); + self.getExtendedBreaks( breaksVec2 ); + shader.uniforms.CSM_cascades = { value: breaksVec2 }; - shader.uniforms.cameraNear = { value: camera.near }; + shader.uniforms.cameraNear = { value: self.camera.near }; shader.uniforms.shadowFar = { value: far }; shaders.set( material, shader );
false
Other
mrdoob
three.js
78a25d5a88d4034ea8d39f7c158fcc54695f9110.json
Avoid shader duplication
examples/jsm/csm/CSM.js
@@ -53,8 +53,7 @@ export default class CSM { this.breaks = []; this.lights = []; - this.shaders = []; - this.materials = []; + this.shaders = new Map(); this.createLights(); this.getBreaks(); @@ -238,39 +237,39 @@ export default class CSM { const breaksVec2 = []; this.getExtendedBreaks( breaksVec2 ); - const self = this; const far = Math.min( this.camera.far, this.maxFar ); + const shaders = this.shaders; + const camera = this.camera; material.onBeforeCompile = function ( shader ) { shader.uniforms.CSM_cascades = { value: breaksVec2 }; - shader.uniforms.cameraNear = { value: self.camera.near }; + shader.uniforms.cameraNear = { value: camera.near }; shader.uniforms.shadowFar = { value: far }; - self.shaders.push( shader ); + shaders.set( material, shader ); }; - this.materials.push( material ); + shaders.set( material, null ); } updateUniforms() { const far = Math.min( this.camera.far, this.maxFar ); + const shaders = this.shaders; - for ( let i = 0; i < this.shaders.length; i ++ ) { + shaders.forEach( function ( shader, material ) { - const shader = this.shaders[ i ]; - const uniforms = shader.uniforms; - this.getExtendedBreaks( uniforms.CSM_cascades.value ); - uniforms.cameraNear.value = this.camera.near; - uniforms.shadowFar.value = far; + if ( shader !== null ) { - } + const uniforms = shader.uniforms; + this.getExtendedBreaks( uniforms.CSM_cascades.value ); + uniforms.cameraNear.value = this.camera.near; + uniforms.shadowFar.value = far; - for ( let i = 0; i < this.materials.length; i ++ ) { + } - const material = this.materials[ i ]; if ( ! this.fade && 'CSM_FADE' in material.defines ) { delete material.defines.CSM_FADE; @@ -283,7 +282,7 @@ export default class CSM { } - } + }, this ); }
false
Other
mrdoob
three.js
aebe7760de76744df6c42935e7c341d58dc3fd7a.json
Add fade toggle
examples/jsm/csm/CSM.js
@@ -47,11 +47,13 @@ export default class CSM { this.lightFar = data.lightFar || 2000; this.lightMargin = data.lightMargin || 200; this.customSplitsCallback = data.customSplitsCallback; + this.fade = false; this.mainFrustum = new Frustum(); this.frustums = []; this.breaks = []; this.lights = []; + this.shaders = []; this.materials = []; this.createLights(); @@ -214,6 +216,12 @@ export default class CSM { material.defines.USE_CSM = 1; material.defines.CSM_CASCADES = this.cascades; + if ( this.fade ) { + + material.defines.CSM_FADE = ''; + + } + const breaksVec2 = []; this.getExtendedBreaks( breaksVec2 ); @@ -226,25 +234,44 @@ export default class CSM { shader.uniforms.cameraNear = { value: self.camera.near }; shader.uniforms.shadowFar = { value: far }; - self.materials.push( shader ); + self.shaders.push( shader ); }; + this.materials.push( material ); } updateUniforms() { const far = Math.min(this.camera.far, this.maxFar); - for ( let i = 0; i < this.materials.length; i ++ ) { + for ( let i = 0; i < this.shaders.length; i ++ ) { - const uniforms = this.materials[ i ].uniforms; + const shader = this.shaders[ i ]; + const uniforms = shader.uniforms; this.getExtendedBreaks( uniforms.CSM_cascades.value ); uniforms.cameraNear.value = this.camera.near; uniforms.shadowFar.value = far; } + for ( let i = 0; i < this.materials.length; i ++ ) { + + const material = this.materials[ i ]; + if ( ! this.fade && 'CSM_FADE' in material.defines ) { + + delete material.defines.CSM_FADE; + material.needsUpdate = true; + + } else { + + material.defines.CSM_FADE = ''; + material.needsUpdate = true; + + } + + } + } getExtendedBreaks( target ) {
true
Other
mrdoob
three.js
aebe7760de76744df6c42935e7c341d58dc3fd7a.json
Add fade toggle
examples/jsm/csm/Shader.js
@@ -78,6 +78,7 @@ IncidentLight directLight; DirectionalLightShadow directionalLightShadow; #endif + #if defined( CSM_FADE ) for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; @@ -114,6 +115,26 @@ IncidentLight directLight; } } + #else + + #pragma unroll_loop + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + + directionalLightShadow = directionalLightShadows[ i ]; + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + #endif + + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometry, material, reflectedLight ); + + } + + #endif #endif
true
Other
mrdoob
three.js
aebe7760de76744df6c42935e7c341d58dc3fd7a.json
Add fade toggle
examples/webgl_shadowmap_csm.html
@@ -26,6 +26,7 @@ var params = { orthographic: false, + fade: false, far: 1000, mode: 'practical', lightX: - 1, @@ -129,13 +130,22 @@ var gui = new GUI(); + window.csm = csm; + gui.add( params, 'orthographic' ).onChange( function ( value ) { csm.camera = value ? orthoCamera : camera; csm.updateFrustums(); } ); + gui.add( params, 'fade' ).onChange( function ( value ) { + + csm.fade = value; + csm.updateUniforms(); + + } ); + gui.add( params, 'far', 1, 5000 ).step( 1 ).name( 'shadow far' ).onChange( function ( value ) { csm.maxFar = value;
true
Other
mrdoob
three.js
a043873b77552bace57fa455ea9fc547aa505e57.json
Add puppeteer checks to eliminate freezing
.travis.yml
@@ -9,19 +9,19 @@ jobs: - &lint-n-unit stage: lint & unit name: lint - script: npm run lint + script: npm run test-lint - <<: *lint-n-unit name: unit script: npm run test-unit - &diff stage: diff name: diff - script: FORCE_COLOR=0 npm run test-diff - env: CI=0 + script: npm run test-diff + env: FORCE_COLOR=0 CI=0 - <<: *diff - env: CI=1 + env: FORCE_COLOR=0 CI=1 - <<: *diff - env: CI=2 + env: FORCE_COLOR=0 CI=2 - <<: *diff - env: CI=3 + env: FORCE_COLOR=0 CI=3
true
Other
mrdoob
three.js
a043873b77552bace57fa455ea9fc547aa505e57.json
Add puppeteer checks to eliminate freezing
package.json
@@ -52,9 +52,9 @@ "build-examples": "rollup -c utils/build/rollup-examples.config.js", "dev": "concurrently --names \"ROLLUP,HTTP\" -c \"bgBlue.bold,bgGreen.bold\" \"rollup -c utils/build/rollup.config.js -w -m inline\" \"serve\"", "dev-test": "concurrently --names \"ROLLUP,ROLLUPTEST,HTTP\" -c \"bgBlue.bold,bgRed.bold,bgGreen.bold\" \"rollup -c utils/build/rollup.config.js -w -m inline\" \"rollup -c test/rollup.unit.config.js -w -m inline\" \"serve\"", - "lint": "eslint src --ext js --ext ts && tsc -p utils/build/tsconfig.lint.json", - "lint-examples": "eslint examples/jsm --ext js --ext ts --ignore-pattern libs && tsc -p utils/build/tsconfig-examples.lint.json", - "test": "npm run test-unit && npm run test-diff", + "test": "npm run test-lint && npm run test-unit", + "test-lint": "eslint src --ext js --ext ts && tsc -p utils/build/tsconfig.lint.json", + "test-lint-examples": "eslint examples/jsm --ext js --ext ts --ignore-pattern libs && tsc -p utils/build/tsconfig-examples.lint.json", "test-unit": "npm run build-test && qunit -r failonlyreporter test/unit/three.source.unit.js", "test-diff": "node --expose-gc test/diff/puppeteer.js", "make-screenshot": "cross-env MAKE=true npm run test-diff"
true
Other
mrdoob
three.js
a043873b77552bace57fa455ea9fc547aa505e57.json
Add puppeteer checks to eliminate freezing
test/diff/README.md
@@ -15,14 +15,23 @@ npx cross-env VISIBLE=ture npm run test-diff ``` ### How it works + +| Travis | Attempts | +|-----------------------------------------|--------------------------------------| +| 61 from 362 failed, time=21:14 | networkidle0 timeout | +| 26 from 362 failed, time=16:22 | with rAF hook | +| 13=1+1+7+4 failed, time=4:26 | with render promise and parallelism | +| 4=0+0+2+2 failed, time=5:13 | with network tax and other settings | +| 4=0+0+2+2 failed, time=3:26 | with progressive attempts | + - ci configs with parallelism - deterministic random/timer/rAF/video for screenshots - increased robustness with hided text, datgui, different flags and timeouts. - pipeline: turn off rAF -> 'networkidle0' -> networkTax -> turn on rAF -> render promise - added 3 progressive attempts for robustness ### Status -97% examples are covered with tests. Random robusness in CI ~85%. Robustness on different machines ~97%. For example in Windows webgl_effects_ascii example always fails or on integrated GPU you will have additional artifacts: webgl_materials_texture_anisotropy, webgl_postprocessing_procedural, webgl_shaders_tonemapping. +97% examples are covered with tests. Random robusness in CI >93%. Robustness on different machines ~97%. For example in Windows webgl_effects_ascii example always fails or on integrated GPU you will have additional artifacts: webgl_materials_texture_anisotropy, webgl_postprocessing_procedural, webgl_shaders_tonemapping. ### Probably wrong screenshots webgl2_multisampled_renderbuffers, webgl_simple_gi, webgl_postprocessing_dof2, webgl_loader_texture_pvrtc
true
Other
mrdoob
three.js
a043873b77552bace57fa455ea9fc547aa505e57.json
Add puppeteer checks to eliminate freezing
test/diff/puppeteer.js
@@ -11,14 +11,8 @@ const png = require( 'pngjs' ).PNG; const fs = require( 'fs' ); const port = 1234; -const pixelThreshold = 0.2; -const maxFailedPixels = 0.05; -const networkTimeout = 600; -const networkTax = 2000; // additional timeout for resources size -const pageSizeMinTax = 1.0; // in mb, when networkTax = 0 -const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax -const renderTimeout = 1200; -const maxAttemptId = 3; // progresseve attempts +const pixelThreshold = 0.2; // threshold error in one pixel +const maxFailedPixels = 0.05; // total failed pixels const exceptionList = [ @@ -34,6 +28,14 @@ const exceptionList = [ ] : [] ); +const networkTimeout = 600; +const networkTax = 2000; // additional timeout for resources size +const pageSizeMinTax = 1.0; // in mb, when networkTax = 0 +const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax +const renderTimeout = 1200; +const maxAttemptId = 3; // progresseve attempts +const progressFunc = n => 1 + n; + console.green = ( msg ) => console.log( `\x1b[32m${ msg }\x1b[37m` ); console.red = ( msg ) => console.log( `\x1b[31m${ msg }\x1b[37m` ); console.null = ( msg ) => {}; @@ -114,7 +116,7 @@ const pup = puppeteer.launch( { /* Loop for each file, with CI parallelism */ - let pageSize, file; + let pageSize, file, attemptProgress; let failedScreenshots = 0; const isParallel = 'CI' in process.env; const beginId = isParallel ? Math.floor( parseInt( process.env.CI.slice( 0, 1 ) ) * files.length / 4 ) : 0; @@ -133,6 +135,7 @@ const pup = puppeteer.launch( { /* Load target page */ file = files[ id ]; + attemptProgress = progressFunc( attemptId ); pageSize = 0; global.gc(); global.gc(); @@ -141,7 +144,7 @@ const pup = puppeteer.launch( { await page.goto( `http://localhost:${ port }/examples/${ file }.html`, { waitUntil: 'networkidle2', - timeout: networkTimeout * ( 1 + attemptId ) + timeout: networkTimeout * attemptProgress } ); } catch { @@ -153,7 +156,7 @@ const pup = puppeteer.launch( { try { - await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptId ) => { + await page.evaluate( async ( pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ) => { /* Prepare page */ @@ -169,7 +172,12 @@ const pup = puppeteer.launch( { style.type = 'text/css'; style.innerHTML = `body { font size: 0 !important; } #info, button, input, body > div.dg.ac, body > div.lbl { display: none !important; }`; - document.getElementsByTagName( 'head' )[ 0 ].appendChild( style ); + let head = document.getElementsByTagName( 'head' ); + if ( head.length > 0 ) { + + head[ 0 ].appendChild( style ); + + } let canvas = document.getElementsByTagName( 'canvas' ); for ( let i = 0; i < canvas.length; ++ i ) { @@ -183,18 +191,21 @@ const pup = puppeteer.launch( { } let resourcesSize = Math.min( 1, ( pageSize / 1024 / 1024 - pageSizeMinTax ) / pageSizeMaxTax ); - await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * ( 1 + attemptId ) ) ); + await new Promise( resolve => setTimeout( resolve, networkTax * resourcesSize * attemptProgress ) ); /* Resolve render promise */ window.chromeRenderStarted = true; await new Promise( function( resolve ) { + if ( typeof performance.wow === 'undefined' ) { + performance.wow = performance.now; + } let renderStart = performance.wow(); let waitingLoop = setInterval( function() { - let renderEcceded = ( performance.wow() - renderStart > renderTimeout * window.chromeMaxFrameId * ( 1 + attemptId ) ); + let renderEcceded = ( performance.wow() - renderStart > renderTimeout * window.chromeMaxFrameId * attemptProgress ); if ( window.chromeRenderFinished || renderEcceded ) { if ( renderEcceded ) { @@ -211,7 +222,7 @@ const pup = puppeteer.launch( { } ); - }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptId ); + }, pageSize, pageSizeMinTax, pageSizeMaxTax, networkTax, renderTimeout, attemptProgress ); } catch ( e ) { @@ -224,7 +235,7 @@ const pup = puppeteer.launch( { } else { console.log( 'Another attempt..' ); - await new Promise( resolve => setTimeout( resolve, networkTimeout * ( 1 + attemptId ) ) ); + await new Promise( resolve => setTimeout( resolve, networkTimeout * attemptProgress ) ); }
true
Other
mrdoob
three.js
cf9357b8e1cfd1a3e0287ed87aef66b707d72b9d.json
Reset numIntersection in projectPlanes()
src/renderers/webgl/WebGLClipping.js
@@ -153,6 +153,7 @@ function WebGLClipping() { } scope.numPlanes = nPlanes; + scope.numIntersection = 0; return dstArray;
false
Other
mrdoob
three.js
fb84d84123f8b433b83c6ffa133a765a00ac380e.json
Fix missing controllerModel usage The throwing error call directly motionController.assertUrl that will be undefined. Update to controllerModel.motionController.assertUrl.
examples/jsm/webxr/XRControllerModelFactory.js
@@ -281,7 +281,7 @@ var XRControllerModelFactory = ( function () { null, () => { - throw new Error( `Asset ${motionController.assetUrl} missing or malformed.` ); + throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` ); } );
false
Other
mrdoob
three.js
a666176d52bcc7e551a1ead756d8bb64381c3715.json
Add readme page in tests and fix typos
test/diff/README.md
@@ -0,0 +1,31 @@ +# Three.js automatic regression testing with CI + +You probably shouldn't run this tests on PC because right now it's not optimized for local usage and you can get different results on different GPUs. Goal is to make quick automated testing inside CI and keep screenshot pack updated for it. + +### Local usage +```shell +# generate new screenshots +npm run make-screenshot <example1_name> ... <exampleN_name> + +# check examples +npm run test-diff <example1_name> ... <exampleN_name> + +# check all examples in browser +npx cross-env VISIBLE=ture npm run test-diff +``` + +### How it works +- ci configs with parallelism +- deterministic random/timer/rAF/video for screenshots +- increased robustness with hided text, datgui, different flags and timeouts. +- pipeline: turn off rAF -> 'networkidle0' -> networkTax -> turn on rAF -> render promise +- added 3 progressive attempts for robustness + +### Status +97% examples are covered with tests. Random robusness in CI ~85%. Robustness on different machines ~97%. For example in Windows webgl_effects_ascii example always fails or on integrated GPU you will have additional artifacts: webgl_materials_texture_anisotropy, webgl_postprocessing_procedural, webgl_shaders_tonemapping. + +### Probably wrong screenshots +webgl2_multisampled_renderbuffers, webgl_simple_gi, webgl_postprocessing_dof2, webgl_loader_texture_pvrtc + +### Contribution +You can help to simplify puppeteer script by suggesting example with [HeadlessExperimental.beginFrame](https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental) CDP API.
true
Other
mrdoob
three.js
a666176d52bcc7e551a1ead756d8bb64381c3715.json
Add readme page in tests and fix typos
test/diff/puppeteer.js
@@ -14,7 +14,7 @@ const port = 1234; const pixelThreshold = 0.2; const maxFailedPixels = 0.05; const networkTimeout = 600; -const networkTax = 2000; // additional timout tax for resources size +const networkTax = 2000; // additional timeout for resources size const pageSizeMinTax = 1.0; // in mb, when networkTax = 0 const pageSizeMaxTax = 5.0; // in mb, when networkTax = networkTax const renderTimeout = 1200; @@ -23,14 +23,14 @@ const maxAttemptId = 3; // progresseve attempts const exceptionList = [ 'index', - 'webgl_loader_texture_pvrtc', // not supported in CI, usless + 'webgl_loader_texture_pvrtc', // not supported in CI, useless 'webgl_materials_envmaps_parallax', 'webgl_test_memory2', // gives fatal error in puppeteer 'webgl_worker_offscreencanvas', // in a worker, not robust ].concat( ( process.platform === "win32" ) ? [ - 'webgl_effects_ascii' // windows fonts + 'webgl_effects_ascii' // windows fonts not supported ] : [] );
true
Other
mrdoob
three.js
8ba1432eac4c0de15f411923dbe44cd0c4ec7c10.json
Update kernelSize type Fix Inconsistent type on `kernelSize` to a number. The plain version of the SSAOPass.js takes a number type but it's typed as a `boolean` here.
examples/jsm/postprocessing/SSAOPass.d.ts
@@ -22,7 +22,7 @@ export class SSAOPass extends Pass { height: boolean; clear: boolean; kernelRadius: number; - kernelSize: boolean; + kernelSize: number; kernel: Vector3[]; noiseTexture: DataTexture; output: number;
false
Other
mrdoob
three.js
9ae6a5a92fe0107dab5f560d552c8b90b5b3bdc4.json
Remove extra whitespace.
examples/webgl_buffergeometry_instancing_interleaved.html
@@ -232,6 +232,4 @@ </body> - - </html>
false
Other
mrdoob
three.js
d9a33bfda6f144558e599473431f0ffc8be32449.json
Remove two InstancedBufferGeometry examples.
examples/files.js
@@ -278,10 +278,8 @@ var files = { "webgl_buffergeometry_drawrange", "webgl_buffergeometry_indexed", "webgl_buffergeometry_instancing", - "webgl_buffergeometry_instancing2", "webgl_buffergeometry_instancing_billboards", - "webgl_buffergeometry_instancing_dynamic", - "webgl_buffergeometry_instancing_interleaved_dynamic", + "webgl_buffergeometry_instancing_interleaved", "webgl_buffergeometry_instancing_lambert", "webgl_buffergeometry_lines", "webgl_buffergeometry_lines_indexed",
true
Other
mrdoob
three.js
d9a33bfda6f144558e599473431f0ffc8be32449.json
Remove two InstancedBufferGeometry examples.
examples/webgl_buffergeometry_instancing2.html
@@ -1,232 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <title>three.js webgl - instancing test (meshes)</title> - <meta charset="utf-8"> - <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> - <link type="text/css" rel="stylesheet" href="main.css"> - <style> - a { - color: #08f; - } - #notSupported { - width: 50%; - margin: auto; - background-color: #f00; - margin-top: 20px; - padding: 10px; - } - </style> -</head> -<body> - - <div id="container"></div> - <div id="info"> - <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - instancing test (meshes) - <div id="notSupported" style="display:none">Sorry your graphics card + browser does not support hardware instancing</div> - </div> - - <script id="vertexShader" type="x-shader/x-vertex"> - precision highp float; - - attribute vec3 instancePosition; - attribute vec4 instanceQuaternion; - attribute vec3 instanceScale; - - varying vec3 vColor; - - vec3 applyTRS( vec3 position, vec3 translation, vec4 quaternion, vec3 scale ) { - - position *= scale; - position += 2.0 * cross( quaternion.xyz, cross( quaternion.xyz, position ) + quaternion.w * position ); - return position + translation; - - } - - void main(){ - - vColor = color; - - vec3 transformed = applyTRS( position.xyz, instancePosition, instanceQuaternion, instanceScale ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( transformed, 1.0 ); - - } - - </script> - - <script id="fragmentShader" type="x-shader/x-fragment"> - - precision highp float; - varying vec3 vColor; - - void main() { - - gl_FragColor = vec4( vColor, 1.0 ); - - } - - </script> - - <script type="module"> - import * as THREE from '../build/three.module.js'; - - import Stats from './jsm/libs/stats.module.js'; - - import { TrackballControls } from './jsm/controls/TrackballControls.js'; - - var container, stats; - - var camera, scene, renderer; - - var controls; - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.01, 100 ); - camera.position.z = 4; - - scene = new THREE.Scene(); - - // - - var geometry = new THREE.IcosahedronBufferGeometry( 0.1, 1 ); - - var colors = []; - - for ( var i = 0, l = geometry.attributes.position.count; i < l; i ++ ) { - - colors.push( Math.random(), Math.random(), Math.random() ); - - } - - geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) ); - - var material = new THREE.MeshBasicMaterial( { color: 0xff0000, vertexColors: THREE.VertexColors } ); - - // - - var instances = 100; - - var instancePositions = []; - var instanceQuaternions = []; - var instanceScales = []; - - // we create for each mesh a counterpart in our instanced geometry data - - for ( var i = 0; i < instances; i ++ ) { - - // the red meshes are drawn with separate draw calls - - var mesh = new THREE.Mesh( geometry, material ); - scene.add( mesh ); - - var position = mesh.position; - var quaternion = mesh.quaternion; - var scale = mesh.scale; - - position.set( Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1 ); - - quaternion.set( Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1 ); - quaternion.normalize(); - - scale.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 ); - - // instanced attribute data - - instancePositions.push( position.x, position.y, position.z ); - instanceQuaternions.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w ); - instanceScales.push( scale.x, scale.y, scale.z ); - - } - - var instancedGeometry = new THREE.InstancedBufferGeometry(); - instancedGeometry.attributes.position = geometry.attributes.position; - instancedGeometry.attributes.color = geometry.attributes.color; - - instancedGeometry.setAttribute( 'instancePosition', new THREE.InstancedBufferAttribute( new Float32Array( instancePositions ), 3 ) ); - instancedGeometry.setAttribute( 'instanceQuaternion', new THREE.InstancedBufferAttribute( new Float32Array( instanceQuaternions ), 4 ) ); - instancedGeometry.setAttribute( 'instanceScale', new THREE.InstancedBufferAttribute( new Float32Array( instanceScales ), 3 ) ); - - // - - var shaderMaterial = new THREE.ShaderMaterial( { - - uniforms: {}, - vertexShader: document.getElementById( 'vertexShader' ).textContent, - fragmentShader: document.getElementById( 'fragmentShader' ).textContent, - vertexColors: true - - } ); - - // counterparts are drawn all at once with a single draw call (via instanced rendering) - - var instancedMesh = new THREE.Mesh( instancedGeometry, shaderMaterial ); - instancedMesh.position.x = 0.1; - scene.add( instancedMesh ); - - // - - renderer = new THREE.WebGLRenderer(); - renderer.setPixelRatio( window.devicePixelRatio ); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - controls = new TrackballControls( camera, renderer.domElement ); - - if ( renderer.extensions.get( 'ANGLE_instanced_arrays' ) === null ) { - - document.getElementById( 'notSupported' ).style.display = ''; - return; - - } - - // - - stats = new Stats(); - container.appendChild( stats.dom ); - - // - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - controls.update(); - - renderer.render( scene, camera ); - - } - - </script> - -</body> - -</html>
true
Other
mrdoob
three.js
d9a33bfda6f144558e599473431f0ffc8be32449.json
Remove two InstancedBufferGeometry examples.
examples/webgl_buffergeometry_instancing_dynamic.html
@@ -1,184 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <title>three.js webgl - indexed instancing (single box), dynamic updates</title> - <meta charset="utf-8"> - <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> - <link type="text/css" rel="stylesheet" href="main.css"> - <style> - a { - color: #08f; - } - #notSupported { - width: 50%; - margin: auto; - background-color: #f00; - margin-top: 20px; - padding: 10px; - } - </style> -</head> -<body> - - <div id="container"></div> - <div id="info"> - <a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - indexed instancing (single box), dynamic updates - <div id="notSupported" style="display:none">Sorry your graphics card + browser does not support hardware instancing</div> - </div> - - <script type="module"> - import * as THREE from '../build/three.module.js'; - - import Stats from './jsm/libs/stats.module.js'; - - var container, stats; - var camera, scene, renderer, mesh; - var offsetAttribute, orientationAttribute; - - var instances = 5000; - var lastTime = 0; - - var moveQ = new THREE.Quaternion( 0.5, 0.5, 0.5, 0.0 ).normalize(); - var tmpQ = new THREE.Quaternion(); - var tmpM = new THREE.Matrix4(); - var currentM = new THREE.Matrix4(); - - init(); - animate(); - - function init() { - - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 ); - - scene = new THREE.Scene(); - scene.background = new THREE.Color( 0x101010 ); - - // geometry - - var bufferGeometry = new THREE.BoxBufferGeometry( 2, 2, 2 ); - - // copying data from a simple box geometry, but you can specify a custom geometry if you want - - var geometry = new THREE.InstancedBufferGeometry(); - geometry.setIndex( bufferGeometry.index ); - geometry.setAttribute( 'position', bufferGeometry.attributes.position ); - geometry.setAttribute( 'uv', bufferGeometry.attributes.uv ); - - // material - - var material = new THREE.MeshBasicMaterial(); - material.map = new THREE.TextureLoader().load( 'textures/crate.gif' ); - - // per instance data - - var matrix = new THREE.Matrix4(); - var offset = new THREE.Vector3(); - var orientation = new THREE.Quaternion(); - var scale = new THREE.Vector3( 1, 1, 1 ); - var x, y, z, w; - - mesh = new THREE.InstancedMesh( geometry, material, instances ); - - for ( var i = 0; i < instances; i ++ ) { - - // offsets - - x = Math.random() * 100 - 50; - y = Math.random() * 100 - 50; - z = Math.random() * 100 - 50; - - offset.set( x, y, z ).normalize(); - offset.multiplyScalar( 5 ); // move out at least 5 units from center in current direction - offset.set( x + offset.x, y + offset.y, z + offset.z ); - - // orientations - - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - z = Math.random() * 2 - 1; - w = Math.random() * 2 - 1; - - orientation.set( x, y, z, w ).normalize(); - - matrix.compose( offset, orientation, scale ); - - mesh.setMatrixAt( i, matrix ); - - } - - scene.add( mesh ); - - renderer = new THREE.WebGLRenderer(); - renderer.setPixelRatio( window.devicePixelRatio ); - renderer.setSize( window.innerWidth, window.innerHeight ); - container.appendChild( renderer.domElement ); - - if ( renderer.extensions.get( 'ANGLE_instanced_arrays' ) === null ) { - - document.getElementById( 'notSupported' ).style.display = ''; - return; - - } - - stats = new Stats(); - container.appendChild( stats.dom ); - - window.addEventListener( 'resize', onWindowResize, false ); - - } - - function onWindowResize() { - - camera.aspect = window.innerWidth / window.innerHeight; - camera.updateProjectionMatrix(); - - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - // - - function animate() { - - requestAnimationFrame( animate ); - - render(); - stats.update(); - - } - - function render() { - - var time = performance.now(); - - mesh.rotation.y = time * 0.00005; - - var delta = ( time - lastTime ) / 5000; - tmpQ.set( moveQ.x * delta, moveQ.y * delta, moveQ.z * delta, 1 ).normalize(); - tmpM.makeRotationFromQuaternion( tmpQ ); - - for ( var i = 0, il = instances; i < il; i ++ ) { - - mesh.getMatrixAt( i, currentM ); - currentM.multiply( tmpM ); - mesh.setMatrixAt( i, currentM ); - - } - - mesh.instanceMatrix.needsUpdate = true; - - lastTime = time; - - renderer.render( scene, camera ); - - } - - </script> - -</body> - - - -</html>
true
Other
mrdoob
three.js
5c863530be7a035308965dc06cb5b0f8a0552716.json
Fix typings and documentation of LoadingManager
src/loaders/LoadingManager.d.ts
@@ -13,23 +13,33 @@ export class LoadingManager { onError?: ( url: string ) => void ); + /** + * Will be called when loading of an item starts. + * @param url The url of the item that started loading. + * @param loaded The number of items already loaded so far. + * @param total The total amount of items to be loaded. + */ onStart?: ( url: string, loaded: number, total: number ) => void; /** - * Will be called when load starts. + * Will be called when all items finish loading. * The default is a function with empty body. */ onLoad: () => void; /** - * Will be called while load progresses. + * Will be called for each loaded item. * The default is a function with empty body. + * @param url The url of the item just loaded. + * @param loaded The number of items already loaded so far. + * @param total The total amount of items to be loaded. */ - onProgress: ( item: any, loaded: number, total: number ) => void; + onProgress: ( url: string, loaded: number, total: number ) => void; /** - * Will be called when each element in the scene completes loading. + * Will be called when item loading fails. * The default is a function with empty body. + * @param url The url of the item that errored. */ onError: ( url: string ) => void;
false
Other
mrdoob
three.js
f3ee9b0b72dca0dd641fa2486f42e6341f4f8338.json
Add blank lines
src/audio/PositionalAudio.d.ts
@@ -1,9 +1,10 @@ import { AudioListener } from './AudioListener'; import { Audio } from './Audio'; -// Override getOutput export class AudioWeaken extends Audio { + getOutput(): any; + } export class PositionalAudio extends AudioWeaken {
false
Other
mrdoob
three.js
c94098295f634599ed510e27792c5e2b618c6b7b.json
Add typings for `stats.module.js`.
examples/jsm/libs/stats.module.d.ts
@@ -0,0 +1,24 @@ +declare interface Stats { + REVISION: number; + dom: HTMLDivElement; + addPanel(panel: Stats.Panel): Stats.Panel; + showPanel(id: number): void; + begin(): void; + end(): void; + update(): void; + domElement: HTMLDivElement; + setMode(id: number): void; +} + +declare function Stats(): Stats; + +declare namespace Stats { + interface Panel { + dom: HTMLCanvasElement; + update(value: number, maxValue: number): void; + } + + function Panel(): Panel; +} + +export default Stats
false
Other
mrdoob
three.js
7aeb82c872e2df45d299dfeab2ed25c4d9d8b860.json
Fix bug in copyTextureToTexture with pixelStorei
src/renderers/WebGLRenderer.js
@@ -1961,6 +1961,12 @@ function WebGLRenderer( parameters ) { textures.setTexture2D( dstTexture, 0 ); + // As another texture upload may have changed pixelStorei + // parameters, make sure they are correct for the dstTexture + _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY ); + _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha ); + _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment ); + if ( srcTexture.isDataTexture ) { _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
false
Other
mrdoob
three.js
df1be6eaeca1f8b56ba3bd2888504862d355a14c.json
Update example to demonstrate issue
examples/webgl_materials_texture_partialupdate.html
@@ -119,10 +119,11 @@ for ( var i = 0; i < size; i ++ ) { var stride = i * 3; + var gradient = i / size; - data[ stride ] = r; - data[ stride + 1 ] = g; - data[ stride + 2 ] = b; + data[ stride ] = r * gradient; + data[ stride + 1 ] = g * gradient; + data[ stride + 2 ] = b * gradient; }
false
Other
mrdoob
three.js
7e51e8d1d181c79a5988a5e73e631c5b462dd221.json
Specify tonemapping exposure for clarity
examples/webgl_loader_gltf.html
@@ -88,6 +88,7 @@ renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1; renderer.outputEncoding = THREE.sRGBEncoding; container.appendChild( renderer.domElement );
true
Other
mrdoob
three.js
7e51e8d1d181c79a5988a5e73e631c5b462dd221.json
Specify tonemapping exposure for clarity
examples/webgl_loader_gltf_extensions.html
@@ -150,6 +150,7 @@ renderer.setSize( window.innerWidth, window.innerHeight ); renderer.outputEncoding = THREE.sRGBEncoding; renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1; renderer.physicallyCorrectLights = true; document.body.appendChild( renderer.domElement );
true
Other
mrdoob
three.js
7e51e8d1d181c79a5988a5e73e631c5b462dd221.json
Specify tonemapping exposure for clarity
examples/webgl_pmrem_test.html
@@ -46,6 +46,7 @@ // tonemapping renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 1; document.body.appendChild( renderer.domElement );
true
Other
mrdoob
three.js
3911e78138d1ca0dd41b75b3ebb5ee8d2a051313.json
Remove single instance of whitelist with allowlist Given the context, allowlist is an appropriate replacement for the single usage of whitelist in the code. We could call it exactly what it is, a supported sub-objects name list, but that is getting verbose.
build/three.js
@@ -44276,7 +44276,7 @@ var objectName = results.nodeName.substring( lastDot + 1 ); - // Object names must be checked against a whitelist. Otherwise, there + // Object names must be checked against an allowlist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters).
true
Other
mrdoob
three.js
3911e78138d1ca0dd41b75b3ebb5ee8d2a051313.json
Remove single instance of whitelist with allowlist Given the context, allowlist is an appropriate replacement for the single usage of whitelist in the code. We could call it exactly what it is, a supported sub-objects name list, but that is getting verbose.
build/three.module.js
@@ -44244,7 +44244,7 @@ Object.assign( PropertyBinding, { const objectName = results.nodeName.substring( lastDot + 1 ); - // Object names must be checked against a whitelist. Otherwise, there + // Object names must be checked against an allowlist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters).
true
Other
mrdoob
three.js
3911e78138d1ca0dd41b75b3ebb5ee8d2a051313.json
Remove single instance of whitelist with allowlist Given the context, allowlist is an appropriate replacement for the single usage of whitelist in the code. We could call it exactly what it is, a supported sub-objects name list, but that is getting verbose.
src/animation/PropertyBinding.js
@@ -173,7 +173,7 @@ Object.assign( PropertyBinding, { const objectName = results.nodeName.substring( lastDot + 1 ); - // Object names must be checked against a whitelist. Otherwise, there + // Object names must be checked against an allowlist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters).
true
Other
mrdoob
three.js
c3003c04a185c4d1f6b8c426d4b6520d237f3676.json
Apply exposure boost to ACES Filmic tone mapping
examples/js/shaders/ACESFilmicToneMappingShader.js
@@ -4,6 +4,9 @@ console.warn( "THREE.ACESFilmicToneMappingShader: As part of the transition to E * * ACES Filmic Tone Mapping Shader by Stephen Hill * source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + * + * this implementation of ACES is modified to accommodate a brighter viewing environment. + * the scale factor of 1/0.6 is subjective. see discussion in #19621. */ THREE.ACESFilmicToneMappingShader = { @@ -78,7 +81,7 @@ THREE.ACESFilmicToneMappingShader = { ' vec4 tex = texture2D( tDiffuse, vUv );', - ' tex.rgb *= exposure;', // pre-exposed, outside of the tone mapping function + ' tex.rgb *= exposure / 0.6;', // pre-exposed, outside of the tone mapping function ' gl_FragColor = vec4( ACESFilmicToneMapping( tex.rgb ), tex.a );',
true
Other
mrdoob
three.js
c3003c04a185c4d1f6b8c426d4b6520d237f3676.json
Apply exposure boost to ACES Filmic tone mapping
examples/jsm/shaders/ACESFilmicToneMappingShader.js
@@ -3,6 +3,9 @@ * * ACES Filmic Tone Mapping Shader by Stephen Hill * source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs + * + * this implementation of ACES is modified to accommodate a brighter viewing environment. + * the scale factor of 1/0.6 is subjective. see discussion in #19621. */ @@ -79,7 +82,7 @@ var ACESFilmicToneMappingShader = { ' vec4 tex = texture2D( tDiffuse, vUv );', - ' tex.rgb *= exposure;', // pre-exposed, outside of the tone mapping function + ' tex.rgb *= exposure / 0.6;', // pre-exposed, outside of the tone mapping function ' gl_FragColor = vec4( ACESFilmicToneMapping( tex.rgb ), tex.a );',
true
Other
mrdoob
three.js
c3003c04a185c4d1f6b8c426d4b6520d237f3676.json
Apply exposure boost to ACES Filmic tone mapping
src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl.js
@@ -40,6 +40,9 @@ vec3 RRTAndODTFit( vec3 v ) { } +// this implementation of ACES is modified to accommodate a brighter viewing environment. +// the scale factor of 1/0.6 is subjective. see discussion in #19621. + vec3 ACESFilmicToneMapping( vec3 color ) { // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT @@ -56,7 +59,7 @@ vec3 ACESFilmicToneMapping( vec3 color ) { vec3( -0.07367, -0.00605, 1.07602 ) ); - color *= toneMappingExposure; + color *= toneMappingExposure / 0.6; color = ACESInputMat * color;
true
Other
mrdoob
three.js
80d1d8f5d4ae45b8f501ebcd4c167a74167a43a8.json
Create just "lint" and "lint-examples" scripts
package.json
@@ -52,10 +52,8 @@ "dev": "concurrently --names \"ROLLUP,HTTP\" -c \"bgBlue.bold,bgGreen.bold\" \"rollup -c utils/build/rollup.config.js -w -m inline\" \"http-server -c-1 -p 8080\"", "dev-test": "concurrently --names \"ROLLUP,ROLLUPTEST,HTTP\" -c \"bgBlue.bold,bgRed.bold,bgGreen.bold\" \"rollup -c utils/build/rollup.config.js -w -m inline\" \"rollup -c test/rollup.unit.config.js -w -m inline\" \"http-server -p 8080\"", "start": "npm run dev", - "lint": "npm run lint-source && npm run lint-typescript && npm run lint-examples", - "lint-source": "eslint src --ext js --ext ts", - "lint-typescript": "tsc -p utils/build/tsconfig.lint.json", - "lint-examples": "eslint examples/jsm --ext js --ext ts --ignore-pattern libs", + "lint": "eslint src --ext js --ext ts && tsc -p utils/build/tsconfig.lint.json", + "lint-examples": "eslint examples/jsm --ext js --ext ts --ignore-pattern libs && tsc -p utils/build/tsconfig-examples.lint.json", "test": "npm run build-test && qunit -r failonlyreporter test/unit/three.source.unit.js", "travis": "npm run lint && npm test" },
true
Other
mrdoob
three.js
80d1d8f5d4ae45b8f501ebcd4c167a74167a43a8.json
Create just "lint" and "lint-examples" scripts
utils/build/tsconfig-examples.lint.json
@@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "noEmit": true, + }, + "include": [ + "../../examples/jsm/**/*.ts" + ] +}
true
Other
mrdoob
three.js
5b2e5ade36cbf18fb0a0b62140aeb99217711243.json
improve packing geometry
examples/jsm/utils/GeometryPackingUtils.js
@@ -32,51 +32,56 @@ var GeometryPackingUtils = { result = new Uint16Array(count * 2); - } else if (encodeMethod == "OCT") { - - result = new Int8Array(count * 2); - - } else { + for (let idx = 0; idx < array.length; idx += 3) { - console.error("Unrecognized encoding method, should be `BASIC` or `OCT`. "); + let encoded; - } + encoded = uInt16Encode(array[idx], array[idx + 1], array[idx + 2]); + result[idx / 3 * 2 + 0] = encoded[0]; + result[idx / 3 * 2 + 1] = encoded[1]; - for (let idx = 0; idx < array.length; idx += 3) { + } - let encoded; - if (encodeMethod == "BASIC") { + } else if (encodeMethod == "OCT") { - encoded = uInt16Encode(array[idx], array[idx + 1], array[idx + 2]); + result = new Int8Array(count * 2); - result[idx / 3 * 2 + 0] = encoded[0]; - result[idx / 3 * 2 + 1] = encoded[1]; + var oct, dec, best, currentCos, bestCos; - } else if (encodeMethod == "OCT") { + for (let idx = 0; idx < array.length; idx += 3) { - var oct, dec, best, currentCos, bestCos; + let encoded; encoded = octEncodeBest(array[idx], array[idx + 1], array[idx + 2]); result[idx / 3 * 2 + 0] = encoded[0]; result[idx / 3 * 2 + 1] = encoded[1]; } + + } else { + + console.error("Unrecognized encoding method, should be `BASIC` or `OCT`. "); + } + mesh.geometry.setAttribute('normal', new THREE.BufferAttribute(result, 2, true)); + mesh.geometry.attributes.normal.needsUpdate = true; mesh.geometry.attributes.normal.isPacked = true; mesh.geometry.attributes.normal.packingMethod = encodeMethod; // modify material - mesh.material = new PackedPhongMaterial().copy(mesh.material); - Object.defineProperty(mesh.material.defines, 'USE_PACKED_NORMAL', { value: "" }); - if (encodeMethod == "BASIC"){ + if (!(mesh.material instanceof PackedPhongMaterial)) { + mesh.material = new PackedPhongMaterial().copy(mesh.material); + } + + if (encodeMethod == "BASIC") { mesh.material.defines.USE_PACKED_NORMAL = 0; } - if (encodeMethod == "OCT"){ + if (encodeMethod == "OCT") { mesh.material.defines.USE_PACKED_NORMAL = 1; } @@ -129,6 +134,18 @@ var GeometryPackingUtils = { bestCos = currentCos; } + var angle = Math.acos(bestCos) * 180 / Math.PI; + + if (angle > 10){ + console.log(angle) + oct = octEncodeVec3(x, y, z, "floor", "floor"); dec = octDecodeVec2(oct); + console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "floor", "floor"))) + console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "ceil", "floor"))) + console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "floor", "ceil"))) + console.log([x, y, z], octDecodeVec2(octEncodeVec3(x, y, z, "ceil", "ceil"))) + + } + return best; } @@ -146,8 +163,8 @@ var GeometryPackingUtils = { } return new Int8Array([ - Math[xfunc](x * 127.5 + (x < 0 ? -1 : 0)), - Math[yfunc](y * 127.5 + (y < 0 ? -1 : 0)) + Math[xfunc](x * 127.5 + (x < 0 ? 1 : 0)), + Math[yfunc](y * 127.5 + (y < 0 ? 1 : 0)) ]); } @@ -160,8 +177,9 @@ var GeometryPackingUtils = { var z = 1 - Math.abs(x) - Math.abs(y); if (z < 0) { + var tmpx = x; x = (1 - Math.abs(y)) * (x >= 0 ? 1 : -1); - y = (1 - Math.abs(x)) * (y >= 0 ? 1 : -1); + y = (1 - Math.abs(tmpx)) * (y >= 0 ? 1 : -1); } var length = Math.sqrt(x * x + y * y + z * z); @@ -179,6 +197,91 @@ var GeometryPackingUtils = { }, + packPositions: function (mesh) { + + if (!mesh.geometry) { + console.error("Mesh must contain geometry property. "); + } + + let position = mesh.geometry.attributes.position; + + if (!position) { + console.error("Geometry must contain position attribute. "); + } + + if (position.isPacked) return; + + if (position.itemSize != 3) { + console.error("position.itemSize is not 3, which cannot be packed. "); + } + + let array = position.array; + let count = position.count; + + let quantized = new Uint16Array(array.length); + + let decodeMat4 = new THREE.Matrix4(); + let min = new Float32Array(3); + let max = new Float32Array(3); + + min[0] = min[1] = min[2] = Number.MAX_VALUE; + max[0] = max[1] = max[2] = -Number.MAX_VALUE; + + for (let i = 0; i < array.length; i += 3) { + min[0] = Math.min(min[0], array[i + 0]); + min[1] = Math.min(min[1], array[i + 1]); + min[2] = Math.min(min[2], array[i + 2]); + max[0] = Math.max(max[0], array[i + 0]); + max[1] = Math.max(max[1], array[i + 1]); + max[2] = Math.max(max[2], array[i + 2]); + } + + decodeMat4.scale(new THREE.Vector3( + (max[0] - min[0]) / 65535, + (max[1] - min[1]) / 65535, + (max[2] - min[2]) / 65535 + )); + + decodeMat4.elements[12] = min[0]; + decodeMat4.elements[13] = min[1]; + decodeMat4.elements[14] = min[2]; + + decodeMat4.transpose(); + + + let multiplier = new Float32Array([ + max[0] !== min[0] ? 65535 / (max[0] - min[0]) : 0, + max[1] !== min[1] ? 65535 / (max[1] - min[1]) : 0, + max[2] !== min[2] ? 65535 / (max[2] - min[2]) : 0 + ]); + + for (let i = 0; i < array.length; i += 3) { + quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]); + quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]); + quantized[i + 2] = Math.floor((array[i + 2] - min[2]) * multiplier[2]); + } + + // IMPORTANT: calculate original geometry bounding info first, before updating packed positions + if (mesh.geometry.boundingBox == null) mesh.geometry.computeBoundingBox(); + if (mesh.geometry.boundingSphere == null) mesh.geometry.computeBoundingSphere(); + + mesh.geometry.setAttribute('position', new THREE.BufferAttribute(quantized, 3)); + mesh.geometry.attributes.position.isPacked = true; + mesh.geometry.attributes.position.needsUpdate = true; + + // modify material + if (!(mesh.material instanceof PackedPhongMaterial)) { + mesh.material = new PackedPhongMaterial().copy(mesh.material); + } + + mesh.material.defines.USE_PACKED_POSITION = 0; + + mesh.material.uniforms.quantizeMat.value = decodeMat4; + mesh.material.uniforms.quantizeMat.needsUpdate = true; + + }, + + changeShaderChunk: function () { THREE.ShaderChunk.beginnormal_vertex = ` @@ -189,25 +292,21 @@ var GeometryPackingUtils = { #endif #ifdef USE_PACKED_NORMAL - #ifdef USE_PACKED_NORMAL == 0 + #ifdef USE_PACKED_NORMAL == 0 // basicEncode float x = objectNormal.x * 2.0 - 1.0; float y = objectNormal.y * 2.0 - 1.0; vec2 scth = vec2(sin(x * PI), cos(x * PI)); vec2 scphi = vec2(sqrt(1.0 - y * y), y); objectNormal = normalize( vec3(scth.y * scphi.x, scth.x * scphi.x, scphi.y) ); - objectNormal = vec3(0.0, 0.0, 1.0); #endif - #ifdef USE_PACKED_NORMAL == 1 - float x = objectNormal.x; - float y = objectNormal.y; - float z = 1.0 - abs(x) - abs(y); - if (z < 0.0) { - x = (1.0 - abs(y)) * (x >= 0.0 ? 1.0 : -1.0); - y = (1.0 - abs(x)) * (y >= 0.0 ? 1.0 : -1.0); + #ifdef USE_PACKED_NORMAL == 1 // octEncode + vec3 v = vec3(objectNormal.xy, 1.0 - abs(objectNormal.x) - abs(objectNormal.y)); + if (v.z < 0.0) + { + v.xy = (1.0 - abs(v.yx)) * vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0); } - float length = sqrt(x * x + y * y + z * z); - objectNormal = normalize( vec3(x / length, y / length, z / length) ); + objectNormal = normalize(v); #endif #endif @@ -216,11 +315,15 @@ var GeometryPackingUtils = { }; - +/** + * PackedPhongMaterial inherited from THREE.MeshPhongMaterial + * + * @param {*} parameters + */ function PackedPhongMaterial(parameters) { THREE.MeshPhongMaterial.call(this); - this.defines = { 'USE_PACKED_NORMAL': '' }; - this.type = 'PackedPhongMaterial'; // IMPORTANT: DO NOT CHANGE THIS TYPE + this.defines = {}; + this.type = 'PackedPhongMaterial'; this.uniforms = PackedPhongShader.uniforms; this.vertexShader = PackedPhongShader.vertexShader; this.fragmentShader = PackedPhongShader.fragmentShader; @@ -233,9 +336,9 @@ var PackedPhongShader = { THREE.ShaderLib.phong.uniforms, - // { - // packedNormal: { value: null } - // } + { + quantizeMat: { value: null } + } ]), @@ -262,7 +365,6 @@ var PackedPhongShader = { THREE.ShaderChunk.clipping_planes_pars_vertex, `#ifdef USE_PACKED_NORMAL - vec3 basicDecode(vec3 packedNormal) { float x = packedNormal.x * 2.0 - 1.0; @@ -274,19 +376,19 @@ var PackedPhongShader = { vec3 octDecode(vec3 packedNormal) { - // float x = packedNormal.x / packedNormal.x < 0.0 ? 127.0 : 128.0; - // float y = packedNormal.y / packedNormal.y < 0.0 ? 127.0 : 128.0; - float x = packedNormal.x; - float y = packedNormal.y; - float z = 1.0 - abs(x) - abs(y); - if (z < 0.0) { - x = (1.0 - abs(y)) * (x >= 0.0 ? 1.0 : -1.0); - y = (1.0 - abs(x)) * (y >= 0.0 ? 1.0 : -1.0); + vec3 v = vec3(packedNormal.xy, 1.0 - abs(packedNormal.x) - abs(packedNormal.y)); + if (v.z < 0.0) + { + v.xy = (1.0 - abs(v.yx)) * vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0); } - float length = sqrt(x * x + y * y + z * z); - return normalize( vec3(x / length, y / length, z / length) ); + return normalize(v); } + #endif`, + `#ifdef USE_PACKED_POSITION + #if USE_PACKED_POSITION == 0 + uniform mat4 quantizeMat; + #endif #endif`, "void main() {", @@ -321,6 +423,13 @@ var PackedPhongShader = { "#endif", THREE.ShaderChunk.begin_vertex, + + `#ifdef USE_PACKED_POSITION + #if USE_PACKED_POSITION == 0 + transformed = ( vec4(transformed, 1.0) * quantizeMat ).xyz; + #endif + #endif`, + THREE.ShaderChunk.morphtarget_vertex, THREE.ShaderChunk.skinning_vertex, THREE.ShaderChunk.displacementmap_vertex,
true
Other
mrdoob
three.js
5b2e5ade36cbf18fb0a0b62140aeb99217711243.json
improve packing geometry
examples/webgl_materials_packed_geometry.html
@@ -32,15 +32,18 @@ var data = { flatShading: false, basicEncode: false, - octEncode: false + octEncode: false, + quantizePosition: false }; + var radius = 100; + init(); animate(); function init() { - GeometryPackingUtils.changeShaderChunk(); + // GeometryPackingUtils.changeShaderChunk(); container = document.createElement('div'); document.body.appendChild(container); @@ -54,29 +57,27 @@ scene = new THREE.Scene(); - camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 1000); + camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 10000000); - camera.position.x = 30; - camera.position.y = 30; - camera.position.z = 30; + camera.position.x = 3 * radius; + camera.position.y = 3 * radius; + camera.position.z = 3 * radius; controls = new OrbitControls(camera, renderer.domElement); // - - // scene.add(new THREE.HemisphereLight(0x222222, 0x666666, 10)); var lights = []; lights[0] = new THREE.PointLight(0xffffff, 1, 0); lights[1] = new THREE.PointLight(0xffffff, 1, 0); lights[2] = new THREE.PointLight(0xffffff, 1, 0); - lights[0].position.set(0, 2000, 0); - lights[1].position.set(1000, 2000, 1000); - lights[2].position.set(- 1000, - 2000, - 1000); + lights[0].position.set(0, 2 * radius, 0); + lights[1].position.set(radius, 2 * radius, radius); + lights[2].position.set(- radius, - 2 * radius, - radius); scene.add(lights[0]); - // scene.add(lights[1]); - // scene.add(lights[2]); + scene.add(lights[1]); + scene.add(lights[2]); // @@ -90,34 +91,37 @@ // meshMaterial.map = texture; - var ballGeom = new THREE.IcosahedronBufferGeometry( 10, 5 ); + var ballGeom = new THREE.IcosahedronBufferGeometry( radius, 4 ); // var ballGeom = new THREE.CylinderBufferGeometry( 5, 5, 20, 32 ); // var ballGeom = new THREE.OctahedronBufferGeometry( 10, 4 ); // var ballGeom = new THREE.BoxBufferGeometry( 10, 10, 10 ); - var ballMesh = new THREE.Mesh(); - ballMesh.add(new THREE.LineSegments(ballGeom, lineMaterial)); - ballMesh.add(new THREE.Mesh(ballGeom, meshMaterial)); + var ballMesh = new THREE.Mesh(ballGeom, meshMaterial); + var ballLineSegments = new THREE.LineSegments(ballGeom, lineMaterial); + + scene.add(ballLineSegments); + scene.add(ballMesh); // gui = new GUI(); function generateGeometry() { - updateGroupGeometry(ballMesh, new THREE.IcosahedronBufferGeometry( 10, 5 ), data); + updateGroupGeometry(ballMesh, ballLineSegments, new THREE.IcosahedronBufferGeometry( radius, 4 ), data); } function updateMaterial() { - ballMesh.children[1].material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, flatShading: data.flatShading }); + ballMesh.material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, flatShading: data.flatShading }); } var folder = gui.addFolder('THREE.IcosahedronBufferGeometry'); folder.open(); folder.add(data, 'flatShading', false).onChange(updateMaterial); folder.add(data, 'basicEncode', false).onChange(generateGeometry); folder.add(data, 'octEncode', false).onChange(generateGeometry); + folder.add(data, 'quantizePosition', false).onChange(generateGeometry); scene.add(ballMesh); @@ -162,7 +166,7 @@ // - function updateGroupGeometry(mesh, geometry, data) { + function updateGroupGeometry(mesh, lineSegments, geometry, data) { if (geometry.isGeometry) { @@ -172,11 +176,12 @@ } - mesh.children[0].geometry.dispose(); - mesh.children[1].geometry.dispose(); + lineSegments.geometry.dispose(); + mesh.geometry.dispose(); - mesh.children[0].geometry = new THREE.WireframeGeometry(geometry); - mesh.children[1].geometry = geometry; + lineSegments.geometry = new THREE.WireframeGeometry(geometry); + mesh.geometry = geometry; + mesh.material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, flatShading: data.flatShading }); var method = ""; if (data.basicEncode) { @@ -186,12 +191,16 @@ } if (method != "") { - GeometryPackingUtils.packNormals(mesh.children[1], method); - } else { - mesh.children[1].material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, flatShading: data.flatShading }); + GeometryPackingUtils.packNormals(mesh, method); + } + + if (data.quantizePosition){ + GeometryPackingUtils.packPositions(mesh); } - // these do not update nicely together if shared + if (method == "" && !data.quantizePosition) { + mesh.material = new THREE.MeshPhongMaterial({ color: 0x156289, emissive: 0x072534, flatShading: data.flatShading }); + } }
true
Other
mrdoob
three.js
94526d96484269b6c503719fda2c89725bbde77f.json
Use new BufferAttribute.applyMatrix4() method
examples/js/loaders/FBXLoader.js
@@ -1590,7 +1590,7 @@ THREE.FBXLoader = ( function () { var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 ); - preTransform.applyToBufferAttribute( positionAttribute ); + positionAttribute.applyMatrix4( preTransform ); geo.setAttribute( 'position', positionAttribute ); @@ -2118,7 +2118,7 @@ THREE.FBXLoader = ( function () { var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 ); positionAttribute.name = name || morphGeoNode.attrName; - preTransform.applyToBufferAttribute( positionAttribute ); + positionAttribute.applyMatrix4( preTransform ); parentGeo.morphAttributes.position.push( positionAttribute );
true
Other
mrdoob
three.js
94526d96484269b6c503719fda2c89725bbde77f.json
Use new BufferAttribute.applyMatrix4() method
examples/jsm/loaders/FBXLoader.js
@@ -1638,7 +1638,7 @@ var FBXLoader = ( function () { var positionAttribute = new Float32BufferAttribute( buffers.vertex, 3 ); - preTransform.applyToBufferAttribute( positionAttribute ); + positionAttribute.applyMatrix4( preTransform ); geo.setAttribute( 'position', positionAttribute ); @@ -2166,7 +2166,7 @@ var FBXLoader = ( function () { var positionAttribute = new Float32BufferAttribute( morphBuffers.vertex, 3 ); positionAttribute.name = name || morphGeoNode.attrName; - preTransform.applyToBufferAttribute( positionAttribute ); + positionAttribute.applyMatrix4( preTransform ); parentGeo.morphAttributes.position.push( positionAttribute );
true
Other
mrdoob
three.js
e001a1372d19f21fdf73a6962d57ccb977ed2390.json
update colors for HTML code snippets in dark theme
docs/prettify/threejs.css
@@ -16,6 +16,9 @@ pre.prettyprint, code.prettyprint { @media (prefers-color-scheme: dark) { + pre .tag, code .tag { color: #2194ce; } /* HTML tag */ + pre .atn, code .atn { color: #BB55FF; } /* HTML attribute name */ + pre .atv, code .atv { color: #30b030; } /* HTML attribute value */ pre .str, code .str { color: #BB55FF; } /* string */ pre .com, code .com { color: #666666; } /* comment */ pre .lit, code .lit { color: #ff3399; } /* literal */
false
Other
mrdoob
three.js
203a725845c30bc2570fd7fa595e51befafc3925.json
Implement support for texture matrix for uv2 Before this change, we only supported one texture matrix for the material that was applied to uv data based on the first texture, in priority order, that needed it. This change adds equivalent support for uv2 - we now transform second UV channel with a second UV transform that is grabbed from aoMap or lightMap (that are the only two textures using it atm). This fixes glTF rendering for files that use KHR_texture_transform on the occlusion texture, including ones produced by gltfpack.
src/renderers/WebGLRenderer.js
@@ -2161,6 +2161,40 @@ function WebGLRenderer( parameters ) { } + // uv repeat and offset setting priorities for uv2 + // 1. ao map + // 2. light map + + var uv2ScaleMap; + + if ( material.aoMap ) { + + uv2ScaleMap = material.aoMap; + + } else if ( material.lightMap ) { + + uv2ScaleMap = material.lightMap; + + } + + if ( uvScaleMap !== undefined ) { + + // backwards compatibility + if ( uv2ScaleMap.isWebGLRenderTarget ) { + + uv2ScaleMap = uv2ScaleMap.texture; + + } + + if ( uv2ScaleMap.matrixAutoUpdate === true ) { + + uv2ScaleMap.updateMatrix(); + + } + + uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); + + } } function refreshUniformsLine( uniforms, material ) {
true
Other
mrdoob
three.js
203a725845c30bc2570fd7fa595e51befafc3925.json
Implement support for texture matrix for uv2 Before this change, we only supported one texture matrix for the material that was applied to uv data based on the first texture, in priority order, that needed it. This change adds equivalent support for uv2 - we now transform second UV channel with a second UV transform that is grabbed from aoMap or lightMap (that are the only two textures using it atm). This fixes glTF rendering for files that use KHR_texture_transform on the occlusion texture, including ones produced by gltfpack.
src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl.js
@@ -4,5 +4,7 @@ export default /* glsl */` attribute vec2 uv2; varying vec2 vUv2; + uniform mat3 uv2Transform; + #endif `;
true
Other
mrdoob
three.js
203a725845c30bc2570fd7fa595e51befafc3925.json
Implement support for texture matrix for uv2 Before this change, we only supported one texture matrix for the material that was applied to uv data based on the first texture, in priority order, that needed it. This change adds equivalent support for uv2 - we now transform second UV channel with a second UV transform that is grabbed from aoMap or lightMap (that are the only two textures using it atm). This fixes glTF rendering for files that use KHR_texture_transform on the occlusion texture, including ones produced by gltfpack.
src/renderers/shaders/ShaderChunk/uv2_vertex.glsl.js
@@ -1,7 +1,7 @@ export default /* glsl */` #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) - vUv2 = uv2; + vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; #endif `;
true
Other
mrdoob
three.js
203a725845c30bc2570fd7fa595e51befafc3925.json
Implement support for texture matrix for uv2 Before this change, we only supported one texture matrix for the material that was applied to uv data based on the first texture, in priority order, that needed it. This change adds equivalent support for uv2 - we now transform second UV channel with a second UV transform that is grabbed from aoMap or lightMap (that are the only two textures using it atm). This fixes glTF rendering for files that use KHR_texture_transform on the occlusion texture, including ones produced by gltfpack.
src/renderers/shaders/UniformsLib.d.ts
@@ -8,6 +8,7 @@ export let UniformsLib: { opacity: IUniform; map: IUniform; uvTransform: IUniform; + uv2Transform: IUniform; alphaMap: IUniform; }; specularmap: {
true
Other
mrdoob
three.js
203a725845c30bc2570fd7fa595e51befafc3925.json
Implement support for texture matrix for uv2 Before this change, we only supported one texture matrix for the material that was applied to uv data based on the first texture, in priority order, that needed it. This change adds equivalent support for uv2 - we now transform second UV channel with a second UV transform that is grabbed from aoMap or lightMap (that are the only two textures using it atm). This fixes glTF rendering for files that use KHR_texture_transform on the occlusion texture, including ones produced by gltfpack.
src/renderers/shaders/UniformsLib.js
@@ -15,6 +15,7 @@ var UniformsLib = { map: { value: null }, uvTransform: { value: new Matrix3() }, + uv2Transform: { value: new Matrix3() }, alphaMap: { value: null },
true
Other
mrdoob
three.js
7f58f35a32a7a3d954d754fe7e6779db413e5940.json
add url to npm in gitignore
.gitignore
@@ -7,7 +7,7 @@ npm-debug.log .jshintrc .vs/ -# npm install --prefix test adds files in the test folder. +# npm install --prefix test adds files in the test folder (https://docs.npmjs.com/configuring-npm/folders.html#executables). # There are 2 kindsof files, those without extension and those with cmd extension. # To ignore files without a extension, following precedure is nessecary: # - ignore all files in the test folder
false
Other
mrdoob
three.js
9df4f897493b1054e162df5f496fc83e4b5e28c1.json
add comments to gitignore
.gitignore
@@ -7,6 +7,12 @@ npm-debug.log .jshintrc .vs/ +# npm install --prefix test adds files in the test folder. +# There are 2 kindsof files, those without extension and those with cmd extension. +# To ignore files without a extension, following precedure is nessecary: +# - ignore all files in the test folder +# - unignore all files in subdirectories of the test folder +# - unignore all files with an extension in the test folder test/* !test/*/ !test/*.*
false
Other
mrdoob
three.js
b757f656ffed63a0ebfd78b665fdc4b753157d51.json
Add ignore for npm install with prefix
.gitignore
@@ -6,5 +6,12 @@ npm-debug.log .jshintrc .vs/ -**/node_modules + +test/* +!test/*/ +!test/*.* +test/*.cmd test/unit/build + + +**/node_modules \ No newline at end of file
false
Other
mrdoob
three.js
f207d07b33ed7ee39c8ed38544b0abe950862509.json
use media queries
docs/prettify/threejs.css
@@ -1,15 +1,28 @@ -pre .str, code .str { color: #BB55FF; } /* string */ +pre .str, code .str { color: #8000ff; } /* string */ pre .kwd, code .kwd { color: #30b030; } /* keyword */ -pre .com, code .com { color: #666666; } /* comment */ +pre .com, code .com { color: #999999; } /* comment */ pre .typ, code .typ { color: #2194ce; } /* type */ -pre .lit, code .lit { color: #ff3399; } /* literal */ +pre .lit, code .lit { color: #ff0080; } /* literal */ pre .pun, code .pun { color: #888888; } /* punctuation */ -pre .pln, code .pln { color: #aaaaaa; } /* plaintext */ +pre .pln, code .pln { color: #444444; } /* plaintext */ pre .dec, code .dec { color: #22c0c4; } /* decimal */ pre.prettyprint, code.prettyprint { - background-color: #333333; + background-color: #F5F5F5; font-family: 'Roboto Mono', monospace; } + +@media (prefers-color-scheme: dark) { + + pre .str, code .str { color: #BB55FF; } /* string */ + pre .com, code .com { color: #666666; } /* comment */ + pre .lit, code .lit { color: #ff3399; } /* literal */ + pre .pln, code .pln { color: #aaaaaa; } /* plaintext */ + + pre.prettyprint, code.prettyprint { + background-color: #333333; + } + +}
false
Other
mrdoob
three.js
5c98448ad8d1659f0b338b3fe34978a3b488e0f8.json
avoid the delayed updating of cube cameras - we can update the unattached cube camera just before attaching it to avoid the unnessary delay - we don't need to hide the sphere temporarily as we're using single sided materials
examples/webgl_materials_cubemap_dynamic.html
@@ -178,26 +178,22 @@ camera.lookAt( scene.position ); - sphere.visible = false; - // pingpong if ( count % 2 === 0 ) { + cubeCamera1.update( renderer, scene ); material.envMap = cubeCamera1.renderTarget.texture; - cubeCamera2.update( renderer, scene ); } else { + cubeCamera2.update( renderer, scene ); material.envMap = cubeCamera2.renderTarget.texture; - cubeCamera1.update( renderer, scene ); } count ++; - sphere.visible = true; - renderer.render( scene, camera ); }
false
Other
mrdoob
three.js
a4e573604cf1694db8f0059798bc97653fd538a6.json
Update JSM modules.
examples/jsm/renderers/CSS3DRenderer.js
@@ -19,11 +19,15 @@ var CSS3DObject = function ( element ) { this.addEventListener( 'removed', function () { - if ( this.element.parentNode !== null ) { + this.traverse( function( object ) { - this.element.parentNode.removeChild( this.element ); + if ( object.element instanceof Element && object.element.parentNode !== null ) { - } + object.element.parentNode.removeChild( object.element ); + + } + + } ); } );
false
Other
mrdoob
three.js
912f8c5d83dc65a93055156efbf482c45cc3be3a.json
Rebuild example modules
examples/jsm/controls/OrbitControls.js
@@ -268,7 +268,7 @@ var OrbitControls = function ( object, domElement ) { document.removeEventListener( 'mousemove', onMouseMove, false ); document.removeEventListener( 'mouseup', onMouseUp, false ); - window.removeEventListener( 'keydown', onKeyDown, false ); + scope.domElement.removeEventListener( 'keydown', onKeyDown, false ); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here? @@ -1146,7 +1146,15 @@ var OrbitControls = function ( object, domElement ) { scope.domElement.addEventListener( 'touchend', onTouchEnd, false ); scope.domElement.addEventListener( 'touchmove', onTouchMove, false ); - window.addEventListener( 'keydown', onKeyDown, false ); + scope.domElement.addEventListener( 'keydown', onKeyDown, false ); + + // make sure element can receive keys. + + if ( scope.domElement.tabIndex === -1 ) { + + scope.domElement.tabIndex = 0; + + } // force an update at start
false
Other
mrdoob
three.js
011f242435076e2b6e5ffbdc68eb0c1485536310.json
use a simple loop
examples/js/loaders/GCodeLoader.js
@@ -204,8 +204,13 @@ THREE.GCodeLoader.prototype = Object.assign( Object.create( THREE.Loader.prototy var layer = layers[ i ]; - vertex.push( ...layer.vertex ) - pathVertex.push( ...layer.pathVertex ) + for ( var j = 0; j < layer.vertex.length; j ++ ) { + vertex.push(layer.vertex[ j ]) + } + + for ( var j = 0; j < layer.pathVertex.length; j ++ ) { + pathVertex.push(layer.pathVertex[ j ]) + } }
true
Other
mrdoob
three.js
011f242435076e2b6e5ffbdc68eb0c1485536310.json
use a simple loop
examples/jsm/loaders/GCodeLoader.js
@@ -215,8 +215,13 @@ GCodeLoader.prototype = Object.assign( Object.create( Loader.prototype ), { var layer = layers[ i ]; - vertex.push( ...layer.vertex ) - pathVertex.push( ...layer.pathVertex ) + for ( var j = 0; j < layer.vertex.length; j ++ ) { + vertex.push(layer.vertex[ j ]) + } + + for ( var j = 0; j < layer.pathVertex.length; j ++ ) { + pathVertex.push(layer.pathVertex[ j ]) + } }
true
Other
mrdoob
three.js
10e77ccb590f67e7b8035747d3ada1791fb386cd.json
Fix uniforms in ShaderMaterialParameters This is to ensure the "uniforms" property of ShaderMaterialParameters is used properly if it is given in the ShaderMaterial constructor.
src/materials/ShaderMaterial.d.ts
@@ -12,7 +12,7 @@ import { MaterialParameters, Material } from './Material'; */ export interface ShaderMaterialParameters extends MaterialParameters { - uniforms?: any; + uniforms?: { [uniform: string]: IUniform }; vertexShader?: string; fragmentShader?: string; linewidth?: number;
false
Other
mrdoob
three.js
5051428960f3f12e83e0df3ea945d68968b19923.json
Fix panning direction
examples/webgl_video_panorama_equirectangular.html
@@ -105,7 +105,7 @@ if ( isUserInteracting === true ) { lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon; - lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat; + lat = ( onPointerDownPointerY - event.clientY ) * 0.1 + onPointerDownLat; }
false
Other
mrdoob
three.js
b1b17b494105916675e57b49d288c2121291a0c7.json
add space around parameters
examples/js/loaders/GCodeLoader.js
@@ -204,8 +204,8 @@ THREE.GCodeLoader.prototype = Object.assign( Object.create( THREE.Loader.prototy var layer = layers[ i ]; - vertex.push(...layer.vertex) - pathVertex.push(...layer.pathVertex) + vertex.push( ...layer.vertex ) + pathVertex.push( ...layer.pathVertex ) }
true
Other
mrdoob
three.js
b1b17b494105916675e57b49d288c2121291a0c7.json
add space around parameters
examples/jsm/loaders/GCodeLoader.js
@@ -215,8 +215,8 @@ GCodeLoader.prototype = Object.assign( Object.create( Loader.prototype ), { var layer = layers[ i ]; - vertex.push(...layer.vertex) - pathVertex.push(...layer.pathVertex) + vertex.push( ...layer.vertex ) + pathVertex.push( ...layer.pathVertex ) }
true
Other
mrdoob
three.js
57a815034605a470bffa0b10af7827966fe959af.json
Add lazy loading to images in examples page
examples/index.html
@@ -169,7 +169,7 @@ <h1><a href="https://threejs.org">three.js</a></h1> '<div class="card">', ' <a href="' + file + '.html" target="viewer">', ' <div class="cover">', - ' <img src="screenshots/' + file + '.png" />', + ' <img src="screenshots/' + file + '.png" loading="lazy" />', ' </div>', ' <div class="title">' + getName( file ) + '</div>', ' </a>',
false
Other
mrdoob
three.js
b49842a39f34770cfe19befc6611828e37485cc2.json
Add patternTexture in type definition file Otherwise tsc will complain when an user try to set the texture
examples/jsm/postprocessing/OutlinePass.d.ts
@@ -8,7 +8,8 @@ import { MeshBasicMaterial, MeshDepthMaterial, ShaderMaterial, - WebGLRenderTarget + WebGLRenderTarget, + Texture } from '../../../src/Three'; import { Pass } from './Pass'; @@ -28,6 +29,7 @@ export class OutlinePass extends Pass { downSampleRatio: number; pulsePeriod: number; resolution: Vector2; + patternTexture: Texture; maskBufferMaterial: MeshBasicMaterial; renderTargetMaskBuffer: WebGLRenderTarget;
false
Other
mrdoob
three.js
bb0168be04bfe6ef689250ca428d2906a8bfb040.json
Fix frustum update
examples/jsm/csm/Frustum.js
@@ -25,6 +25,9 @@ export default class Frustum { getViewSpaceVertices() { const maxFar = this.maxFar; + const projectionMatrix = this.projectionMatrix; + const isOrthographic = projectionMatrix.elements[ 2 * 4 + 3 ] === 0; + inverseProjectionMatrix.getInverse( this.projectionMatrix ); // 3 --- 0 vertices.near/far order @@ -55,7 +58,15 @@ export default class Frustum { v.applyMatrix4( inverseProjectionMatrix ); const absZ = Math.abs( v.z ); - v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) ); + if ( isOrthographic ) { + + v.z *= Math.min( maxFar / absZ, 1.0 ); + + } else { + + v.multiplyScalar( Math.min( maxFar / absZ, 1.0 ) ); + + } } );
true
Other
mrdoob
three.js
bb0168be04bfe6ef689250ca428d2906a8bfb040.json
Fix frustum update
examples/webgl_shadowmap_csm.html
@@ -216,9 +216,18 @@ csm.update( camera.matrix ); controls.update(); - updateOrthoCamera(); - - renderer.render( scene, params.orthographic ? orthoCamera : camera ); + + if ( params.orthographic ) { + + updateOrthoCamera(); + csm.updateFrustums(); + renderer.render( scene, orthoCamera ); + + } else { + + renderer.render( scene, camera ); + + } }
true
Other
mrdoob
three.js
aa471233929f7691bfc46474554510aedc8c2cdf.json
Add ortho camera to example
examples/webgl_shadowmap_csm.html
@@ -22,15 +22,50 @@ import { GUI } from './jsm/libs/dat.gui.module.js'; import * as CSM from './jsm/csm/CSM.js'; - var renderer, scene, camera, controls, csm; + var renderer, scene, camera, orthoCamera, controls, csm; + + var params = { + orthographic: false, + far: 1000, + mode: 'practical', + lightX: - 1, + lightY: - 1, + lightZ: - 1, + margin: 100, + lightFar: 5000, + lightNear: 1, + helper: function () { + + var helper = csm.helper( camera.matrix ); + scene.add( helper ); + + } + }; init(); animate(); + function updateOrthoCamera() { + + var size = controls.target.distanceTo( camera.position ); + var aspect = camera.aspect; + + orthoCamera.left = size * aspect / - 2; + orthoCamera.right = size * aspect / 2; + + orthoCamera.top = size / 2; + orthoCamera.bottom = size / - 2; + orthoCamera.position.copy( camera.position ); + orthoCamera.rotation.copy( camera.rotation ); + orthoCamera.updateProjectionMatrix(); + + } + function init() { scene = new THREE.Scene(); scene.background = new THREE.Color( '#454e61' ); camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 5000 ); + orthoCamera = new THREE.OrthographicCamera(); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); @@ -47,23 +82,6 @@ var ambientLight = new THREE.AmbientLight( 0xffffff, 0.5 ); scene.add( ambientLight ); - var params = { - far: 1000, - mode: 'practical', - lightX: - 1, - lightY: - 1, - lightZ: - 1, - margin: 100, - lightFar: 5000, - lightNear: 1, - helper: function () { - - var helper = csm.helper( camera.matrix ); - scene.add( helper ); - - } - }; - csm = new CSM.default({ maxFar: params.far, cascades: 4, @@ -111,6 +129,13 @@ var gui = new GUI(); + gui.add( params, 'orthographic' ).onChange( function ( value ) { + + csm.camera = value ? orthoCamera : camera; + csm.updateFrustums(); + + } ); + gui.add( params, 'far', 1, 5000 ).step( 1 ).name( 'shadow far' ).onChange( function ( value ) { csm.maxFar = value; @@ -178,7 +203,7 @@ camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); - csm.setAspect( camera.aspect ); + updateOrthoCamera(); renderer.setSize( window.innerWidth, window.innerHeight ); @@ -191,8 +216,9 @@ csm.update( camera.matrix ); controls.update(); - - renderer.render( scene, camera ); + updateOrthoCamera(); + + renderer.render( scene, params.orthographic ? orthoCamera : camera ); }
false
Other
mrdoob
three.js
d1c934903a41bd10c9bfa61dd3c1f88ac4f2d2c4.json
replace frustum vertex with vector3
examples/jsm/csm/Frustum.js
@@ -3,7 +3,6 @@ */ import { MathUtils, Vector3 } from '../../../build/three.module.js'; -import FrustumVertex from './FrustumVertex.js'; export default class Frustum { @@ -36,17 +35,17 @@ export default class Frustum { // 2 --- 1 this.vertices.near.push( - new FrustumVertex( this.nearPlaneX, this.nearPlaneY, - this.near ), - new FrustumVertex( this.nearPlaneX, - this.nearPlaneY, - this.near ), - new FrustumVertex( - this.nearPlaneX, - this.nearPlaneY, - this.near ), - new FrustumVertex( - this.nearPlaneX, this.nearPlaneY, - this.near ) + new Vector3( this.nearPlaneX, this.nearPlaneY, - this.near ), + new Vector3( this.nearPlaneX, - this.nearPlaneY, - this.near ), + new Vector3( - this.nearPlaneX, - this.nearPlaneY, - this.near ), + new Vector3( - this.nearPlaneX, this.nearPlaneY, - this.near ) ); this.vertices.far.push( - new FrustumVertex( this.farPlaneX, this.farPlaneY, - this.far ), - new FrustumVertex( this.farPlaneX, - this.farPlaneY, - this.far ), - new FrustumVertex( - this.farPlaneX, - this.farPlaneY, - this.far ), - new FrustumVertex( - this.farPlaneX, this.farPlaneY, - this.far ) + new Vector3( this.farPlaneX, this.farPlaneY, - this.far ), + new Vector3( this.farPlaneX, - this.farPlaneY, - this.far ), + new Vector3( - this.farPlaneX, - this.farPlaneY, - this.far ), + new Vector3( - this.farPlaneX, this.farPlaneY, - this.far ) ); return this.vertices; @@ -69,7 +68,7 @@ export default class Frustum { for ( let j = 0; j < 4; j ++ ) { - cascade.vertices.near.push( new FrustumVertex().fromLerp( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] ) ); + cascade.vertices.near.push( new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i - 1 ] ) ); } @@ -83,7 +82,7 @@ export default class Frustum { for ( let j = 0; j < 4; j ++ ) { - cascade.vertices.far.push( new FrustumVertex().fromLerp( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] ) ); + cascade.vertices.far.push( new Vector3().lerpVectors( this.vertices.near[ j ], this.vertices.far[ j ], breaks[ i ] ) ); } @@ -106,11 +105,11 @@ export default class Frustum { point.set( this.vertices.near[ i ].x, this.vertices.near[ i ].y, this.vertices.near[ i ].z ); point.applyMatrix4( cameraMatrix ); - result.vertices.near.push( new FrustumVertex( point.x, point.y, point.z ) ); + result.vertices.near.push( new Vector3( point.x, point.y, point.z ) ); point.set( this.vertices.far[ i ].x, this.vertices.far[ i ].y, this.vertices.far[ i ].z ); point.applyMatrix4( cameraMatrix ); - result.vertices.far.push( new FrustumVertex( point.x, point.y, point.z ) ); + result.vertices.far.push( new Vector3( point.x, point.y, point.z ) ); }
true