1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-05 19:42:38 +02:00
Daniel Neto 2023-12-11 11:59:56 -03:00
parent f0f62670c5
commit 7e26256cac
4563 changed files with 1246712 additions and 17558 deletions

View file

@ -0,0 +1,11 @@
import { BufferAttribute, BufferGeometry, InterleavedBufferAttribute, TrianglesDrawModes, Mesh, Line, Points } from '../../../src/Three';
export namespace BufferGeometryUtils {
export function mergeBufferGeometries( geometries: BufferGeometry[], useGroups?: boolean ): BufferGeometry;
export function mergeBufferAttributes( attributes: BufferAttribute[] ): BufferAttribute;
export function interleaveAttributes( attributes: BufferAttribute[] ): InterleavedBufferAttribute;
export function estimateBytesUsed( geometry: BufferGeometry ): number;
export function mergeVertices( geometry: BufferGeometry, tolerance?: number ): BufferGeometry;
export function toTrianglesDrawMode( geometry: BufferGeometry, drawMode: TrianglesDrawModes ): BufferGeometry;
export function computeMorphedAttributes( object: Mesh | Line | Points ): Object;
}

View file

@ -0,0 +1,935 @@
import {
BufferAttribute,
BufferGeometry,
Float32BufferAttribute,
InterleavedBuffer,
InterleavedBufferAttribute,
TriangleFanDrawMode,
TriangleStripDrawMode,
TrianglesDrawMode,
Vector3
} from '../../../build/three.module.js';
var BufferGeometryUtils = {
computeTangents: function ( geometry ) {
geometry.computeTangents();
console.warn( 'THREE.BufferGeometryUtils: .computeTangents() has been removed. Use BufferGeometry.computeTangents() instead.' );
},
/**
* @param {Array<BufferGeometry>} geometries
* @param {Boolean} useGroups
* @return {BufferGeometry}
*/
mergeBufferGeometries: function ( geometries, useGroups ) {
var isIndexed = geometries[ 0 ].index !== null;
var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
var attributes = {};
var morphAttributes = {};
var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
var mergedGeometry = new BufferGeometry();
var offset = 0;
for ( var i = 0; i < geometries.length; ++ i ) {
var geometry = geometries[ i ];
var attributesCount = 0;
// ensure that all geometries are indexed, or none
if ( isIndexed !== ( geometry.index !== null ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
return null;
}
// gather attributes, exit early if they're different
for ( var name in geometry.attributes ) {
if ( ! attributesUsed.has( name ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
return null;
}
if ( attributes[ name ] === undefined ) attributes[ name ] = [];
attributes[ name ].push( geometry.attributes[ name ] );
attributesCount ++;
}
// ensure geometries have the same number of attributes
if ( attributesCount !== attributesUsed.size ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
return null;
}
// gather morph attributes, exit early if they're different
if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
return null;
}
for ( var name in geometry.morphAttributes ) {
if ( ! morphAttributesUsed.has( name ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
return null;
}
if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
}
// gather .userData
mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
mergedGeometry.userData.mergedUserData.push( geometry.userData );
if ( useGroups ) {
var count;
if ( isIndexed ) {
count = geometry.index.count;
} else if ( geometry.attributes.position !== undefined ) {
count = geometry.attributes.position.count;
} else {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
return null;
}
mergedGeometry.addGroup( offset, count, i );
offset += count;
}
}
// merge indices
if ( isIndexed ) {
var indexOffset = 0;
var mergedIndex = [];
for ( var i = 0; i < geometries.length; ++ i ) {
var index = geometries[ i ].index;
for ( var j = 0; j < index.count; ++ j ) {
mergedIndex.push( index.getX( j ) + indexOffset );
}
indexOffset += geometries[ i ].attributes.position.count;
}
mergedGeometry.setIndex( mergedIndex );
}
// merge attributes
for ( var name in attributes ) {
var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
if ( ! mergedAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
return null;
}
mergedGeometry.setAttribute( name, mergedAttribute );
}
// merge morph attributes
for ( var name in morphAttributes ) {
var numMorphTargets = morphAttributes[ name ][ 0 ].length;
if ( numMorphTargets === 0 ) break;
mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
mergedGeometry.morphAttributes[ name ] = [];
for ( var i = 0; i < numMorphTargets; ++ i ) {
var morphAttributesToMerge = [];
for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
}
var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
if ( ! mergedMorphAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
return null;
}
mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
}
}
return mergedGeometry;
},
/**
* @param {Array<BufferAttribute>} attributes
* @return {BufferAttribute}
*/
mergeBufferAttributes: function ( attributes ) {
var TypedArray;
var itemSize;
var normalized;
var arrayLength = 0;
for ( var i = 0; i < attributes.length; ++ i ) {
var attribute = attributes[ i ];
if ( attribute.isInterleavedBufferAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
return null;
}
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
if ( TypedArray !== attribute.array.constructor ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
return null;
}
if ( itemSize === undefined ) itemSize = attribute.itemSize;
if ( itemSize !== attribute.itemSize ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
return null;
}
if ( normalized === undefined ) normalized = attribute.normalized;
if ( normalized !== attribute.normalized ) {
console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
return null;
}
arrayLength += attribute.array.length;
}
var array = new TypedArray( arrayLength );
var offset = 0;
for ( var i = 0; i < attributes.length; ++ i ) {
array.set( attributes[ i ].array, offset );
offset += attributes[ i ].array.length;
}
return new BufferAttribute( array, itemSize, normalized );
},
/**
* @param {Array<BufferAttribute>} attributes
* @return {Array<InterleavedBufferAttribute>}
*/
interleaveAttributes: function ( attributes ) {
// Interleaves the provided attributes into an InterleavedBuffer and returns
// a set of InterleavedBufferAttributes for each attribute
var TypedArray;
var arrayLength = 0;
var stride = 0;
// calculate the the length and type of the interleavedBuffer
for ( var i = 0, l = attributes.length; i < l; ++ i ) {
var attribute = attributes[ i ];
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
if ( TypedArray !== attribute.array.constructor ) {
console.error( 'AttributeBuffers of different types cannot be interleaved' );
return null;
}
arrayLength += attribute.array.length;
stride += attribute.itemSize;
}
// Create the set of buffer attributes
var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
var offset = 0;
var res = [];
var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
for ( var j = 0, l = attributes.length; j < l; j ++ ) {
var attribute = attributes[ j ];
var itemSize = attribute.itemSize;
var count = attribute.count;
var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
res.push( iba );
offset += itemSize;
// Move the data for each attribute into the new interleavedBuffer
// at the appropriate offset
for ( var c = 0; c < count; c ++ ) {
for ( var k = 0; k < itemSize; k ++ ) {
iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
}
}
}
return res;
},
/**
* @param {Array<BufferGeometry>} geometry
* @return {number}
*/
estimateBytesUsed: function ( geometry ) {
// Return the estimated memory used by this geometry in bytes
// Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
// for InterleavedBufferAttributes.
var mem = 0;
for ( var name in geometry.attributes ) {
var attr = geometry.getAttribute( name );
mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
}
var indices = geometry.getIndex();
mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
return mem;
},
/**
* @param {BufferGeometry} geometry
* @param {number} tolerance
* @return {BufferGeometry>}
*/
mergeVertices: function ( geometry, tolerance = 1e-4 ) {
tolerance = Math.max( tolerance, Number.EPSILON );
// Generate an index buffer if the geometry doesn't have one, or optimize it
// if it's already available.
var hashToIndex = {};
var indices = geometry.getIndex();
var positions = geometry.getAttribute( 'position' );
var vertexCount = indices ? indices.count : positions.count;
// next value for triangle indices
var nextIndex = 0;
// attributes and new attribute arrays
var attributeNames = Object.keys( geometry.attributes );
var attrArrays = {};
var morphAttrsArrays = {};
var newIndices = [];
var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
// initialize the arrays
for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
var name = attributeNames[ i ];
attrArrays[ name ] = [];
var morphAttr = geometry.morphAttributes[ name ];
if ( morphAttr ) {
morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
}
}
// convert the error tolerance to an amount of decimal places to truncate to
var decimalShift = Math.log10( 1 / tolerance );
var shiftMultiplier = Math.pow( 10, decimalShift );
for ( var i = 0; i < vertexCount; i ++ ) {
var index = indices ? indices.getX( i ) : i;
// Generate a hash for the vertex attributes at the current index 'i'
var hash = '';
for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
var name = attributeNames[ j ];
var attribute = geometry.getAttribute( name );
var itemSize = attribute.itemSize;
for ( var k = 0; k < itemSize; k ++ ) {
// double tilde truncates the decimal value
hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
}
}
// Add another reference to the vertex if it's already
// used by another index
if ( hash in hashToIndex ) {
newIndices.push( hashToIndex[ hash ] );
} else {
// copy data to the new index in the attribute arrays
for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
var name = attributeNames[ j ];
var attribute = geometry.getAttribute( name );
var morphAttr = geometry.morphAttributes[ name ];
var itemSize = attribute.itemSize;
var newarray = attrArrays[ name ];
var newMorphArrays = morphAttrsArrays[ name ];
for ( var k = 0; k < itemSize; k ++ ) {
var getterFunc = getters[ k ];
newarray.push( attribute[ getterFunc ]( index ) );
if ( morphAttr ) {
for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
}
}
}
}
hashToIndex[ hash ] = nextIndex;
newIndices.push( nextIndex );
nextIndex ++;
}
}
// Generate typed arrays from new attribute arrays and update
// the attributeBuffers
const result = geometry.clone();
for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
var name = attributeNames[ i ];
var oldAttribute = geometry.getAttribute( name );
var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
result.setAttribute( name, attribute );
// Update the attribute arrays
if ( name in morphAttrsArrays ) {
for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
result.morphAttributes[ name ][ j ] = morphAttribute;
}
}
}
// indices
result.setIndex( newIndices );
return result;
},
/**
* @param {BufferGeometry} geometry
* @param {number} drawMode
* @return {BufferGeometry>}
*/
toTrianglesDrawMode: function ( geometry, drawMode ) {
if ( drawMode === TrianglesDrawMode ) {
console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
return geometry;
}
if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
var index = geometry.getIndex();
// generate index if not present
if ( index === null ) {
var indices = [];
var position = geometry.getAttribute( 'position' );
if ( position !== undefined ) {
for ( var i = 0; i < position.count; i ++ ) {
indices.push( i );
}
geometry.setIndex( indices );
index = geometry.getIndex();
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
return geometry;
}
}
//
var numberOfTriangles = index.count - 2;
var newIndices = [];
if ( drawMode === TriangleFanDrawMode ) {
// gl.TRIANGLE_FAN
for ( var i = 1; i <= numberOfTriangles; i ++ ) {
newIndices.push( index.getX( 0 ) );
newIndices.push( index.getX( i ) );
newIndices.push( index.getX( i + 1 ) );
}
} else {
// gl.TRIANGLE_STRIP
for ( var i = 0; i < numberOfTriangles; i ++ ) {
if ( i % 2 === 0 ) {
newIndices.push( index.getX( i ) );
newIndices.push( index.getX( i + 1 ) );
newIndices.push( index.getX( i + 2 ) );
} else {
newIndices.push( index.getX( i + 2 ) );
newIndices.push( index.getX( i + 1 ) );
newIndices.push( index.getX( i ) );
}
}
}
if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
}
// build final geometry
var newGeometry = geometry.clone();
newGeometry.setIndex( newIndices );
newGeometry.clearGroups();
return newGeometry;
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
return geometry;
}
},
/**
* Calculates the morphed attributes of a morphed/skinned BufferGeometry.
* Helpful for Raytracing or Decals.
* @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
* @return {Object} An Object with original position/normal attributes and morphed ones.
*/
computeMorphedAttributes: function ( object ) {
if ( object.geometry.isBufferGeometry !== true ) {
console.error( 'THREE.BufferGeometryUtils: Geometry is not of type BufferGeometry.' );
return null;
}
var _vA = new Vector3();
var _vB = new Vector3();
var _vC = new Vector3();
var _tempA = new Vector3();
var _tempB = new Vector3();
var _tempC = new Vector3();
var _morphA = new Vector3();
var _morphB = new Vector3();
var _morphC = new Vector3();
function _calculateMorphedAttributeData(
object,
material,
attribute,
morphAttribute,
morphTargetsRelative,
a,
b,
c,
modifiedAttributeArray
) {
_vA.fromBufferAttribute( attribute, a );
_vB.fromBufferAttribute( attribute, b );
_vC.fromBufferAttribute( attribute, c );
var morphInfluences = object.morphTargetInfluences;
if ( material.morphTargets && morphAttribute && morphInfluences ) {
_morphA.set( 0, 0, 0 );
_morphB.set( 0, 0, 0 );
_morphC.set( 0, 0, 0 );
for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
var influence = morphInfluences[ i ];
var morphAttribute = morphAttribute[ i ];
if ( influence === 0 ) continue;
_tempA.fromBufferAttribute( morphAttribute, a );
_tempB.fromBufferAttribute( morphAttribute, b );
_tempC.fromBufferAttribute( morphAttribute, c );
if ( morphTargetsRelative ) {
_morphA.addScaledVector( _tempA, influence );
_morphB.addScaledVector( _tempB, influence );
_morphC.addScaledVector( _tempC, influence );
} else {
_morphA.addScaledVector( _tempA.sub( _vA ), influence );
_morphB.addScaledVector( _tempB.sub( _vB ), influence );
_morphC.addScaledVector( _tempC.sub( _vC ), influence );
}
}
_vA.add( _morphA );
_vB.add( _morphB );
_vC.add( _morphC );
}
if ( object.isSkinnedMesh ) {
object.boneTransform( a, _vA );
object.boneTransform( b, _vB );
object.boneTransform( c, _vC );
}
modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
}
var geometry = object.geometry;
var material = object.material;
var a, b, c;
var index = geometry.index;
var positionAttribute = geometry.attributes.position;
var morphPosition = geometry.morphAttributes.position;
var morphTargetsRelative = geometry.morphTargetsRelative;
var normalAttribute = geometry.attributes.normal;
var morphNormal = geometry.morphAttributes.position;
var groups = geometry.groups;
var drawRange = geometry.drawRange;
var i, j, il, jl;
var group, groupMaterial;
var start, end;
var modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
var modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
if ( index !== null ) {
// indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
groupMaterial = material[ group.materialIndex ];
start = Math.max( group.start, drawRange.start );
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = index.getX( j );
b = index.getX( j + 1 );
c = index.getX( j + 2 );
_calculateMorphedAttributeData(
object,
groupMaterial,
positionAttribute,
morphPosition,
morphTargetsRelative,
a, b, c,
modifiedPosition
);
_calculateMorphedAttributeData(
object,
groupMaterial,
normalAttribute,
morphNormal,
morphTargetsRelative,
a, b, c,
modifiedNormal
);
}
}
} else {
start = Math.max( 0, drawRange.start );
end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = index.getX( i );
b = index.getX( i + 1 );
c = index.getX( i + 2 );
_calculateMorphedAttributeData(
object,
material,
positionAttribute,
morphPosition,
morphTargetsRelative,
a, b, c,
modifiedPosition
);
_calculateMorphedAttributeData(
object,
material,
normalAttribute,
morphNormal,
morphTargetsRelative,
a, b, c,
modifiedNormal
);
}
}
} else if ( positionAttribute !== undefined ) {
// non-indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
groupMaterial = material[ group.materialIndex ];
start = Math.max( group.start, drawRange.start );
end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = j;
b = j + 1;
c = j + 2;
_calculateMorphedAttributeData(
object,
groupMaterial,
positionAttribute,
morphPosition,
morphTargetsRelative,
a, b, c,
modifiedPosition
);
_calculateMorphedAttributeData(
object,
groupMaterial,
normalAttribute,
morphNormal,
morphTargetsRelative,
a, b, c,
modifiedNormal
);
}
}
} else {
start = Math.max( 0, drawRange.start );
end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = i;
b = i + 1;
c = i + 2;
_calculateMorphedAttributeData(
object,
material,
positionAttribute,
morphPosition,
morphTargetsRelative,
a, b, c,
modifiedPosition
);
_calculateMorphedAttributeData(
object,
material,
normalAttribute,
morphNormal,
morphTargetsRelative,
a, b, c,
modifiedNormal
);
}
}
}
var morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
var morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
return {
positionAttribute: positionAttribute,
normalAttribute: normalAttribute,
morphedPositionAttribute: morphedPositionAttribute,
morphedNormalAttribute: morphedNormalAttribute
};
}
};
export { BufferGeometryUtils };

