tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

76 lignes · 2559 octetsBrut · Historique
1<script lang="ts">
2 import { T, useTask } from '@threlte/core';
3 import { useGltf, type IntersectionEvent } from '@threlte/extras';
4 import { untrack } from 'svelte';
5 import * as THREE from 'three';
6 import { MODELS, hash, mulberry32 } from '$lib/assets/manifest';
7
8 interface Props {
9 symbol: string;
10 position: [number, number, number];
11 onclick?: (e: IntersectionEvent<MouseEvent>) => void;
12 }
13
14 let { symbol, position, onclick }: Props = $props();
15
16 // The rock model is fixed per field symbol; a field never changes symbol while mounted
17 // (it is keyed by symbol in the parent), so reading it once is intended.
18 const gltf = useGltf(MODELS.rocks[hash(untrack(() => symbol)) % MODELS.rocks.length]);
19
20 const COUNT = 42;
21 let group = $state<THREE.Group>();
22 let inst = $state<THREE.InstancedMesh | null>(null);
23
24 // Build the instanced field once the rock model arrives.
25 $effect(() => {
26 const g = $gltf;
27 if (!g || inst) return;
28 let source: THREE.Mesh | null = null;
29 g.scene.updateMatrixWorld(true);
30 g.scene.traverse((o) => {
31 if (!source && (o as THREE.Mesh).isMesh) source = o as THREE.Mesh;
32 });
33 if (!source) return;
34 const src: THREE.Mesh = source;
35
36 // The GLB node may carry its own scale/rotation; bake it into a private copy of the
37 // geometry so every instance matches how the model looks on its own.
38 const geo = src.geometry.clone().applyMatrix4(src.matrixWorld);
39 const mesh = new THREE.InstancedMesh(geo, src.material as THREE.Material, COUNT);
40 const rng = mulberry32(hash(symbol));
41 const dummy = new THREE.Object3D();
42 for (let i = 0; i < COUNT; i++) {
43 const angle = rng() * Math.PI * 2;
44 const radius = 4 + rng() * 9;
45 dummy.position.set(Math.cos(angle) * radius, (rng() - 0.5) * 4, Math.sin(angle) * radius);
46 dummy.rotation.set(rng() * Math.PI * 2, rng() * Math.PI * 2, rng() * Math.PI * 2);
47 dummy.scale.setScalar(0.3 + rng() * 0.9);
48 dummy.updateMatrix();
49 mesh.setMatrixAt(i, dummy.matrix);
50 }
51 mesh.instanceMatrix.needsUpdate = true;
52 mesh.computeBoundingSphere(); // raycasting needs the instances' bounds, not one rock's
53 inst = mesh;
54 });
55
56 // Free our geometry copy and the instance buffer; the material belongs to the cached GLTF.
57 $effect(() => {
58 const mesh = inst;
59 if (!mesh) return;
60 return () => {
61 mesh.geometry.dispose();
62 mesh.dispose();
63 };
64 });
65
66 // slow tumble of the whole belt
67 useTask((delta) => {
68 if (group) group.rotation.y += delta * 0.02;
69 });
70</script>
71
72<T.Group {position} bind:ref={group}>
73 {#if inst}
74 <T is={inst} {onclick} />
75 {/if}
76</T.Group>