Spaces:
Running
Running
| // viewer.js | |
| // ============================== | |
| async function loadImageAsTexture(url, app) { | |
| return new Promise((resolve, reject) => { | |
| const img = new window.Image(); | |
| img.crossOrigin = "anonymous"; | |
| img.onload = function () { | |
| const tex = new pc.Texture(app.graphicsDevice, { | |
| width: img.width, | |
| height: img.height, | |
| format: pc.PIXELFORMAT_R8_G8_B8_A8 | |
| }); | |
| tex.setSource(img); | |
| resolve(tex); | |
| }; | |
| img.onerror = reject; | |
| img.src = url; | |
| }); | |
| } | |
| // --- Patch all window.Image to force crossOrigin="anonymous" --- | |
| (function () { | |
| const OriginalImage = window.Image; | |
| window.Image = function (...args) { | |
| const img = new OriginalImage(...args); | |
| img.crossOrigin = "anonymous"; | |
| return img; | |
| }; | |
| })(); | |
| function hexToRgbaArray(hex) { | |
| try { | |
| hex = hex.replace("#", ""); | |
| if (hex.length === 6) hex += "FF"; | |
| if (hex.length !== 8) return [1, 1, 1, 1]; | |
| const num = parseInt(hex, 16); | |
| return [ | |
| ((num >> 24) & 0xff) / 255, | |
| ((num >> 16) & 0xff) / 255, | |
| ((num >> 8) & 0xff) / 255, | |
| (num & 0xff) / 255 | |
| ]; | |
| } catch (e) { | |
| alert("hexToRgbaArray error: " + e); | |
| return [1, 1, 1, 1]; | |
| } | |
| } | |
| // ----- Utility: Recursive scene traversal ----- | |
| function traverse(entity, callback) { | |
| callback(entity); | |
| if (entity.children) { | |
| entity.children.forEach((child) => traverse(child, callback)); | |
| } | |
| } | |
| // Charger orbit-camera.js **par application** | |
| const ORBIT_URL = "https://mikafil-viewer-sgos.static.hf.space/orbit-camera.js"; | |
| function loadOrbitScriptsForApp(app, instanceId) { | |
| return new Promise((resolve, reject) => { | |
| // Si déjà enregistré dans CETTE app, ne rien faire | |
| try { | |
| if (app?.scripts?.get && app.scripts.get("orbitCamera")) return resolve(); | |
| } catch (_) {} | |
| const asset = new pc.Asset("orbit-" + instanceId, "script", { url: ORBIT_URL }); | |
| app.assets.add(asset); | |
| asset.once("load", () => resolve()); | |
| asset.once("error", (e) => { | |
| console.error("[viewer.js] orbit-camera.js load error:", e); | |
| reject(e); | |
| }); | |
| app.assets.load(asset); | |
| }); | |
| } | |
| let pc; | |
| export let app = null; | |
| let cameraEntity = null; | |
| let modelEntity = null; | |
| let viewerInitialized = false; | |
| let resizeObserver = null; | |
| let chosenCameraX, chosenCameraY, chosenCameraZ; | |
| let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minPivotY, minY; | |
| let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ; | |
| let presentoirScaleX, presentoirScaleY, presentoirScaleZ; | |
| let sogsUrl, glbUrl, presentoirUrl; | |
| let color_bg_hex, color_bg, espace_expo_bool; | |
| export async function initializeViewer(config, instanceId) { | |
| if (viewerInitialized) return; | |
| const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent); | |
| const isMobile = isIOS || /Android/i.test(navigator.userAgent); | |
| // Config | |
| sogsUrl = config.sogs_json_url; | |
| glbUrl = | |
| config.glb_url !== undefined | |
| ? config.glb_url | |
| : "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb"; | |
| presentoirUrl = | |
| config.presentoir_url !== undefined | |
| ? config.presentoir_url | |
| : "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb"; | |
| minZoom = parseFloat(config.minZoom || "1"); | |
| maxZoom = parseFloat(config.maxZoom || "20"); | |
| minAngle = parseFloat(config.minAngle || "-45"); | |
| maxAngle = parseFloat(config.maxAngle || "90"); | |
| minAzimuth = | |
| config.minAzimuth !== undefined ? parseFloat(config.minAzimuth) : -360; | |
| maxAzimuth = | |
| config.maxAzimuth !== undefined ? parseFloat(config.maxAzimuth) : 360; | |
| minPivotY = parseFloat(config.minPivotY || "0"); | |
| minY = config.minY !== undefined ? parseFloat(config.minY) : 0; | |
| modelX = config.modelX !== undefined ? parseFloat(config.modelX) : 0; | |
| modelY = config.modelY !== undefined ? parseFloat(config.modelY) : 0; | |
| modelZ = config.modelZ !== undefined ? parseFloat(config.modelZ) : 0; | |
| modelScale = config.modelScale !== undefined ? parseFloat(config.modelScale) : 1; | |
| modelRotationX = | |
| config.modelRotationX !== undefined ? parseFloat(config.modelRotationX) : 0; | |
| modelRotationY = | |
| config.modelRotationY !== undefined ? parseFloat(config.modelRotationY) : 0; | |
| modelRotationZ = | |
| config.modelRotationZ !== undefined ? parseFloat(config.modelRotationZ) : 0; | |
| presentoirScaleX = | |
| config.presentoirScaleX !== undefined ? parseFloat(config.presentoirScaleX) : 0; | |
| presentoirScaleY = | |
| config.presentoirScaleY !== undefined ? parseFloat(config.presentoirScaleY) : 0; | |
| presentoirScaleZ = | |
| config.presentoirScaleZ !== undefined ? parseFloat(config.presentoirScaleZ) : 0; | |
| const cameraX = config.cameraX !== undefined ? parseFloat(config.cameraX) : 0; | |
| const cameraY = config.cameraY !== undefined ? parseFloat(config.cameraY) : 2; | |
| const cameraZ = config.cameraZ !== undefined ? parseFloat(config.cameraZ) : 5; | |
| const cameraXPhone = | |
| config.cameraXPhone !== undefined ? parseFloat(config.cameraXPhone) : cameraX; | |
| const cameraYPhone = | |
| config.cameraYPhone !== undefined ? parseFloat(config.cameraYPhone) : cameraY; | |
| const cameraZPhone = | |
| config.cameraZPhone !== undefined ? parseFloat(config.cameraZPhone) : cameraZ * 1.5; | |
| color_bg_hex = | |
| config.canvas_background !== undefined ? config.canvas_background : "#FFFFFF"; | |
| espace_expo_bool = | |
| config.espace_expo_bool !== undefined ? config.espace_expo_bool : false; | |
| color_bg = hexToRgbaArray(color_bg_hex); | |
| chosenCameraX = isMobile ? cameraXPhone : cameraX; | |
| chosenCameraY = isMobile ? cameraYPhone : cameraY; | |
| chosenCameraZ = isMobile ? cameraZPhone : cameraZ; | |
| // Canvas | |
| const canvasId = "canvas-" + instanceId; | |
| const progressDialog = document.getElementById("progress-dialog-" + instanceId); | |
| const viewerContainer = document.getElementById("viewer-container-" + instanceId); | |
| let oldCanvas = document.getElementById(canvasId); | |
| if (oldCanvas) oldCanvas.remove(); | |
| const canvas = document.createElement("canvas"); | |
| canvas.id = canvasId; | |
| canvas.className = "ply-canvas"; | |
| canvas.style.width = "100%"; | |
| canvas.style.height = "100%"; | |
| canvas.setAttribute("tabindex", "0"); | |
| viewerContainer.insertBefore(canvas, progressDialog); | |
| // Gestes / molette | |
| canvas.style.touchAction = "none"; | |
| canvas.style.webkitTouchCallout = "none"; | |
| canvas.addEventListener("gesturestart", (e) => e.preventDefault()); | |
| canvas.addEventListener("gesturechange", (e) => e.preventDefault()); | |
| canvas.addEventListener("gestureend", (e) => e.preventDefault()); | |
| canvas.addEventListener("dblclick", (e) => e.preventDefault()); | |
| canvas.addEventListener( | |
| "touchstart", | |
| (e) => { | |
| if (e.touches.length > 1) e.preventDefault(); | |
| }, | |
| { passive: false } | |
| ); | |
| canvas.addEventListener( | |
| "wheel", | |
| (e) => { | |
| e.preventDefault(); | |
| }, | |
| { passive: false } | |
| ); | |
| // --- Clavier : bloquer le scroll seulement quand le pointeur est au-dessus du canvas --- | |
| const scrollKeys = new Set([ | |
| "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", | |
| "PageUp", "PageDown", "Home", "End", " ", "Space", "Spacebar" | |
| ]); | |
| let isPointerOverCanvas = false; | |
| const focusCanvas = () => canvas.focus({ preventScroll: true }); | |
| const onPointerEnter = () => { isPointerOverCanvas = true; focusCanvas(); }; | |
| const onPointerLeave = () => { | |
| isPointerOverCanvas = false; | |
| if (document.activeElement === canvas) canvas.blur(); | |
| }; | |
| canvas.addEventListener("pointerenter", onPointerEnter); | |
| canvas.addEventListener("pointerleave", onPointerLeave); | |
| canvas.addEventListener("mouseenter", onPointerEnter); | |
| canvas.addEventListener("mouseleave", onPointerLeave); | |
| canvas.addEventListener("mousedown", focusCanvas); | |
| canvas.addEventListener("touchstart", () => { focusCanvas(); }, { passive: false }); | |
| canvas.addEventListener("blur", () => { isPointerOverCanvas = false; }); | |
| const onKeyDownCapture = (e) => { | |
| if (!isPointerOverCanvas) return; | |
| if (scrollKeys.has(e.key) || scrollKeys.has(e.code)) { | |
| e.preventDefault(); | |
| } | |
| }; | |
| window.addEventListener("keydown", onKeyDownCapture, true); | |
| progressDialog.style.display = "block"; | |
| if (!pc) { | |
| pc = await import("https://esm.run/playcanvas"); | |
| window.pc = pc; | |
| } | |
| // App | |
| const device = await pc.createGraphicsDevice(canvas, { | |
| deviceTypes: ["webgl2"], | |
| glslangUrl: "https://playcanvas.vercel.app/static/lib/glslang/glslang.js", | |
| twgslUrl: "https://playcanvas.vercel.app/static/lib/twgsl/twgsl.js", | |
| antialias: false | |
| }); | |
| device.maxPixelRatio = Math.min(window.devicePixelRatio, 2); | |
| const opts = new pc.AppOptions(); | |
| opts.graphicsDevice = device; | |
| opts.mouse = new pc.Mouse(canvas); | |
| opts.touch = new pc.TouchDevice(canvas); | |
| //opts.keyboard = new pc.Keyboard(canvas); // clavier par canvas | |
| opts.componentSystems = [ | |
| pc.RenderComponentSystem, | |
| pc.CameraComponentSystem, | |
| pc.LightComponentSystem, | |
| pc.ScriptComponentSystem, | |
| pc.GSplatComponentSystem, | |
| pc.CollisionComponentSystem, | |
| pc.RigidbodyComponentSystem | |
| ]; | |
| opts.resourceHandlers = [ | |
| pc.TextureHandler, | |
| pc.ContainerHandler, | |
| pc.ScriptHandler, | |
| pc.GSplatHandler | |
| ]; | |
| app = new pc.Application(canvas, opts); | |
| app.setCanvasFillMode(pc.FILLMODE_NONE); | |
| app.setCanvasResolution(pc.RESOLUTION_AUTO); | |
| resizeObserver = new ResizeObserver((entries) => { | |
| entries.forEach((entry) => { | |
| app.resizeCanvas(entry.contentRect.width, entry.contentRect.height); | |
| }); | |
| }); | |
| resizeObserver.observe(viewerContainer); | |
| window.addEventListener("resize", () => | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight) | |
| ); | |
| app.on("destroy", () => { | |
| resizeObserver.disconnect(); | |
| if (opts.keyboard && opts.keyboard.detach) opts.keyboard.detach(); | |
| window.removeEventListener("keydown", onKeyDownCapture, true); | |
| canvas.removeEventListener("pointerenter", onPointerEnter); | |
| canvas.removeEventListener("pointerleave", onPointerLeave); | |
| canvas.removeEventListener("mouseenter", onPointerEnter); | |
| canvas.removeEventListener("mouseleave", onPointerLeave); | |
| canvas.removeEventListener("mousedown", focusCanvas); | |
| canvas.removeEventListener("touchstart", focusCanvas); | |
| }); | |
| // Assets (sans orbit-camera ici) | |
| const assets = { | |
| sogs: new pc.Asset("gsplat", "gsplat", { url: sogsUrl }), | |
| glb: new pc.Asset("glb", "container", { url: glbUrl }), | |
| presentoir: new pc.Asset("presentoir", "container", { url: presentoirUrl }) | |
| }; | |
| for (const key in assets) app.assets.add(assets[key]); | |
| const loader = new pc.AssetListLoader(Object.values(assets), app.assets); | |
| loader.load(async () => { | |
| // Charger et enregistrer orbit-camera.js pour CETTE app | |
| await loadOrbitScriptsForApp(app, instanceId); | |
| app.start(); | |
| progressDialog.style.display = "none"; | |
| // Entités | |
| modelEntity = new pc.Entity("model"); | |
| modelEntity.addComponent("gsplat", { asset: assets.sogs }); | |
| modelEntity.setLocalPosition(modelX, modelY, modelZ); | |
| modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ); | |
| modelEntity.setLocalScale(modelScale, modelScale, modelScale); | |
| app.root.addChild(modelEntity); | |
| const glbEntity = assets.glb.resource.instantiateRenderEntity(); | |
| app.root.addChild(glbEntity); | |
| const presentoirEntity = assets.presentoir.resource.instantiateRenderEntity(); | |
| presentoirEntity.setLocalScale(presentoirScaleX, presentoirScaleY, presentoirScaleZ); | |
| app.root.addChild(presentoirEntity); | |
| if (!espace_expo_bool) { | |
| let matSol = new pc.StandardMaterial(); | |
| matSol.blendType = pc.BLEND_NONE; | |
| matSol.emissive = new pc.Color(color_bg); | |
| matSol.emissiveIntensity = 1; | |
| matSol.useLighting = false; | |
| matSol.update(); | |
| traverse(presentoirEntity, (node) => { | |
| if (node.render && node.render.meshInstances) { | |
| for (let mi of node.render.meshInstances) mi.material = matSol; | |
| } | |
| }); | |
| traverse(glbEntity, (node) => { | |
| if (node.render && node.render.meshInstances) { | |
| for (let mi of node.render.meshInstances) mi.material = matSol; | |
| } | |
| }); | |
| } | |
| // Caméra + scripts orbit | |
| cameraEntity = new pc.Entity("camera"); | |
| cameraEntity.addComponent("camera", { | |
| clearColor: new pc.Color(color_bg), | |
| nearClip: 0.001, | |
| farClip: 100 | |
| }); | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelEntity.getPosition()); | |
| cameraEntity.addComponent("script"); | |
| cameraEntity.script.create("orbitCamera", { | |
| attributes: { | |
| focusEntity: modelEntity, | |
| inertiaFactor: 0.2, | |
| distanceMax: maxZoom, | |
| distanceMin: minZoom, | |
| pitchAngleMax: maxAngle, | |
| pitchAngleMin: minAngle, | |
| yawAngleMax: maxAzimuth, | |
| yawAngleMin: minAzimuth, | |
| minY: minY, | |
| frameOnStart: false | |
| } | |
| }); | |
| cameraEntity.script.create("orbitCameraInputMouse"); | |
| cameraEntity.script.create("orbitCameraInputTouch"); | |
| cameraEntity.script.create("orbitCameraInputKeyboard", { | |
| attributes: { forwardSpeed: 1.2, strafeSpeed: 1.2 } | |
| }); | |
| app.root.addChild(cameraEntity); | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| app.once("update", () => resetViewerCamera()); | |
| // Tooltips (optionnel) | |
| try { | |
| if (config.tooltips_url) { | |
| import("./tooltips.js").then((tooltipsModule) => { | |
| tooltipsModule.initializeTooltips({ | |
| app, | |
| cameraEntity, | |
| modelEntity, | |
| tooltipsUrl: config.tooltips_url, | |
| defaultVisible: !!config.showTooltipsDefault, | |
| moveDuration: config.tooltipMoveDuration || 0.6 | |
| }); | |
| }).catch(() => {}); | |
| } | |
| } catch (_) {} | |
| viewerInitialized = true; | |
| }); | |
| } | |
| export function resetViewerCamera() { | |
| try { | |
| if (!cameraEntity || !modelEntity || !app) return; | |
| const orbitCam = cameraEntity.script.orbitCamera; | |
| if (!orbitCam) return; | |
| const modelPos = modelEntity.getPosition(); | |
| const tempEnt = new pc.Entity(); | |
| tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| tempEnt.lookAt(modelPos); | |
| const dist = new pc.Vec3() | |
| .sub2(new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ), modelPos) | |
| .length(); | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelPos); | |
| orbitCam.pivotPoint = modelPos.clone(); | |
| orbitCam._targetDistance = dist; | |
| orbitCam._distance = dist; | |
| const rot = tempEnt.getRotation(); | |
| const fwd = new pc.Vec3(); | |
| rot.transformVector(pc.Vec3.FORWARD, fwd); | |
| const yaw = Math.atan2(-fwd.x, -fwd.z) * pc.math.RAD_TO_DEG; | |
| const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0); | |
| const rotNoYaw = new pc.Quat().mul2(yawQuat, rot); | |
| const fNoYaw = new pc.Vec3(); | |
| rotNoYaw.transformVector(pc.Vec3.FORWARD, fNoYaw); | |
| const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG; | |
| orbitCam._targetYaw = yaw; | |
| orbitCam._yaw = yaw; | |
| orbitCam._targetPitch = pitch; | |
| orbitCam._pitch = pitch; | |
| if (orbitCam._updatePosition) orbitCam._updatePosition(); | |
| tempEnt.destroy(); | |
| } catch (e) { | |
| console.error("[VIEWER DEBUG] resetViewerCamera error", e); | |
| } | |
| } | |