View file

@ -0,0 +1,9 @@
import { Mesh } from '../../../src/Three';
export namespace GeometryCompressionUtils {
export function compressNormals( mesh: Mesh, encodeMethod: String ): void;
export function compressPositions( mesh: Mesh ): void;
export function compressUvs( mesh: Mesh ): void;
}

View file

@ -0,0 +1,913 @@
/**
* Octahedron and Quantization encodings based on work by:
*
* @link https://github.com/tsherif/mesh-quantization-example
*
*/
import {
BufferAttribute,
Matrix3,
Matrix4,
MeshPhongMaterial,
ShaderChunk,
ShaderLib,
UniformsUtils,
Vector3
} from '../../../build/three.module.js';
var GeometryCompressionUtils = {
/**
* Make the input mesh.geometry's normal attribute encoded and compressed by 3 different methods.
* Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the normal data.
*
* @param {THREE.Mesh} mesh
* @param {String} encodeMethod "DEFAULT" || "OCT1Byte" || "OCT2Byte" || "ANGLES"
*
*/
compressNormals: function ( mesh, encodeMethod ) {
if ( ! mesh.geometry ) {
console.error( 'Mesh must contain geometry. ' );
}
const normal = mesh.geometry.attributes.normal;
if ( ! normal ) {
console.error( 'Geometry must contain normal attribute. ' );
}
if ( normal.isPacked ) return;
if ( normal.itemSize != 3 ) {
console.error( 'normal.itemSize is not 3, which cannot be encoded. ' );
}
const array = normal.array;
const count = normal.count;
let result;
if ( encodeMethod == 'DEFAULT' ) {
// TODO: Add 1 byte to the result, making the encoded length to be 4 bytes.
result = new Uint8Array( count * 3 );
for ( let idx = 0; idx < array.length; idx += 3 ) {
const encoded = this.EncodingFuncs.defaultEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
result[ idx + 0 ] = encoded[ 0 ];
result[ idx + 1 ] = encoded[ 1 ];
result[ idx + 2 ] = encoded[ 2 ];
}
mesh.geometry.setAttribute( 'normal', new BufferAttribute( result, 3, true ) );
mesh.geometry.attributes.normal.bytes = result.length * 1;
} else if ( encodeMethod == 'OCT1Byte' ) {
/**
* It is not recommended to use 1-byte octahedron normals encoding unless you want to extremely reduce the memory usage
* As it makes vertex data not aligned to a 4 byte boundary which may harm some WebGL implementations and sometimes the normal distortion is visible
* Please refer to @zeux 's comments in https://github.com/mrdoob/three.js/pull/18208
*/
result = new Int8Array( count * 2 );
for ( let idx = 0; idx < array.length; idx += 3 ) {
const encoded = this.EncodingFuncs.octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 1 );
result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
}
mesh.geometry.setAttribute( 'normal', new BufferAttribute( result, 2, true ) );
mesh.geometry.attributes.normal.bytes = result.length * 1;
} else if ( encodeMethod == 'OCT2Byte' ) {
result = new Int16Array( count * 2 );
for ( let idx = 0; idx < array.length; idx += 3 ) {
const encoded = this.EncodingFuncs.octEncodeBest( array[ idx ], array[ idx + 1 ], array[ idx + 2 ], 2 );
result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
}
mesh.geometry.setAttribute( 'normal', new BufferAttribute( result, 2, true ) );
mesh.geometry.attributes.normal.bytes = result.length * 2;
} else if ( encodeMethod == 'ANGLES' ) {
result = new Uint16Array( count * 2 );
for ( let idx = 0; idx < array.length; idx += 3 ) {
const encoded = this.EncodingFuncs.anglesEncode( array[ idx ], array[ idx + 1 ], array[ idx + 2 ] );
result[ idx / 3 * 2 + 0 ] = encoded[ 0 ];
result[ idx / 3 * 2 + 1 ] = encoded[ 1 ];
}
mesh.geometry.setAttribute( 'normal', new BufferAttribute( result, 2, true ) );
mesh.geometry.attributes.normal.bytes = result.length * 2;
} else {
console.error( 'Unrecognized encoding method, should be `DEFAULT` or `ANGLES` or `OCT`. ' );
}
mesh.geometry.attributes.normal.needsUpdate = true;
mesh.geometry.attributes.normal.isPacked = true;
mesh.geometry.attributes.normal.packingMethod = encodeMethod;
// modify material
if ( ! ( mesh.material instanceof PackedPhongMaterial ) ) {
mesh.material = new PackedPhongMaterial().copy( mesh.material );
}
if ( encodeMethod == 'ANGLES' ) {
mesh.material.defines.USE_PACKED_NORMAL = 0;
}
if ( encodeMethod == 'OCT1Byte' ) {
mesh.material.defines.USE_PACKED_NORMAL = 1;
}
if ( encodeMethod == 'OCT2Byte' ) {
mesh.material.defines.USE_PACKED_NORMAL = 1;
}
if ( encodeMethod == 'DEFAULT' ) {
mesh.material.defines.USE_PACKED_NORMAL = 2;
}
},
/**
* Make the input mesh.geometry's position attribute encoded and compressed.
* Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the position data.
*
* @param {THREE.Mesh} mesh
*
*/
compressPositions: function ( mesh ) {
if ( ! mesh.geometry ) {
console.error( 'Mesh must contain geometry. ' );
}
const 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. ' );
}
const array = position.array;
const encodingBytes = 2;
const result = this.EncodingFuncs.quantizedEncode( array, encodingBytes );
const quantized = result.quantized;
const decodeMat = result.decodeMat;
// 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 BufferAttribute( quantized, 3 ) );
mesh.geometry.attributes.position.isPacked = true;
mesh.geometry.attributes.position.needsUpdate = true;
mesh.geometry.attributes.position.bytes = quantized.length * encodingBytes;
// modify material
if ( ! ( mesh.material instanceof PackedPhongMaterial ) ) {
mesh.material = new PackedPhongMaterial().copy( mesh.material );
}
mesh.material.defines.USE_PACKED_POSITION = 0;
mesh.material.uniforms.quantizeMatPos.value = decodeMat;
mesh.material.uniforms.quantizeMatPos.needsUpdate = true;
},
/**
* Make the input mesh.geometry's uv attribute encoded and compressed.
* Also will change the mesh.material to `PackedPhongMaterial` which let the vertex shader program decode the uv data.
*
* @param {THREE.Mesh} mesh
*
*/
compressUvs: function ( mesh ) {
if ( ! mesh.geometry ) {
console.error( 'Mesh must contain geometry property. ' );
}
const uvs = mesh.geometry.attributes.uv;
if ( ! uvs ) {
console.error( 'Geometry must contain uv attribute. ' );
}
if ( uvs.isPacked ) return;
const range = { min: Infinity, max: - Infinity };
const array = uvs.array;
for ( let i = 0; i < array.length; i ++ ) {
range.min = Math.min( range.min, array[ i ] );
range.max = Math.max( range.max, array[ i ] );
}
let result;
if ( range.min >= - 1.0 && range.max <= 1.0 ) {
// use default encoding method
result = new Uint16Array( array.length );
for ( let i = 0; i < array.length; i += 2 ) {
const encoded = this.EncodingFuncs.defaultEncode( array[ i ], array[ i + 1 ], 0, 2 );
result[ i ] = encoded[ 0 ];
result[ i + 1 ] = encoded[ 1 ];
}
mesh.geometry.setAttribute( 'uv', new BufferAttribute( result, 2, true ) );
mesh.geometry.attributes.uv.isPacked = true;
mesh.geometry.attributes.uv.needsUpdate = true;
mesh.geometry.attributes.uv.bytes = result.length * 2;
if ( ! ( mesh.material instanceof PackedPhongMaterial ) ) {
mesh.material = new PackedPhongMaterial().copy( mesh.material );
}
mesh.material.defines.USE_PACKED_UV = 0;
} else {
// use quantized encoding method
result = this.EncodingFuncs.quantizedEncodeUV( array, 2 );
mesh.geometry.setAttribute( 'uv', new BufferAttribute( result.quantized, 2 ) );
mesh.geometry.attributes.uv.isPacked = true;
mesh.geometry.attributes.uv.needsUpdate = true;
mesh.geometry.attributes.uv.bytes = result.quantized.length * 2;
if ( ! ( mesh.material instanceof PackedPhongMaterial ) ) {
mesh.material = new PackedPhongMaterial().copy( mesh.material );
}
mesh.material.defines.USE_PACKED_UV = 1;
mesh.material.uniforms.quantizeMatUV.value = result.decodeMat;
mesh.material.uniforms.quantizeMatUV.needsUpdate = true;
}
},
EncodingFuncs: {
defaultEncode: function ( x, y, z, bytes ) {
if ( bytes == 1 ) {
const tmpx = Math.round( ( x + 1 ) * 0.5 * 255 );
const tmpy = Math.round( ( y + 1 ) * 0.5 * 255 );
const tmpz = Math.round( ( z + 1 ) * 0.5 * 255 );
return new Uint8Array( [ tmpx, tmpy, tmpz ] );
} else if ( bytes == 2 ) {
const tmpx = Math.round( ( x + 1 ) * 0.5 * 65535 );
const tmpy = Math.round( ( y + 1 ) * 0.5 * 65535 );
const tmpz = Math.round( ( z + 1 ) * 0.5 * 65535 );
return new Uint16Array( [ tmpx, tmpy, tmpz ] );
} else {
console.error( 'number of bytes must be 1 or 2' );
}
},
defaultDecode: function ( array, bytes ) {
if ( bytes == 1 ) {
return [
( ( array[ 0 ] / 255 ) * 2.0 ) - 1.0,
( ( array[ 1 ] / 255 ) * 2.0 ) - 1.0,
( ( array[ 2 ] / 255 ) * 2.0 ) - 1.0,
];
} else if ( bytes == 2 ) {
return [
( ( array[ 0 ] / 65535 ) * 2.0 ) - 1.0,
( ( array[ 1 ] / 65535 ) * 2.0 ) - 1.0,
( ( array[ 2 ] / 65535 ) * 2.0 ) - 1.0,
];
} else {
console.error( 'number of bytes must be 1 or 2' );
}
},
// for `Angles` encoding
anglesEncode: function ( x, y, z ) {
const normal0 = parseInt( 0.5 * ( 1.0 + Math.atan2( y, x ) / Math.PI ) * 65535 );
const normal1 = parseInt( 0.5 * ( 1.0 + z ) * 65535 );
return new Uint16Array( [ normal0, normal1 ] );
},
// for `Octahedron` encoding
octEncodeBest: function ( x, y, z, bytes ) {
var oct, dec, best, currentCos, bestCos;
// Test various combinations of ceil and floor
// to minimize rounding errors
best = oct = octEncodeVec3( x, y, z, 'floor', 'floor' );
dec = octDecodeVec2( oct );
bestCos = dot( x, y, z, dec );
oct = octEncodeVec3( x, y, z, 'ceil', 'floor' );
dec = octDecodeVec2( oct );
currentCos = dot( x, y, z, dec );
if ( currentCos > bestCos ) {
best = oct;
bestCos = currentCos;
}
oct = octEncodeVec3( x, y, z, 'floor', 'ceil' );
dec = octDecodeVec2( oct );
currentCos = dot( x, y, z, dec );
if ( currentCos > bestCos ) {
best = oct;
bestCos = currentCos;
}
oct = octEncodeVec3( x, y, z, 'ceil', 'ceil' );
dec = octDecodeVec2( oct );
currentCos = dot( x, y, z, dec );
if ( currentCos > bestCos ) {
best = oct;
}
return best;
function octEncodeVec3( x0, y0, z0, xfunc, yfunc ) {
var x = x0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
var y = y0 / ( Math.abs( x0 ) + Math.abs( y0 ) + Math.abs( z0 ) );
if ( z < 0 ) {
var tempx = ( 1 - Math.abs( y ) ) * ( x >= 0 ? 1 : - 1 );
var tempy = ( 1 - Math.abs( x ) ) * ( y >= 0 ? 1 : - 1 );
x = tempx;
y = tempy;
var diff = 1 - Math.abs( x ) - Math.abs( y );
if ( diff > 0 ) {
diff += 0.001;
x += x > 0 ? diff / 2 : - diff / 2;
y += y > 0 ? diff / 2 : - diff / 2;
}
}
if ( bytes == 1 ) {
return new Int8Array( [
Math[ xfunc ]( x * 127.5 + ( x < 0 ? 1 : 0 ) ),
Math[ yfunc ]( y * 127.5 + ( y < 0 ? 1 : 0 ) )
] );
}
if ( bytes == 2 ) {
return new Int16Array( [
Math[ xfunc ]( x * 32767.5 + ( x < 0 ? 1 : 0 ) ),
Math[ yfunc ]( y * 32767.5 + ( y < 0 ? 1 : 0 ) )
] );
}
}
function octDecodeVec2( oct ) {
var x = oct[ 0 ];
var y = oct[ 1 ];
if ( bytes == 1 ) {
x /= x < 0 ? 127 : 128;
y /= y < 0 ? 127 : 128;
} else if ( bytes == 2 ) {
x /= x < 0 ? 32767 : 32768;
y /= y < 0 ? 32767 : 32768;
}
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( tmpx ) ) * ( y >= 0 ? 1 : - 1 );
}
var length = Math.sqrt( x * x + y * y + z * z );
return [
x / length,
y / length,
z / length
];
}
function dot( x, y, z, vec3 ) {
return x * vec3[ 0 ] + y * vec3[ 1 ] + z * vec3[ 2 ];
}
},
quantizedEncode: function ( array, bytes ) {
let quantized, segments;
if ( bytes == 1 ) {
quantized = new Uint8Array( array.length );
segments = 255;
} else if ( bytes == 2 ) {
quantized = new Uint16Array( array.length );
segments = 65535;
} else {
console.error( 'number of bytes error! ' );
}
const decodeMat = new Matrix4();
const min = new Float32Array( 3 );
const 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 ] );
}
decodeMat.scale( new Vector3(
( max[ 0 ] - min[ 0 ] ) / segments,
( max[ 1 ] - min[ 1 ] ) / segments,
( max[ 2 ] - min[ 2 ] ) / segments
) );
decodeMat.elements[ 12 ] = min[ 0 ];
decodeMat.elements[ 13 ] = min[ 1 ];
decodeMat.elements[ 14 ] = min[ 2 ];
decodeMat.transpose();
const multiplier = new Float32Array( [
max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0,
max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0,
max[ 2 ] !== min[ 2 ] ? segments / ( 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 ] );
}
return {
quantized: quantized,
decodeMat: decodeMat
};
},
quantizedEncodeUV: function ( array, bytes ) {
let quantized, segments;
if ( bytes == 1 ) {
quantized = new Uint8Array( array.length );
segments = 255;
} else if ( bytes == 2 ) {
quantized = new Uint16Array( array.length );
segments = 65535;
} else {
console.error( 'number of bytes error! ' );
}
const decodeMat = new Matrix3();
const min = new Float32Array( 2 );
const max = new Float32Array( 2 );
min[ 0 ] = min[ 1 ] = Number.MAX_VALUE;
max[ 0 ] = max[ 1 ] = - Number.MAX_VALUE;
for ( let i = 0; i < array.length; i += 2 ) {
min[ 0 ] = Math.min( min[ 0 ], array[ i + 0 ] );
min[ 1 ] = Math.min( min[ 1 ], array[ i + 1 ] );
max[ 0 ] = Math.max( max[ 0 ], array[ i + 0 ] );
max[ 1 ] = Math.max( max[ 1 ], array[ i + 1 ] );
}
decodeMat.scale(
( max[ 0 ] - min[ 0 ] ) / segments,
( max[ 1 ] - min[ 1 ] ) / segments
);
decodeMat.elements[ 6 ] = min[ 0 ];
decodeMat.elements[ 7 ] = min[ 1 ];
decodeMat.transpose();
const multiplier = new Float32Array( [
max[ 0 ] !== min[ 0 ] ? segments / ( max[ 0 ] - min[ 0 ] ) : 0,
max[ 1 ] !== min[ 1 ] ? segments / ( max[ 1 ] - min[ 1 ] ) : 0
] );
for ( let i = 0; i < array.length; i += 2 ) {
quantized[ i + 0 ] = Math.floor( ( array[ i + 0 ] - min[ 0 ] ) * multiplier[ 0 ] );
quantized[ i + 1 ] = Math.floor( ( array[ i + 1 ] - min[ 1 ] ) * multiplier[ 1 ] );
}
return {
quantized: quantized,
decodeMat: decodeMat
};
}
}
};
/**
* `PackedPhongMaterial` inherited from THREE.MeshPhongMaterial
*
* @param {Object} parameters
*/
function PackedPhongMaterial( parameters ) {
MeshPhongMaterial.call( this );
this.defines = {};
this.type = 'PackedPhongMaterial';
this.uniforms = UniformsUtils.merge( [
ShaderLib.phong.uniforms,
{
quantizeMatPos: { value: null },
quantizeMatUV: { value: null }
}
] );
this.vertexShader = [
'#define PHONG',
'varying vec3 vViewPosition;',
'#ifndef FLAT_SHADED',
'varying vec3 vNormal;',
'#endif',
ShaderChunk.common,
ShaderChunk.uv_pars_vertex,
ShaderChunk.uv2_pars_vertex,
ShaderChunk.displacementmap_pars_vertex,
ShaderChunk.envmap_pars_vertex,
ShaderChunk.color_pars_vertex,
ShaderChunk.fog_pars_vertex,
ShaderChunk.morphtarget_pars_vertex,
ShaderChunk.skinning_pars_vertex,
ShaderChunk.shadowmap_pars_vertex,
ShaderChunk.logdepthbuf_pars_vertex,
ShaderChunk.clipping_planes_pars_vertex,
`#ifdef USE_PACKED_NORMAL
#if USE_PACKED_NORMAL == 0
vec3 decodeNormal(vec3 packedNormal)
{
float x = packedNormal.x * 2.0 - 1.0;
float y = packedNormal.y * 2.0 - 1.0;
vec2 scth = vec2(sin(x * PI), cos(x * PI));
vec2 scphi = vec2(sqrt(1.0 - y * y), y);
return normalize( vec3(scth.y * scphi.x, scth.x * scphi.x, scphi.y) );
}
#endif
#if USE_PACKED_NORMAL == 1
vec3 decodeNormal(vec3 packedNormal)
{
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);
}
return normalize(v);
}
#endif
#if USE_PACKED_NORMAL == 2
vec3 decodeNormal(vec3 packedNormal)
{
vec3 v = (packedNormal * 2.0) - 1.0;
return normalize(v);
}
#endif
#endif`,
`#ifdef USE_PACKED_POSITION
#if USE_PACKED_POSITION == 0
uniform mat4 quantizeMatPos;
#endif
#endif`,
`#ifdef USE_PACKED_UV
#if USE_PACKED_UV == 1
uniform mat3 quantizeMatUV;
#endif
#endif`,
`#ifdef USE_PACKED_UV
#if USE_PACKED_UV == 0
vec2 decodeUV(vec2 packedUV)
{
vec2 uv = (packedUV * 2.0) - 1.0;
return uv;
}
#endif
#if USE_PACKED_UV == 1
vec2 decodeUV(vec2 packedUV)
{
vec2 uv = ( vec3(packedUV, 1.0) * quantizeMatUV ).xy;
return uv;
}
#endif
#endif`,
'void main() {',
ShaderChunk.uv_vertex,
`#ifdef USE_UV
#ifdef USE_PACKED_UV
vUv = decodeUV(vUv);
#endif
#endif`,
ShaderChunk.uv2_vertex,
ShaderChunk.color_vertex,
ShaderChunk.beginnormal_vertex,
`#ifdef USE_PACKED_NORMAL
objectNormal = decodeNormal(objectNormal);
#endif
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif
`,
ShaderChunk.morphnormal_vertex,
ShaderChunk.skinbase_vertex,
ShaderChunk.skinnormal_vertex,
ShaderChunk.defaultnormal_vertex,
'#ifndef FLAT_SHADED',
' vNormal = normalize( transformedNormal );',
'#endif',
ShaderChunk.begin_vertex,
`#ifdef USE_PACKED_POSITION
#if USE_PACKED_POSITION == 0
transformed = ( vec4(transformed, 1.0) * quantizeMatPos ).xyz;
#endif
#endif`,
ShaderChunk.morphtarget_vertex,
ShaderChunk.skinning_vertex,
ShaderChunk.displacementmap_vertex,
ShaderChunk.project_vertex,
ShaderChunk.logdepthbuf_vertex,
ShaderChunk.clipping_planes_vertex,
'vViewPosition = - mvPosition.xyz;',
ShaderChunk.worldpos_vertex,
ShaderChunk.envmap_vertex,
ShaderChunk.shadowmap_vertex,
ShaderChunk.fog_vertex,
'}',
].join( '\n' );
// Use the original MeshPhongMaterial's fragmentShader.
this.fragmentShader = [
'#define PHONG',
'uniform vec3 diffuse;',
'uniform vec3 emissive;',
'uniform vec3 specular;',
'uniform float shininess;',
'uniform float opacity;',
ShaderChunk.common,
ShaderChunk.packing,
ShaderChunk.dithering_pars_fragment,
ShaderChunk.color_pars_fragment,
ShaderChunk.uv_pars_fragment,
ShaderChunk.uv2_pars_fragment,
ShaderChunk.map_pars_fragment,
ShaderChunk.alphamap_pars_fragment,
ShaderChunk.aomap_pars_fragment,
ShaderChunk.lightmap_pars_fragment,
ShaderChunk.emissivemap_pars_fragment,
ShaderChunk.envmap_common_pars_fragment,
ShaderChunk.envmap_pars_fragment,
ShaderChunk.cube_uv_reflection_fragment,
ShaderChunk.fog_pars_fragment,
ShaderChunk.bsdfs,
ShaderChunk.lights_pars_begin,
ShaderChunk.lights_phong_pars_fragment,
ShaderChunk.shadowmap_pars_fragment,
ShaderChunk.bumpmap_pars_fragment,
ShaderChunk.normalmap_pars_fragment,
ShaderChunk.specularmap_pars_fragment,
ShaderChunk.logdepthbuf_pars_fragment,
ShaderChunk.clipping_planes_pars_fragment,
'void main() {',
ShaderChunk.clipping_planes_fragment,
'vec4 diffuseColor = vec4( diffuse, opacity );',
'ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );',
'vec3 totalEmissiveRadiance = emissive;',
ShaderChunk.logdepthbuf_fragment,
ShaderChunk.map_fragment,
ShaderChunk.color_fragment,
ShaderChunk.alphamap_fragment,
ShaderChunk.alphatest_fragment,
ShaderChunk.specularmap_fragment,
ShaderChunk.normal_fragment_begin,
ShaderChunk.normal_fragment_maps,
ShaderChunk.emissivemap_fragment,
// accumulation
ShaderChunk.lights_phong_fragment,
ShaderChunk.lights_fragment_begin,
ShaderChunk.lights_fragment_maps,
ShaderChunk.lights_fragment_end,
// modulation
ShaderChunk.aomap_fragment,
'vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;',
ShaderChunk.envmap_fragment,
'gl_FragColor = vec4( outgoingLight, diffuseColor.a );',
ShaderChunk.tonemapping_fragment,
ShaderChunk.encodings_fragment,
ShaderChunk.fog_fragment,
ShaderChunk.premultiplied_alpha_fragment,
ShaderChunk.dithering_fragment,
'}',
].join( '\n' );
this.setValues( parameters );
}
PackedPhongMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
export { GeometryCompressionUtils, PackedPhongMaterial };

