Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
5638 lines (4655 loc) · 197 KB
/
Copy pathserver.js
File metadata and controls
5638 lines (4655 loc) · 197 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import os from 'os';
import { spawn } from 'child_process';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco3d from 'draco3dgltf';
import { createServer as createViteServer } from 'vite';
import { applyReclassifications, IFC_TYPES, reclassifiableTypeNames } from './src/ifc-patcher.js';
import { IFC_CATEGORIES } from './src/ifc-catalog.js';
import { candidateDocumentForIfcType } from './src/ifc-classification-kb.js';
import planToGlb from './src/plan2glb_route.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const QWEN_ENV_KEYS = [
'QWEN_LLAMA_SERVER_BIN',
'QWEN_MODEL_PATH',
'QWEN_LLAMA_HOST',
'QWEN_LLAMA_PORT',
'QWEN_LLAMA_CONTEXT',
'QWEN_LLAMA_BATCH',
'QWEN_AUTO_START',
'QWEN_RERANKER_URL',
];
function repairQwenEnvNewlines(content) {
let repaired = String(content || '');
for (const key of QWEN_ENV_KEYS) {
repaired = repaired.replace(new RegExp(`([^\r\n])(?=${key}=)`, 'g'), '$1\n');
}
return repaired;
}
function parseEnvLines(content) {
return repairQwenEnvNewlines(content).split(/\r?\n/);
}
function loadLocalEnvFiles() {
for (const filename of ['.env', '.env.local']) {
const envPath = path.join(__dirname, filename);
if (!fs.existsSync(envPath)) continue;
const lines = parseEnvLines(fs.readFileSync(envPath, 'utf8'));
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
if (!match) continue;
const key = match[1];
let value = match[2].trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1);
}
if (!(key in process.env)) process.env[key] = value;
}
}
}
loadLocalEnvFiles();
const app = express();
const PORT = 3737;
const upload = multer({
dest: path.join(__dirname, 'uploads'),
limits: { fileSize: 500 * 1024 * 1024 } // 500 MB
});
let dracoDecoderModulePromise = null;
function getDracoDecoderModule() {
if (!dracoDecoderModulePromise) {
dracoDecoderModulePromise = draco3d.createDecoderModule();
}
return dracoDecoderModulePromise;
}
async function createGLTFReader() {
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
// Required for GLBs using KHR_draco_mesh_compression. Without this explicit
// dependency @gltf-transform can fail with errors such as:
// "undefined is not an object (evaluating 'decoderModule.DT_FLOAT32')".
io.registerDependencies({
'draco3d.decoder': await getDracoDecoderModule()
});
return io;
}
['uploads', 'outputs'].forEach(dir => {
const p = path.join(__dirname, dir);
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
});
// Allow large IFC payloads for the /api/reexport endpoint
app.use(express.json({ limit: '200mb' }));
app.use(express.urlencoded({ limit: '200mb', extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// Draco decoder files for the pure Three.js GLB modeler. This keeps Draco-compressed
// GLBs loadable in /modeler.html without requiring a CDN.
app.use('/vendor/draco', express.static(path.join(__dirname, 'node_modules/three/examples/jsm/libs/draco')));
// Vite is used only to serve the BIM viewer module with local npm imports.
// The converter UI and /api/convert remain handled by Express.
const vite = await createViteServer({
root: __dirname,
server: { middlewareMode: true },
appType: 'custom',
publicDir: false
});
app.use(vite.middlewares);
app.use(planToGlb);
app.get('/viewer.html', (req, res, next) => {
const viewerPath = path.join(__dirname, 'public', 'viewer.html');
if (fs.existsSync(viewerPath)) {
return res.sendFile(viewerPath);
}
next();
});
app.get('/modeler.html', (req, res, next) => {
const modelerPath = path.join(__dirname, 'public', 'modeler.html');
if (fs.existsSync(modelerPath)) {
return res.sendFile(modelerPath);
}
next();
});
// ─────────────────────────────────────────────────────────────────────────────
// STEP-21 string escaping
// ─────────────────────────────────────────────────────────────────────────────
function escapeIFCString(s) {
if (!s) return '';
return String(s)
.replace(/\\/g, '\\\\')
.replace(/'/g, "''")
.replace(/[^\x20-\x7E]/g, '_');
}
// ─────────────────────────────────────────────────────────────────────────────
// GLB extraction
// ─────────────────────────────────────────────────────────────────────────────
function computeBoundingBox(positions) {
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < positions.length; i += 3) {
for (let j = 0; j < 3; j++) {
const v = positions[i + j];
if (v < min[j]) min[j] = v;
if (v > max[j]) max[j] = v;
}
}
return { min, max };
}
function safeNodeExtras(node) {
try {
const extras = node?.getExtras?.();
return extras && typeof extras === 'object' ? extras : {};
} catch {
return {};
}
}
function parseSmeltCoordinateOrigin(extras = {}) {
const source = extras?.smeltCoordinateOrigin || extras?.smeltWorldOrigin || extras?.coordinateOrigin;
if (!source || typeof source !== 'object') return null;
const x = Number(source.x ?? source[0]);
const y = Number(source.y ?? source[1]);
const z = Number(source.z ?? source[2]);
if (![x, y, z].every(Number.isFinite)) return null;
return { x, y, z };
}
// Types qu'un émetteur (Smelt Studio notamment) peut imposer via extras.smeltIfcType.
// Ils court-circuitent la classification heuristique, qui ne sert qu'aux GLB anonymes.
const TRUSTED_IFC_TYPES = {
IFCSPACE: 'space',
IFCWALL: 'wall',
IFCSLAB: 'slab',
IFCROOF: 'roof',
IFCDOOR: 'door',
IFCWINDOW: 'window',
IFCSANITARYTERMINAL: 'sanitary',
IFCFURNITURE: 'furniture',
IFCELECTRICAPPLIANCE: 'appliance',
IFCCOVERING: 'covering',
};
function manualIfcTypeFromExtras(extras, nodeName = '') {
const raw = String(extras?.smeltIfcType || extras?.ifcType || extras?.IFCType || '').toUpperCase();
if (raw === 'IFCSPACE') return 'IFCSPACE';
if (/^IFCSPACE[_\s#-]/i.test(String(nodeName || ''))) return 'IFCSPACE';
if (/^Generated IFC Spaces/i.test(String(nodeName || ''))) return '';
// Un type explicite n'est pris au pied de la lettre que s'il est signé par Smelt Studio,
// pour ne pas faire confiance à des métadonnées arbitraires venues d'autres outils.
if (extras?.smeltSource === 'Smelt Studio' && TRUSTED_IFC_TYPES[raw]) return raw;
return '';
}
function trustedClassification(mesh) {
const raw = String(mesh?.manualIfcType || '').toUpperCase();
if (!raw || raw === 'IFCSPACE') return null;
return TRUSTED_IFC_TYPES[raw] || null;
}
function extractMaterialInfo(primitive) {
const material = primitive.getMaterial();
if (!material) {
return {
color: null,
materialName: '',
opacity: 1,
hasSourceMaterial: false
};
}
const base = material.getBaseColorFactor() || [1, 1, 1, 1];
return {
color: { r: base[0], g: base[1], b: base[2] },
materialName: material.getName() || '',
opacity: base[3] ?? 1,
hasSourceMaterial: true
};
}
async function extractMeshesFromGLB(glbPath) {
const io = await createGLTFReader();
const document = await io.read(glbPath);
const root = document.getRoot();
const extracted = [];
for (const node of root.listNodes()) {
const mesh = node.getMesh();
if (!mesh) continue;
const worldMatrix = node.getWorldMatrix();
const extras = safeNodeExtras(node);
const nodeName = node.getName() || mesh.getName() || 'unnamed';
const manualIfcType = manualIfcTypeFromExtras(extras, nodeName);
for (const primitive of mesh.listPrimitives()) {
const positionAttr = primitive.getAttribute('POSITION');
const indicesAccessor = primitive.getIndices();
if (!positionAttr) continue;
const positions = positionAttr.getArray();
const indices = indicesAccessor ? indicesAccessor.getArray() : null;
if (!indices || indices.length === 0) continue;
const coordinateOrigin = parseSmeltCoordinateOrigin(extras);
// Keep this as Float64Array/JS double. Some IFC-derived GLBs are rebased
// around a local origin to avoid Float32 quantization during editing; when
// converting back to IFC, re-apply the world offset here without collapsing
// the precision back into Float32.
const transformed = new Float64Array(positions.length);
const originX = coordinateOrigin?.x || 0;
const originY = coordinateOrigin?.y || 0;
const originZ = coordinateOrigin?.z || 0;
for (let i = 0; i < positions.length; i += 3) {
const x = positions[i], y = positions[i + 1], z = positions[i + 2];
transformed[i] = worldMatrix[0] * x + worldMatrix[4] * y + worldMatrix[8] * z + worldMatrix[12] + originX;
transformed[i + 1] = worldMatrix[1] * x + worldMatrix[5] * y + worldMatrix[9] * z + worldMatrix[13] + originY;
transformed[i + 2] = worldMatrix[2] * x + worldMatrix[6] * y + worldMatrix[10] * z + worldMatrix[14] + originZ;
}
const materialInfo = extractMaterialInfo(primitive);
extracted.push({
name: nodeName,
positions: transformed,
indices: Array.from(indices),
bbox: computeBoundingBox(transformed),
manualIfcType,
smeltSource: extras?.smeltSource || '',
smeltOriginalLocalId: extras?.smeltOriginalLocalId || null,
smeltPredefinedType: extras?.smeltPredefinedType || null,
...materialInfo
});
}
}
return extracted;
}
// ─────────────────────────────────────────────────────────────────────────────
// Mesh classification
// ─────────────────────────────────────────────────────────────────────────────
function isManualSpaceMesh(mesh) {
return String(mesh?.manualIfcType || '').toUpperCase() === 'IFCSPACE';
}
const STOREY_LEVEL_TOLERANCE = 0.28;
// Tuned for older buildings: a ground-floor ceiling of ~2.18m should still
// allow the next real level to be detected. Lower to ~1.85 only for very low
// split-level buildings; raise to ~2.30 for modern regular buildings.
const MIN_STOREY_HEIGHT = 2.0;
const STOREY_MIN_SCORE = 3.0;
function bboxStats(mesh) {
const [minX, minY, minZ] = mesh.bbox.min;
const [maxX, maxY, maxZ] = mesh.bbox.max;
const sizeX = maxX - minX;
const sizeY = maxY - minY; // Y vertical in glTF
const sizeZ = maxZ - minZ;
const horizontal = Math.max(sizeX, sizeZ);
const minHoriz = Math.min(sizeX, sizeZ);
const areaXZ = Math.max(0, sizeX) * Math.max(0, sizeZ);
return {
minX, minY, minZ, maxX, maxY, maxZ,
sizeX, sizeY, sizeZ,
horizontal,
minHoriz,
areaXZ,
centerY: (minY + maxY) / 2
};
}
function globalMeshBounds(meshes) {
if (!meshes || meshes.length === 0) {
return null;
}
const bounds = {
min: [Infinity, Infinity, Infinity],
max: [-Infinity, -Infinity, -Infinity]
};
for (const mesh of meshes) {
for (let i = 0; i < 3; i++) {
bounds.min[i] = Math.min(bounds.min[i], mesh.bbox.min[i]);
bounds.max[i] = Math.max(bounds.max[i], mesh.bbox.max[i]);
}
}
const size = [
bounds.max[0] - bounds.min[0],
bounds.max[1] - bounds.min[1],
bounds.max[2] - bounds.min[2]
];
return {
...bounds,
size,
maxDimension: Math.max(...size),
verticalDimension: size[1]
};
}
function inferModelScale(meshes) {
const bounds = globalMeshBounds(meshes);
if (!bounds) {
return {
scale: 1,
applied: false,
assumedInputUnit: 'metre',
reason: 'no geometry',
originalMaxDimension: 0,
normalizedMaxDimension: 0
};
}
const maxDimension = bounds.maxDimension;
const verticalDimension = bounds.verticalDimension;
// IFC output is declared in metres. Many GLB files from CAD/BIM/web exports
// are stored in millimetres even though glTF is unitless. If exported as-is,
// BIMData / IfcOpenShell will read a 5000mm wall as 5000m.
//
// Keep this deliberately conservative:
// - > 500 units vertical is almost certainly mm for an architectural model.
// - > 1000 units global extent is also a strong mm signal.
// - do not guess centimetres automatically; that is too risky for sites.
const likelyMillimetres =
verticalDimension > 500 ||
maxDimension > 1000;
if (likelyMillimetres) {
return {
scale: 0.001,
applied: true,
assumedInputUnit: 'millimetre',
outputUnit: 'metre',
reason: `large model extent detected (max=${maxDimension.toFixed(2)}, vertical=${verticalDimension.toFixed(2)})`,
originalMaxDimension: maxDimension,
normalizedMaxDimension: maxDimension * 0.001
};
}
return {
scale: 1,
applied: false,
assumedInputUnit: 'metre',
outputUnit: 'metre',
reason: `model extent already plausible in metres (max=${maxDimension.toFixed(2)}, vertical=${verticalDimension.toFixed(2)})`,
originalMaxDimension: maxDimension,
normalizedMaxDimension: maxDimension
};
}
function applyScaleToMeshes(meshes, scaleInfo) {
const scale = Number(scaleInfo?.scale || 1);
if (!Number.isFinite(scale) || scale <= 0 || Math.abs(scale - 1) < 1e-12) {
return scaleInfo;
}
for (const mesh of meshes) {
for (let i = 0; i < mesh.positions.length; i++) {
mesh.positions[i] *= scale;
}
mesh.bbox = computeBoundingBox(mesh.positions);
mesh.appliedInputScale = scale;
}
return {
...scaleInfo,
boundsAfterScale: globalMeshBounds(meshes)
};
}
function normalizeMeshUnits(meshes) {
const scaleInfo = inferModelScale(meshes);
return applyScaleToMeshes(meshes, scaleInfo);
}
function searchableText(mesh) {
return `${mesh.name || ''} ${mesh.materialName || ''}`.toLowerCase();
}
function hasDoorHint(mesh) {
return /\b(door|doors|porte|portes|ouvrant|battant)\b/i.test(searchableText(mesh));
}
function hasWindowHint(mesh) {
return /\b(window|windows|fenetre|fenêtres|fenetre|vitre|vitrage|glass|glazing)\b/i.test(searchableText(mesh));
}
function hasWallHint(mesh) {
return /\b(wall|walls|mur|murs|cloison|partition)\b/i.test(searchableText(mesh));
}
function hasExteriorWallHint(mesh) {
return /(exterior|external|outside|facade|façade|facades|façades|exterieur|extérieur|exterieure|extérieure|envelope|enveloppe|bardage|cladding)/i.test(searchableText(mesh));
}
function hasSlabHint(mesh) {
return /\b(slab|floor|floors|plancher|dalle|ceiling|plafond)\b/i.test(searchableText(mesh));
}
function hasBeamHint(mesh) {
return /\b(beam|beams|beem|beems|poutre|poutres|joist|joists|girder|girders|lintel|lintels|linteau|linteaux|ipe|hea|heb|ipn)\b/i.test(searchableText(mesh));
}
function hasRoofHint(mesh) {
return /\b(roof|roofs|roofing|rooftop|toit|toits|toiture|toitures|couverture|couvertures|tuile|tuiles|shingle|shingles)\b/i.test(searchableText(mesh));
}
function hasRoofStructureHint(mesh) {
// Terms that indicate roof framing / charpente rather than floor framing.
// Keep accented and non-accented French variants for real-world mesh names.
return /\b(roof\s*beam|roof\s*joist|roof\s*rafter|roof\s*truss|rafter|rafters|truss|trusses|purlin|purlins|ridge|ridge\s*beam|toit|toiture|charpente|charpentes|chevron|chevrons|panne|pannes|faitiere|faîtière|faitage|faîtage|arbaletrier|arbalétrier|ferme|fermes)\b/i.test(searchableText(mesh));
}
function hasColumnHint(mesh) {
// English + French names commonly found in GLB exports.
return /\b(column|columns|pillar|pillars|post|posts|colonne|colonnes|poteau|poteaux|pilier|piliers|potelet|potelets)\b/i.test(searchableText(mesh));
}
function hasStairHint(mesh) {
// Keep both accented and non-accented French terms.
return /\b(stair|stairs|staircase|stairway|step|steps|escalier|escaliers|marche|marches|emmarchement|emmarchements|volee|volée|volees|volées|contremarche|contremarches|giron|girons)\b/i.test(searchableText(mesh));
}
function clusterLevels(values, tolerance = STOREY_LEVEL_TOLERANCE) {
const sorted = values
.filter(v => Number.isFinite(v.y))
.sort((a, b) => a.y - b.y);
if (sorted.length === 0) return [];
const clusters = [[sorted[0]]];
for (let i = 1; i < sorted.length; i++) {
const cluster = clusters[clusters.length - 1];
const clusterY = weightedAverage(cluster);
if (Math.abs(sorted[i].y - clusterY) <= tolerance) cluster.push(sorted[i]);
else clusters.push([sorted[i]]);
}
return clusters;
}
function weightedAverage(cluster) {
const totalWeight = cluster.reduce((sum, item) => sum + item.weight, 0) || 1;
return cluster.reduce((sum, item) => sum + item.y * item.weight, 0) / totalWeight;
}
function dedupeStoreyLevels(levels) {
const deduped = [];
for (const level of levels.sort((a, b) => a - b)) {
if (deduped.length === 0 || level - deduped[deduped.length - 1] >= MIN_STOREY_HEIGHT) {
deduped.push(level);
}
}
return deduped;
}
function floorForY(y, storeys) {
if (!storeys || storeys.length === 0) return { elevation: 0, name: 'Storey 0' };
let current = storeys[0];
for (const storey of storeys) {
if (storey.elevation <= y + 0.15) current = storey;
else break;
}
return current;
}
function bboxOverlapsXZ(a, b, tol = 0) {
const A = bboxStats(a);
const B = bboxStats(b);
return (A.minX < B.maxX + tol && A.maxX > B.minX - tol &&
A.minZ < B.maxZ + tol && A.maxZ > B.minZ - tol);
}
function bboxOverlapRatioXZ(candidate, host, tol = 0) {
const C = bboxStats(candidate);
const H = bboxStats(host);
const ix = Math.max(0, Math.min(C.maxX, H.maxX + tol) - Math.max(C.minX, H.minX - tol));
const iz = Math.max(0, Math.min(C.maxZ, H.maxZ + tol) - Math.max(C.minZ, H.minZ - tol));
const candidateArea = Math.max(0.0001, C.sizeX * C.sizeZ);
return (ix * iz) / candidateArea;
}
function triangleFaceAnalysis(mesh) {
if (mesh.faceAnalysis) return mesh.faceAnalysis;
let totalArea = 0;
let verticalArea = 0;
let horizontalArea = 0;
let flatArea = 0;
let inclinedArea = 0;
let normalXArea = 0;
let normalYArea = 0;
let normalZArea = 0;
const positions = mesh.positions;
const indices = mesh.indices;
for (let i = 0; i < indices.length; i += 3) {
const ia = indices[i] * 3;
const ib = indices[i + 1] * 3;
const ic = indices[i + 2] * 3;
const ax = positions[ia];
const ay = positions[ia + 1];
const az = positions[ia + 2];
const bx = positions[ib];
const by = positions[ib + 1];
const bz = positions[ib + 2];
const cx = positions[ic];
const cy = positions[ic + 1];
const cz = positions[ic + 2];
const ux = bx - ax;
const uy = by - ay;
const uz = bz - az;
const vx = cx - ax;
const vy = cy - ay;
const vz = cz - az;
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const normalLength = Math.hypot(nx, ny, nz);
if (normalLength < 1e-9) continue;
const area = normalLength / 2;
const anx = Math.abs(nx / normalLength);
const any = Math.abs(ny / normalLength); // Y is vertical in glTF.
const anz = Math.abs(nz / normalLength);
totalArea += area;
normalXArea += anx * area;
normalYArea += any * area;
normalZArea += anz * area;
// A vertical face has a mostly horizontal normal, so abs(normal.y) is small.
if (any < 0.35) verticalArea += area;
// A horizontal face has a mostly vertical normal.
if (any > 0.75) horizontalArea += area;
// Stricter flatness and sloped roof-like areas. A roof pitch of roughly
// 10–60 degrees produces a vertical component below ~0.98 and above ~0.5,
// but we keep the band wider to survive noisy triangulation.
if (any > 0.95) flatArea += area;
if (any >= 0.25 && any <= 0.95) inclinedArea += area;
}
const safeTotal = Math.max(totalArea, 1e-9);
mesh.faceAnalysis = {
totalArea,
verticalArea,
horizontalArea,
verticalRatio: verticalArea / safeTotal,
horizontalRatio: horizontalArea / safeTotal,
flatRatio: flatArea / safeTotal,
inclinedRatio: inclinedArea / safeTotal,
normalXRatio: normalXArea / safeTotal,
normalYRatio: normalYArea / safeTotal,
normalZRatio: normalZArea / safeTotal
};
return mesh.faceAnalysis;
}
function horizontalFaceLevels(mesh) {
if (mesh.horizontalFaceLevels) return mesh.horizontalFaceLevels;
const positions = mesh.positions;
const indices = mesh.indices;
const samples = [];
let totalHorizontalArea = 0;
for (let i = 0; i < indices.length; i += 3) {
const ia = indices[i] * 3;
const ib = indices[i + 1] * 3;
const ic = indices[i + 2] * 3;
const ax = positions[ia], ay = positions[ia + 1], az = positions[ia + 2];
const bx = positions[ib], by = positions[ib + 1], bz = positions[ib + 2];
const cx = positions[ic], cy = positions[ic + 1], cz = positions[ic + 2];
const ux = bx - ax, uy = by - ay, uz = bz - az;
const vx = cx - ax, vy = cy - ay, vz = cz - az;
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const normalLength = Math.hypot(nx, ny, nz);
if (normalLength < 1e-9) continue;
const area = normalLength / 2;
const any = Math.abs(ny / normalLength);
// Horizontal tread/landing-like faces. Filter out tiny triangles so noisy
// bevels or triangulated decoration do not create fake stair levels.
if (any >= 0.78 && area >= 0.01) {
const y = (ay + by + cy) / 3;
samples.push({ y, weight: area, area });
totalHorizontalArea += area;
}
}
const clusters = clusterLevels(samples, 0.08)
.map(cluster => ({
y: weightedAverage(cluster),
area: cluster.reduce((sum, item) => sum + item.area, 0),
count: cluster.length
}))
.filter(cluster => cluster.area >= Math.max(0.03, totalHorizontalArea * 0.015))
.sort((a, b) => a.y - b.y);
const yMin = clusters.length > 0 ? clusters[0].y : 0;
const yMax = clusters.length > 0 ? clusters[clusters.length - 1].y : 0;
const gaps = [];
for (let i = 1; i < clusters.length; i++) gaps.push(clusters[i].y - clusters[i - 1].y);
mesh.horizontalFaceLevels = {
clusters,
count: clusters.length,
yMin,
yMax,
ySpan: yMax - yMin,
totalHorizontalArea,
avgGap: gaps.length > 0 ? gaps.reduce((sum, gap) => sum + gap, 0) / gaps.length : 0
};
return mesh.horizontalFaceLevels;
}
function looksLikeStair(mesh) {
const s = bboxStats(mesh);
if (hasDoorHint(mesh) || hasWindowHint(mesh) || hasBeamHint(mesh) || hasRoofHint(mesh)) return false;
const explicitStair = hasStairHint(mesh);
// Key fix: don't classify large vertical wall surfaces as stairs just
// because openings create several horizontal ledges.
if (!explicitStair && looksLikeDominantWallPlane(mesh)) {
mesh.stairRejectionReason = 'dominant_wall_plane';
return false;
}
const confidence = stairStepConfidence(mesh);
if (explicitStair) {
return s.horizontal >= 0.45 && s.sizeY >= 0.08 && confidence >= 1.8;
}
return confidence >= 4.4;
}
function looksLikeColumn(mesh) {
const s = bboxStats(mesh);
const f = triangleFaceAnalysis(mesh);
if (hasDoorHint(mesh) || hasWindowHint(mesh) || hasBeamHint(mesh) || hasRoofHint(mesh) || hasStairHint(mesh)) return false;
const planMax = Math.max(s.sizeX, s.sizeZ);
const planMin = Math.min(s.sizeX, s.sizeZ);
const planAspect = planMax / Math.max(planMin, 0.001);
const namedColumn =
hasColumnHint(mesh) &&
s.sizeY >= 0.7 &&
planMax <= 1.8 &&
planMin >= 0.04 &&
planAspect <= 5.0;
// Generic column/post: compact footprint + tall vertical object. The aspect
// cap prevents doors, thin wall strips and façade mullions from becoming
// columns too easily.
const compactVertical =
s.sizeY >= 1.3 &&
planMax >= 0.10 &&
planMax <= 1.15 &&
planMin >= 0.08 &&
planAspect <= 3.2 &&
s.sizeY / Math.max(planMax, 0.001) >= 1.8 &&
s.areaXZ <= 1.35 &&
f.verticalRatio >= 0.28;
if (namedColumn || compactVertical) {
mesh.columnDetectionReason = namedColumn ? 'named_column' : 'compact_vertical_member';
return true;
}
return false;
}
function slopedBeamMetrics(mesh) {
const s = bboxStats(mesh);
// Sloped rafters / roof beams can have a large vertical bbox because their
// long axis is diagonal. Axis-aligned bbox rules then mistake them for walls.
// We therefore inspect the 2D section made by the long horizontal axis and Y:
// a sloped beam is long along a diagonal but very narrow perpendicular to it.
const useZLongAxis = s.sizeX <= 0.35 && s.sizeZ >= 0.9 && s.sizeY >= 0.25;
const useXLongAxis = s.sizeZ <= 0.35 && s.sizeX >= 0.9 && s.sizeY >= 0.25;
if (!useZLongAxis && !useXLongAxis) return null;
const positions = mesh.positions;
const samples = [];
for (let i = 0; i < positions.length; i += 3) {
samples.push({
h: useZLongAxis ? positions[i + 2] : positions[i],
y: positions[i + 1]
});
}
const hValues = samples.map(p => p.h);
const yValues = samples.map(p => p.y);
const hSpan = Math.max(...hValues) - Math.min(...hValues);
const ySpan = Math.max(...yValues) - Math.min(...yValues);
if (hSpan <= 0 || ySpan <= 0) return null;
function perpendicularSpan(sign = 1) {
const uxRaw = hSpan;
const uyRaw = sign * ySpan;
const len = Math.hypot(uxRaw, uyRaw);
const vx = -uyRaw / len;
const vy = uxRaw / len;
const projected = samples.map(p => p.h * vx + p.y * vy);
return Math.max(...projected) - Math.min(...projected);
}
const perpSpan = Math.min(perpendicularSpan(1), perpendicularSpan(-1));
const sideThickness = useZLongAxis ? s.sizeX : s.sizeZ;
const diagonalLength = Math.hypot(hSpan, ySpan);
const slope = ySpan / Math.max(hSpan, 0.001);
const maxCrossSection = Math.max(sideThickness, perpSpan);
return {
sideThickness,
perpSpan,
diagonalLength,
slope,
hSpan,
ySpan,
slenderness: diagonalLength / Math.max(maxCrossSection, 0.001)
};
}
function looksLikeSlopedBeam(mesh) {
const m = slopedBeamMetrics(mesh);
if (!m) return false;
return (
m.sideThickness >= 0.025 &&
m.sideThickness <= 0.35 &&
m.perpSpan <= 0.38 &&
m.diagonalLength >= 1.2 &&
m.slope >= 0.05 &&
m.slope <= 2.2 &&
m.slenderness >= 6.0
);
}
function looksLikeBeam(mesh) {
const s = bboxStats(mesh);
const f = triangleFaceAnalysis(mesh);
if (hasDoorHint(mesh) || hasWindowHint(mesh) || hasColumnHint(mesh) || hasStairHint(mesh)) return false;
// A generic "roof" surface should remain a roof, but roof-structure names
// such as rafter / chevron / panne / charpente can still be beams.
const roofOnly = hasRoofHint(mesh) && !hasBeamHint(mesh) && !hasRoofStructureHint(mesh);
if (roofOnly) return false;
const length = s.horizontal;
const width = s.minHoriz;
const height = s.sizeY;
// Named beams are strong signals, but still require plausible dimensions.
const namedBeam =
hasBeamHint(mesh) &&
length >= 0.5 &&
height >= 0.05 &&
height <= 1.5 &&
width <= 1.2;
// Generic beams: elongated, horizontal, modest cross-section, with enough
// vertical side faces to avoid classifying paper-thin strips or floor slabs.
const elongated = length >= 1.0 && length / Math.max(width, height, 0.001) >= 3.0;
const crossSectionOk = width >= 0.04 && width <= 0.9 && height >= 0.08 && height <= 0.9;
const notHugePanel = s.areaXZ <= Math.max(12, length * 1.2);
const hasBeamFaces = f.verticalRatio >= 0.25;
const slopedBeam = looksLikeSlopedBeam(mesh);
if (namedBeam || slopedBeam || (elongated && crossSectionOk && notHugePanel && hasBeamFaces)) {
mesh.beamDetectionReason = namedBeam
? 'named_beam'
: (slopedBeam ? 'sloped_oriented_member' : 'elongated_horizontal_member');
return true;
}
return false;
}
function looksLikeRoofCandidate(mesh) {
const s = bboxStats(mesh);
const f = triangleFaceAnalysis(mesh);
if (hasDoorHint(mesh) || hasWindowHint(mesh) || hasBeamHint(mesh)) return false;
if (s.horizontal < 0.8 || s.areaXZ < 0.8) return false;
const namedRoof = hasRoofHint(mesh);
// Sloped roof: significant inclined area, not mostly vertical like a wall.
const slopedRoof =
f.inclinedRatio >= 0.28 &&
f.verticalRatio <= 0.55 &&
s.sizeY >= 0.12 &&
s.horizontal >= 1.0;
// Flat roof candidates are handled later, because we need the global top of
// the building to distinguish them from intermediate floor slabs.
const flatRoofCandidate =
f.flatRatio >= 0.45 &&
s.sizeY < 0.7 &&
s.areaXZ >= 2.0;
if (namedRoof || slopedRoof || flatRoofCandidate) {
mesh.roofCandidate = true;
mesh.roofDetectionReason = namedRoof ? 'named_roof' : (slopedRoof ? 'sloped_surface' : 'flat_top_candidate');
return true;
}
return false;
}
function hasSimilarStackedOpeningPanel(candidate, candidates) {
const c = bboxStats(candidate);
// Very thin panels of the same plan position repeated on several storeys are
// much more likely to be windows than walls. This catches old-house windows
// that start close to the storey level and would otherwise be read as doors
// or thin wall fragments.
if (c.minHoriz > 0.20) return false;
if (c.horizontal < 0.45 || c.horizontal > 3.2) return false;
if (c.sizeY < 0.55 || c.sizeY > 2.25) return false;
return candidates.some(other => {
if (other === candidate) return false;
const o = bboxStats(other);
if (o.minHoriz > 0.22) return false;
if (o.horizontal < 0.45 || o.horizontal > 3.2) return false;
if (o.sizeY < 0.55 || o.sizeY > 2.35) return false;
const samePlan =
bboxOverlapsXZ(candidate, other, 0.12) &&
bboxOverlapRatioXZ(candidate, other, 0.12) >= 0.60 &&
bboxOverlapRatioXZ(other, candidate, 0.12) >= 0.60;
const similarWidth = Math.abs(c.horizontal - o.horizontal) <= Math.max(0.20, c.horizontal * 0.18);
const similarThickness = Math.abs(c.minHoriz - o.minHoriz) <= 0.12;
const verticallySeparated = Math.abs(c.centerY - o.centerY) >= 0.75;
return samePlan && similarWidth && similarThickness && verticallySeparated;
});
}
function looksLikeWindowPanel(candidate, candidates, storeys, hostWall = null) {
const s = bboxStats(candidate);
if (hasDoorHint(candidate)) return false;
if (hasBeamHint(candidate) || hasColumnHint(candidate) || hasStairHint(candidate) || hasRoofHint(candidate)) return false;
const veryThinPanel = s.minHoriz <= 0.20;
const plausibleWindowSize =
s.sizeY >= 0.55 &&
s.sizeY <= 2.25 &&
s.horizontal >= 0.45 &&
s.horizontal <= 3.2;
if (!veryThinPanel || !plausibleWindowSize) return false;
const floor = floorForY(s.minY, storeys);
const floorIdx = storeys.indexOf(floor);
const bottomOffset = s.minY - floor.elevation;
const repeatedPanel = hasSimilarStackedOpeningPanel(candidate, candidates);
const explicitWindow = hasWindowHint(candidate) || candidate.opacity < 0.65;
const externalLikeHost = Boolean(
hostWall &&
(hostWall.likelyExternalWall || hasExteriorWallHint(hostWall) || hostWall.wallDetectionReason === 'vertical_facade')
);
// Tall old-building windows can start slightly below or very close to the
// detected storey elevation due to thick floors/sills. Without this rule,
// they are often classified as doors or walls.
const upperStoreyTallWindowPanel =
floorIdx > 0 &&
s.horizontal >= 0.95 &&
s.sizeY <= 2.10 &&
bottomOffset >= -0.25 &&
bottomOffset <= 0.30 &&
(externalLikeHost || repeatedPanel);
if (explicitWindow || repeatedPanel || upperStoreyTallWindowPanel) {
candidate.windowDetectionReason = explicitWindow
? 'window_hint_or_glass'
: (repeatedPanel ? 'stacked_thin_panel' : 'upper_storey_thin_panel');
return true;
}
return false;