MikaFil commited on
Commit
6ac2e40
·
verified ·
1 Parent(s): de20365

Update viewer.js

Browse files
Files changed (1) hide show
  1. viewer.js +333 -313
viewer.js CHANGED
@@ -10,337 +10,357 @@ let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minPivotY, min
10
  let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ;
11
  let sogsUrl, glbUrl, canvasBg;
12
 
13
- function hexToRgbaArray(hex) {
14
- try {
15
- hex = hex.replace("#", "");
16
- if (hex.length === 6) hex += "FF";
17
- if (hex.length !== 8) return [1, 1, 1, 1];
18
- const num = parseInt(hex, 16);
19
- return [
20
- ((num >> 24) & 0xFF) / 255,
21
- ((num >> 16) & 0xFF) / 255,
22
- ((num >> 8) & 0xFF) / 255,
23
- (num & 0xFF) / 255
24
- ];
25
- } catch (e) {
26
- return [1, 1, 1, 1];
27
- }
28
  }
29
 
30
- async function loadImageAsTexture(url, app) {
31
- return new Promise((resolve, reject) => {
32
- const img = new window.Image();
33
- img.crossOrigin = "anonymous";
34
- img.onload = function() {
35
- const tex = new pc.Texture(app.graphicsDevice, {
36
- width: img.width,
37
- height: img.height,
38
- format: pc.PIXELFORMAT_R8_G8_B8_A8,
 
 
 
 
 
39
  });
40
- tex.setSource(img);
41
- resolve(tex);
42
- };
43
- img.onerror = reject;
44
- img.src = url;
45
- });
46
- }
47
-
48
- export async function initializeViewer(config, instanceId) {
49
-
50
- const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
51
- const isMobile = isIOS || /Android/i.test(navigator.userAgent);
52
-
53
- try {
54
- // Parse config
55
- sogsUrl = config.sogs_json_url;
56
- glbUrl = config.glb_url;
57
- canvasBg = config.canvas_background || "#ffffff";
58
- minZoom = parseFloat(config.minZoom || "1");
59
- maxZoom = parseFloat(config.maxZoom || "20");
60
- minAngle = parseFloat(config.minAngle || "-45");
61
- maxAngle = parseFloat(config.maxAngle || "90");
62
- minAzimuth= (config.minAzimuth !== undefined) ? parseFloat(config.minAzimuth) : -360;
63
- maxAzimuth= (config.maxAzimuth !== undefined) ? parseFloat(config.maxAzimuth) : 360;
64
- minPivotY = parseFloat(config.minPivotY || "0");
65
- minY = (config.minY !== undefined) ? parseFloat(config.minY) : 0;
66
-
67
- modelX = (config.modelX !== undefined) ? parseFloat(config.modelX) : 0;
68
- modelY = (config.modelY !== undefined) ? parseFloat(config.modelY) : 0;
69
- modelZ = (config.modelZ !== undefined) ? parseFloat(config.modelZ) : 0;
70
- modelScale = (config.modelScale !== undefined) ? parseFloat(config.modelScale) : 1;
71
- modelRotationX = (config.modelRotationX !== undefined) ? parseFloat(config.modelRotationX) : 0;
72
- modelRotationY = (config.modelRotationY !== undefined) ? parseFloat(config.modelRotationY) : 0;
73
- modelRotationZ = (config.modelRotationZ !== undefined) ? parseFloat(config.modelRotationZ) : 0;
74
-
75
- const cameraX = (config.cameraX !== undefined) ? parseFloat(config.cameraX) : 0;
76
- const cameraY = (config.cameraY !== undefined) ? parseFloat(config.cameraY) : 2;
77
- const cameraZ = (config.cameraZ !== undefined) ? parseFloat(config.cameraZ) : 5;
78
- const cameraXPhone = (config.cameraXPhone !== undefined) ? parseFloat(config.cameraXPhone) : cameraX;
79
- const cameraYPhone = (config.cameraYPhone !== undefined) ? parseFloat(config.cameraYPhone) : cameraY;
80
- const cameraZPhone = (config.cameraZPhone !== undefined) ? parseFloat(config.cameraZPhone) : (cameraZ * 1.5);
81
-
82
- chosenCameraX = isMobile ? cameraXPhone : cameraX;
83
- chosenCameraY = isMobile ? cameraYPhone : cameraY;
84
- chosenCameraZ = isMobile ? cameraZPhone : cameraZ;
85
-
86
- const canvasId = 'canvas-' + instanceId;
87
- const progressDialog = document.getElementById('progress-dialog-' + instanceId);
88
- const progressIndicator= document.getElementById('progress-indicator-' + instanceId);
89
- const viewerContainer = document.getElementById('viewer-container-' + instanceId);
90
-
91
- let oldCanvas = document.getElementById(canvasId);
92
- if (oldCanvas) oldCanvas.remove();
93
-
94
- const canvas = document.createElement('canvas');
95
- canvas.id = canvasId;
96
- canvas.className = 'ply-canvas';
97
- canvas.style.width = "100%";
98
- canvas.style.height = "100%";
99
- canvas.setAttribute('tabindex', '0');
100
- viewerContainer.insertBefore(canvas, progressDialog);
101
-
102
- // Apply background color from config if present
103
- canvas.style.background = canvasBg;
104
-
105
- canvas.style.touchAction = "none";
106
- canvas.style.webkitTouchCallout = "none";
107
- canvas.addEventListener('gesturestart', e => e.preventDefault());
108
- canvas.addEventListener('gesturechange', e => e.preventDefault());
109
- canvas.addEventListener('gestureend', e => e.preventDefault());
110
- canvas.addEventListener('dblclick', e => e.preventDefault());
111
- canvas.addEventListener('touchstart', e => { if (e.touches.length > 1) e.preventDefault(); }, { passive: false });
112
-
113
- // --- Mouse wheel suppression
114
- canvas.addEventListener('wheel', (e) => {
115
- e.preventDefault(); // Only block page scroll if mouse is over viewer
116
- }, { passive: false });
117
-
118
- if (progressDialog) progressDialog.style.display = 'block';
119
-
120
-
121
- if (!pc) {
122
- pc = await import("https://cdn.jsdelivr.net/npm/playcanvas@latest/+esm");
123
- window.pc = pc;
124
  }
 
 
 
125
 
126
- // Create app and graphics device
127
- let device;
128
  try {
129
- device = await pc.createGraphicsDevice(canvas, {
130
- deviceTypes: ["webgl2", "webgl1"],
131
- glslangUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/glslang/glslang.js",
132
- twgslUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/twgsl/twgsl.js",
133
- antialias: false
134
- });
135
- device.maxPixelRatio = Math.min(window.devicePixelRatio, 2);
 
 
 
136
  } catch (e) {
137
- throw e;
 
 
 
 
 
 
 
 
138
  }
 
139
 
140
- const opts = new pc.AppOptions();
141
- opts.graphicsDevice = device;
142
- opts.mouse = new pc.Mouse(canvas);
143
- opts.touch = new pc.TouchDevice(canvas);
144
- opts.componentSystems = [
145
- pc.RenderComponentSystem,
146
- pc.CameraComponentSystem,
147
- pc.LightComponentSystem,
148
- pc.ScriptComponentSystem,
149
- pc.GSplatComponentSystem,
150
- pc.CollisionComponentSystem,
151
- pc.RigidbodyComponentSystem
152
- ];
153
- opts.resourceHandlers = [
154
- pc.TextureHandler,
155
- pc.ContainerHandler,
156
- pc.ScriptHandler,
157
- pc.GSplatHandler
158
- ];
159
-
160
- app = new pc.Application(canvas, opts);
161
- app.setCanvasFillMode(pc.FILLMODE_NONE);
162
- app.setCanvasResolution(pc.RESOLUTION_AUTO);
163
-
164
-
165
- // Resizing
166
- resizeObserver = new ResizeObserver(entries => {
167
- entries.forEach(entry => {
168
- try {
169
- app.resizeCanvas(entry.contentRect.width, entry.contentRect.height);
170
- } catch (e) { }
171
- });
172
- });
173
- resizeObserver.observe(viewerContainer);
174
-
175
- window.addEventListener('resize', () => {
176
- try {
177
- app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
178
- } catch (e) { }
179
- });
180
- app.on('destroy', () => resizeObserver.disconnect());
181
-
182
- // Prepare asset loading (SOGS as 'gsplat')
183
- const assets = {
184
- sogs: new pc.Asset('gsplat', 'gsplat', { url: sogsUrl }),
185
- orbit: new pc.Asset('script', 'script', { url: "https://mikafil-viewer-sgos.static.hf.space/orbit-camera.js" }),
186
- glb: new pc.Asset('glb', 'container', { url: glbUrl }),
187
- };
188
- for (const key in assets) app.assets.add(assets[key]);
189
-
190
- // Individual asset error listeners
191
- assets.sogs.on('error', (err) => { });
192
- assets.orbit.on('error', (err) => { });
193
- if (assets.glb) assets.glb.on('error', (err) => { });
194
-
195
- assets.sogs.ready(() => { });
196
- assets.orbit.ready(() => { });
197
- if (assets.glb) assets.glb.ready(() => { });
198
-
199
- const loader = new pc.AssetListLoader(Object.values(assets), app.assets);
200
-
201
- loader.on('error', (err) => { });
202
-
203
- loader.load(() => {
204
-
205
- try {
206
- app.start();
207
- } catch (e) {
208
- throw e;
209
- }
210
-
211
- if (progressDialog) progressDialog.style.display = 'none';
212
-
213
- // Add SOGS model
214
- try {
215
- modelEntity = new pc.Entity('model');
216
- modelEntity.addComponent('gsplat', { asset: assets.sogs });
217
- modelEntity.setLocalPosition(modelX, modelY, modelZ);
218
- modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
219
- modelEntity.setLocalScale(modelScale, modelScale, modelScale);
220
- app.root.addChild(modelEntity);
221
- } catch (e) {
222
- throw e;
223
- }
224
 
225
- // Add the GLB entity if provided
226
- try {
227
- if (assets.glb && assets.glb.resource && assets.glb.resource.instantiateRenderEntity) {
228
- const glbEntity = assets.glb.resource.instantiateRenderEntity();
229
- app.root.addChild(glbEntity);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  }
231
- } catch (e) { }
232
-
233
- // CAMERA
234
- try {
235
- cameraEntity = new pc.Entity('camera');
236
- // Support background color
237
- let bg = [1, 1, 1, 1];
238
- if (canvasBg && /^#?[0-9a-f]{6,8}$/i.test(canvasBg.replace("#", ""))) {
239
- bg = hexToRgbaArray(canvasBg);
 
 
 
 
240
  }
241
- cameraEntity.addComponent('camera', { clearColor: new pc.Color(bg[0], bg[1], bg[2], bg[3]) });
242
- cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
243
- cameraEntity.lookAt(modelEntity.getPosition());
244
- cameraEntity.addComponent('script');
245
-
246
- // Pass all attributes to Orbit Camera script
247
- cameraEntity.script.create('orbitCamera', {
248
- attributes: {
249
- focusEntity: modelEntity,
250
- inertiaFactor: 0.2,
251
- distanceMax: maxZoom,
252
- distanceMin: minZoom,
253
- pitchAngleMax: maxAngle,
254
- pitchAngleMin: minAngle,
255
- yawAngleMax: maxAzimuth,
256
- yawAngleMin: minAzimuth,
257
- minY: minY,
258
- frameOnStart: false
259
- }
260
- });
261
- cameraEntity.script.create('orbitCameraInputMouse');
262
- cameraEntity.script.create('orbitCameraInputTouch');
263
- app.root.addChild(cameraEntity);
264
-
265
- } catch (e) { }
266
-
267
- try {
268
- app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
269
- } catch (e) { }
270
-
271
- try {
272
- app.once('update', () => resetViewerCamera());
273
- } catch (e) { }
274
-
275
- // Tooltips support (optional)
276
- try {
277
- if (config.tooltips_url) {
278
- import('https://mikafil-viewer-sgos.static.hf.space/tooltips.js').then(tooltipsModule => {
279
- tooltipsModule.initializeTooltips({
280
- app,
281
- cameraEntity,
282
- modelEntity,
283
- tooltipsUrl: config.tooltips_url,
284
- defaultVisible: !!config.showTooltipsDefault,
285
- moveDuration: config.tooltipMoveDuration || 0.6
286
  });
287
- }).catch(e => { });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  }
289
- } catch (e) { }
290
 
291
- viewerInitialized = true;
292
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
- } catch (e) {
295
- throw e;
296
- }
297
  }
298
 
299
- // Resets the viewer camera (as in your PLY example)
300
  export function resetViewerCamera() {
301
- try {
302
- if (!cameraEntity || !modelEntity || !app) {
303
- return;
304
- }
305
- const orbitCam = cameraEntity.script.orbitCamera;
306
- if (!orbitCam) {
307
- return;
308
- }
 
 
 
 
 
309
 
310
- const modelPos = modelEntity.getPosition();
311
- const tempEnt = new pc.Entity();
312
- tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
313
- tempEnt.lookAt(modelPos);
314
-
315
- const dist = new pc.Vec3().sub2(
316
- new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ),
317
- modelPos
318
- ).length();
319
-
320
- cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
321
- cameraEntity.lookAt(modelPos);
322
-
323
- orbitCam.pivotPoint = modelPos.clone();
324
- orbitCam._targetDistance = dist;
325
- orbitCam._distance = dist;
326
-
327
- const rot = tempEnt.getRotation();
328
- const fwd = new pc.Vec3();
329
- rot.transformVector(pc.Vec3.FORWARD, fwd);
330
-
331
- const yaw = Math.atan2(-fwd.x, -fwd.z) * pc.math.RAD_TO_DEG;
332
- const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0);
333
- const rotNoYaw = new pc.Quat().mul2(yawQuat, rot);
334
- const fNoYaw = new pc.Vec3();
335
- rotNoYaw.transformVector(pc.Vec3.FORWARD, fNoYaw);
336
- const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG;
337
-
338
- orbitCam._targetYaw = yaw;
339
- orbitCam._yaw = yaw;
340
- orbitCam._targetPitch = pitch;
341
- orbitCam._pitch = pitch;
342
- if (orbitCam._updatePosition) orbitCam._updatePosition();
343
-
344
- tempEnt.destroy();
345
- } catch (e) { }
346
  }
 