View file

@ -0,0 +1,9 @@
import {
Vector3
} from '../../../src/Three';
export namespace GeometryUtils {
export function hilbert2D( center?: Vector3, size?: number, iterations?: number, v0?: number, v1?: number, v2?: number, v3?: number ): Vector3[];
export function hilbert3D( center?: Vector3, size?: number, iterations?: number, v0?: number, v1?: number, v2?: number, v3?: number, v4?: number, v5?: number, v6?: number, v7?: number ): Vector3[];
export function gosper( size?: number ): number[];
}

249
node_modules/three/examples/jsm/utils/GeometryUtils.js generated vendored Normal file
View file

@ -0,0 +1,249 @@
import {
Vector3
} from '../../../build/three.module.js';
var GeometryUtils = {
/**
* Generates 2D-Coordinates in a very fast way.
*
* Based on work by:
* @link http://www.openprocessing.org/sketch/15493
*
* @param center Center of Hilbert curve.
* @param size Total width of Hilbert curve.
* @param iterations Number of subdivisions.
* @param v0 Corner index -X, -Z.
* @param v1 Corner index -X, +Z.
* @param v2 Corner index +X, +Z.
* @param v3 Corner index +X, -Z.
*/
hilbert2D: function ( center, size, iterations, v0, v1, v2, v3 ) {
// Default Vars
var center = center !== undefined ? center : new Vector3( 0, 0, 0 ),
size = size !== undefined ? size : 10,
half = size / 2,
iterations = iterations !== undefined ? iterations : 1,
v0 = v0 !== undefined ? v0 : 0,
v1 = v1 !== undefined ? v1 : 1,
v2 = v2 !== undefined ? v2 : 2,
v3 = v3 !== undefined ? v3 : 3
;
var vec_s = [
new Vector3( center.x - half, center.y, center.z - half ),
new Vector3( center.x - half, center.y, center.z + half ),
new Vector3( center.x + half, center.y, center.z + half ),
new Vector3( center.x + half, center.y, center.z - half )
];
var vec = [
vec_s[ v0 ],
vec_s[ v1 ],
vec_s[ v2 ],
vec_s[ v3 ]
];
// Recurse iterations
if ( 0 <= -- iterations ) {
var tmp = [];
Array.prototype.push.apply( tmp, GeometryUtils.hilbert2D( vec[ 0 ], half, iterations, v0, v3, v2, v1 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert2D( vec[ 1 ], half, iterations, v0, v1, v2, v3 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert2D( vec[ 2 ], half, iterations, v0, v1, v2, v3 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert2D( vec[ 3 ], half, iterations, v2, v1, v0, v3 ) );
// Return recursive call
return tmp;
}
// Return complete Hilbert Curve.
return vec;
},
/**
* Generates 3D-Coordinates in a very fast way.
*
* Based on work by:
* @link http://www.openprocessing.org/visuals/?visualID=15599
*
* @param center Center of Hilbert curve.
* @param size Total width of Hilbert curve.
* @param iterations Number of subdivisions.
* @param v0 Corner index -X, +Y, -Z.
* @param v1 Corner index -X, +Y, +Z.
* @param v2 Corner index -X, -Y, +Z.
* @param v3 Corner index -X, -Y, -Z.
* @param v4 Corner index +X, -Y, -Z.
* @param v5 Corner index +X, -Y, +Z.
* @param v6 Corner index +X, +Y, +Z.
* @param v7 Corner index +X, +Y, -Z.
*/
hilbert3D: function ( center, size, iterations, v0, v1, v2, v3, v4, v5, v6, v7 ) {
// Default Vars
var center = center !== undefined ? center : new Vector3( 0, 0, 0 ),
size = size !== undefined ? size : 10,
half = size / 2,
iterations = iterations !== undefined ? iterations : 1,
v0 = v0 !== undefined ? v0 : 0,
v1 = v1 !== undefined ? v1 : 1,
v2 = v2 !== undefined ? v2 : 2,
v3 = v3 !== undefined ? v3 : 3,
v4 = v4 !== undefined ? v4 : 4,
v5 = v5 !== undefined ? v5 : 5,
v6 = v6 !== undefined ? v6 : 6,
v7 = v7 !== undefined ? v7 : 7
;
var vec_s = [
new Vector3( center.x - half, center.y + half, center.z - half ),
new Vector3( center.x - half, center.y + half, center.z + half ),
new Vector3( center.x - half, center.y - half, center.z + half ),
new Vector3( center.x - half, center.y - half, center.z - half ),
new Vector3( center.x + half, center.y - half, center.z - half ),
new Vector3( center.x + half, center.y - half, center.z + half ),
new Vector3( center.x + half, center.y + half, center.z + half ),
new Vector3( center.x + half, center.y + half, center.z - half )
];
var vec = [
vec_s[ v0 ],
vec_s[ v1 ],
vec_s[ v2 ],
vec_s[ v3 ],
vec_s[ v4 ],
vec_s[ v5 ],
vec_s[ v6 ],
vec_s[ v7 ]
];
// Recurse iterations
if ( -- iterations >= 0 ) {
var tmp = [];
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 0 ], half, iterations, v0, v3, v4, v7, v6, v5, v2, v1 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 1 ], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 2 ], half, iterations, v0, v7, v6, v1, v2, v5, v4, v3 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 3 ], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 4 ], half, iterations, v2, v3, v0, v1, v6, v7, v4, v5 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 5 ], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 6 ], half, iterations, v4, v3, v2, v5, v6, v1, v0, v7 ) );
Array.prototype.push.apply( tmp, GeometryUtils.hilbert3D( vec[ 7 ], half, iterations, v6, v5, v2, v1, v0, v3, v4, v7 ) );
// Return recursive call
return tmp;
}
// Return complete Hilbert Curve.
return vec;
},
/**
* Generates a Gosper curve (lying in the XY plane)
*
* https://gist.github.com/nitaku/6521802
*
* @param size The size of a single gosper island.
*/
gosper: function ( size ) {
size = ( size !== undefined ) ? size : 1;
function fractalize( config ) {
var output;
var input = config.axiom;
for ( var i = 0, il = config.steps; 0 <= il ? i < il : i > il; 0 <= il ? i ++ : i -- ) {
output = '';
for ( var j = 0, jl = input.length; j < jl; j ++ ) {
var char = input[ j ];
if ( char in config.rules ) {
output += config.rules[ char ];
} else {
output += char;
}
}
input = output;
}
return output;
}
function toPoints( config ) {
var currX = 0, currY = 0;
var angle = 0;
var path = [ 0, 0, 0 ];
var fractal = config.fractal;
for ( var i = 0, l = fractal.length; i < l; i ++ ) {
var char = fractal[ i ];
if ( char === '+' ) {
angle += config.angle;
} else if ( char === '-' ) {
angle -= config.angle;
} else if ( char === 'F' ) {
currX += config.size * Math.cos( angle );
currY += - config.size * Math.sin( angle );
path.push( currX, currY, 0 );
}
}
return path;
}
//
var gosper = fractalize( {
axiom: 'A',
steps: 4,
rules: {
A: 'A+BF++BF-FA--FAFA-BF+',
B: '-FA+BFBF++BF+FA--FA-B'
}
} );
var points = toPoints( {
fractal: gosper,
size: size,
angle: Math.PI / 3 // 60 degrees
} );
return points;
}
};
export { GeometryUtils };

