Skip to content

Commit

Permalink
v0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
caijie committed May 7, 2023
1 parent 35c5cd3 commit 880adfb
Showing 1 changed file with 17 additions and 51 deletions.
68 changes: 17 additions & 51 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,67 +1,33 @@
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";
import { BufferAttribute } from "three";

import "./App.css";

// Function to add vertex colors to the geometry
const Scene = ({ file }: { file: string }) => {
const [obj, setObj] = useState<THREE.Object3D | null>(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<THREE.Event>) => {
if (child instanceof THREE.Mesh) {
child.material = material;
}
});
//return the object
return <primitive object={obj} scale={0.05}/>

// Add the new color attribute to the geometry and return it
geometry.setAttribute("color", colorAttribute);
return geometry;
};

return obj ? <primitive object={obj} scale={0.05} /> : null;
};

const App = () => {
Expand Down

0 comments on commit 880adfb

Please sign in to comment.