gltfpack-sys 0.1.2

Rust bindings for gltfpack - optimize and compress glTF/GLB files
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
<!doctype html>
<html lang="en">
	<head>
		<title>meshoptimizer - demo</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
		<style>
			body {
				font-family: Monospace;
				background-color: #300a24;
				color: #fff;
				margin: 0px;
				overflow: hidden;
				display: flex;
				flex-direction: column;
				height: 100vh;
			}
			#info {
				color: #fff;
				position: absolute;
				top: 10px;
				width: 100%;
				text-align: center;
				z-index: 100;
				display: block;
			}
			#info a,
			.button {
				color: #f00;
				font-weight: bold;
				text-decoration: underline;
				cursor: pointer;
			}
			#grid-container {
				width: 100%;
				flex: 1;
				display: grid;
				grid-template-columns: repeat(var(--grid-columns, 1), 1fr);
				grid-auto-rows: minmax(300px, 1fr);
				overflow-y: auto;
			}
			.renderer-container {
				position: relative;
				width: 100%;
				height: 100%;
			}
			.renderer-container canvas {
				width: 100% !important;
				height: 100% !important;
				display: block;
				user-select: none;
			}
			.renderer-label {
				position: absolute;
				top: 10px;
				left: 10px;
				background-color: rgba(0, 0, 0, 0.5);
				padding: 5px 10px;
				border-radius: 5px;
				pointer-events: auto;
				font-size: 14px;
				transition: background-color 0.2s;
			}
			.renderer-label:hover {
				background-color: rgba(0, 0, 0, 0.7);
			}
			.renderer-label.focused {
				background-color: rgba(255, 100, 100, 0.7);
				color: white;
			}
			.renderer-label.clickable {
				cursor: pointer;
			}
			.stats-label {
				position: absolute;
				top: 45px;
				left: 10px;
				background-color: rgba(0, 0, 0, 0.5);
				padding: 5px 10px;
				border-radius: 5px;
				pointer-events: none;
				font-size: 12px;
				line-height: 1.4;
			}

			.renderer-container.hidden {
				display: none;
			}

			/* Custom scrollbar styling */
			#grid-container::-webkit-scrollbar {
				width: 16px;
			}

			#grid-container::-webkit-scrollbar-track {
				background: rgba(255, 255, 255, 0.1);
			}

			#grid-container::-webkit-scrollbar-thumb {
				background: rgba(255, 255, 255, 0.3);
				border-radius: 8px;
			}

			#grid-container::-webkit-scrollbar-thumb:hover {
				background: rgba(255, 255, 255, 0.5);
			}
		</style>

		<script async src="https://cdn.jsdelivr.net/npm/es-module-shims@2.0.10/dist/es-module-shims.min.js"></script>
		<script type="importmap">
			{
				"imports": {
					"three": "https://cdn.jsdelivr.net/npm/three@0.174.0/build/three.module.js",
					"three-examples/": "https://cdn.jsdelivr.net/npm/three@0.174.0/examples/jsm/",
					"lil-gui": "https://cdn.jsdelivr.net/npm/lil-gui@0.20.0/dist/lil-gui.esm.js"
				}
			}
		</script>
	</head>

	<body>
		<div id="grid-container"></div>
		<input type="file" id="fileInput" style="display: none" accept=".obj,.glb" multiple />

		<script type="module">
			import * as THREE from 'three';
			import { GLTFLoader } from 'three-examples/loaders/GLTFLoader.js';
			import { OBJLoader } from 'three-examples/loaders/OBJLoader.js';
			import { OrbitControls } from 'three-examples/controls/OrbitControls.js';
			import { mergeVertices } from 'three-examples/utils/BufferGeometryUtils.js';
			import { MeshoptDecoder } from '../js/meshopt_decoder.module.js';
			import { MeshoptSimplifier } from '../js/meshopt_simplifier.module.js';
			import { GUI } from 'lil-gui';

			var container, gridContainer;
			var camera, clock;
			var renderers = [];
			var scenes = [];
			var controls = [];
			var models = [];
			var mixers = [];
			var viewStats = [];

			// Focus tracking
			var focusedViewIndex = -1; // -1 means no focus (show all)

			// Track camera distance for autoLod
			var lastCameraDistance = 0;

			var settings = {
				wireframe: false,
				wireframeOverlay: false,
				animate: false,
				pointSize: 1.0,
				ratio: 1.0,
				debugOverlay: false,
				sloppy: false,
				permissive: false,
				lockBorder: false,
				preprune: 0.0,
				prune: true,
				regularize: false,
				solve: false,
				useAttributes: true,
				errorThresholdLog10: 1,
				errorScaled: true,
				normalWeight: 1.0,
				colorWeight: 1.0,
				textureWeight: 0.0,
				autoLod: false,
				autoLodFactor: 1.0,
				gridColumns: 2,

				loadFile: function () {
					var input = document.getElementById('fileInput');
					input.onchange = function () {
						var files = Array.from(input.files).sort(function (a, b) {
							var an = a.name.split('.')[0];
							var bn = b.name.split('.')[0];
							return an.localeCompare(bn);
						});
						loadFiles(files);
					};
					input.click();
				},

				updateModule: function () {
					reload();
					simplify();
				},
				autoUpdate: false,
				autoUpdateStatus: '',
			};

			var gui = new GUI({ width: 300 });
			var guiDisplay = gui.addFolder('Display');
			guiDisplay.add(settings, 'wireframe').onChange(update);
			guiDisplay.add(settings, 'wireframeOverlay').onChange(simplify); // requires debug data rebuild
			guiDisplay.add(settings, 'animate').onChange(update);
			guiDisplay.add(settings, 'pointSize', 1, 16).onChange(update);
			guiDisplay.add(settings, 'debugOverlay').onChange(simplify); // requires debug data rebuild
			guiDisplay.add(settings, 'gridColumns', 1, 6, 1).onChange(updateGridLayout);

			var guiSimplify = gui.addFolder('Simplify');
			guiSimplify.add(settings, 'ratio', 0, 1, 0.01).onChange(simplify);
			guiSimplify.add(settings, 'sloppy').onChange(simplify);
			guiSimplify.add(settings, 'permissive').onChange(simplify);
			guiSimplify.add(settings, 'lockBorder').onChange(simplify);
			guiSimplify.add(settings, 'prune').onChange(simplify);
			guiSimplify.add(settings, 'regularize').onChange(simplify);
			guiSimplify.add(settings, 'solve').onChange(simplify);
			guiSimplify.add(settings, 'preprune', 0, 0.2, 0.01).onChange(simplify);
			guiSimplify.add(settings, 'useAttributes').onChange(simplify).onFinishChange(updateSettings);

			var guiAttributes = [];
			guiAttributes.push(guiSimplify.add(settings, 'normalWeight', 0, 2, 0.01).onChange(simplify));
			guiAttributes.push(guiSimplify.add(settings, 'colorWeight', 0, 2, 0.01).onChange(simplify));
			guiAttributes.push(guiSimplify.add(settings, 'textureWeight', 0, 100, 0.1).onChange(simplify));

			guiSimplify.add(settings, 'errorScaled').onChange(simplify);
			guiSimplify.add(settings, 'errorThresholdLog10', 0, 3, 0.1).onChange(simplify);

			var guiLod = gui.addFolder('LOD');
			guiLod.add(settings, 'autoLod').onChange(simplify);
			guiLod.add(settings, 'autoLodFactor', 0, 10, 0.01).onChange(simplify);

			var guiLoad = gui.addFolder('Load');
			guiLoad.add(settings, 'loadFile');
			guiLoad.add(settings, 'updateModule');
			guiLoad.add(settings, 'autoUpdate').onChange(autoReload);
			guiLoad.add(settings, 'autoUpdateStatus').listen();

			updateSettings();
			init();
			loadDefault();
			animate();

			function loadFiles(files) {
				// Clear existing views
				clearViews();

				if (files.length > 0) {
					// Set grid columns based on the number of files, up to the max setting
					const columns = Math.min(files.length, settings.gridColumns);
					document.documentElement.style.setProperty('--grid-columns', columns);

					// Load each file into a separate view
					for (var i = 0; i < files.length; i++) {
						var file = files[i];
						var uri = URL.createObjectURL(file);
						var ext = file.name.split('.').pop().toLowerCase();

						createView(i, file.name);
						loadIntoView(i, uri, ext);
					}
				}
			}

			function updateGridLayout() {
				if (renderers.length > 0) {
					var visibleViews = focusedViewIndex >= 0 ? 1 : renderers.length;
					var columns = Math.min(visibleViews, settings.gridColumns);
					document.documentElement.style.setProperty('--grid-columns', columns);

					// Set grid cell height based on whether we're in single view or grid mode
					if (columns > 1) {
						// In grid mode, make cells square by calculating height based on viewport width
						var cellWidth = Math.floor(window.innerWidth / columns);
						document.documentElement.style.setProperty('--grid-cell-height', cellWidth + 'px');
					} else {
						// Single view mode, use full height
						document.documentElement.style.setProperty('--grid-cell-height', '100vh');
					}

					updateRendererSizes();
				}
			}

			// Helper function to handle autoLOD updates - no longer tied to camera rotation
			function updateAutoLod() {
				if (settings.autoLod) {
					// Check if distance has changed significantly
					var center = new THREE.Vector3();
					var currentDistance = camera.position.distanceTo(center);

					if (Math.abs(currentDistance - lastCameraDistance) > 1e-3) {
						lastCameraDistance = currentDistance;
						simplify();
					}
				}
			}

			function updateSettings() {
				for (var i = 0; i < guiAttributes.length; ++i) {
					guiAttributes[i].enable(settings.useAttributes);
				}
			}

			function clearViews() {
				// Remove all existing renderers and clear arrays
				for (var i = 0; i < renderers.length; i++) {
					var container = renderers[i].domElement.parentElement;
					if (container) {
						container.parentElement.removeChild(container);
					}
				}

				renderers = [];
				scenes = [];
				controls = [];
				models = [];
				mixers = [];
				viewStats = [];

				// Reset focus state
				focusedViewIndex = -1;

				// Clear the grid container
				gridContainer.innerHTML = '';
			}

			function updateLabelsClickability() {
				var isClickable = renderers.length > 1;

				for (var i = 0; i < renderers.length; i++) {
					var container = renderers[i].domElement.parentElement;
					var label = container.querySelector('.renderer-label');

					if (isClickable) {
						label.classList.add('clickable');
						label.title = 'Click to focus on this view';
					} else {
						label.classList.remove('clickable');
						label.title = '';
					}
				}
			}

			function toggleFocus(viewIndex) {
				if (focusedViewIndex === viewIndex) {
					// Currently focused on this view, unfocus (show all)
					focusedViewIndex = -1;
				} else {
					// Focus on this view
					focusedViewIndex = viewIndex;
				}
				updateFocusDisplay();
				simplify(); // Re-run simplify with new focus state
			}

			function updateFocusDisplay() {
				for (var i = 0; i < renderers.length; i++) {
					var container = renderers[i].domElement.parentElement;
					var label = container.querySelector('.renderer-label');

					if (focusedViewIndex === -1) {
						// No focus - show all containers
						container.classList.remove('hidden');
						label.classList.remove('focused');
						if (renderers.length > 1) {
							label.title = 'Click to focus on this view';
						}
					} else if (focusedViewIndex === i) {
						// This is the focused view
						container.classList.remove('hidden');
						label.classList.add('focused');
						label.title = 'Click to exit focus mode';
					} else {
						// Hide non-focused views
						container.classList.add('hidden');
						label.classList.remove('focused');
					}
				}

				// Update grid layout when focus changes
				updateGridLayout();
			}

			function createView(index, name) {
				// Create renderer container
				var rendererContainer = document.createElement('div');
				rendererContainer.className = 'renderer-container';
				gridContainer.appendChild(rendererContainer);

				// Add label with file name
				var label = document.createElement('div');
				label.className = 'renderer-label';
				label.textContent = name;
				label.onclick = function () {
					if (renderers.length > 1) {
						toggleFocus(index);
					}
				};
				rendererContainer.appendChild(label);

				// Add stats label
				var statsLabel = document.createElement('div');
				statsLabel.className = 'stats-label';
				rendererContainer.appendChild(statsLabel);

				// Initialize stats for this view
				viewStats.push({
					triangles: 0,
					vertices: 0,
					error: 0,
					ratio: 0,
					label: statsLabel,
				});

				// Create renderer
				var renderer = new THREE.WebGLRenderer();
				renderer.setPixelRatio(window.devicePixelRatio);
				rendererContainer.appendChild(renderer.domElement);
				renderers.push(renderer);

				// Create scene
				var scene = new THREE.Scene();
				scene.background = new THREE.Color(0x300a24);
				scenes.push(scene);

				// Add lighting
				var ambientLight = new THREE.AmbientLight(0xcccccc, 1);
				scene.add(ambientLight);

				var pointLightR = new THREE.PointLight(0xffffff, 4);
				pointLightR.position.set(3, 3, 0);
				pointLightR.decay = 0.5;
				scene.add(pointLightR);

				var pointLightL = new THREE.PointLight(0xffffff, 1);
				pointLightL.position.set(-3, 5, 0);
				pointLightL.decay = 0.5;
				scene.add(pointLightL);

				// Create controls
				var control = new OrbitControls(camera, renderer.domElement);
				control.addEventListener('change', updateAutoLod);
				controls.push(control);

				// Set null placeholders
				models.push(null);
				mixers.push(null);

				// Adjust renderer size
				updateRendererSizes();

				// Update label clickability for all views
				updateLabelsClickability();
			}

			function simplifyMesh(geo, threshold, scale) {
				var attributes = 8; // 3 color, 3 normal, 2 uv

				var positions = new Float32Array(geo.attributes.position.array).slice(); // clone for solve
				var indices = new Uint32Array(geo.index.array).slice(); // clone for solve, upcast 16-bit indices for _InternalDebug
				var target = settings.autoLod ? 0 : Math.floor((indices.length * settings.ratio) / 3) * 3;

				if (settings.useAttributes) {
					var attrib = new Float32Array(geo.attributes.position.count * attributes);

					for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
						if (geo.attributes.normal) {
							attrib[i * attributes + 0] = geo.attributes.normal.getX(i);
							attrib[i * attributes + 1] = geo.attributes.normal.getY(i);
							attrib[i * attributes + 2] = geo.attributes.normal.getZ(i);
						}

						if (geo.attributes.color) {
							attrib[i * attributes + 3] = geo.attributes.color.getX(i);
							attrib[i * attributes + 4] = geo.attributes.color.getY(i);
							attrib[i * attributes + 5] = geo.attributes.color.getZ(i);
						}

						if (geo.attributes.uv) {
							attrib[i * attributes + 6] = geo.attributes.uv.getX(i);
							attrib[i * attributes + 7] = geo.attributes.uv.getY(i);
						}
					}

					var attrib_weights = [
						settings.normalWeight,
						settings.normalWeight,
						settings.normalWeight,
						settings.colorWeight,
						settings.colorWeight,
						settings.colorWeight,
						settings.textureWeight,
						settings.textureWeight,
					];
				} else {
					var attrib = new Float32Array();
					var attrib_weights = [];
					attributes = 0;
				}

				var flags = [];
				if (settings.lockBorder) {
					flags.push('LockBorder');
				}
				if (settings.prune) {
					flags.push('Prune');
				}
				if (settings.regularize) {
					flags.push('Regularize');
				}
				if (settings.permissive) {
					flags.push('Permissive');
				}
				if (settings.debugOverlay) {
					flags.push('_InternalDebug');
				}

				var locks = new Uint8Array(geo.attributes.position.count);

				if (settings.permissive) {
					var pos_cache = {};
					var pos_remap = [];

					var unique = 0;

					for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
						var px = geo.attributes.position.getX(i);
						var py = geo.attributes.position.getY(i);
						var pz = geo.attributes.position.getZ(i);
						var pk = px.toString() + ' ' + py.toString() + ' ' + pz.toString();

						if (pos_cache[pk] === undefined) {
							pos_cache[pk] = i;
							pos_remap[i] = i;
							unique++;
						} else {
							pos_remap[i] = pos_cache[pk];
						}
					}

					if (geo.attributes.normal) {
						for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
							if (pos_remap[i] != i) {
								var rx = geo.attributes.normal.getX(pos_remap[i]),
									ry = geo.attributes.normal.getY(pos_remap[i]),
									rz = geo.attributes.normal.getZ(pos_remap[i]);
								var nx = geo.attributes.normal.getX(i),
									ny = geo.attributes.normal.getY(i),
									nz = geo.attributes.normal.getZ(i);

								// keep sharp edges
								if (rx * nx + ry * ny + rz * nz < 0.25) {
									locks[i] |= 2;
								}
							}
						}
					}

					if (geo.attributes.uv) {
						for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
							if (pos_remap[i] != i) {
								var ru = geo.attributes.uv.getX(pos_remap[i]),
									rv = geo.attributes.uv.getY(pos_remap[i]);
								var u = geo.attributes.uv.getX(i),
									v = geo.attributes.uv.getY(i);

								// keep UV seams
								if (u != ru || v != rv) {
									locks[i] |= 2;
								}
							}
						}
					}
				}

				var stride = geo.attributes.position instanceof THREE.InterleavedBufferAttribute ? geo.attributes.position.data.stride : 3;

				if (settings.preprune > 0) {
					indices = MeshoptSimplifier.simplifyPrune(indices, positions, stride, settings.preprune / scale);
					target = Math.min(target, indices.length);
				}

				var S = MeshoptSimplifier; // to avoid line breaks below...
				var res = settings.sloppy
					? S.simplifySloppy(indices, positions, stride, null, target, threshold)
					: settings.solve
						? S.simplifyWithUpdate(indices, positions, stride, attrib, attributes, attrib_weights, locks, target, threshold, flags)
						: S.simplifyWithAttributes(indices, positions, stride, attrib, attributes, attrib_weights, locks, target, threshold, flags);

				if (!settings.sloppy && settings.solve) {
					res[0] = indices.slice(0, res[0]);
				}

				var rgeo = geo.clone();

				var dind = res[0];
				var dlen = dind.length;

				if (settings.debugOverlay) {
					// we need extra indices for debug overlay
					dind = Array.from(dind);

					var mask = (1 << 28) - 1;

					for (var kind = 1; kind <= 5; ++kind) {
						var offset = dind.length;

						for (var i = 0; i < dlen; i += 3) {
							for (var e = 0; e < 3; ++e) {
								var a = dind[i + e],
									b = dind[i + ((e + 1) % 3)];
								var ak = (a >> 28) & 7,
									bk = (b >> 28) & 7;

								if ((a >> 31 != 0 || kind == 3) && (ak == kind || bk == kind) && (ak == kind || ak == 4) && (bk == kind || bk == 4)) {
									// edge of current kind (allow one of the vertices to be locked)
									// note: complex edges ignore loop metadata
									dind.push(a & mask);
									dind.push(a & mask);
									dind.push(b & mask);
								} else if (a >> 31 != 0 && kind == 5 && ak != bk && ak != 4 && bk != 4) {
									// mixed edge (neither vertex is locked, and they are of different kinds)
									dind.push(a & mask);
									dind.push(a & mask);
									dind.push(b & mask);
								} else if (kind == 4 && ak == kind && bk == kind) {
									// locked edge (not be marked as a loop)
									dind.push(a & mask);
									dind.push(a & mask);
									dind.push(b & mask);
								}
							}
						}

						if (offset != dind.length) {
							rgeo.addGroup(offset, dind.length - offset, kind + 1); // +1 to skip overlay
							offset = dind.length;
						}
					}

					// clear debug bits for actual indices
					for (var i = 0; i < dlen; i++) {
						dind[i] &= mask;
					}

					if (settings.wireframeOverlay) {
						rgeo.addGroup(0, dlen, 1); // 1=overlay
					}
				} else if (settings.wireframeOverlay) {
					rgeo.addGroup(0, dind.length, 1); // 1=overlay
				}

				rgeo.index.array = new Uint32Array(dind);
				rgeo.index.count = dind.length;
				rgeo.index.needsUpdate = true;

				if (settings.solve) {
					rgeo.attributes.position = new THREE.BufferAttribute(positions, stride);

					if (settings.useAttributes) {
						for (var i = 0, e = geo.attributes.position.count; i < e; ++i) {
							var nx = attrib[i * attributes + 0];
							var ny = attrib[i * attributes + 1];
							var nz = attrib[i * attributes + 2];

							var nl = Math.sqrt(nx * nx + ny * ny + nz * nz);

							if (nl > 0) {
								attrib[i * attributes + 0] = nx / nl;
								attrib[i * attributes + 1] = ny / nl;
								attrib[i * attributes + 2] = nz / nl;
							}
						}

						var attribbuf = new THREE.InterleavedBuffer(attrib, attrib_weights.length);

						if (geo.attributes.normal) {
							rgeo.attributes.normal = new THREE.InterleavedBufferAttribute(attribbuf, 3, 0, false);
						}
						if (geo.attributes.color) {
							rgeo.attributes.color = new THREE.InterleavedBufferAttribute(attribbuf, 3, 3, false);
						}
						if (geo.attributes.uv) {
							rgeo.attributes.uv = new THREE.InterleavedBufferAttribute(attribbuf, 2, 6, false);
						}
					}
				}

				rgeo.addGroup(0, dlen, 0);

				return [rgeo, dlen / 3, res[1]];
			}

			function simplifyPoints(geo) {
				var positions = new Float32Array(geo.attributes.position.array);
				var colors = undefined;

				var target = Math.floor(geo.attributes.position.count * settings.ratio);

				if (settings.useAttributes && geo.attributes.color) {
					colors = new Float32Array(geo.attributes.color.array);
				}

				var pos_stride = geo.attributes.position instanceof THREE.InterleavedBufferAttribute ? geo.attributes.position.data.stride : 3;
				var col_stride =
					geo.attributes.color instanceof THREE.InterleavedBufferAttribute
						? geo.attributes.color.data.stride
						: geo.attributes.color.itemSize;

				// note: we are converting source color array without normalization; if the color data is quantized, we need to divide by 255 to normalize it
				var colorScale = geo.attributes.color && geo.attributes.color.normalized ? 255 : 1;

				console.time('simplify');

				var res = MeshoptSimplifier.simplifyPoints(positions, pos_stride, target, colors, col_stride, settings.colorWeight / colorScale);

				console.timeEnd('simplify');

				console.log('simplified to', res.length);

				geo.index = new THREE.BufferAttribute(res, 1);
			}

			function getRadius(obj) {
				var box = new THREE.Box3().setFromObject(obj);
				return box.max.sub(box.min).length() / 2;
			}

			function simplify() {
				MeshoptSimplifier.ready.then(function () {
					var threshold = Math.pow(10, -settings.errorThresholdLog10);

					if (settings.autoLod) {
						// compute distance to model sphere
						// ideally this should actually use the real radius and center :) but we rescale/center the model when loading
						var center = new THREE.Vector3();
						var radius = 1;
						var distance = Math.max(camera.position.distanceTo(center) - radius, 0);
						var loderrortarget = 1e-3 * (2 * Math.tan(camera.fov * 0.5 * (Math.PI / 180))); // ~1 pixel at 1k x 1k

						// note: we are currently cutting corners wrt handling the actual mesh scale
						// since we rescale the entire scene to fit a unit box, we can directly feed the threshold
						// this works correctly if there's just one mesh or scales match; ideally we tweak this to compute
						// threshold per mesh based on relative scale between mesh and scene.
						// this also computes distance to model *center* instead of surface boundary so features on the boundary
						// might be simplified more than they should be.
						threshold = distance * loderrortarget * settings.autoLodFactor;
					}

					// Process each scene
					for (var sceneIndex = 0; sceneIndex < scenes.length; sceneIndex++) {
						var scene = scenes[sceneIndex];
						if (focusedViewIndex >= 0 && sceneIndex != focusedViewIndex) {
							continue;
						}

						// Reset stats for this view
						var stats = viewStats[sceneIndex];
						stats.triangles = 0;
						stats.vertices = 0;
						stats.error = 0;
						stats.ratio = 0;

						var rnum = 0;
						var rden = 0;

						var extent = getRadius(scene);

						scene.traverse(function (object) {
							if (object.isMesh && object.geometry.index) {
								if (!object.original) {
									object.original = object.geometry.clone();

									// use small depth offset to avoid overlay z-fighting with the original mesh
									// has to be done on the main material as overlays use lines that don't support depth offset
									object.material.polygonOffset = true;
									object.material.polygonOffsetFactor = 0.5;
									object.material.polygonOffsetUnits = 16;

									object.material = [
										object.material,
										new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true }), // overlay
										new THREE.MeshBasicMaterial({ color: 0x0000ff, wireframe: true }), // border
										new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }), // seam
										new THREE.MeshBasicMaterial({ color: 0x009f9f, wireframe: true }), // complex
										new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }), // locked
										new THREE.MeshBasicMaterial({ color: 0xff9f00, wireframe: true }), // mixed edge
									];
								}

								var scale = settings.errorScaled ? getRadius(object) / extent : 1.0;

								var [geo, tri, err] = simplifyMesh(object.original, threshold / scale, scale);

								object.geometry = geo;

								stats.error = Math.max(stats.error, err * scale);
								stats.triangles += tri;
								stats.vertices += object.geometry.attributes.position.count;

								rnum += tri;
								rden += object.original.index.count / 3;
							}
							if (object.isPoints) {
								simplifyPoints(object.geometry);

								stats.vertices += object.geometry.index.count;

								rnum += object.geometry.index.count;
								rden += object.geometry.attributes.position.count;
							}
						});

						stats.ratio = rden > 0 ? (rnum / rden) * 100 : 0;

						// Update stats display for this view
						updateStatsDisplay(sceneIndex);
					}
				});
			}

			function updateStatsDisplay(viewIndex) {
				if (viewIndex >= 0 && viewIndex < viewStats.length) {
					var stats = viewStats[viewIndex];

					stats.label.innerHTML =
						'Triangles: ' +
						stats.triangles +
						'<br>' +
						'Vertices: ' +
						stats.vertices +
						'<br>' +
						'Error: ' +
						stats.error.toExponential(3) +
						'<br>' +
						'Ratio: ' +
						stats.ratio.toFixed(1) +
						'%';
				}
			}

			function reload() {
				var simp = import('/js/meshopt_simplifier.module.js?x=' + Date.now());
				MeshoptSimplifier.ready = simp.then(function (s) {
					return s.MeshoptSimplifier.ready.then(function () {
						for (var prop in s.MeshoptSimplifier) {
							MeshoptSimplifier[prop] = s.MeshoptSimplifier[prop];
						}
					});
				});
			}

			var moduleLastModified = 0;

			function autoReload() {
				if (!settings.autoUpdate) return;

				fetch('/js/meshopt_simplifier.module.js?x=' + Date.now(), { method: 'HEAD' })
					.then(function (r) {
						var last = r.headers.get('Last-Modified');
						if (last != moduleLastModified) {
							moduleLastModified = last;
							reload();
							simplify();
						}

						settings.autoUpdateStatus = new Date(last).toLocaleTimeString();
						setTimeout(autoReload, 1000);
					})
					.catch(function (e) {
						settings.autoUpdateStatus = 'error';
						setTimeout(autoReload, 5000);
					});
			}

			function update() {
				for (var sceneIndex = 0; sceneIndex < scenes.length; sceneIndex++) {
					var scene = scenes[sceneIndex];

					scene.traverse(function (child) {
						if (child.isMesh) {
							if (Array.isArray(child.material)) {
								child.material[0].wireframe = settings.wireframe;
							} else {
								child.material.wireframe = settings.wireframe;
							}
						}
						if (child.isPoints) {
							child.material.size = settings.pointSize;
						}
					});
				}
			}

			function loadIntoView(viewIndex, path, ext) {
				if (models[viewIndex]) {
					scenes[viewIndex].remove(models[viewIndex]);
					models[viewIndex] = undefined;
					mixers[viewIndex] = undefined;
				}

				var onProgress = function (xhr) {};
				var onError = function (e) {
					console.log(e);
				};

				function center(model) {
					var bbox = new THREE.Box3().setFromObject(model);
					var scale = 2 / Math.max(bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y, bbox.max.z - bbox.min.z);
					var offset = new THREE.Vector3().addVectors(bbox.max, bbox.min).multiplyScalar(scale / 2);

					model.scale.set(scale, scale, scale);
					model.position.set(-offset.x, -offset.y, -offset.z);
				}

				if (ext == 'gltf' || ext == 'glb') {
					var loader = new GLTFLoader();
					loader.setMeshoptDecoder(MeshoptDecoder);
					loader.load(
						path,
						function (gltf) {
							models[viewIndex] = gltf.scene;
							center(models[viewIndex]);
							scenes[viewIndex].add(models[viewIndex]);

							mixers[viewIndex] = new THREE.AnimationMixer(models[viewIndex]);

							if (gltf.animations.length) {
								mixers[viewIndex].clipAction(gltf.animations[gltf.animations.length - 1]).play();
							}

							// Apply simplification
							simplify();
						},
						onProgress,
						onError
					);
				} else if (ext == 'obj') {
					var loader = new OBJLoader();
					loader.load(
						path,
						function (obj) {
							obj.traverse(function (node) {
								if (node.isMesh) {
									// obj loader does not index the geometry, so we need to do it ourselves
									node.geometry = mergeVertices(node.geometry);

									// we use groups and multiple materials for debug visualization, so merge all of the source ones for now
									if (Array.isArray(node.material)) {
										node.material = node.material[0];
										node.geometry.clearGroups();
									}
								}
							});

							models[viewIndex] = obj;
							center(models[viewIndex]);
							scenes[viewIndex].add(models[viewIndex]);

							// Apply simplification
							simplify();
						},
						onProgress,
						onError
					);
				} else {
					console.error('Unsupported file format');
				}
			}

			function loadDefault() {
				// Create a single view with the default model
				document.documentElement.style.setProperty('--grid-columns', 1);
				createView(0, 'pirate.glb');
				loadIntoView(0, 'pirate.glb', 'glb');
			}

			function init() {
				container = document.createElement('div');
				document.body.appendChild(container);

				gridContainer = document.getElementById('grid-container');

				// Create a single camera shared by all views
				camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
				camera.position.y = 1.0;
				camera.position.z = 3.0;

				clock = new THREE.Clock();

				window.addEventListener('resize', updateRendererSizes, false);
			}

			function updateRendererSizes() {
				// Calculate the correct aspect ratio based on a visible view
				var container = renderers[focusedViewIndex >= 0 ? focusedViewIndex : 0].domElement.parentElement;
				var aspectRatio = container.clientWidth / container.clientHeight;

				// Update camera aspect ratio once
				camera.aspect = aspectRatio;
				camera.updateProjectionMatrix();

				// Update all renderer sizes
				for (var i = 0; i < renderers.length; i++) {
					var domElement = renderers[i].domElement;
					var container = domElement.parentElement;

					// Use the container's actual dimensions
					var width = container.clientWidth;
					var height = container.clientHeight;

					renderers[i].setSize(width, height);
				}
			}

			function animate() {
				requestAnimationFrame(animate);

				// Update all controls
				for (var i = 0; i < controls.length; i++) {
					controls[i].update();
				}

				// Update animation mixers
				if (settings.animate) {
					var delta = clock.getDelta();
					for (var i = 0; i < mixers.length; i++) {
						if (mixers[i]) {
							mixers[i].update(delta);
						}
					}
				}

				// Render only visible views
				for (var i = 0; i < renderers.length; i++) {
					// Only render if view is visible (not hidden by focus mode)
					if (focusedViewIndex === -1 || focusedViewIndex === i) {
						renderers[i].render(scenes[i], camera);
					}
				}
			}
		</script>
	</body>
</html>