10
  let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ;
11
  let sogsUrl, glbUrl, canvasBg;
12
 
13
+ // --- Utility to proxy URLs ---
14
+ function corsify(url) {
15
+ if (!url) return url;
16
+ if (url.startsWith("blob:")) return url; // already blob
17
+ if (url.startsWith("https://corsproxy.io/?")) return url;
18
+ if (!/^https?:\/\//.test(url)) return url;
19
+ return "https://corsproxy.io/?" + url;
 
 
 
 
 
 
 
 
20
  }
21
 
22
+ // --- Patch SOGS meta.json for CORS on all file fields ---
23
+ async function patchSogsJsonForCors(config) {
24
+ const originalMetaUrl = config.sogs_json_url;
25
+ const baseDir = originalMetaUrl.substring(0, originalMetaUrl.lastIndexOf('/') + 1);
26
+ const corsPrefix = "https://corsproxy.io/?";
27
+ const resp = await fetch(corsPrefix + originalMetaUrl);
28
+ if (!resp.ok) throw new Error("Failed to fetch meta.json via proxy");
29
+ const meta = await resp.json();
30
+ for (const key of Object.keys(meta)) {
31
+ if (meta[key].files) {
32
+ meta[key].files = meta[key].files.map(filename => {
33
+ let url = filename;
34
+ if (!filename.startsWith("http")) url = baseDir + filename;
35
+ return corsify(url);
36
  });
37
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  }
39
+ const metaBlob = new Blob([JSON.stringify(meta)], { type: "application/json" });
40
+ config.sogs_json_url = URL.createObjectURL(metaBlob);
41
+ }
42
 
43
+ function hexToRgbaArray(hex) {
 
44
  try {
45
+ hex = hex.replace("#", "");
46
+ if (hex.length === 6) hex += "FF";
47
+ if (hex.length !== 8) return [1, 1, 1, 1];
48
+ const num = parseInt(hex, 16);
49
+ return [
50
+ ((num >> 24) & 0xFF) / 255,
51
+ ((num >> 16) & 0xFF) / 255,
52
+ ((num >> 8) & 0xFF) / 255,
53
+ (num & 0xFF) / 255
54
+ ];
55
  } catch (e) {
56
+ return [1, 1, 1, 1];
57
+ }
58
+ }
59
+
60
+ // --- Main Entry ---
61
+ export async function initializeViewer(config, instanceId) {
62
+ // Proxy assets for CORS safety
63
+ if (config.sogs_json_url && config.sogs_json_url.includes("huggingface.co")) {
64
+ await patchSogsJsonForCors(config);
65
  }
66
+ if (config.glb_url) config.glb_url = corsify(config.glb_url);
67
 
68
+ const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
69
+ const isMobile = isIOS || /Android/i.test(navigator.userAgent);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ try {
72
+ // Parse config
73
+ sogsUrl = config.sogs_json_url;
74
+ glbUrl = config.glb_url;
75
+ canvasBg = config.canvas_background || "#ffffff";
76
+ minZoom = parseFloat(config.minZoom || "1");
77
+ maxZoom = parseFloat(config.maxZoom || "20");
78
+ minAngle = parseFloat(config.minAngle || "-45");
79
+ maxAngle = parseFloat(config.maxAngle || "90");
80
+ minAzimuth = (config.minAzimuth !== undefined) ? parseFloat(config.minAzimuth) : -360;
81
+ maxAzimuth = (config.maxAzimuth !== undefined) ? parseFloat(config.maxAzimuth) : 360;
82
+ minPivotY = parseFloat(config.minPivotY || "0");
83
+ minY = (config.minY !== undefined) ? parseFloat(config.minY) : 0;
84
+
85
+ modelX = (config.modelX !== undefined) ? parseFloat(config.modelX) : 0;
86
+ modelY = (config.modelY !== undefined) ? parseFloat(config.modelY) : 0;
87
+ modelZ = (config.modelZ !== undefined) ? parseFloat(config.modelZ) : 0;
88
+ modelScale = (config.modelScale !== undefined) ? parseFloat(config.modelScale) : 1;
89
+ modelRotationX = (config.modelRotationX !== undefined) ? parseFloat(config.modelRotationX) : 0;
90
+ modelRotationY = (config.modelRotationY !== undefined) ? parseFloat(config.modelRotationY) : 0;
91
+ modelRotationZ = (config.modelRotationZ !== undefined) ? parseFloat(config.modelRotationZ) : 0;
92
+
93
+ const cameraX = (config.cameraX !== undefined) ? parseFloat(config.cameraX) : 0;
94
+ const cameraY = (config.cameraY !== undefined) ? parseFloat(config.cameraY) : 2;
95
+ const cameraZ = (config.cameraZ !== undefined) ? parseFloat(config.cameraZ) : 5;
96
+ const cameraXPhone = (config.cameraXPhone !== undefined) ? parseFloat(config.cameraXPhone) : cameraX;
97
+ const cameraYPhone = (config.cameraYPhone !== undefined) ? parseFloat(config.cameraYPhone) : cameraY;
98
+ const cameraZPhone = (config.cameraZPhone !== undefined) ? parseFloat(config.cameraZPhone) : (cameraZ * 1.5);
99
+
100
+ chosenCameraX = isMobile ? cameraXPhone : cameraX;
101
+ chosenCameraY = isMobile ? cameraYPhone : cameraY;
102
+ chosenCameraZ = isMobile ? cameraZPhone : cameraZ;
103
+
104
+ const canvasId = 'canvas-' + instanceId;
105
+ const progressDialog = document.getElementById('progress-dialog-' + instanceId);
106
+ const progressIndicator = document.getElementById('progress-indicator-' + instanceId);
107
+ const viewerContainer = document.getElementById('viewer-container-' + instanceId);
108
+
109
+ let oldCanvas = document.getElementById(canvasId);
110
+ if (oldCanvas) oldCanvas.remove();
111
+
112
+ const canvas = document.createElement('canvas');
113
+ canvas.id = canvasId;
114
+ canvas.className = 'ply-canvas';
115
+ canvas.style.width = "100%";
116
+ canvas.style.height = "100%";
117
+ canvas.setAttribute('tabindex', '0');
118
+ viewerContainer.insertBefore(canvas, progressDialog);
119
+
120
+ // Apply background color from config if present
121
+ canvas.style.background = canvasBg;
122
+
123
+ canvas.style.touchAction = "none";
124
+ canvas.style.webkitTouchCallout = "none";
125
+ canvas.addEventListener('gesturestart', e => e.preventDefault());
126
+ canvas.addEventListener('gesturechange', e => e.preventDefault());
127
+ canvas.addEventListener('gestureend', e => e.preventDefault());
128
+ canvas.addEventListener('dblclick', e => e.preventDefault());
129
+ canvas.addEventListener('touchstart', e => { if (e.touches.length > 1) e.preventDefault(); }, { passive: false });
130
+
131
+ // --- Mouse wheel suppression
132
+ canvas.addEventListener('wheel', (e) => {
133
+ e.preventDefault(); // Only block page scroll if mouse is over viewer
134
+ }, { passive: false });
135
+
136
+ if (progressDialog) progressDialog.style.display = 'block';
137
+
138
+ if (!pc) {
139
+ pc = await import("https://cdn.jsdelivr.net/npm/playcanvas@latest/+esm");
140
+ window.pc = pc;
141
  }
142
+
143
+ // Create app and graphics device
144
+ let device;
145
+ try {
146
+ device = await pc.createGraphicsDevice(canvas, {
147
+ deviceTypes: ["webgl2", "webgl1"],
148
+ glslangUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/glslang/glslang.js",
149
+ twgslUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/twgsl/twgsl.js",
150
+ antialias: false
151
+ });
152
+ device.maxPixelRatio = Math.min(window.devicePixelRatio, 2);
153
+ } catch (e) {
154
+ throw e;
155
  }
156
+
157
+ const opts = new pc.AppOptions();
158
+ opts.graphicsDevice = device;
159
+ opts.mouse = new pc.Mouse(canvas);
160
+ opts.touch = new pc.TouchDevice(canvas);
161
+ opts.componentSystems = [
162
+ pc.RenderComponentSystem,
163
+ pc.CameraComponentSystem,
164
+ pc.LightComponentSystem,
165
+ pc.ScriptComponentSystem,
166
+ pc.GSplatComponentSystem,
167
+ pc.CollisionComponentSystem,
168
+ pc.RigidbodyComponentSystem
169
+ ];
170
+ opts.resourceHandlers = [
171
+ pc.TextureHandler,
172
+ pc.ContainerHandler,
173
+ pc.ScriptHandler,
174
+ pc.GSplatHandler
175
+ ];
176
+
177
+ app = new pc.Application(canvas, opts);
178
+ app.setCanvasFillMode(pc.FILLMODE_NONE);
179
+ app.setCanvasResolution(pc.RESOLUTION_AUTO);
180
+
181
+ // Resizing
182
+ resizeObserver = new ResizeObserver(entries => {
183
+ entries.forEach(entry => {
184
+ try {
185
+ app.resizeCanvas(entry.contentRect.width, entry.contentRect.height);
186
+ } catch (e) { }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  });
188
+ });
189
+ resizeObserver.observe(viewerContainer);
190
+
191
+ window.addEventListener('resize', () => {
192
+ try {
193
+ app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
194
+ } catch (e) { }
195
+ });
196
+ app.on('destroy', () => resizeObserver.disconnect());
197
+
198
+ // Prepare asset loading (SOGS as 'gsplat')
199
+ const assets = {
200
+ sogs: new pc.Asset('gsplat', 'gsplat', { url: sogsUrl }),
201
+ orbit: new pc.Asset('script', 'script', { url: "https://mikafil-viewer-sgos.static.hf.space/orbit-camera.js" }),
202
+ glb: glbUrl ? new pc.Asset('glb', 'container', { url: glbUrl }) : null,
203
+ };
204
+ for (const key in assets) {
205
+ if (assets[key]) app.assets.add(assets[key]);
206
  }
 
207
 
208
+ // Individual asset error listeners
209
+ if (assets.sogs) assets.sogs.on('error', (err) => { console.error("SOGS asset error:", err); });
210
+ if (assets.orbit) assets.orbit.on('error', (err) => { console.error("Orbit asset error:", err); });
211
+ if (assets.glb) assets.glb.on('error', (err) => { console.error("GLB asset error:", err); });
212
+
213
+ if (assets.sogs) assets.sogs.ready(() => { });
214
+ if (assets.orbit) assets.orbit.ready(() => { });
215
+ if (assets.glb) assets.glb.ready(() => { });
216
+
217
+ const loader = new pc.AssetListLoader(Object.values(assets).filter(Boolean), app.assets);
218
+
219
+ loader.on('error', (err) => { console.error("AssetListLoader error:", err); });
220
+
221
+ loader.load(() => {
222
+
223
+ try {
224
+ app.start();
225
+ } catch (e) {
226
+ throw e;
227
+ }
228
+
229
+ if (progressDialog) progressDialog.style.display = 'none';
230
+
231
+ // Add SOGS model
232
+ try {
233
+ modelEntity = new pc.Entity('model');
234
+ if (assets.sogs) {
235
+ modelEntity.addComponent('gsplat', { asset: assets.sogs });
236
+ }
237
+ modelEntity.setLocalPosition(modelX, modelY, modelZ);
238
+ modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
239
+ modelEntity.setLocalScale(modelScale, modelScale, modelScale);
240
+ app.root.addChild(modelEntity);
241
+ } catch (e) {
242
+ throw e;
243
+ }
244
+
245
+ // Add the GLB entity if provided
246
+ try {
247
+ if (assets.glb && assets.glb.resource && typeof assets.glb.resource.instantiateRenderEntity === "function") {
248
+ const glbEntity = assets.glb.resource.instantiateRenderEntity();
249
+ if (glbEntity) app.root.addChild(glbEntity);
250
+ }
251
+ } catch (e) { }
252
+
253
+ // CAMERA
254
+ try {
255
+ cameraEntity = new pc.Entity('camera');
256
+ // Support background color
257
+ let bg = [1, 1, 1, 1];
258
+ if (canvasBg && /^#?[0-9a-f]{6,8}$/i.test(canvasBg.replace("#", ""))) {
259
+ bg = hexToRgbaArray(canvasBg);
260
+ }
261
+ cameraEntity.addComponent('camera', { clearColor: new pc.Color(bg[0], bg[1], bg[2], bg[3]) });
262
+ cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
263
+ cameraEntity.lookAt(modelEntity.getPosition());
264
+ cameraEntity.addComponent('script');
265
+
266
+ // Pass all attributes to Orbit Camera script
267
+ cameraEntity.script.create('orbitCamera', {
268
+ attributes: {
269
+ focusEntity: modelEntity,
270
+ inertiaFactor: 0.2,
271
+ distanceMax: maxZoom,
272
+ distanceMin: minZoom,
273
+ pitchAngleMax: maxAngle,
274
+ pitchAngleMin: minAngle,
275
+ yawAngleMax: maxAzimuth,
276
+ yawAngleMin: minAzimuth,
277
+ minY: minY,
278
+ frameOnStart: false
279
+ }
280
+ });
281
+ cameraEntity.script.create('orbitCameraInputMouse');
282
+ cameraEntity.script.create('orbitCameraInputTouch');
283
+ app.root.addChild(cameraEntity);
284
+
285
+ } catch (e) { }
286
+
287
+ try {
288
+ app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
289
+ } catch (e) { }
290
+
291
+ try {
292
+ app.once('update', () => resetViewerCamera());
293
+ } catch (e) { }
294
+
295
+ // Tooltips support (optional)
296
+ try {
297
+ if (config.tooltips_url) {
298
+ import('https://mikafil-viewer-sgos.static.hf.space/tooltips.js').then(tooltipsModule => {
299
+ tooltipsModule.initializeTooltips({
300
+ app,
301
+ cameraEntity,
302
+ modelEntity,
303
+ tooltipsUrl: config.tooltips_url,
304
+ defaultVisible: !!config.showTooltipsDefault,
305
+ moveDuration: config.tooltipMoveDuration || 0.6
306
+ });
307
+ }).catch(e => { });
308
+ }
309
+ } catch (e) { }
310
+
311
+ viewerInitialized = true;
312
+ });
313
 
314
+ } catch (e) {
315
+ throw e;
316
+ }
317
  }
318
 
319
+ // Resets the viewer camera
320
  export function resetViewerCamera() {
321
+ try {
322
+ if (!cameraEntity || !modelEntity || !app) {
323
+ return;
324
+ }
325
+ const orbitCam = cameraEntity.script.orbitCamera;
326
+ if (!orbitCam) {
327
+ return;
328
+ }
329
+
330
+ const modelPos = modelEntity.getPosition();
331
+ const tempEnt = new pc.Entity();
332
+ tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
333
+ tempEnt.lookAt(modelPos);
334
 
335
+ const dist = new pc.Vec3().sub2(
336
+ new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ),
337
+ modelPos
338
+ ).length();
339
+
340
+ cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
341
+ cameraEntity.lookAt(modelPos);
342
+
343
+ orbitCam.pivotPoint = modelPos.clone();
344
+ orbitCam._targetDistance = dist;
345
+ orbitCam._distance = dist;
346
+
347
+ const rot = tempEnt.getRotation();
348
+ const fwd = new pc.Vec3();
349
+ rot.transformVector(pc.Vec3.FORWARD, fwd);
350
+
351
+ const yaw = Math.atan2(-fwd.x, -fwd.z) * pc.math.RAD_TO_DEG;
352
+ const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0);
353
+ const rotNoYaw = new pc.Quat().mul2(yawQuat, rot);
354
+ const fNoYaw = new pc.Vec3();
355
+ rotNoYaw.transformVector(pc.Vec3.FORWARD, fNoYaw);
356
+ const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG;
357
+
358
+ orbitCam._targetYaw = yaw;
359
+ orbitCam._yaw = yaw;
360
+ orbitCam._targetPitch = pitch;
361
+ orbitCam._pitch = pitch;
362
+ if (orbitCam._updatePosition) orbitCam._updatePosition();
363
+
364
+ tempEnt.destroy();
365
+ } catch (e) { }
 
 
 
 
 
366
  }