View file

@ -0,0 +1,12 @@
import {
WebGLRenderer,
MeshStandardMaterial
} from '../../../src/Three';
export class RoughnessMipmapper {
constructor( renderer:WebGLRenderer );
generateMipmaps( material:MeshStandardMaterial ): void;
dispose(): void;
}

View file

@ -0,0 +1,293 @@
/**
* This class generates custom mipmaps for a roughness map by encoding the lost variation in the
* normal map mip levels as increased roughness in the corresponding roughness mip levels. This
* helps with rendering accuracy for MeshStandardMaterial, and also helps with anti-aliasing when
* using PMREM. If the normal map is larger than the roughness map, the roughness map will be
* enlarged to match the dimensions of the normal map.
*/
import {
MathUtils,
Mesh,
NoBlending,
OrthographicCamera,
PlaneGeometry,
RawShaderMaterial,
Vector2,
WebGLRenderTarget
} from '../../../build/three.module.js';
var _mipmapMaterial = _getMipmapMaterial();
var _mesh = new Mesh( new PlaneGeometry( 2, 2 ), _mipmapMaterial );
var _flatCamera = new OrthographicCamera( 0, 1, 0, 1, 0, 1 );
var _tempTarget = null;
var _renderer = null;
function RoughnessMipmapper( renderer ) {
_renderer = renderer;
_renderer.compile( _mesh, _flatCamera );
}
RoughnessMipmapper.prototype = {
constructor: RoughnessMipmapper,
generateMipmaps: function ( material ) {
if ( 'roughnessMap' in material === false ) return;
var { roughnessMap, normalMap } = material;
if ( roughnessMap === null || normalMap === null || ! roughnessMap.generateMipmaps || material.userData.roughnessUpdated ) return;
material.userData.roughnessUpdated = true;
var width = Math.max( roughnessMap.image.width, normalMap.image.width );
var height = Math.max( roughnessMap.image.height, normalMap.image.height );
if ( ! MathUtils.isPowerOfTwo( width ) || ! MathUtils.isPowerOfTwo( height ) ) return;
var oldTarget = _renderer.getRenderTarget();
var autoClear = _renderer.autoClear;
_renderer.autoClear = false;
if ( _tempTarget === null || _tempTarget.width !== width || _tempTarget.height !== height ) {
if ( _tempTarget !== null ) _tempTarget.dispose();
_tempTarget = new WebGLRenderTarget( width, height, { depthBuffer: false } );
_tempTarget.scissorTest = true;
}
if ( width !== roughnessMap.image.width || height !== roughnessMap.image.height ) {
var params = {
wrapS: roughnessMap.wrapS,
wrapT: roughnessMap.wrapT,
magFilter: roughnessMap.magFilter,
minFilter: roughnessMap.minFilter,
depthBuffer: false
};
var newRoughnessTarget = new WebGLRenderTarget( width, height, params );
newRoughnessTarget.texture.generateMipmaps = true;
// Setting the render target causes the memory to be allocated.
_renderer.setRenderTarget( newRoughnessTarget );
material.roughnessMap = newRoughnessTarget.texture;
if ( material.metalnessMap == roughnessMap ) material.metalnessMap = material.roughnessMap;
if ( material.aoMap == roughnessMap ) material.aoMap = material.roughnessMap;
}
_mipmapMaterial.uniforms.roughnessMap.value = roughnessMap;
_mipmapMaterial.uniforms.normalMap.value = normalMap;
var position = new Vector2( 0, 0 );
var texelSize = _mipmapMaterial.uniforms.texelSize.value;
for ( var mip = 0; width >= 1 && height >= 1; ++ mip, width /= 2, height /= 2 ) {
// Rendering to a mip level is not allowed in webGL1. Instead we must set
// up a secondary texture to write the result to, then copy it back to the
// proper mipmap level.
texelSize.set( 1.0 / width, 1.0 / height );
if ( mip == 0 ) texelSize.set( 0.0, 0.0 );
_tempTarget.viewport.set( position.x, position.y, width, height );
_tempTarget.scissor.set( position.x, position.y, width, height );
_renderer.setRenderTarget( _tempTarget );
_renderer.render( _mesh, _flatCamera );
_renderer.copyFramebufferToTexture( position, material.roughnessMap, mip );
_mipmapMaterial.uniforms.roughnessMap.value = material.roughnessMap;
}
if ( roughnessMap !== material.roughnessMap ) roughnessMap.dispose();
_renderer.setRenderTarget( oldTarget );
_renderer.autoClear = autoClear;
},
dispose: function () {
_mipmapMaterial.dispose();
_mesh.geometry.dispose();
if ( _tempTarget != null ) _tempTarget.dispose();
}
};
function _getMipmapMaterial() {
var shaderMaterial = new RawShaderMaterial( {
uniforms: {
roughnessMap: { value: null },
normalMap: { value: null },
texelSize: { value: new Vector2( 1, 1 ) }
},
vertexShader: /* glsl */`
precision mediump float;
precision mediump int;
attribute vec3 position;
attribute vec2 uv;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4( position, 1.0 );
}
`,
fragmentShader: /* glsl */`
precision mediump float;
precision mediump int;
varying vec2 vUv;
uniform sampler2D roughnessMap;
uniform sampler2D normalMap;
uniform vec2 texelSize;
#define ENVMAP_TYPE_CUBE_UV
vec4 envMapTexelToLinear( vec4 a ) { return a; }
#include <cube_uv_reflection_fragment>
float roughnessToVariance( float roughness ) {
float variance = 0.0;
if ( roughness >= r1 ) {
variance = ( r0 - roughness ) * ( v1 - v0 ) / ( r0 - r1 ) + v0;
} else if ( roughness >= r4 ) {
variance = ( r1 - roughness ) * ( v4 - v1 ) / ( r1 - r4 ) + v1;
} else if ( roughness >= r5 ) {
variance = ( r4 - roughness ) * ( v5 - v4 ) / ( r4 - r5 ) + v4;
} else {
float roughness2 = roughness * roughness;
variance = 1.79 * roughness2 * roughness2;
}
return variance;
}
float varianceToRoughness( float variance ) {
float roughness = 0.0;
if ( variance >= v1 ) {
roughness = ( v0 - variance ) * ( r1 - r0 ) / ( v0 - v1 ) + r0;
} else if ( variance >= v4 ) {
roughness = ( v1 - variance ) * ( r4 - r1 ) / ( v1 - v4 ) + r1;
} else if ( variance >= v5 ) {
roughness = ( v4 - variance ) * ( r5 - r4 ) / ( v4 - v5 ) + r4;
} else {
roughness = pow( 0.559 * variance, 0.25 ); // 0.559 = 1.0 / 1.79
}
return roughness;
}
void main() {
gl_FragColor = texture2D( roughnessMap, vUv, - 1.0 );
if ( texelSize.x == 0.0 ) return;
float roughness = gl_FragColor.g;
float variance = roughnessToVariance( roughness );
vec3 avgNormal;
for ( float x = - 1.0; x < 2.0; x += 2.0 ) {
for ( float y = - 1.0; y < 2.0; y += 2.0 ) {
vec2 uv = vUv + vec2( x, y ) * 0.25 * texelSize;
avgNormal += normalize( texture2D( normalMap, uv, - 1.0 ).xyz - 0.5 );
}
}
variance += 1.0 - 0.25 * length( avgNormal );
gl_FragColor.g = varianceToRoughness( variance );
}
`,
blending: NoBlending,
depthTest: false,
depthWrite: false
} );
shaderMaterial.type = 'RoughnessMipmapper';
return shaderMaterial;
}
export { RoughnessMipmapper };

