Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/flo-bit/flo-bit.github.io. my personal website, w/ astro, svelte, tailwind, typescript, threlte flo-bit.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248import { BufferGeometry, Float32BufferAttribute, Mesh, MeshStandardMaterial, Object3D, Quaternion, Vector3, IcosahedronGeometry} from 'three';import { Biome, type BiomeOptions } from './biome';import { loadModels } from './models';
import { PlanetMaterialWithCaustics } from './materials/OceanCausticsMaterial';import { createAtmosphereMaterial } from './materials/AtmosphereMaterial';import { createBufferGeometry } from './helper/helper';
export type PlanetOptions = { scatter?: number;
ground?: number;
detail?: number;
atmosphere?: { enabled?: boolean; color?: Vector3; height?: number; };
material?: 'normal' | 'caustics';
biome?: BiomeOptions;};
export class Planet { worker: Worker;
callbacks: Record<number, (data: Mesh) => void>; requestId: number;
biome: Biome;
biomeOptions: BiomeOptions; options: PlanetOptions;
vegetationPositions?: Record<string, Vector3[]>;
constructor(options: PlanetOptions = {}) { this.options = options;
this.biome = new Biome(options.biome); this.biomeOptions = this.biome.options;
this.worker = new Worker(new URL('worker.ts', import.meta.url), { type: 'module' }); this.worker.onmessage = this.handleMessage.bind(this); this.callbacks = {}; this.requestId = 0; }
handleMessage(event: { data: { type: 'geometry'; data: { positions: number[]; colors: number[]; normals: number[]; oceanPositions: number[]; oceanColors: number[]; oceanNormals: number[]; vegetation: Record<string, Vector3[]>; oceanMorphPositions: number[]; oceanMorphNormals: number[]; }; requestId: number; }; }) { const { data, requestId } = event.data;
const callback = this.callbacks[requestId]; if (!callback) { console.error('No callback found for requestId:', requestId); return; }
const geometry = createBufferGeometry(data.positions, data.colors, data.normals);
const oceanGeometry = createBufferGeometry( data.oceanPositions, data.oceanColors, data.oceanNormals );
oceanGeometry.morphAttributes.position = [ new Float32BufferAttribute(data.oceanMorphPositions, 3) ]; oceanGeometry.morphAttributes.normal = [new Float32BufferAttribute(data.oceanMorphNormals, 3)];
this.vegetationPositions = data.vegetation;
const materialOptions = { vertexColors: true };
const material = this.options.material === 'caustics' ? new PlanetMaterialWithCaustics(materialOptions) : new MeshStandardMaterial(materialOptions);
const planetMesh = new Mesh(geometry, material); planetMesh.castShadow = true;
if (this.options.material === 'caustics') { planetMesh.onBeforeRender = (renderer, scene, camera, geometry, material) => { if (material instanceof PlanetMaterialWithCaustics) { material.update(); } }; }
const oceanMesh = new Mesh( oceanGeometry, new MeshStandardMaterial({ vertexColors: true, transparent: true, opacity: 0.7, metalness: 0.5, roughness: 0.5 }) );
planetMesh.add(oceanMesh); oceanMesh.onBeforeRender = (renderer, scene, camera, geometry, material) => { // update morph targets if (oceanMesh.morphTargetInfluences) oceanMesh.morphTargetInfluences[0] = Math.sin(performance.now() / 1000) * 0.5 + 0.5; };
if (this.options.atmosphere?.enabled !== false) { this.addAtmosphere(planetMesh); } callback(planetMesh);
delete this.callbacks[requestId]; }
async create(): Promise<Mesh> { // let collection = "stylized_nature";
const models = this.biomeOptions.vegetation?.items.map((item) => { return item.name; });
const loaded: Promise<Object3D[] | Mesh>[] = [];
for (const model of models ?? []) { const loadedModels = loadModels(model); //, collection); loaded.push(loadedModels); }
const planetPromise = this.createMesh(); loaded.push(planetPromise);
await Promise.all(loaded);
const planet = await planetPromise;
for (let i = 0; i < loaded.length - 1; i++) { const models = (await loaded[i]) as Object3D[]; const name = models[0].userData.name;
const positions = this.vegetationPositions?.[name];
if (!positions) continue;
let item = this.biomeOptions.vegetation?.items[i];
for (const position of positions) { const model = models[Math.floor(Math.random() * models.length)].clone(); model.position.set(0, 1, 0); this.updatePosition(model, new Vector3(position.x, position.y, position.z)); model.scale.setScalar(0.04);
model.traverse((child) => { if (child instanceof Mesh) { let color = item?.colors?.[child.material.name]; if (color?.array) { let randomColor = color.array[Math.floor(Math.random() * color.array.length)]; child.material.color.setHex(randomColor); }
if (child.material.name === 'Snow') { child.material.roughness = 0.2; child.material.color.setHex(0xffffff); } child.castShadow = false; child.receiveShadow = true; } }); planet.add(model); } }
return planetPromise; }
async createMesh(): Promise<Mesh> { return new Promise((resolve) => { const requestId = this.requestId++; this.callbacks[requestId] = resolve;
this.worker.postMessage({ type: 'createGeometry', requestId, data: this.options }); }); }
addAtmosphere(planet: Mesh) { // Create the atmosphere geometry const atmosphereGeometry = new IcosahedronGeometry( this.options.atmosphere?.height ?? 1.2, this.options.detail ?? 20 ); const atmosphere = new Mesh( atmosphereGeometry, createAtmosphereMaterial(this.options.atmosphere?.color, new Vector3(5, 2, 2)) ); atmosphere.renderOrder = 1; planet.add(atmosphere); }
updatePosition(item: Object3D, pos: Vector3) { item.position.copy(pos);
const currentRotation = new Quaternion(); const a = item.up.clone().normalize(); const b = pos.clone().normalize();
currentRotation.setFromUnitVectors(a, b);
item.quaternion.copy(currentRotation);
item.up = b; }}