@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,129 @@
1
+ #!/usr/bin/env bun
2
+ // cli/search.ts — Recherche de pièces (FTS5 + filtres)
3
+
4
+ import { join } from 'node:path'
5
+ import parser from "yargs-parser";
6
+ import BrickIndex, { type SearchResult } from "..";
7
+
8
+ function printHelp(): void {
9
+ console.log(`
10
+ Usage: bun run cli/search.ts [query] [options]
11
+
12
+ Options:
13
+ --data <path> Path vers dossier ou est extrait brick-index-data
14
+ --format <type> Format de sortie (json|human) (default: human)
15
+
16
+ Exemples:
17
+ bun run cli/search.ts "brick 2x4"
18
+ bun run cli/search.ts "brick 2x4" --format json
19
+ bun run cli/search.ts "racing" --category "Technic" --color 15
20
+ bun run cli/search.ts --ldraw 3001
21
+ bun run cli/search.ts --rebrickable 3001
22
+ bun run cli/search.ts --lego 3001pb01
23
+ bun run cli/search.ts "wheel" --no-stickers
24
+ `);
25
+ }
26
+
27
+
28
+
29
+ type SearchOptions = {
30
+ query?: string;
31
+ lego?: string;
32
+ rebrickable?: string;
33
+ ldraw?: string;
34
+ category?: string;
35
+ color?: number;
36
+ exclude_stickers?: boolean;
37
+ help?: boolean;
38
+ format?: string;
39
+ data: string
40
+ };
41
+
42
+ export async function run(args: string[] = []): Promise<void> {
43
+ const parsed = parser(args, {
44
+ alias: { h: "help" },
45
+ string: ["ldraw", "rebrickable", "lego", "category", "color", "data", "format"],
46
+ boolean: ["help", "h", "no-stickers"],
47
+ default: {
48
+ data: join(import.meta.dir, "..", "..", "data")
49
+ }
50
+ });
51
+
52
+ if (parsed['help'] || parsed['h']) {
53
+ printHelp();
54
+ return;
55
+ }
56
+
57
+ const options: SearchOptions = {
58
+ query: parsed._.join(' ') as string | undefined,
59
+ category: parsed['category'],
60
+ color: parsed['color'] ? (parsed['color'] as number) : undefined,
61
+ exclude_stickers: (parsed['no-stickers'] as boolean) || undefined,
62
+ format: parsed['format'],
63
+ data: parsed['data']
64
+ };
65
+
66
+ const brickIndex = new BrickIndex({ dataDir: options.data })
67
+
68
+ // const colorTable = ldrawParser.colorTable;
69
+
70
+ let results: SearchResult;
71
+ let mode = "";
72
+ let query = ''
73
+
74
+ if (options.query) {
75
+ mode = `Search FTS`;
76
+ query = options.query
77
+ results = await brickIndex.search({
78
+ q: options.query,
79
+ category: options.category,
80
+ color: options.color,
81
+ excludeStickers: options.exclude_stickers,
82
+ });
83
+ } else {
84
+ printHelp();
85
+ brickIndex.close();
86
+ return;
87
+ }
88
+
89
+ if (results.total === 0) {
90
+ console.log(`Aucun résultat "${mode}" pour "${query}"`);
91
+ brickIndex.close();
92
+ return;
93
+ }
94
+
95
+ const format = options.format ?? 'human';
96
+
97
+ if (format === 'json') {
98
+ console.log(JSON.stringify({ total: results.total, items: results.items }, null, 2));
99
+ brickIndex.close();
100
+ return;
101
+ }
102
+
103
+ console.log(`\n${results.total} résultat(s) pour ${query}:\n`);
104
+ console.log("LDraw | Nom | Tag | Couleurs / Refs");
105
+ console.log("--------|----------------------------------------|-------------------|-----------------");
106
+
107
+ function variantCounts(variants: { color: number; legoRef: string }[]): string {
108
+ const colors = new Set(variants.map(v => v.color));
109
+ const legos = new Set(variants.map(v => v.legoRef));
110
+ return `${colors.size} / ${legos.size}`;
111
+ }
112
+
113
+ for (const r of results.items) {
114
+ const nameBase = r.name ?? "";
115
+ const name = nameBase.length > 39 ? nameBase.slice(0, 36) + "..." : nameBase;
116
+ const tagBase = r.tag ?? "";
117
+ const tag = tagBase.length > 18 ? tagBase.slice(0, 17) + "..." : tagBase;
118
+ console.log(`${r.ldrawRef.padEnd(8)}| ${name.padEnd(39)}| ${tag.padEnd(18)}| ${variantCounts(r.variants ?? [])}`);
119
+ }
120
+ brickIndex.close();
121
+ }
122
+
123
+ // Exécution directe (bun run cli/search.ts)
124
+ if (process.argv[1]?.replace(/\\/g, "/").endsWith("/search.ts")) {
125
+ run(process.argv.slice(2)).catch((err) => {
126
+ console.error("Erreur:", 'message' in err ? err.message : err);
127
+ process.exit(1);
128
+ });
129
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { default, type SearchParams, type SearchResult, type Part, type PartMetadata, type PartBoundingBox, type LengthUnit, type PartGeometry, type PartGeometryMesh, type PartGeometryEdges, type GeometryOptions, type GeometryLengthUnit, type PartMaterial } from './lib';
package/src/lib/db.ts ADDED
@@ -0,0 +1,258 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { existsSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { normalizeDimension } from "./keyword";
5
+
6
+
7
+ export type SearchMode = "ldraw" | "rebrickable" | "lego";
8
+
9
+ // Pièce canonique (UNE ligne par ldraw_ref).
10
+ // Couleurs / refs LEGO vivent dans part_variants, pas ici.
11
+ export interface PartRow {
12
+ ldrawRef: string
13
+ name: string
14
+ category: string
15
+ keywords: string | null
16
+ tag: string | null
17
+ }
18
+
19
+ export interface ElementRow {
20
+ legoRef: string;
21
+ color: number;
22
+ }
23
+
24
+ export interface PartVariant {
25
+ color: number;
26
+ // Un variant = un élément LEGO : lego_ref et color sont toujours présents (NOT NULL).
27
+ legoRef: string;
28
+ }
29
+
30
+ export interface DistinctPartRow extends PartRow {
31
+ variants: PartVariant[];
32
+ }
33
+
34
+ export interface SearchFilters {
35
+ category?: string;
36
+ color?: number;
37
+ excludeStickers?: boolean;
38
+ }
39
+
40
+ function buildFtsConditions(
41
+ query: string,
42
+ filters: SearchFilters = {},
43
+ ): { sql: string; params: Record<string, unknown> } {
44
+ const conditions: string[] = [];
45
+ const params: Record<string, unknown> = {};
46
+
47
+ // On normalise les dimensions de la requête (« 2 x 2 » -> « 2x2 ») afin de matcher
48
+ // les jetons indexés de la même façon. Cf. normalizeDimension.
49
+ const normalizedQuery = normalizeDimension(query);
50
+
51
+ if (normalizedQuery) {
52
+ conditions.push("parts_fts MATCH $query");
53
+ params["$query"] = `${normalizedQuery ? '"' + normalizedQuery + '"' : ''}*`;
54
+ }
55
+ if (filters.category) {
56
+ conditions.push("p.category = $category");
57
+ params["$category"] = filters.category;
58
+ }
59
+ if (filters.color !== undefined && filters.color !== null) {
60
+ // La couleur vit dans part_variants : on ne garde que les pièces
61
+ // possedant au moins un variant de cette couleur.
62
+ conditions.push("p.ldraw_ref IN (SELECT ldraw_ref FROM part_variants WHERE color = $color)");
63
+ params["$color"] = filters.color;
64
+ }
65
+ if (filters.excludeStickers) {
66
+ conditions.push("p.category != 'Stickers'");
67
+ }
68
+
69
+ return { sql: conditions.join(" AND "), params };
70
+ }
71
+
72
+ export class DB {
73
+
74
+ private db: Database
75
+ constructor(database: Database | string) {
76
+ if (typeof(database) == 'string') {
77
+ if (!existsSync(database)) {
78
+ throw new Error(`[db] Base de données introuvable: ${database}\nIl faut lancer "bun run init --data ${dirname(database)}" pour télécharger les données`)
79
+ }
80
+ this.db = new Database(database, { readonly: true })
81
+ console.error(`[db] Ouverture de la base de données: ${database} (readonly)`)
82
+ } else {
83
+ this.db = database
84
+ }
85
+ }
86
+
87
+ get internalDb(): Database {
88
+ return this.db;
89
+ }
90
+
91
+ // searchByRef(ref: string, mode: SearchMode, options?: { limit?: number; offset?: number }): PartRow[] {
92
+ // let sql: string;
93
+ // const params: { $ref: string; $limit?: number; $offset?: number } = { $ref: ref };
94
+
95
+ // if (mode === "ldraw") {
96
+ // sql = `
97
+ // SELECT ldraw_ref AS ldrawRef, name, category, keywords, tag
98
+ // FROM parts
99
+ // WHERE ldraw_ref = $ref
100
+ // ORDER BY ldraw_ref`;
101
+ // } else if (mode === "lego") {
102
+ // // lego_ref est stocké dans part_variants.
103
+ // sql = `
104
+ // SELECT p.ldraw_ref AS ldrawRef, p.name, p.category, p.keywords, p.tag
105
+ // FROM parts p
106
+ // JOIN part_variants pv ON pv.ldraw_ref = p.ldraw_ref
107
+ // WHERE pv.lego_ref = $ref
108
+ // ORDER BY p.ldraw_ref`;
109
+ // } else {
110
+ // // rebrickable : plus de colonne dans le nouveau schéma.
111
+ // return [];
112
+ // }
113
+
114
+ // if (options?.limit != null) {
115
+ // sql += " LIMIT $limit";
116
+ // params.$limit = options.limit;
117
+ // }
118
+ // if (options?.offset != null) {
119
+ // if (options.limit == null) sql += " LIMIT -1";
120
+ // sql += " OFFSET $offset";
121
+ // params.$offset = options.offset;
122
+ // }
123
+ // return this.db.prepare(sql).all(params) as PartRow[];
124
+ // }
125
+
126
+ // countByRef(ref: string, mode: SearchMode): number {
127
+ // if (mode === "rebrickable") return 0;
128
+
129
+ // let sql: string;
130
+ // const params: { $ref: string } = { $ref: ref };
131
+
132
+ // if (mode === "ldraw") {
133
+ // sql = `SELECT COUNT(*) as count FROM parts WHERE ldraw_ref = $ref`;
134
+ // } else {
135
+ // sql = `
136
+ // SELECT COUNT(*) as count
137
+ // FROM parts p
138
+ // JOIN part_variants pv ON pv.ldraw_ref = p.ldraw_ref
139
+ // WHERE pv.lego_ref = $ref`;
140
+ // }
141
+
142
+ // const result = this.db.prepare(sql).get(params) as { count: number } | null;
143
+ // return result?.count ?? 0;
144
+ // }
145
+
146
+ countDistinctFts(query: string, filters: SearchFilters = {}): number {
147
+ // Une seule ligne FTS par pièce : COUNT(*) et COUNT(DISTINCT ldraw_ref)
148
+ // sont équivalents ici, on garde DISTINCT pour la clarté sémantique.
149
+ const { sql, params } = buildFtsConditions(query, filters);
150
+ const whereClause = sql.length > 0 ? `WHERE ${sql}` : "";
151
+
152
+ // TODO corriger le typage
153
+ const result = this.db.prepare<{ count: number }, any>(`
154
+ SELECT COUNT(DISTINCT p.ldraw_ref) as count
155
+ FROM parts p
156
+ JOIN parts_fts ON parts_fts.ldraw_ref = p.ldraw_ref
157
+ ${whereClause}
158
+ `).get({ ...params });
159
+
160
+ return result?.count ?? 0;
161
+ }
162
+
163
+ searchDistinct(query: string, filters: SearchFilters = {}, limit: number = 50, offset: number = 0): DistinctPartRow[] {
164
+ const { sql, params } = buildFtsConditions(query, filters);
165
+ const whereClause = sql.length > 0 ? `WHERE ${sql}` : "";
166
+ const orderBy = query ? "ORDER BY parts_fts.rank" : "ORDER BY p.ldraw_ref";
167
+
168
+ // TODO corriger le typage
169
+ // parts contient déjà UNE ligne par ldraw_ref : pas de GROUP BY nécessaire.
170
+ const rows = this.db.prepare(`
171
+ SELECT p.ldraw_ref AS ldrawRef, p.name, p.category, p.keywords, p.tag
172
+ FROM parts p
173
+ JOIN parts_fts ON parts_fts.ldraw_ref = p.ldraw_ref
174
+ ${whereClause}
175
+ ${orderBy}
176
+ LIMIT $limit OFFSET $offset
177
+ `).all({ ...params, $limit: limit, $offset: offset } as never) as DistinctPartRow[];
178
+
179
+ if (rows.length === 0) return rows;
180
+
181
+ const byRef = this.getVariantsByRefs(rows.map(r => r.ldrawRef));
182
+ for (const row of rows) {
183
+ row.variants = byRef.get(row.ldrawRef) ?? [];
184
+ }
185
+
186
+ return rows;
187
+ }
188
+
189
+ getVariantsByRefs(refs: string[]): Map<string, PartVariant[]> {
190
+ // Les variants (couleurs / refs LEGO) sont dans part_variants.
191
+ const byRef = new Map<string, PartVariant[]>();
192
+ if (refs.length === 0) return byRef;
193
+
194
+ const variants = this.db.prepare<{ ldrawRef: string; color: number; legoRef: string }, string[]>(`
195
+ SELECT ldraw_ref AS ldrawRef, color, lego_ref AS legoRef
196
+ FROM part_variants
197
+ WHERE ldraw_ref IN (${refs.map(() => "?").join(", ")})
198
+ ORDER BY ldraw_ref, color
199
+ `).all(...refs);
200
+
201
+ for (const v of variants) {
202
+ const list = byRef.get(v.ldrawRef);
203
+ if (list) list.push({ color: v.color, legoRef: v.legoRef });
204
+ else byRef.set(v.ldrawRef, [{ color: v.color, legoRef: v.legoRef }]);
205
+ }
206
+
207
+ return byRef;
208
+ }
209
+
210
+ getByLdrawRef(ldrawRef: string): PartRow | undefined {
211
+ // Recherche indexée par ref LDraw.
212
+ const result = this.db.prepare<PartRow, [{$ref: string}]>(`
213
+ SELECT ldraw_ref AS ldrawRef, name, category, keywords, tag
214
+ FROM parts
215
+ WHERE ldraw_ref = $ref
216
+ LIMIT 1
217
+ `).get({ $ref: ldrawRef });
218
+ return result ?? undefined;
219
+ }
220
+
221
+ getByLegoRef(legoRef: string): { ldrawRef: string, legoRef: string, color: number } | undefined {
222
+ // Recherche indexée par ref LDraw.
223
+ const result = this.db.prepare<{ ldrawRef: string, legoRef: string, color: number }, [{$ref: string}]>(`
224
+ SELECT ldraw_ref AS ldrawRef, lego_ref as legoRef, color
225
+ FROM part_variants
226
+ WHERE lego_ref = $ref
227
+ LIMIT 1
228
+ `).get({ $ref: legoRef });
229
+ return result ?? undefined;
230
+ }
231
+
232
+ /** Liste toutes les references LDraw du catalogue (triées par ref). */
233
+ getAllLdrawRefs(): string[] {
234
+ return this.db.prepare<{ ldrawRef: string }, []>(`
235
+ SELECT ldraw_ref AS ldrawRef
236
+ FROM parts
237
+ ORDER BY ldraw_ref
238
+ `).all().map(row => row.ldrawRef);
239
+ }
240
+
241
+ getElementVariants(ldrawRef: string): ElementRow[] {
242
+ return this.db.prepare<ElementRow, [{$ref: string}]>(`
243
+ SELECT lego_ref AS legoRef, color
244
+ FROM part_variants
245
+ WHERE ldraw_ref = $ref
246
+ ORDER BY color
247
+ `).all({ $ref: ldrawRef })
248
+ }
249
+
250
+ getCategories(): string[] {
251
+ return this.db.prepare<{category: string}, []>(`
252
+ SELECT DISTINCT category
253
+ FROM parts
254
+ WHERE category IS NOT NULL
255
+ ORDER BY category
256
+ `).all().map(item => item.category);
257
+ }
258
+ }
@@ -0,0 +1,4 @@
1
+
2
+ export function printHelp(cmd: string, helpText: string): void {
3
+ console.log(`\nUsage: bun run ${cmd}\n${helpText}`);
4
+ }
@@ -0,0 +1,267 @@
1
+ // geometry.ts — Transforme une FlatGeometry (parser LDraw) en une géométrie
2
+ // jsonifiable, indexée par couleur, prête à bâtir un mesh + matériau côté front.
3
+ //
4
+ // Le parser n'explose que la géométrie brute (triangle-soup, sans normales) et
5
+ // n'exporte pas ses helpers de weld : on réimplémente ici la transformée
6
+ // (unité + repère) dans ce module, et le weld/normales dans `weld.ts`. La logique
7
+ // est volontairement pure et sans dépendance DB/-parser, pour rester testable hors-connexion.
8
+
9
+ import type { FlatGeometry } from "@gigatrappeur/ldraw-parser"
10
+ import type { PartBoundingBox } from "./part"
11
+ import { buildPartMaterial, fallbackMaterial, type MaterialOptions, type PartMaterial } from "./material"
12
+ import { weldTriangles, type WeldOptions, type TriVertex, type NormalMode } from "./weld"
13
+
14
+ export type { PartMaterial, WeldOptions }
15
+
16
+ /** Unités de longueur prises en charge (mêmes que le parser LDraw). */
17
+ export type GeometryLengthUnit = "ldu" | "mm" | "cm" | "m" | "in" | "studs"
18
+
19
+ /** Vecteur 2D (UV). */
20
+ export interface Vec2 {
21
+ u: number
22
+ v: number
23
+ }
24
+
25
+ /** Vecteur 3D. */
26
+ export interface Vec3 {
27
+ x: number
28
+ y: number
29
+ z: number
30
+ }
31
+
32
+ /** Facteur de multiplication d'une coordonnée LDU vers l'unité demandée. */
33
+ export const SCALE_FROM_LDU: Record<GeometryLengthUnit, number> = {
34
+ ldu: 1,
35
+ /** 1 LDU = 0,4 mm */
36
+ mm: 0.4,
37
+ /** 1 LDU = 0,04 cm */
38
+ cm: 0.04,
39
+ /** 1 LDU = 0,0004 m */
40
+ m: 0.0004,
41
+ /** 1 LDU = 0,4 mm en inches */
42
+ in: 0.015748031496062992,
43
+ /** 1 LDU = 1/20 stud */
44
+ studs: 0.05,
45
+ }
46
+
47
+ export interface GeometryOptions {
48
+ /** Unité de sortie des positions (defaut : « studs »). */
49
+ unit?: GeometryLengthUnit
50
+ /** Repère Y-up (Three.js) au lieu du repère LDraw (Y-down) (defaut : « true »). */
51
+ yUp?: boolean
52
+ /**
53
+ * Dédoublonnage de sommets (weld) :
54
+ * - défaut `{ epsilon: 1e-4 }` → sommets fusionnés par position (+ UV),
55
+ * indices indexant un buffer de sommets partagé ;
56
+ * - `false` → soupe de triangles (aucun weld, indices séquentiels).
57
+ */
58
+ weld?: WeldOptions | false
59
+ /**
60
+ * Normales à produire :
61
+ * - « flat » : normales de face (defaut),
62
+ * - « smooth » : normals lissées (avec fente), requiert un weld,
63
+ * - `false` : aucune normale.
64
+ */
65
+ normals?: "flat" | "smooth" | false
66
+ /** Options transmises à la construction des matériaux (côté, flat shading…). */
67
+ material?: MaterialOptions
68
+ }
69
+
70
+ export interface PartGeometryMesh {
71
+ /** Code couleur LDraw du mesh. */
72
+ colorCode: number
73
+ /** Matériau PBR associé (dérivé de la couleur). */
74
+ material: PartMaterial
75
+ /** Table de positions plate [x, y, z, x, y, z, …]. */
76
+ positions: number[]
77
+ /** Table de normales plate [nx, ny, nz, …], ou null si absentes. */
78
+ normals: number[] | null
79
+ /** Indices des sommets (pointeur vers `positions`), toujours présents. */
80
+ indices: number[]
81
+ /** Table d'UVs plate [u, v, …], ou null si absents. */
82
+ uvs: number[] | null
83
+ /** Nombre de triangles du mesh. */
84
+ triangleCount: number
85
+ }
86
+
87
+ export interface PartGeometryEdges {
88
+ /** Code couleur LDraw des arêtes. */
89
+ colorCode: number
90
+ /** Matériau PBR associé. */
91
+ material: PartMaterial
92
+ /** Lignes plates [x, y, z, x, y, z, …] (début/fin de chaque segment). */
93
+ lines: number[]
94
+ }
95
+
96
+ export interface PartGeometry {
97
+ /** Reference LDraw de la pièce. */
98
+ ldrawRef: string
99
+ /** Unité de sortie. */
100
+ unit: GeometryLengthUnit
101
+ /** Repère de coordonnées. */
102
+ coordinateSystem: "y-up" | "y-down"
103
+ /** Boîte englobante axe-à-axe dans l'unité de sortie. */
104
+ aabb: PartBoundingBox
105
+ /** Meshs groupés par couleur. */
106
+ meshes: PartGeometryMesh[]
107
+ /** Arêtes (contours) de la pièce. */
108
+ edges: PartGeometryEdges[]
109
+ }
110
+
111
+ /** Vecteur 3D en écriture compacte. */
112
+ type Vec = [number, number, number]
113
+
114
+ /** Applique la transformation d'unité (+ retournement Y-down → Y-up) à une position. */
115
+ function transformPosition(v: Vec3, scale: number, yUp: boolean): Vec3 {
116
+ let { x, y, z } = v
117
+ if (yUp) { y = -y; z = -z }
118
+ // `+ 0` normalise le zéro négatif (−0 → 0) évité par la négation Y-up.
119
+ return {
120
+ x: x * scale + 0,
121
+ y: y * scale + 0,
122
+ z: z * scale + 0,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Transforme une boîte englobante brute (min/max en LDU, repère LDraw Y-down)
128
+ * dans l'unité et le repère de sortie. C'est la source unique de vérité pour la
129
+ * transformée de box : le listing bulk (`getAllBoundingBoxes`) l'utilise car le
130
+ * parser expose l'AABB brute en LDU, tandis que `convertFlatGeometry` calcule la
131
+ * sienne directement sur des positions déjà transformées (inchangée).
132
+ *
133
+ * Le repère Y-up négant y et z, le min et le max s'échangent sur ces axes :
134
+ * `min.y(sortie) = -max.y(entrée) * scale`, etc. L'échelle étant positive,
135
+ * l'ordre des extrémités ne fait que se retourner, pas se mélanger.
136
+ */
137
+ export function transformAabb(
138
+ aabb: { min: Vec3; max: Vec3 },
139
+ scale: number,
140
+ yUp: boolean,
141
+ ): PartBoundingBox {
142
+ const min: Vec = yUp
143
+ ? [aabb.min.x * scale + 0, -aabb.max.y * scale + 0, -aabb.max.z * scale + 0]
144
+ : [aabb.min.x * scale + 0, aabb.min.y * scale + 0, aabb.min.z * scale + 0]
145
+ const max: Vec = yUp
146
+ ? [aabb.max.x * scale + 0, -aabb.min.y * scale + 0, -aabb.min.z * scale + 0]
147
+ : [aabb.max.x * scale + 0, aabb.max.y * scale + 0, aabb.max.z * scale + 0]
148
+ return {
149
+ min,
150
+ max,
151
+ size: [max[0] - min[0], max[1] - min[1], max[2] - min[2]],
152
+ center: [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2],
153
+ }
154
+ }
155
+
156
+ /** Met à jour une boîte englobante axe-à-axe depuis une table de positions. */
157
+ function updateAabb(positions: number[], aabb: { min: Vec; max: Vec }): void {
158
+ for (let i = 0; i < positions.length; i += 3) {
159
+ const x = positions[i]!, y = positions[i + 1]!, z = positions[i + 2]!
160
+ if (x < aabb.min[0]!) aabb.min[0] = x
161
+ if (y < aabb.min[1]!) aabb.min[1] = y
162
+ if (z < aabb.min[2]!) aabb.min[2] = z
163
+ if (x > aabb.max[0]!) aabb.max[0] = x
164
+ if (y > aabb.max[1]!) aabb.max[1] = y
165
+ if (z > aabb.max[2]!) aabb.max[2] = z
166
+ }
167
+ }
168
+
169
+ /** Résout la matériau d'un mesh depuis son code couleur et le tableau des couleurs. */
170
+ function resolveMaterial(colorCode: number, colorTable: FlatGeometry["colorTable"], options: MaterialOptions): PartMaterial {
171
+ const color = colorTable?.get(colorCode)
172
+ return color ? buildPartMaterial(color, options) : fallbackMaterial(colorCode, options)
173
+ }
174
+
175
+ /**
176
+ * Convertit une `FlatGeometry` du parser en une {@link PartGeometry} jsonifiable,
177
+ * indexée par couleur, avec matériaux dérivés.
178
+ *
179
+ * @param ldrawRef reference de la pièce (stockée dans la structure retournée)
180
+ * @param geometry géométrie brute du parser (`part.geometry`)
181
+ * @param options unité, repère et normales
182
+ */
183
+ export function convertFlatGeometry(ldrawRef: string, geometry: FlatGeometry, options: GeometryOptions = {}): PartGeometry {
184
+ const unit = options.unit ?? "studs"
185
+ const yUp = options.yUp ?? true
186
+ const scale = SCALE_FROM_LDU[unit]
187
+ const materialOptions = options.material ?? {}
188
+
189
+ const meshes: PartGeometryMesh[] = []
190
+
191
+ for (const mesh of geometry.meshes) {
192
+ const triangles = mesh.triangles
193
+
194
+ // Triangles transformés (unité + repère), réutilisables par le weld.
195
+ const transformed: TriVertex[] = []
196
+ for (const tri of triangles) {
197
+ transformed.push({
198
+ a: { position: transformPosition(tri.a.position, scale, yUp), uv: tri.a.uv },
199
+ b: { position: transformPosition(tri.b.position, scale, yUp), uv: tri.b.uv },
200
+ c: { position: transformPosition(tri.c.position, scale, yUp), uv: tri.c.uv },
201
+ })
202
+ }
203
+
204
+ // Weld (dédoublonnage des sommets) + normales en un seul passage.
205
+ const weldMode = options.weld !== false
206
+ const normalMode: NormalMode = options.normals === false
207
+ ? "none"
208
+ : options.normals === "smooth"
209
+ ? "smooth"
210
+ : "flat"
211
+ const weldOpts: WeldOptions = options.weld === false ? {} : (options.weld ?? {})
212
+ const result = weldTriangles(transformed, weldOpts, { weld: weldMode, normals: normalMode })
213
+
214
+ meshes.push({
215
+ colorCode: mesh.colorCode,
216
+ material: resolveMaterial(mesh.colorCode, geometry.colorTable, materialOptions),
217
+ positions: result.positions,
218
+ normals: result.normals,
219
+ indices: result.indices,
220
+ uvs: result.uvs,
221
+ triangleCount: result.triangleCount,
222
+ })
223
+ }
224
+
225
+ // Arêtes (contours) : mêmes transformations, format « lignes ».
226
+ const edges: PartGeometryEdges[] = geometry.edges.map((eg) => {
227
+ const lines: number[] = []
228
+ for (const seg of eg.segments) {
229
+ const s = transformPosition(seg.start, scale, yUp)
230
+ const e = transformPosition(seg.end, scale, yUp)
231
+ lines.push(s.x, s.y, s.z, e.x, e.y, e.z)
232
+ }
233
+ return {
234
+ colorCode: eg.colorCode,
235
+ material: resolveMaterial(eg.colorCode, geometry.colorTable, materialOptions),
236
+ lines,
237
+ }
238
+ })
239
+
240
+ // Boîte englobante dans l'unité de sortie : les positions des mesh sont
241
+ // déjà transformées (unité + repère), on prend min/max puis on en dérive
242
+ // la taille et le centre.
243
+ const aabb = {
244
+ min: [Infinity, Infinity, Infinity] as Vec,
245
+ max: [-Infinity, -Infinity, -Infinity] as Vec,
246
+ }
247
+ for (const mesh of meshes) updateAabb(mesh.positions, aabb)
248
+ const size: Vec = [
249
+ aabb.max[0]! - aabb.min[0]!,
250
+ aabb.max[1]! - aabb.min[1]!,
251
+ aabb.max[2]! - aabb.min[2]!,
252
+ ]
253
+ const center: Vec = [
254
+ (aabb.min[0]! + aabb.max[0]!) / 2,
255
+ (aabb.min[1]! + aabb.max[1]!) / 2,
256
+ (aabb.min[2]! + aabb.max[2]!) / 2,
257
+ ]
258
+
259
+ return {
260
+ ldrawRef,
261
+ unit,
262
+ coordinateSystem: yUp ? "y-up" : "y-down",
263
+ aabb: { min: aabb.min, max: aabb.max, size, center },
264
+ meshes,
265
+ edges,
266
+ }
267
+ }
@@ -0,0 +1,7 @@
1
+
2
+ export { default } from "./ldraw-index";
3
+ export type { SearchParams, SearchResult, Part, PartMetadata, Color, PartBoundingBoxEntry, LengthUnit } from "./ldraw-index";
4
+ export type { PartBoundingBox } from "./part";
5
+ export type { PartGeometry, PartGeometryMesh, PartGeometryEdges, GeometryOptions, GeometryLengthUnit, WeldOptions } from "./geometry";
6
+ export type { PartMaterial } from "./material";
7
+
@@ -0,0 +1,24 @@
1
+ // keyword.ts — Normalisation des dimensions (noms et mots-clés) type LEGO (côté recherche).
2
+ //
3
+ // Réplique de brick-index-data/src/keyword.ts (NE PAS modifier sans refléter le
4
+ // changement dans l'autre repo). Les dimensions s'écrivent de façons variables
5
+ // (« 2 x 2 », « 2 x 2 », « 2×2 »…) ; on les unifie en forme canonique « 2x2 »
6
+ // afin que la requête MATCH corresponde aux jetons indexés.
7
+
8
+ /**
9
+ * Normalise une notation de dimension :
10
+ * « 2 x 2 », « 2×2 », « 2 X 2 » -> « 2x2 »
11
+ * « 2 x 2 x 2 », « 2×2×2 » -> « 2x2x2 »
12
+ *
13
+ * — unifie le signe de multiplication (« · » et « × ») en « x » ;
14
+ * — supprime les espaces autour du « x » entre chiffres et le remet en minuscule.
15
+ *
16
+ * Ne touche que les chaînes de dimensions : « box » ou « 16898 » restent intacts.
17
+ */
18
+ export function normalizeDimension(text: string): string {
19
+ return text
20
+ .replace(/[·×]/g, "x") // · et × -> x (unifie le signe de multiplication)
21
+ // « 2 x 2 x 2 » (1 à N dimensions) -> « 2x2x2 » : on retire les espaces et on minuscule le x.
22
+ .replace(/(\d+\s*[xX]\s*)+\d+/g, match =>
23
+ match.replace(/\s+/g, "").replace(/[xX]/g, "x"));
24
+ }