14
node_modules/three/examples/jsm/utils/SceneUtils.d.ts generated vendored Normal file
View file

@ -0,0 +1,14 @@
import { Geometry, Group, InstancedMesh, Material, Object3D, Scene } from '../../../src/Three';
export namespace SceneUtils {
export function createMeshesFromInstancedMesh( instancedMesh: InstancedMesh ): Group;
export function createMultiMaterialObject( geometry: Geometry, materials: Material[] ): Group;
/**
* @deprecated Use scene.attach( child ) instead.
*/
export function detach( child: Object3D, parent: Object3D, scene: Scene ): void;
/**
* @deprecated Use parent.attach( child ) instead.
*/
export function attach( child: Object3D, scene: Scene, parent: Object3D ): void;
}

66
node_modules/three/examples/jsm/utils/SceneUtils.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
import {
Group,
Mesh
} from '../../../build/three.module.js';
var SceneUtils = {
createMeshesFromInstancedMesh: function ( instancedMesh ) {
var group = new Group();
var count = instancedMesh.count;
var geometry = instancedMesh.geometry;
var material = instancedMesh.material;
for ( var i = 0; i < count; i ++ ) {
var mesh = new Mesh( geometry, material );
instancedMesh.getMatrixAt( i, mesh.matrix );
mesh.matrix.decompose( mesh.position, mesh.quaternion, mesh.scale );
group.add( mesh );
}
group.copy( instancedMesh );
group.updateMatrixWorld(); // ensure correct world matrices of meshes
return group;
},
createMultiMaterialObject: function ( geometry, materials ) {
var group = new Group();
for ( var i = 0, l = materials.length; i < l; i ++ ) {
group.add( new Mesh( geometry, materials[ i ] ) );
}
return group;
},
detach: function ( child, parent, scene ) {
console.warn( 'THREE.SceneUtils: detach() has been deprecated. Use scene.attach( child ) instead.' );
scene.attach( child );
},
attach: function ( child, scene, parent ) {
console.warn( 'THREE.SceneUtils: attach() has been deprecated. Use parent.attach( child ) instead.' );
parent.attach( child );
}
};
export { SceneUtils };

