Skip to content

Commit

Permalink
Fixes issue with framing a quantized GLTF
Browse files Browse the repository at this point in the history
fixes #2450
  • Loading branch information
SrirachaSource committed Jun 8, 2021
1 parent 067e36b commit dc1824a
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions packages/model-viewer/src/three-components/ModelUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Object3D, Vector3} from 'three';
import {BufferAttribute, InterleavedBufferAttribute, Object3D, Vector3} from 'three';


/**
* Gets a scale value to perform inverse quantization of a vertex value
* Reference:
* https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
* @param buffer A gltf vertex buffer
* @returns A scale value based on KHR_mesh_quantization or 1 if the buffer is
* not quantized.
*/
export const getNormalizedComponentScale =
(buffer: BufferAttribute|InterleavedBufferAttribute) => {
const array: ArrayLike<number> = buffer.array;

if (array instanceof Int8Array) {
return 1 / 127;
} else if (array instanceof Uint8Array) {
return 1 / 255;
} else if (array instanceof Int16Array) {
return 1 / 32767;
} else if (array instanceof Uint16Array) {
return 1 / 65535;
}

return 1;
};
/**
* Moves Three.js objects from one parent to another
*/
Expand Down Expand Up @@ -49,17 +74,21 @@ export const reduceVertices = <T>(
for (i = 0, l = vertices.length; i < l; i++) {
vertex.copy(vertices[i]);
vertex.applyMatrix4(object.matrixWorld);

value = func(value, vertex);
}

} else if (geometry.isBufferGeometry) {
const {position} = geometry.attributes;

if (position !== undefined) {
const scale = getNormalizedComponentScale(position);

for (i = 0, l = position.count; i < l; i++) {
vertex.fromBufferAttribute(position, i)
.applyMatrix4(object.matrixWorld);
vertex.fromBufferAttribute(position, i);
if (position.normalized) {
vertex.multiplyScalar(scale);
}
vertex.applyMatrix4(object.matrixWorld);

value = func(value, vertex);
}
Expand Down

0 comments on commit dc1824a

Please sign in to comment.