I added the following Center.js file to my project.
import { Box3, Vector3, Sphere, Group } from 'three'
import * as React from 'react'
import { useThree } from '@react-three/fiber'
export const Center = React.forwardRef(function Center(
{
children,
disable,
disableX,
disableY,
disableZ,
left,
right,
top,
bottom,
front,
back,
onCentered,
precise = true,
cacheKey = 0,
...props
},
fRef
) {
const ref = React.useRef(null)
const outer = React.useRef(null)
const inner = React.useRef(null)
React.useLayoutEffect(() => {
outer.current.matrixWorld.identity()
const box3 = new Box3().setFromObject(inner.current, precise)
const center = new Vector3()
const sphere = new Sphere()
const width = box3.max.x - box3.min.x
const height = box3.max.y - box3.min.y
const depth = box3.max.z - box3.min.z
box3.getCenter(center)
box3.getBoundingSphere(sphere)
const vAlign = top ? height / 2 : bottom ? -height / 2 : 0
const hAlign = left ? -width / 2 : right ? width / 2 : 0
const dAlign = front ? depth / 2 : back ? -depth / 2 : 0
outer.current.position.set(
disable || disableX ? 0 : -center.x + hAlign,
disable || disableY ? 0 : -center.y + vAlign,
disable || disableZ ? 0 : -center.z + dAlign
)
// Only fire onCentered if the bounding box has changed
if (typeof onCentered !== 'undefined') {
onCentered({
parent: ref.current.parent,
container: ref.current,
width,
height,
depth,
boundingBox: box3,
boundingSphere: sphere,
center: center,
verticalAlignment: vAlign,
horizontalAlignment: hAlign,
depthAlignment: dAlign,
})
}
}, [cacheKey, onCentered, top, left, front, disable, disableX, disableY, disableZ, precise, right, bottom, back])
React.useImperativeHandle(fRef, () => ref.current, [])
return (
<group ref={ref} {...props}>
<group ref={outer}>
<group ref={inner}>{children}</group>
</group>
</group>
)
})
Then used it in the following manner.
<Canvas>
<Center>
<mesh ref={meshReference} {...props}>
<primitive object={geometry} attach="geometry" />
<meshNormalMaterial />
</mesh>
</Center>
</Canvas>
However, It is still not centered
Note that THREE.BufferGeometry.computeBoundingSphere()
is still NaN and I can’t figure out how. Nothing I do is working and it is something as simple as finding the center of the shape. I can import the file, put it on the screen, but past that nothing works. Can’t center it, can’t compute the bounding sphere, can’t find the object center.
For example:
meshReference.current.geometry.computeBoundingBox()
meshReference.current.geometry.computeBoundingSphere();
let size = new Vector3()
meshReference.current.geometry.boundingBox.getCenter(size)
console.log("Size: " + JSON.stringify(size))
size is apparently 0,0,0 for the shape above, which makes no sense