View file

@ -0,0 +1,10 @@
import { Light } from '../../../src/Three';
export class ShadowMapViewer {
constructor( light: Light )
}

View file

@ -0,0 +1,207 @@
import {
DoubleSide,
LinearFilter,
Mesh,
MeshBasicMaterial,
OrthographicCamera,
PlaneGeometry,
Scene,
ShaderMaterial,
Texture,
UniformsUtils
} from '../../../build/three.module.js';
import { UnpackDepthRGBAShader } from '../shaders/UnpackDepthRGBAShader.js';
/**
* This is a helper for visualising a given light's shadow map.
* It works for shadow casting lights: DirectionalLight and SpotLight.
* It renders out the shadow map and displays it on a HUD.
*
* Example usage:
* 1) Import ShadowMapViewer into your app.
*
* 2) Create a shadow casting light and name it optionally:
* var light = new DirectionalLight( 0xffffff, 1 );
* light.castShadow = true;
* light.name = 'Sun';
*
* 3) Create a shadow map viewer for that light and set its size and position optionally:
* var shadowMapViewer = new ShadowMapViewer( light );
* shadowMapViewer.size.set( 128, 128 ); //width, height default: 256, 256
* shadowMapViewer.position.set( 10, 10 ); //x, y in pixel default: 0, 0 (top left corner)
*
* 4) Render the shadow map viewer in your render loop:
* shadowMapViewer.render( renderer );
*
* 5) Optionally: Update the shadow map viewer on window resize:
* shadowMapViewer.updateForWindowResize();
*
* 6) If you set the position or size members directly, you need to call shadowMapViewer.update();
*/
var ShadowMapViewer = function ( light ) {
//- Internals
var scope = this;
var doRenderLabel = ( light.name !== undefined && light.name !== '' );
var userAutoClearSetting;
//Holds the initial position and dimension of the HUD
var frame = {
x: 10,
y: 10,
width: 256,
height: 256
};
var camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 10 );
camera.position.set( 0, 0, 2 );
var scene = new Scene();
//HUD for shadow map
var shader = UnpackDepthRGBAShader;
var uniforms = UniformsUtils.clone( shader.uniforms );
var material = new ShaderMaterial( {
uniforms: uniforms,
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader
} );
var plane = new PlaneGeometry( frame.width, frame.height );
var mesh = new Mesh( plane, material );
scene.add( mesh );
//Label for light's name
var labelCanvas, labelMesh;
if ( doRenderLabel ) {
labelCanvas = document.createElement( 'canvas' );
var context = labelCanvas.getContext( '2d' );
context.font = 'Bold 20px Arial';
var labelWidth = context.measureText( light.name ).width;
labelCanvas.width = labelWidth;
labelCanvas.height = 25; //25 to account for g, p, etc.
context.font = 'Bold 20px Arial';
context.fillStyle = 'rgba( 255, 0, 0, 1 )';
context.fillText( light.name, 0, 20 );
var labelTexture = new Texture( labelCanvas );
labelTexture.magFilter = LinearFilter;
labelTexture.minFilter = LinearFilter;
labelTexture.needsUpdate = true;
var labelMaterial = new MeshBasicMaterial( { map: labelTexture, side: DoubleSide } );
labelMaterial.transparent = true;
var labelPlane = new PlaneGeometry( labelCanvas.width, labelCanvas.height );
labelMesh = new Mesh( labelPlane, labelMaterial );
scene.add( labelMesh );
}
function resetPosition() {
scope.position.set( scope.position.x, scope.position.y );
}
//- API
// Set to false to disable displaying this shadow map
this.enabled = true;
// Set the size of the displayed shadow map on the HUD
this.size = {
width: frame.width,
height: frame.height,
set: function ( width, height ) {
this.width = width;
this.height = height;
mesh.scale.set( this.width / frame.width, this.height / frame.height, 1 );
//Reset the position as it is off when we scale stuff
resetPosition();
}
};
// Set the position of the displayed shadow map on the HUD
this.position = {
x: frame.x,
y: frame.y,
set: function ( x, y ) {
this.x = x;
this.y = y;
var width = scope.size.width;
var height = scope.size.height;
mesh.position.set( - window.innerWidth / 2 + width / 2 + this.x, window.innerHeight / 2 - height / 2 - this.y, 0 );
if ( doRenderLabel ) labelMesh.position.set( mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0 );
}
};
this.render = function ( renderer ) {
if ( this.enabled ) {
//Because a light's .shadowMap is only initialised after the first render pass
//we have to make sure the correct map is sent into the shader, otherwise we
//always end up with the scene's first added shadow casting light's shadowMap
//in the shader
//See: https://github.com/mrdoob/three.js/issues/5932
uniforms.tDiffuse.value = light.shadow.map.texture;
userAutoClearSetting = renderer.autoClear;
renderer.autoClear = false; // To allow render overlay
renderer.clearDepth();
renderer.render( scene, camera );
renderer.autoClear = userAutoClearSetting; //Restore user's setting
}
};
this.updateForWindowResize = function () {
if ( this.enabled ) {
camera.left = window.innerWidth / - 2;
camera.right = window.innerWidth / 2;
camera.top = window.innerHeight / 2;
camera.bottom = window.innerHeight / - 2;
camera.updateProjectionMatrix();
this.update();
}
};
this.update = function () {
this.position.set( this.position.x, this.position.y );
this.size.set( this.size.width, this.size.height );
};
//Force an update to set position/size
this.update();
};
ShadowMapViewer.prototype.constructor = ShadowMapViewer;
export { ShadowMapViewer };

