diff --git a/src/App.tsx b/src/App.tsx index 162453d..57ebeb3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,6 @@ import * as THREE from "three"; import { useState, useEffect } from "react"; -import { Canvas } from "@react-three/fiber"; +import { Canvas, applyProps, useFrame, useLoader, useGraph } from '@react-three/fiber' import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader"; import { OrbitControls } from "@react-three/drei"; import { Suspense } from "react"; @@ -8,60 +8,26 @@ import { BufferAttribute } from "three"; import "./App.css"; +// Function to add vertex colors to the geometry const Scene = ({ file }: { file: string }) => { - const [obj, setObj] = useState(null); - - useEffect(() => { - const loader = new OBJLoader(); - - loader.load(file, (obj) => { - // Create a material with vertex colors - const material = new THREE.MeshPhysicalMaterial({ vertexColors: true, - side:THREE.FrontSide, - metalness: 1.0, - roughness: 0.3 }); - - // For each child of the loaded object, assign the new material and add vertex colors - obj.traverse((child) => { - if (child instanceof THREE.Mesh) { - child.material = material; - child.geometry = addVertexColors(child.geometry); - //child.geometry.computeVertexNormals(); - } - }); - - setObj(obj); + //load the obj file + const obj: THREE.Group = useLoader(OBJLoader, file) + //create a material with vertex colors + const material: THREE.MeshPhysicalMaterial = new THREE.MeshPhysicalMaterial({ + vertexColors: true, + side: THREE.FrontSide, + metalness: 1.0, + roughness: 0.3 }); - }, [file]); - - // Function to add vertex colors to the geometry - const addVertexColors = (geometry: any) => { - // Create a new buffer attribute for the vertex colors - const colorAttribute = new BufferAttribute( - new Float32Array(geometry.attributes.position.count * 3), - 3 - ); - - // For each vertex, get the color from the obj file and assign it to the new color attribute - for (let i = 0; i < geometry.attributes.position.count; i++) { - const vertexColor = geometry.attributes.color.array.slice( - i * 3, - i * 3 + 3 - ); - colorAttribute.setXYZ( - i, - vertexColor[0], - vertexColor[1], - vertexColor[2] - ); + //for each child of the loaded object, assign the new material and add vertex colors + obj.traverse((child: THREE.Object3D) => { + if (child instanceof THREE.Mesh) { + child.material = material; } + }); + //return the object + return - // Add the new color attribute to the geometry and return it - geometry.setAttribute("color", colorAttribute); - return geometry; - }; - - return obj ? : null; }; const App = () => {