Skip to content

Commit fb405ea

Browse files
authored
Merge pull request #17939 from zeux/gltf-bounds
GLTFLoader: Pre-compute geometry bounds using attribute min/max
2 parents e761d60 + 02a8d5c commit fb405ea

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

examples/js/loaders/GLTFLoader.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2267,6 +2267,72 @@ THREE.GLTFLoader = ( function () {
22672267

22682268
};
22692269

2270+
/**
2271+
* @param {THREE.BufferGeometry} geometry
2272+
* @param {GLTF.Primitive} primitiveDef
2273+
* @param {GLTFParser} parser
2274+
*/
2275+
function computeBounds( geometry, primitiveDef, parser ) {
2276+
2277+
var attributes = primitiveDef.attributes;
2278+
2279+
var box = new THREE.Box3();
2280+
2281+
if ( attributes.POSITION !== undefined ) {
2282+
2283+
var accessor = parser.json.accessors[ attributes.POSITION ];
2284+
var min = accessor.min;
2285+
var max = accessor.max;
2286+
2287+
box.set(
2288+
new THREE.Vector3( min[0], min[1], min[2] ),
2289+
new THREE.Vector3( max[0], max[1], max[2] ) );
2290+
2291+
} else {
2292+
2293+
return;
2294+
}
2295+
2296+
var targets = primitiveDef.targets;
2297+
2298+
if ( targets !== undefined ) {
2299+
2300+
var vector = new THREE.Vector3();
2301+
2302+
for ( var i = 0, il = targets.length; i < il; i ++ ) {
2303+
2304+
var target = targets[ i ];
2305+
2306+
if ( target.POSITION !== undefined ) {
2307+
2308+
var accessor = parser.json.accessors[ target.POSITION ];
2309+
var min = accessor.min;
2310+
var max = accessor.max;
2311+
2312+
// we need to get max of absolute components because target weight is [-1,1]
2313+
vector.setX( Math.max( Math.abs( min[0] ), Math.abs( max[0] ) ) );
2314+
vector.setY( Math.max( Math.abs( min[1] ), Math.abs( max[1] ) ) );
2315+
vector.setZ( Math.max( Math.abs( min[2] ), Math.abs( max[2] ) ) );
2316+
2317+
box.expandByVector( vector );
2318+
2319+
}
2320+
2321+
}
2322+
2323+
}
2324+
2325+
geometry.boundingBox = box;
2326+
2327+
var sphere = new THREE.Sphere();
2328+
2329+
box.getCenter( sphere.center );
2330+
sphere.radius = box.min.distanceTo( box.max ) / 2;
2331+
2332+
geometry.boundingSphere = sphere;
2333+
2334+
}
2335+
22702336
/**
22712337
* @param {THREE.BufferGeometry} geometry
22722338
* @param {GLTF.Primitive} primitiveDef
@@ -2315,6 +2381,8 @@ THREE.GLTFLoader = ( function () {
23152381

23162382
assignExtrasToUserData( geometry, primitiveDef );
23172383

2384+
computeBounds( geometry, primitiveDef, parser );
2385+
23182386
return Promise.all( pending ).then( function () {
23192387

23202388
return primitiveDef.targets !== undefined

0 commit comments

Comments
 (0)