View file

@ -0,0 +1,32 @@
import { AnimationClip, Bone, Matrix4, Object3D, Skeleton, SkeletonHelper } from '../../../src/Three';
export namespace SkeletonUtils {
export function retarget( target: Object3D | Skeleton,
source: Object3D | Skeleton,
options: {} ): void;
export function retargetClip( target: Skeleton | Object3D,
source: Skeleton | Object3D,
clip: AnimationClip,
options: {} ): AnimationClip;
export function getHelperFromSkeleton( skeleton: Skeleton ): SkeletonHelper;
export function getSkeletonOffsets( target: Object3D | Skeleton,
source: Object3D | Skeleton,
options: {} ): Matrix4[];
export function renameBones( skeleton: Skeleton, names: {} ): any;
export function getBones( skeleton: Skeleton | Bone[] ): Bone[];
export function getBoneByName( name: string, skeleton: Skeleton ): Bone;
export function getNearestBone( bone: Bone, names: {} ): Bone;
export function findBoneTrackData( name: string, tracks: any[] ): {};
export function getEqualsBonesNames( skeleton: Skeleton, targetSkeleton: Skeleton ): string[];
export function clone( source: Object3D ): Object3D;
}

594
node_modules/three/examples/jsm/utils/SkeletonUtils.js generated vendored Normal file
View file

