@gigatrappeur/ldraw-index 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,269 @@
1
+ import LDrawParser, { type LengthUnit } from "@gigatrappeur/ldraw-parser"
2
+
3
+ import { buildPartMetadata, type PartBoundingBox, type PartMetadata } from "./part";
4
+ import { DB, type PartVariant } from "./db";
5
+ import { buildPartMaterial } from "./material";
6
+ import { convertFlatGeometry, SCALE_FROM_LDU, transformAabb, type GeometryOptions, type GeometryLengthUnit, type PartGeometry } from "./geometry";
7
+
8
+ export type { PartMetadata, LengthUnit }
9
+
10
+ export interface LdrawIndexOptions {
11
+ /**
12
+ * Dossier contenant les données d'indexation
13
+ */
14
+ dataDir: string
15
+ }
16
+
17
+
18
+ export interface SearchParams {
19
+ q?: string;
20
+ color?: number;
21
+ category?: string;
22
+ limit?: number;
23
+ offset?: number;
24
+ excludeStickers?: boolean;
25
+ }
26
+
27
+ export interface SearchResult {
28
+ items: Part[];
29
+ total: number;
30
+ limit: number;
31
+ offset: number;
32
+ }
33
+
34
+
35
+ export interface Part {
36
+ ldrawRef: string
37
+ name: string
38
+ category: string
39
+ tag: string | null
40
+ keywords: string[]
41
+ variants?: PartVariant[]
42
+ }
43
+
44
+ export interface Color {
45
+ code: number
46
+ name: string
47
+ color: string
48
+ material: {
49
+ name: string
50
+ color: [number, number, number]
51
+ metalness: number
52
+ roughness: number
53
+ transparent: boolean
54
+ opacity: number
55
+ depthWrite: boolean
56
+ side: 0 | 2
57
+ flatShading: boolean
58
+ emissive?: [number, number, number]
59
+ emissiveIntensity?: number
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Référence LDraw et sa boîte englobante (unité de sortie), issue du listing
65
+ * bulk — voir {@link LdrawIndex.getAllBoundingBoxes}.
66
+ */
67
+ export interface PartBoundingBoxEntry {
68
+ /** Reference LDraw de la pièce. */
69
+ ldrawRef: string
70
+ /** Boîte englobante axe-à-axe (min, max, size, center) dans l'unité de sortie. */
71
+ boundingBox: PartBoundingBox
72
+ }
73
+
74
+ export default class LdrawIndex {
75
+ private db: DB;
76
+ private parser: LDrawParser;
77
+
78
+ constructor(options: LdrawIndexOptions) {
79
+ this.db = new DB(options.dataDir + '/ldraw-data.sqlite')
80
+ this.parser = new LDrawParser({ libraryRoot: options.dataDir + '/ldraw' });
81
+ }
82
+
83
+ // Cache + génération (lecture + écriture)
84
+ async search(params: SearchParams): Promise<SearchResult> {
85
+ let items: Part[] = [];
86
+ let total = 0;
87
+ const limit = params.limit ?? 50;
88
+ const offset = params.offset ?? 0;
89
+
90
+ total = this.db.countDistinctFts(params.q || '', {
91
+ category: params.category,
92
+ color: params.color,
93
+ excludeStickers: params.excludeStickers,
94
+ });
95
+ const results = this.db.searchDistinct(params.q || '', {
96
+ category: params.category,
97
+ color: params.color,
98
+ excludeStickers: params.excludeStickers,
99
+ }, limit, offset);
100
+ items = results.map(r => ({
101
+ ldrawRef: r.ldrawRef,
102
+ name: r.name,
103
+ category: r.category,
104
+ tag: r.tag,
105
+ variants: r.variants,
106
+ keywords: r.keywords ? r.keywords.split(/[, ]/) : [],
107
+ }));
108
+
109
+ return {
110
+ items,
111
+ total,
112
+ limit,
113
+ offset,
114
+ };
115
+ }
116
+
117
+ async get(ref: string): Promise<PartMetadata> {
118
+ const part = this.db.getByLdrawRef(ref);
119
+ if (!part) {
120
+ throw new Error(`Part not found: ${ref}`);
121
+ }
122
+ return buildPartMetadata(this.db, part, this.parser.colorTable, this.parser);
123
+ }
124
+
125
+
126
+ async getByLegoRef(legoRef: string): Promise<{ ldrawRef: string, legoRef: string, color: number } | undefined> {
127
+ return this.db.getByLegoRef(legoRef);
128
+ }
129
+
130
+
131
+ /**
132
+ * Récupère la géométrie triangulée d'une pièce, jsonifiable, groupée par
133
+ * couleur et munie de son matériau : chaque mesh se monte directement en un
134
+ * `THREE.BufferGeometry` + matériau côté front.
135
+ *
136
+ * Nécessite `data/ldraw/` (le parsing des `.dat`).
137
+ *
138
+ * @param ref reference LDraw de la pièce
139
+ * @param options unité de sortie, repère (Y-up par défaut), weld des
140
+ * sommets (activé par défaut) et normales
141
+ */
142
+ async getGeometry(ref: string, options: GeometryOptions = {}): Promise<PartGeometry> {
143
+ const part = this.db.getByLdrawRef(ref);
144
+ if (!part) {
145
+ throw new Error(`Part not found: ${ref}`);
146
+ }
147
+
148
+ const parsed = await this.parser.parse(`${part.ldrawRef}.dat`);
149
+ return convertFlatGeometry(part.ldrawRef, parsed.geometry, options);
150
+ }
151
+
152
+
153
+ /**
154
+ * Récupère la boîte englobante de toutes les pièces du catalogue.
155
+ *
156
+ * Le parser calcule l'AABB au parse d'un `.dat` (aucune méthode bulk), donc
157
+ * on parcourt les refs de la DB en séquentiel et on parse chacune. Les
158
+ * pièces sans fichier `.dat` (ou en échec de parsing) sont ignorées.
159
+ *
160
+ * La transformée (unité + repère) est partagée avec `getGeometry` via
161
+ * {@link transformAabb} : le `boundingBox` retourné y est identique.
162
+ *
163
+ * Nécessite `data/ldraw/` (le parsing des `.dat`).
164
+ *
165
+ * @param options.unit unité de sortie des coordonnées (défaut : « studs »)
166
+ * @param options.yUp repère Y-up (défaut : « true », pareil que getGeometry)
167
+ */
168
+ async getAllBoundingBoxes(options: { unit?: GeometryLengthUnit; yUp?: boolean } = {}): Promise<PartBoundingBoxEntry[]> {
169
+ const unit = options.unit ?? "studs";
170
+ const yUp = options.yUp ?? true;
171
+ const scale = SCALE_FROM_LDU[unit];
172
+
173
+ const entries: PartBoundingBoxEntry[] = [];
174
+ for (const ref of this.db.getAllLdrawRefs()) {
175
+ try {
176
+ const { geometry: { aabb } } = await this.parser.parse(`${ref}.dat`);
177
+ entries.push({ ldrawRef: ref, boundingBox: transformAabb(aabb, scale, yUp) });
178
+ } catch {
179
+ // Pièce sans `.dat` (ou géométrie vide) : on l'ignore.
180
+ }
181
+ }
182
+ return entries;
183
+ }
184
+
185
+
186
+ async listCategories(): Promise<string[]> {
187
+ return this.db.getCategories();
188
+ }
189
+
190
+ async listColors(): Promise<Color[]> {
191
+ const colors: Color[] = [];
192
+
193
+ for (const [code, ldColor] of await this.parser.colorTable.getTable()) {
194
+ const [r, g, b, a] = ldColor.rgba;
195
+
196
+ // Métallicité / rugosité / emission sont dérivées de la finition LDraw.
197
+ // On les centralise dans buildPartMaterial pour ne pas les dupliquer.
198
+ const base = buildPartMaterial(ldColor, { side: "double", flatShading: true });
199
+
200
+ const newColor: Color = {
201
+ code,
202
+ name: ldColor.name,
203
+ color: `rgba(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)}, ${Math.round(a * 100) / 100})`,
204
+ material: {
205
+ name: `LDRAW-${code} - ${ldColor.name}`,
206
+ color: base.color,
207
+ metalness: base.metalness,
208
+ roughness: base.roughness,
209
+ transparent: base.transparent,
210
+ opacity: base.opacity,
211
+ depthWrite: a >= 1,
212
+ // alphaTest: 0.5
213
+ side: a >= 1 ? 2 : 0, //THREE.DoubleSide = 2 sinon 0
214
+ flatShading: base.flatShading,
215
+ },
216
+ }
217
+ if (base.emissiveIntensity && base.emissive) {
218
+ newColor.material.emissive = base.emissive
219
+ newColor.material.emissiveIntensity = base.emissiveIntensity;
220
+ }
221
+
222
+ colors.push(newColor)
223
+
224
+ }
225
+
226
+ return colors;
227
+ }
228
+
229
+ async generate(ref: string, format: "glb", options?: { color?: number, weld?: false | { smoothNormals?: boolean }, transmission?: boolean, normals?: boolean, unit?: LengthUnit }): Promise<Uint8Array<ArrayBuffer>>
230
+ async generate(ref: string, format: "svg" | "gltf", options?: { width?: number, azimuth?: number, elevation?: number, color?: number, weld?: false | { smoothNormals?: boolean }, transmission?: boolean, normals?: boolean }): Promise<string>
231
+ async generate(ref: string, format: "svg" | "glb" | "gltf", options?: { width?: number, azimuth?: number, elevation?: number, color?: number, weld?: false | { smoothNormals?: boolean }; transmission?: boolean; normals?: boolean, unit?: LengthUnit }): Promise<Uint8Array | string> {
232
+
233
+ const part = this.db.getByLdrawRef(ref);
234
+ if (!part) {
235
+ throw new Error(`Part not found: ${ref}`);
236
+ }
237
+
238
+ const result = await this.parser.parse(`${part.ldrawRef}.dat`, options?.color != undefined ? { defaultColor: options.color } : undefined);
239
+
240
+ let content: Uint8Array | string;
241
+ if (format == 'gltf') {
242
+ content = JSON.stringify(await result.toGltf({
243
+ transmission: options?.transmission ?? true,
244
+ weld: options?.weld ?? { smoothNormals: true },
245
+ normals: options?.normals ?? false
246
+ }))
247
+ } else if (format === "glb") {
248
+ content = await result.toGlb({
249
+ transmission: options?.transmission ?? true,
250
+ weld: options?.weld ?? { smoothNormals: true },
251
+ normals: options?.normals ?? false
252
+ }, options?.unit || 'studs');
253
+ } else {
254
+ content = result.toSvg({
255
+ width: options?.width ?? 512,
256
+ azimuth: options?.azimuth ?? 30,
257
+ elevation: options?.elevation ?? 15,
258
+ showEdges: false
259
+ });
260
+ }
261
+
262
+ return content;
263
+ }
264
+
265
+
266
+ close() {
267
+ this.db.internalDb.close();
268
+ }
269
+ }
@@ -0,0 +1,122 @@
1
+ // material.ts — Dérive un matériau PBR (jsonifiable) depuis une couleur LDraw.
2
+ //
3
+ // Réutilisé à la fois par `listColors()` (catalogue de couleurs) et par
4
+ // `getGeometry()` (matériau associé à chaque mesh d'une géométrie). Centralise
5
+ // la logique « finish LDraw → metalness / roughness » qui sinon serait dupliquée.
6
+
7
+ /**
8
+ * Sous-ensemble de `LDrawColor` (parser LDraw, type non-exporté) que l'on peut
9
+ * consister sans importer le type du tiers. La couleur réelle du parser est
10
+ * structurellement assignable vers cette interface.
11
+ */
12
+ export interface LDrawColorLike {
13
+ /** Code couleur LDraw. */
14
+ code: number
15
+ /** Nom humain de la couleur. */
16
+ name: string
17
+ /** RGBA chaque composante entre 0 et 1. */
18
+ rgba: [number, number, number, number]
19
+ /** Finition (NORMAL, METAL, CHROME, PEARLESCENT, RUBBER, MATTE_METALLIC…). */
20
+ finish: string
21
+ /** Luminance 0-255 (couleurs électroluminescentes). */
22
+ luminance: number
23
+ /** Indique si la couleur est transparente (alpha < 1). */
24
+ isTransparent: boolean
25
+ /** Hexadécimal « #rrggbb » le cas échéant. */
26
+ hex?: string
27
+ }
28
+
29
+ export interface PartMaterial {
30
+ /** Code couleur LDraw. */
31
+ code: number
32
+ /** Nom de la couleur. */
33
+ name: string
34
+ /** Hexadécimal de la couleur. */
35
+ hex: string
36
+ /** RGB chacune entre 0 et 1. */
37
+ color: [number, number, number]
38
+ /** Metallicité PBR (0-1). */
39
+ metalness: number
40
+ /** Rugosité PBR (0-1). */
41
+ roughness: number
42
+ /** La couleur est transparente. */
43
+ transparent: boolean
44
+ /** Opacité (alpha) entre 0 et 1. */
45
+ opacity: number
46
+ /** Côté de rendu : face visible (front), à l'inverse (back), ou les deux (double). */
47
+ side: "front" | "back" | "double"
48
+ /** Flat shading activé (bords tranchants, typique des briques LEGO). */
49
+ flatShading: boolean
50
+ /** RGB emissive chacune entre 0 et 1 (couleurs luticolores). */
51
+ emissive?: [number, number, number]
52
+ /** Intensité de l'emission (0-1). */
53
+ emissiveIntensity?: number
54
+ }
55
+
56
+ export interface MaterialOptions {
57
+ /** Côté de rendu (defaut : « double »). */
58
+ side?: "front" | "back" | "double"
59
+ /** Flat shading (defaut : « true »). */
60
+ flatShading?: boolean
61
+ /** Utilise la transmission ( verre ) plutôt que l'alpha mode pour les transparents. */
62
+ transmission?: boolean
63
+ }
64
+
65
+ /**
66
+ * Construit un matériau PBR jsonifiable depuis une couleur LDraw.
67
+ *
68
+ * @param color couleur LDraw (ou objet compatible {@link LDrawColorLike})
69
+ * @param options réglages optionnels du matériau
70
+ */
71
+ export function buildPartMaterial(color: LDrawColorLike, options: MaterialOptions = {}): PartMaterial {
72
+ const [r, g, b, a] = color.rgba
73
+ const side = options.side ?? "double"
74
+ const flatShading = options.flatShading ?? true
75
+
76
+ let metalness = 0
77
+ let roughness = 0.8
78
+ switch (color.finish) {
79
+ case "CHROME": metalness = 1.0; roughness = 0.03; break
80
+ case "METAL": metalness = 1.0; roughness = 0.25; break
81
+ case "PEARLESCENT": metalness = 0.4; roughness = 0.30; break
82
+ case "RUBBER": metalness = 0.0; roughness = 0.95; break
83
+ case "MATTE_METALLIC": metalness = 0.8; roughness = 0.60; break
84
+ }
85
+
86
+ const material: PartMaterial = {
87
+ code: color.code,
88
+ name: color.name,
89
+ hex: color.hex ?? "#000000",
90
+ color: [r, g, b],
91
+ metalness,
92
+ roughness,
93
+ transparent: color.isTransparent,
94
+ opacity: a,
95
+ side,
96
+ flatShading,
97
+ }
98
+
99
+ if (color.luminance > 0) {
100
+ const emissiveIntensity = color.luminance / 255
101
+ material.emissive = [r * emissiveIntensity, g * emissiveIntensity, b * emissiveIntensity]
102
+ material.emissiveIntensity = emissiveIntensity
103
+ }
104
+
105
+ return material
106
+ }
107
+
108
+ /** Matériau par défaut (blanc mate) utilisé quand une couleur manque au tableau. */
109
+ export function fallbackMaterial(code: number, options: MaterialOptions = {}): PartMaterial {
110
+ return buildPartMaterial(
111
+ {
112
+ code,
113
+ name: `#${code}`,
114
+ rgba: [1, 1, 1, 1],
115
+ finish: "NORMAL",
116
+ luminance: 0,
117
+ isTransparent: false,
118
+ hex: "#ffffff",
119
+ },
120
+ options,
121
+ )
122
+ }
@@ -0,0 +1,143 @@
1
+ import { DB, type PartRow } from "./db";
2
+
3
+ export interface ColorTableLike {
4
+ get(code: number): Promise<{ name: string; rgba: [number, number, number, number] }>;
5
+ }
6
+
7
+ /**
8
+ * Bounding box (boîte englobante axe-à-axe) d'une pièce, en units LDraw.
9
+ * Les tableaux sont des vecteurs [x, y, z].
10
+ */
11
+ export interface PartBoundingBox {
12
+ /** Coin de coordonnées minimales. */
13
+ min: [number, number, number];
14
+ /** Coin de coordonnées maximales. */
15
+ max: [number, number, number];
16
+ /** Dimensions de la boîte (max − min), i.e. longueur × largeur × hauteur. */
17
+ size: [number, number, number];
18
+ /** Centre de la boîte. */
19
+ center: [number, number, number];
20
+ }
21
+
22
+ /**
23
+ * Interface minimale pour extraire le bounding box depuis le parser LDraw.
24
+ * On ne dépend que de la géométrie plate (`geometry.aabb`), pas du reste
25
+ * de `LDrawPart`, pour rester découplé et testable hors-connexion.
26
+ */
27
+ export interface BoundingBoxParser {
28
+ parse(
29
+ name: string,
30
+ ctxOverride?: { defaultColor?: number },
31
+ ): Promise<{
32
+ geometry: {
33
+ aabb: {
34
+ min: { x: number; y: number; z: number };
35
+ max: { x: number; y: number; z: number };
36
+ size: { x: number; y: number; z: number };
37
+ center: { x: number; y: number; z: number };
38
+ };
39
+ };
40
+ }>;
41
+ }
42
+
43
+ export interface PartMetadata {
44
+ ldrawRef: string;
45
+ name: string | null;
46
+ category: string | null;
47
+ colorCount: number;
48
+ elementCount: number;
49
+ keywords: string[];
50
+ variants: Array<{ color: number; colorName: string; colorRgba: string; legoRefs: string[]; isTransparent: boolean }>;
51
+ /** Boîte englobante axe-à-axe de la pièce (units LDraw), ou null si le .dat est absent. */
52
+ boundingBox: PartBoundingBox | null;
53
+ }
54
+
55
+ export async function buildPartMetadata(
56
+ db: DB,
57
+ part: PartRow,
58
+ colorTable: ColorTableLike,
59
+ parser?: BoundingBoxParser,
60
+ ): Promise<PartMetadata> {
61
+ const elements = db.getElementVariants(part.ldrawRef);
62
+ const uniqueColors = [...new Set(elements.map(e => e.color).filter((c): c is number => c !== null))];
63
+
64
+ const byColor = new Map<number, string[]>();
65
+ for (const e of elements) {
66
+ if (e.color !== null && e.color !== undefined) {
67
+ if (!byColor.has(e.color)) byColor.set(e.color, []);
68
+ if (e.legoRef) byColor.get(e.color)!.push(e.legoRef);
69
+ }
70
+ }
71
+
72
+ const variants: PartMetadata["variants"] = [];
73
+ for (const [color, legoRefs] of byColor) {
74
+ let variantColor = { name: 'Inconnu', rgba: '1,1,1,1' };
75
+ try {
76
+ const ldColor = await colorTable.get(color);
77
+ variantColor = {
78
+ name: ldColor.name,
79
+ rgba: ldColor.rgba.map((v: number) => String(v)).join(','),
80
+ };
81
+ } catch {
82
+ // color not found, use defaults
83
+ }
84
+ const isTransparent = parseFloat(variantColor.rgba.split(',')[3] ?? '1') < 1;
85
+ variants.push({ color, colorName: variantColor.name, colorRgba: variantColor.rgba, legoRefs, isTransparent });
86
+ }
87
+
88
+ // La boîte englobante ne dépend que de la géométrie (la couleur n'a pas
89
+ // d'influence), on la dérive du parser LDraw si disponible. Échoue silencieusement → null.
90
+ let boundingBox: PartBoundingBox | null = null;
91
+ if (parser) {
92
+ try {
93
+ const { geometry: { aabb } } = await parser.parse(`${part.ldrawRef}.dat`);
94
+ boundingBox = {
95
+ min: [aabb.min.x, aabb.min.y, aabb.min.z],
96
+ max: [aabb.max.x, aabb.max.y, aabb.max.z],
97
+ size: [aabb.size.x, aabb.size.y, aabb.size.z],
98
+ center: [aabb.center.x, aabb.center.y, aabb.center.z],
99
+ };
100
+ } catch {
101
+ boundingBox = null;
102
+ }
103
+ }
104
+
105
+ return {
106
+ ldrawRef: part.ldrawRef,
107
+ name: part.name,
108
+ category: part.category,
109
+ colorCount: uniqueColors.length,
110
+ elementCount: elements.length,
111
+ keywords: (part.keywords || '').split(' ').filter(Boolean),
112
+ variants,
113
+ boundingBox,
114
+ };
115
+ }
116
+
117
+ export function displayPartMetadata(metadata: PartMetadata): void {
118
+ console.log(`Nom: ${metadata.name}`);
119
+ console.log(`LDraw: ${metadata.ldrawRef}`);
120
+ console.log(`Catégorie: ${metadata.category ?? 'N/A'}`);
121
+ console.log(`Mots-clés: ${metadata.keywords.join(", ")}`);
122
+ console.log();
123
+ console.log(`Couleurs: ${metadata.colorCount}`);
124
+ console.log(`Elements: ${metadata.elementCount}`);
125
+ console.log();
126
+
127
+ if (metadata.boundingBox) {
128
+ const { min, max, size, center } = metadata.boundingBox;
129
+ console.log(`Bounding box (units LDraw):`);
130
+ console.log(` min : (${min[0]}, ${min[1]}, ${min[2]})`);
131
+ console.log(` max : (${max[0]}, ${max[1]}, ${max[2]})`);
132
+ console.log(` taille (L×l×H) : ${size[0]} × ${size[1]} × ${size[2]}`);
133
+ console.log(` centre : (${center[0]}, ${center[1]}, ${center[2]})`);
134
+ console.log();
135
+ }
136
+
137
+ if (metadata.variants.length > 0) {
138
+ console.log("Variantes:");
139
+ for (const v of metadata.variants) {
140
+ console.log(` ${v.color} (${v.colorName}): ${v.legoRefs.join(", ")}`);
141
+ }
142
+ }
143
+ }