@ -0,0 +1,594 @@
import {
AnimationClip,
AnimationMixer,
Euler,
Matrix4,
Quaternion,
QuaternionKeyframeTrack,
SkeletonHelper,
Vector2,
Vector3,
VectorKeyframeTrack
} from '../../../build/three.module.js';
var SkeletonUtils = {
retarget: function () {
var pos = new Vector3(),
quat = new Quaternion(),
scale = new Vector3(),
bindBoneMatrix = new Matrix4(),
relativeMatrix = new Matrix4(),
globalMatrix = new Matrix4();
return function ( target, source, options ) {
options = options || {};
options.preserveMatrix = options.preserveMatrix !== undefined ? options.preserveMatrix : true;
options.preservePosition = options.preservePosition !== undefined ? options.preservePosition : true;
options.preserveHipPosition = options.preserveHipPosition !== undefined ? options.preserveHipPosition : false;
options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
options.hip = options.hip !== undefined ? options.hip : 'hip';
options.names = options.names || {};
var sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones( source ),
bones = target.isObject3D ? target.skeleton.bones : this.getBones( target ),
bindBones,
bone, name, boneTo,
bonesPosition, i;
// reset bones
if ( target.isObject3D ) {
target.skeleton.pose();
} else {
options.useTargetMatrix = true;
options.preserveMatrix = false;
}
if ( options.preservePosition ) {
bonesPosition = [];
for ( i = 0; i < bones.length; i ++ ) {
bonesPosition.push( bones[ i ].position.clone() );
}
}
if ( options.preserveMatrix ) {
// reset matrix
target.updateMatrixWorld();
target.matrixWorld.identity();
// reset children matrix
for ( i = 0; i < target.children.length; ++ i ) {
target.children[ i ].updateMatrixWorld( true );
}
}
if ( options.offsets ) {
bindBones = [];
for ( i = 0; i < bones.length; ++ i ) {
bone = bones[ i ];
name = options.names[ bone.name ] || bone.name;
if ( options.offsets && options.offsets[ name ] ) {
bone.matrix.multiply( options.offsets[ name ] );
bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
bone.updateMatrixWorld();
}
bindBones.push( bone.matrixWorld.clone() );
}
}
for ( i = 0; i < bones.length; ++ i ) {
bone = bones[ i ];
name = options.names[ bone.name ] || bone.name;
boneTo = this.getBoneByName( name, sourceBones );
globalMatrix.copy( bone.matrixWorld );
if ( boneTo ) {
boneTo.updateMatrixWorld();
if ( options.useTargetMatrix ) {
relativeMatrix.copy( boneTo.matrixWorld );
} else {
relativeMatrix.copy( target.matrixWorld ).invert();
relativeMatrix.multiply( boneTo.matrixWorld );
}
// ignore scale to extract rotation
scale.setFromMatrixScale( relativeMatrix );
relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
// apply to global matrix
globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
if ( target.isObject3D ) {
var boneIndex = bones.indexOf( bone ),
wBindMatrix = bindBones ? bindBones[ boneIndex ] : bindBoneMatrix.copy( target.skeleton.boneInverses[ boneIndex ] ).invert();
globalMatrix.multiply( wBindMatrix );
}
globalMatrix.copyPosition( relativeMatrix );
}
if ( bone.parent && bone.parent.isBone ) {
bone.matrix.copy( bone.parent.matrixWorld ).invert();
bone.matrix.multiply( globalMatrix );
} else {
bone.matrix.copy( globalMatrix );
}
if ( options.preserveHipPosition && name === options.hip ) {
bone.matrix.setPosition( pos.set( 0, bone.position.y, 0 ) );
}
bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
bone.updateMatrixWorld();
}
if ( options.preservePosition ) {
for ( i = 0; i < bones.length; ++ i ) {
bone = bones[ i ];
name = options.names[ bone.name ] || bone.name;
if ( name !== options.hip ) {
bone.position.copy( bonesPosition[ i ] );
}
}
}
if ( options.preserveMatrix ) {
// restore matrix
target.updateMatrixWorld( true );
}
};
}(),
retargetClip: function ( target, source, clip, options ) {
options = options || {};
options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
options.fps = options.fps !== undefined ? options.fps : 30;
options.names = options.names || [];
if ( ! source.isObject3D ) {
source = this.getHelperFromSkeleton( source );
}
var numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
delta = 1 / options.fps,
convertedTracks = [],
mixer = new AnimationMixer( source ),
bones = this.getBones( target.skeleton ),
boneDatas = [],
positionOffset,
bone, boneTo, boneData,
name, i, j;
mixer.clipAction( clip ).play();
mixer.update( 0 );
source.updateMatrixWorld();
for ( i = 0; i < numFrames; ++ i ) {
var time = i * delta;
this.retarget( target, source, options );
for ( j = 0; j < bones.length; ++ j ) {
name = options.names[ bones[ j ].name ] || bones[ j ].name;
boneTo = this.getBoneByName( name, source.skeleton );
if ( boneTo ) {
bone = bones[ j ];
boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
if ( options.hip === name ) {
if ( ! boneData.pos ) {
boneData.pos = {
times: new Float32Array( numFrames ),
values: new Float32Array( numFrames * 3 )
};
}
if ( options.useFirstFramePosition ) {
if ( i === 0 ) {
positionOffset = bone.position.clone();
}
bone.position.sub( positionOffset );
}
boneData.pos.times[ i ] = time;
bone.position.toArray( boneData.pos.values, i * 3 );
}
if ( ! boneData.quat ) {
boneData.quat = {
times: new Float32Array( numFrames ),
values: new Float32Array( numFrames * 4 )
};
}
boneData.quat.times[ i ] = time;
bone.quaternion.toArray( boneData.quat.values, i * 4 );
}
}
mixer.update( delta );
source.updateMatrixWorld();
}
for ( i = 0; i < boneDatas.length; ++ i ) {
boneData = boneDatas[ i ];
if ( boneData ) {
if ( boneData.pos ) {
convertedTracks.push( new VectorKeyframeTrack(
'.bones[' + boneData.bone.name + '].position',
boneData.pos.times,
boneData.pos.values
) );
}
convertedTracks.push( new QuaternionKeyframeTrack(
'.bones[' + boneData.bone.name + '].quaternion',
boneData.quat.times,
boneData.quat.values
) );
}
}
mixer.uncacheAction( clip );
return new AnimationClip( clip.name, - 1, convertedTracks );
},
getHelperFromSkeleton: function ( skeleton ) {
var source = new SkeletonHelper( skeleton.bones[ 0 ] );
source.skeleton = skeleton;
return source;
},
getSkeletonOffsets: function () {
var targetParentPos = new Vector3(),
targetPos = new Vector3(),
sourceParentPos = new Vector3(),
sourcePos = new Vector3(),
targetDir = new Vector2(),
sourceDir = new Vector2();
return function ( target, source, options ) {
options = options || {};
options.hip = options.hip !== undefined ? options.hip : 'hip';
options.names = options.names || {};
if ( ! source.isObject3D ) {
source = this.getHelperFromSkeleton( source );
}
var nameKeys = Object.keys( options.names ),
nameValues = Object.values( options.names ),
sourceBones = source.isObject3D ? source.skeleton.bones : this.getBones( source ),
bones = target.isObject3D ? target.skeleton.bones : this.getBones( target ),
offsets = [],
bone, boneTo,
name, i;
target.skeleton.pose();
for ( i = 0; i < bones.length; ++ i ) {
bone = bones[ i ];
name = options.names[ bone.name ] || bone.name;
boneTo = this.getBoneByName( name, sourceBones );
if ( boneTo && name !== options.hip ) {
var boneParent = this.getNearestBone( bone.parent, nameKeys ),
boneToParent = this.getNearestBone( boneTo.parent, nameValues );
boneParent.updateMatrixWorld();
boneToParent.updateMatrixWorld();
targetParentPos.setFromMatrixPosition( boneParent.matrixWorld );
targetPos.setFromMatrixPosition( bone.matrixWorld );
sourceParentPos.setFromMatrixPosition( boneToParent.matrixWorld );
sourcePos.setFromMatrixPosition( boneTo.matrixWorld );
targetDir.subVectors(
new Vector2( targetPos.x, targetPos.y ),
new Vector2( targetParentPos.x, targetParentPos.y )
).normalize();
sourceDir.subVectors(
new Vector2( sourcePos.x, sourcePos.y ),
new Vector2( sourceParentPos.x, sourceParentPos.y )
).normalize();
var laterialAngle = targetDir.angle() - sourceDir.angle();
var offset = new Matrix4().makeRotationFromEuler(
new Euler(
0,
0,
laterialAngle
)
);
bone.matrix.multiply( offset );
bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
bone.updateMatrixWorld();
offsets[ name ] = offset;
}
}
return offsets;
};
}(),
renameBones: function ( skeleton, names ) {
var bones = this.getBones( skeleton );
for ( var i = 0; i < bones.length; ++ i ) {
var bone = bones[ i ];
if ( names[ bone.name ] ) {
bone.name = names[ bone.name ];
}
}
return this;
},
getBones: function ( skeleton ) {
return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
},
getBoneByName: function ( name, skeleton ) {
for ( var i = 0, bones = this.getBones( skeleton ); i < bones.length; i ++ ) {
if ( name === bones[ i ].name )
return bones[ i ];
}
},
getNearestBone: function ( bone, names ) {
while ( bone.isBone ) {
if ( names.indexOf( bone.name ) !== - 1 ) {
return bone;
}
bone = bone.parent;
}
},
findBoneTrackData: function ( name, tracks ) {
var regexp = /\[(.*)\]\.(.*)/,
result = { name: name };
for ( var i = 0; i < tracks.length; ++ i ) {
// 1 is track name
// 2 is track type
var trackData = regexp.exec( tracks[ i ].name );
if ( trackData && name === trackData[ 1 ] ) {
result[ trackData[ 2 ] ] = i;
}
}
return result;
},
getEqualsBonesNames: function ( skeleton, targetSkeleton ) {
var sourceBones = this.getBones( skeleton ),
targetBones = this.getBones( targetSkeleton ),
bones = [];
search : for ( var i = 0; i < sourceBones.length; i ++ ) {
var boneName = sourceBones[ i ].name;
for ( var j = 0; j < targetBones.length; j ++ ) {
if ( boneName === targetBones[ j ].name ) {
bones.push( boneName );
continue search;
}
}
}
return bones;
},
clone: function ( source ) {
var sourceLookup = new Map();
var cloneLookup = new Map();
var clone = source.clone();
parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
sourceLookup.set( clonedNode, sourceNode );
cloneLookup.set( sourceNode, clonedNode );
} );
clone.traverse( function ( node ) {
if ( ! node.isSkinnedMesh ) return;
var clonedMesh = node;
var sourceMesh = sourceLookup.get( node );
var sourceBones = sourceMesh.skeleton.bones;
clonedMesh.skeleton = sourceMesh.skeleton.clone();
clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
return cloneLookup.get( bone );
} );
clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
} );
return clone;
}
};
function parallelTraverse( a, b, callback ) {
callback( a, b );
for ( var i = 0; i < a.children.length; i ++ ) {
parallelTraverse( a.children[ i ], b.children[ i ], callback );
}
}
export { SkeletonUtils };

3
node_modules/three/examples/jsm/utils/UVsDebug.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import { Geometry } from '../../../src/Three';
export function UVsDebug( geometry: Geometry, size: number ): HTMLCanvasElement;

174
node_modules/three/examples/jsm/utils/UVsDebug.js generated vendored Normal file
View file

@ -0,0 +1,174 @@
import {
Vector2
} from '../../../build/three.module.js';
/**
* tool for "unwrapping" and debugging three.js geometries UV mapping
*
* Sample usage:
* document.body.appendChild( UVsDebug( new THREE.SphereGeometry( 10, 10, 10, 10 ) );
*
*/
var UVsDebug = function ( geometry, size ) {
// handles wrapping of uv.x > 1 only
var abc = 'abc';
var a = new Vector2();
var b = new Vector2();
var uvs = [
new Vector2(),
new Vector2(),
new Vector2()
];
var face = [];
var canvas = document.createElement( 'canvas' );
var width = size || 1024; // power of 2 required for wrapping
var height = size || 1024;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext( '2d' );
ctx.lineWidth = 1;
ctx.strokeStyle = 'rgb( 63, 63, 63 )';
ctx.textAlign = 'center';
// paint background white
ctx.fillStyle = 'rgb( 255, 255, 255 )';
ctx.fillRect( 0, 0, width, height );
if ( geometry.isGeometry ) {
console.error( 'THREE.UVsDebug no longer supports Geometry. Use THREE.BufferGeometry instead.' );
return;
} else {
var index = geometry.index;
var uvAttribute = geometry.attributes.uv;
if ( index ) {
// indexed geometry
for ( var i = 0, il = index.count; i < il; i += 3 ) {
face[ 0 ] = index.getX( i );
face[ 1 ] = index.getX( i + 1 );
face[ 2 ] = index.getX( i + 2 );
uvs[ 0 ].fromBufferAttribute( uvAttribute, face[ 0 ] );
uvs[ 1 ].fromBufferAttribute( uvAttribute, face[ 1 ] );
uvs[ 2 ].fromBufferAttribute( uvAttribute, face[ 2 ] );
processFace( face, uvs, i / 3 );
}
} else {
// non-indexed geometry
for ( var i = 0, il = uvAttribute.count; i < il; i += 3 ) {
face[ 0 ] = i;
face[ 1 ] = i + 1;
face[ 2 ] = i + 2;
uvs[ 0 ].fromBufferAttribute( uvAttribute, face[ 0 ] );
uvs[ 1 ].fromBufferAttribute( uvAttribute, face[ 1 ] );
uvs[ 2 ].fromBufferAttribute( uvAttribute, face[ 2 ] );
processFace( face, uvs, i / 3 );
}
}
}
return canvas;
function processFace( face, uvs, index ) {
// draw contour of face
ctx.beginPath();
a.set( 0, 0 );
for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
var uv = uvs[ j ];
a.x += uv.x;
a.y += uv.y;
if ( j === 0 ) {
ctx.moveTo( uv.x * ( width - 2 ) + 0.5, ( 1 - uv.y ) * ( height - 2 ) + 0.5 );
} else {
ctx.lineTo( uv.x * ( width - 2 ) + 0.5, ( 1 - uv.y ) * ( height - 2 ) + 0.5 );
}
}
ctx.closePath();
ctx.stroke();
// calculate center of face
a.divideScalar( uvs.length );
// label the face number
ctx.font = '18px Arial';
ctx.fillStyle = 'rgb( 63, 63, 63 )';
ctx.fillText( index, a.x * width, ( 1 - a.y ) * height );
if ( a.x > 0.95 ) {
// wrap x // 0.95 is arbitrary
ctx.fillText( index, ( a.x % 1 ) * width, ( 1 - a.y ) * height );
}
//
ctx.font = '12px Arial';
ctx.fillStyle = 'rgb( 191, 191, 191 )';
// label uv edge orders
for ( j = 0, jl = uvs.length; j < jl; j ++ ) {
var uv = uvs[ j ];
b.addVectors( a, uv ).divideScalar( 2 );
var vnum = face[ j ];
ctx.fillText( abc[ j ] + vnum, b.x * width, ( 1 - b.y ) * height );
if ( b.x > 0.95 ) {
// wrap x
ctx.fillText( abc[ j ] + vnum, ( b.x % 1 ) * width, ( 1 - b.y ) * height );
}
}
}
};
export { UVsDebug };