File size: 52,928 Bytes
dcdc07a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "id": "camera-control3-d",
  "name": "Camera Control3 D",
  "description": "A 3D camera control component using Three.js.",
  "author": "multimodalart",
  "tags": [
    "3D",
    "Image"
  ],
  "category": "Input",
  "html_template": "\n        <div id=\"camera-control-wrapper\" style=\"width: 100%; height: 450px; position: relative; background: #1a1a1a; border-radius: 12px; overflow: hidden;\">\n            <div id=\"prompt-overlay\" style=\"position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.8); padding: 8px 16px; border-radius: 8px; font-family: monospace; font-size: 12px; color: #00ff88; white-space: nowrap; z-index: 10;\"></div>\n        </div>\n        ",
  "css_template": "",
  "js_on_load": "\n        (() => {\n            const wrapper = element.querySelector('#camera-control-wrapper');\n            const promptOverlay = element.querySelector('#prompt-overlay');\n            \n            // Wait for THREE to load\n            const initScene = () => {\n                if (typeof THREE === 'undefined') {\n                    setTimeout(initScene, 100);\n                    return;\n                }\n                \n                // Scene setup\n                const scene = new THREE.Scene();\n                scene.background = new THREE.Color(0x1a1a1a);\n                \n                const camera = new THREE.PerspectiveCamera(50, wrapper.clientWidth / wrapper.clientHeight, 0.1, 1000);\n                camera.position.set(4.5, 3, 4.5);\n                camera.lookAt(0, 0.75, 0);\n                \n                const renderer = new THREE.WebGLRenderer({ antialias: true });\n                renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n                renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n                wrapper.insertBefore(renderer.domElement, promptOverlay);\n                \n                // Lighting\n                scene.add(new THREE.AmbientLight(0xffffff, 0.6));\n                const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);\n                dirLight.position.set(5, 10, 5);\n                scene.add(dirLight);\n                \n                // Grid\n                scene.add(new THREE.GridHelper(8, 16, 0x333333, 0x222222));\n                \n                // Constants - reduced distances for tighter framing\n                const CENTER = new THREE.Vector3(0, 0.75, 0);\n                const BASE_DISTANCE = 1.6;\n                const AZIMUTH_RADIUS = 2.4;\n                const ELEVATION_RADIUS = 1.8;\n                \n                // State\n                let azimuthAngle = props.value?.azimuth || 0;\n                let elevationAngle = props.value?.elevation || 0;\n                let distanceFactor = props.value?.distance || 1.0;\n                \n                // Mappings - reduced wide shot multiplier\n                const azimuthSteps = [0, 45, 90, 135, 180, 225, 270, 315];\n                const elevationSteps = [-30, 0, 30, 60];\n                const distanceSteps = [0.6, 1.0, 1.4];\n                \n                const azimuthNames = {\n                    0: 'front view', 45: 'front-right quarter view', 90: 'right side view',\n                    135: 'back-right quarter view', 180: 'back view', 225: 'back-left quarter view',\n                    270: 'left side view', 315: 'front-left quarter view'\n                };\n                const elevationNames = { '-30': 'low-angle shot', '0': 'eye-level shot', '30': 'elevated shot', '60': 'high-angle shot' };\n                const distanceNames = { '0.6': 'close-up', '1': 'medium shot', '1.4': 'wide shot' };\n                \n                function snapToNearest(value, steps) {\n                    return steps.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n                }\n                \n                // Create placeholder texture (smiley face)\n                function createPlaceholderTexture() {\n                    const canvas = document.createElement('canvas');\n                    canvas.width = 256;\n                    canvas.height = 256;\n                    const ctx = canvas.getContext('2d');\n                    ctx.fillStyle = '#3a3a4a';\n                    ctx.fillRect(0, 0, 256, 256);\n                    ctx.fillStyle = '#ffcc99';\n                    ctx.beginPath();\n                    ctx.arc(128, 128, 80, 0, Math.PI * 2);\n                    ctx.fill();\n                    ctx.fillStyle = '#333';\n                    ctx.beginPath();\n                    ctx.arc(100, 110, 10, 0, Math.PI * 2);\n                    ctx.arc(156, 110, 10, 0, Math.PI * 2);\n                    ctx.fill();\n                    ctx.strokeStyle = '#333';\n                    ctx.lineWidth = 3;\n                    ctx.beginPath();\n                    ctx.arc(128, 130, 35, 0.2, Math.PI - 0.2);\n                    ctx.stroke();\n                    return new THREE.CanvasTexture(canvas);\n                }\n                \n                // Target image plane\n                let currentTexture = createPlaceholderTexture();\n                const planeMaterial = new THREE.MeshBasicMaterial({ map: currentTexture, side: THREE.DoubleSide });\n                let targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n                targetPlane.position.copy(CENTER);\n                scene.add(targetPlane);\n                \n                // Function to update texture from image URL\n                function updateTextureFromUrl(url) {\n                    if (!url) {\n                        // Reset to placeholder\n                        planeMaterial.map = createPlaceholderTexture();\n                        planeMaterial.needsUpdate = true;\n                        // Reset plane to square\n                        scene.remove(targetPlane);\n                        targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n                        targetPlane.position.copy(CENTER);\n                        scene.add(targetPlane);\n                        return;\n                    }\n                    \n                    const loader = new THREE.TextureLoader();\n                    loader.crossOrigin = 'anonymous';\n                    loader.load(url, (texture) => {\n                        texture.minFilter = THREE.LinearFilter;\n                        texture.magFilter = THREE.LinearFilter;\n                        planeMaterial.map = texture;\n                        planeMaterial.needsUpdate = true;\n                        \n                        // Adjust plane aspect ratio to match image\n                        const img = texture.image;\n                        if (img && img.width && img.height) {\n                            const aspect = img.width / img.height;\n                            const maxSize = 1.5;\n                            let planeWidth, planeHeight;\n                            if (aspect > 1) {\n                                planeWidth = maxSize;\n                                planeHeight = maxSize / aspect;\n                            } else {\n                                planeHeight = maxSize;\n                                planeWidth = maxSize * aspect;\n                            }\n                            scene.remove(targetPlane);\n                            targetPlane = new THREE.Mesh(\n                                new THREE.PlaneGeometry(planeWidth, planeHeight),\n                                planeMaterial\n                            );\n                            targetPlane.position.copy(CENTER);\n                            scene.add(targetPlane);\n                        }\n                    }, undefined, (err) => {\n                        console.error('Failed to load texture:', err);\n                    });\n                }\n                \n                // Check for initial imageUrl\n                if (props.imageUrl) {\n                    updateTextureFromUrl(props.imageUrl);\n                }\n                \n                // Camera model\n                const cameraGroup = new THREE.Group();\n                const bodyMat = new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 });\n                const body = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.22, 0.38), bodyMat);\n                cameraGroup.add(body);\n                const lens = new THREE.Mesh(\n                    new THREE.CylinderGeometry(0.09, 0.11, 0.18, 16),\n                    new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 })\n                );\n                lens.rotation.x = Math.PI / 2;\n                lens.position.z = 0.26;\n                cameraGroup.add(lens);\n                scene.add(cameraGroup);\n                \n                // GREEN: Azimuth ring\n                const azimuthRing = new THREE.Mesh(\n                    new THREE.TorusGeometry(AZIMUTH_RADIUS, 0.04, 16, 64),\n                    new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.3 })\n                );\n                azimuthRing.rotation.x = Math.PI / 2;\n                azimuthRing.position.y = 0.05;\n                scene.add(azimuthRing);\n                \n                const azimuthHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.5 })\n                );\n                azimuthHandle.userData.type = 'azimuth';\n                scene.add(azimuthHandle);\n                \n                // PINK: Elevation arc\n                const arcPoints = [];\n                for (let i = 0; i <= 32; i++) {\n                    const angle = THREE.MathUtils.degToRad(-30 + (90 * i / 32));\n                    arcPoints.push(new THREE.Vector3(-0.8, ELEVATION_RADIUS * Math.sin(angle) + CENTER.y, ELEVATION_RADIUS * Math.cos(angle)));\n                }\n                const arcCurve = new THREE.CatmullRomCurve3(arcPoints);\n                const elevationArc = new THREE.Mesh(\n                    new THREE.TubeGeometry(arcCurve, 32, 0.04, 8, false),\n                    new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.3 })\n                );\n                scene.add(elevationArc);\n                \n                const elevationHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.5 })\n                );\n                elevationHandle.userData.type = 'elevation';\n                scene.add(elevationHandle);\n                \n                // ORANGE: Distance line & handle\n                const distanceLineGeo = new THREE.BufferGeometry();\n                const distanceLine = new THREE.Line(distanceLineGeo, new THREE.LineBasicMaterial({ color: 0xffa500 }));\n                scene.add(distanceLine);\n                \n                const distanceHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0xffa500, emissive: 0xffa500, emissiveIntensity: 0.5 })\n                );\n                distanceHandle.userData.type = 'distance';\n                scene.add(distanceHandle);\n                \n                function updatePositions() {\n                    const distance = BASE_DISTANCE * distanceFactor;\n                    const azRad = THREE.MathUtils.degToRad(azimuthAngle);\n                    const elRad = THREE.MathUtils.degToRad(elevationAngle);\n                    \n                    const camX = distance * Math.sin(azRad) * Math.cos(elRad);\n                    const camY = distance * Math.sin(elRad) + CENTER.y;\n                    const camZ = distance * Math.cos(azRad) * Math.cos(elRad);\n                    \n                    cameraGroup.position.set(camX, camY, camZ);\n                    cameraGroup.lookAt(CENTER);\n                    \n                    azimuthHandle.position.set(AZIMUTH_RADIUS * Math.sin(azRad), 0.05, AZIMUTH_RADIUS * Math.cos(azRad));\n                    elevationHandle.position.set(-0.8, ELEVATION_RADIUS * Math.sin(elRad) + CENTER.y, ELEVATION_RADIUS * Math.cos(elRad));\n                    \n                    const orangeDist = distance - 0.5;\n                    distanceHandle.position.set(\n                        orangeDist * Math.sin(azRad) * Math.cos(elRad),\n                        orangeDist * Math.sin(elRad) + CENTER.y,\n                        orangeDist * Math.cos(azRad) * Math.cos(elRad)\n                    );\n                    distanceLineGeo.setFromPoints([cameraGroup.position.clone(), CENTER.clone()]);\n                    \n                    // Update prompt\n                    const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n                    const elSnap = snapToNearest(elevationAngle, elevationSteps);\n                    const distSnap = snapToNearest(distanceFactor, distanceSteps);\n                    const distKey = distSnap === 1 ? '1' : distSnap.toFixed(1);\n                    const prompt = '<sks> ' + azimuthNames[azSnap] + ' ' + elevationNames[String(elSnap)] + ' ' + distanceNames[distKey];\n                    promptOverlay.textContent = prompt;\n                }\n                \n                function updatePropsAndTrigger() {\n                    const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n                    const elSnap = snapToNearest(elevationAngle, elevationSteps);\n                    const distSnap = snapToNearest(distanceFactor, distanceSteps);\n                    \n                    props.value = { azimuth: azSnap, elevation: elSnap, distance: distSnap };\n                    trigger('change', props.value);\n                }\n                \n                // Raycasting\n                const raycaster = new THREE.Raycaster();\n                const mouse = new THREE.Vector2();\n                let isDragging = false;\n                let dragTarget = null;\n                let dragStartMouse = new THREE.Vector2();\n                let dragStartDistance = 1.0;\n                const intersection = new THREE.Vector3();\n                \n                const canvas = renderer.domElement;\n                \n                canvas.addEventListener('mousedown', (e) => {\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n                    \n                    raycaster.setFromCamera(mouse, camera);\n                    const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n                    \n                    if (intersects.length > 0) {\n                        isDragging = true;\n                        dragTarget = intersects[0].object;\n                        dragTarget.material.emissiveIntensity = 1.0;\n                        dragTarget.scale.setScalar(1.3);\n                        dragStartMouse.copy(mouse);\n                        dragStartDistance = distanceFactor;\n                        canvas.style.cursor = 'grabbing';\n                    }\n                });\n                \n                canvas.addEventListener('mousemove', (e) => {\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n                    \n                    if (isDragging && dragTarget) {\n                        raycaster.setFromCamera(mouse, camera);\n                        \n                        if (dragTarget.userData.type === 'azimuth') {\n                            const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n                                if (azimuthAngle < 0) azimuthAngle += 360;\n                            }\n                        } else if (dragTarget.userData.type === 'elevation') {\n                            const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                const relY = intersection.y - CENTER.y;\n                                const relZ = intersection.z;\n                                elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n                            }\n                        } else if (dragTarget.userData.type === 'distance') {\n                            const deltaY = mouse.y - dragStartMouse.y;\n                            distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n                        }\n                        updatePositions();\n                    } else {\n                        raycaster.setFromCamera(mouse, camera);\n                        const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n                        [azimuthHandle, elevationHandle, distanceHandle].forEach(h => {\n                            h.material.emissiveIntensity = 0.5;\n                            h.scale.setScalar(1);\n                        });\n                        if (intersects.length > 0) {\n                            intersects[0].object.material.emissiveIntensity = 0.8;\n                            intersects[0].object.scale.setScalar(1.1);\n                            canvas.style.cursor = 'grab';\n                        } else {\n                            canvas.style.cursor = 'default';\n                        }\n                    }\n                });\n                \n                const onMouseUp = () => {\n                    if (dragTarget) {\n                        dragTarget.material.emissiveIntensity = 0.5;\n                        dragTarget.scale.setScalar(1);\n                        \n                        // Snap and animate\n                        const targetAz = snapToNearest(azimuthAngle, azimuthSteps);\n                        const targetEl = snapToNearest(elevationAngle, elevationSteps);\n                        const targetDist = snapToNearest(distanceFactor, distanceSteps);\n                        \n                        const startAz = azimuthAngle, startEl = elevationAngle, startDist = distanceFactor;\n                        const startTime = Date.now();\n                        \n                        function animateSnap() {\n                            const t = Math.min((Date.now() - startTime) / 200, 1);\n                            const ease = 1 - Math.pow(1 - t, 3);\n                            \n                            let azDiff = targetAz - startAz;\n                            if (azDiff > 180) azDiff -= 360;\n                            if (azDiff < -180) azDiff += 360;\n                            azimuthAngle = startAz + azDiff * ease;\n                            if (azimuthAngle < 0) azimuthAngle += 360;\n                            if (azimuthAngle >= 360) azimuthAngle -= 360;\n                            \n                            elevationAngle = startEl + (targetEl - startEl) * ease;\n                            distanceFactor = startDist + (targetDist - startDist) * ease;\n                            \n                            updatePositions();\n                            if (t < 1) requestAnimationFrame(animateSnap);\n                            else updatePropsAndTrigger();\n                        }\n                        animateSnap();\n                    }\n                    isDragging = false;\n                    dragTarget = null;\n                    canvas.style.cursor = 'default';\n                };\n                \n                canvas.addEventListener('mouseup', onMouseUp);\n                canvas.addEventListener('mouseleave', onMouseUp);\n                // Touch support for mobile\n                canvas.addEventListener('touchstart', (e) => {\n                    e.preventDefault();\n                    const touch = e.touches[0];\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n                    \n                    raycaster.setFromCamera(mouse, camera);\n                    const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n                    \n                    if (intersects.length > 0) {\n                        isDragging = true;\n                        dragTarget = intersects[0].object;\n                        dragTarget.material.emissiveIntensity = 1.0;\n                        dragTarget.scale.setScalar(1.3);\n                        dragStartMouse.copy(mouse);\n                        dragStartDistance = distanceFactor;\n                    }\n                }, { passive: false });\n                \n                canvas.addEventListener('touchmove', (e) => {\n                    e.preventDefault();\n                    const touch = e.touches[0];\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n                    \n                    if (isDragging && dragTarget) {\n                        raycaster.setFromCamera(mouse, camera);\n                        \n                        if (dragTarget.userData.type === 'azimuth') {\n                            const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n                                if (azimuthAngle < 0) azimuthAngle += 360;\n                            }\n                        } else if (dragTarget.userData.type === 'elevation') {\n                            const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                const relY = intersection.y - CENTER.y;\n                                const relZ = intersection.z;\n                                elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n                            }\n                        } else if (dragTarget.userData.type === 'distance') {\n                            const deltaY = mouse.y - dragStartMouse.y;\n                            distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n                        }\n                        updatePositions();\n                    }\n                }, { passive: false });\n                \n                canvas.addEventListener('touchend', (e) => {\n                    e.preventDefault();\n                    onMouseUp();\n                }, { passive: false });\n                \n                canvas.addEventListener('touchcancel', (e) => {\n                    e.preventDefault();\n                    onMouseUp();\n                }, { passive: false });\n                \n                // Initial update\n                updatePositions();\n                \n                // Render loop\n                function render() {\n                    requestAnimationFrame(render);\n                    renderer.render(scene, camera);\n                }\n                render();\n                \n                // Handle resize\n                new ResizeObserver(() => {\n                    camera.aspect = wrapper.clientWidth / wrapper.clientHeight;\n                    camera.updateProjectionMatrix();\n                    renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n                }).observe(wrapper);\n                \n                // Store update functions for external calls\n                wrapper._updateFromProps = (newVal) => {\n                    if (newVal && typeof newVal === 'object') {\n                        azimuthAngle = newVal.azimuth ?? azimuthAngle;\n                        elevationAngle = newVal.elevation ?? elevationAngle;\n                        distanceFactor = newVal.distance ?? distanceFactor;\n                        updatePositions();\n                    }\n                };\n                \n                wrapper._updateTexture = updateTextureFromUrl;\n                \n                // Watch for prop changes (imageUrl and value)\n                let lastImageUrl = props.imageUrl;\n                let lastValue = JSON.stringify(props.value);\n                setInterval(() => {\n                    // Check imageUrl changes\n                    if (props.imageUrl !== lastImageUrl) {\n                        lastImageUrl = props.imageUrl;\n                        updateTextureFromUrl(props.imageUrl);\n                    }\n                    // Check value changes (from sliders)\n                    const currentValue = JSON.stringify(props.value);\n                    if (currentValue !== lastValue) {\n                        lastValue = currentValue;\n                        if (props.value && typeof props.value === 'object') {\n                            azimuthAngle = props.value.azimuth ?? azimuthAngle;\n                            elevationAngle = props.value.elevation ?? elevationAngle;\n                            distanceFactor = props.value.distance ?? distanceFactor;\n                            updatePositions();\n                        }\n                    }\n                }, 100);\n            };\n            \n            initScene();\n        })();\n        ",
  "default_props": {
    "value": {
      "azimuth": 0,
      "elevation": 0,
      "distance": 1.0
    },
    "imageUrl": null
  },
  "head": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js\"></script>",
  "python_code": "class CameraControl3D(gr.HTML):\n    \"\"\"\n    A 3D camera control component using Three.js.\n    Outputs: { azimuth: number, elevation: number, distance: number }\n    Accepts imageUrl prop to display user's uploaded image on the plane.\n    \"\"\"\n    def __init__(self, value=None, imageUrl=None, **kwargs):\n        if value is None:\n            value = {\"azimuth\": 0, \"elevation\": 0, \"distance\": 1.0}\n\n        html_template = \"\"\"\n        <div id=\"camera-control-wrapper\" style=\"width: 100%; height: 450px; position: relative; background: #1a1a1a; border-radius: 12px; overflow: hidden;\">\n            <div id=\"prompt-overlay\" style=\"position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.8); padding: 8px 16px; border-radius: 8px; font-family: monospace; font-size: 12px; color: #00ff88; white-space: nowrap; z-index: 10;\"></div>\n        </div>\n        \"\"\"\n\n        js_on_load = \"\"\"\n        (() => {\n            const wrapper = element.querySelector('#camera-control-wrapper');\n            const promptOverlay = element.querySelector('#prompt-overlay');\n\n            // Wait for THREE to load\n            const initScene = () => {\n                if (typeof THREE === 'undefined') {\n                    setTimeout(initScene, 100);\n                    return;\n                }\n\n                // Scene setup\n                const scene = new THREE.Scene();\n                scene.background = new THREE.Color(0x1a1a1a);\n\n                const camera = new THREE.PerspectiveCamera(50, wrapper.clientWidth / wrapper.clientHeight, 0.1, 1000);\n                camera.position.set(4.5, 3, 4.5);\n                camera.lookAt(0, 0.75, 0);\n\n                const renderer = new THREE.WebGLRenderer({ antialias: true });\n                renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n                renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n                wrapper.insertBefore(renderer.domElement, promptOverlay);\n\n                // Lighting\n                scene.add(new THREE.AmbientLight(0xffffff, 0.6));\n                const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);\n                dirLight.position.set(5, 10, 5);\n                scene.add(dirLight);\n\n                // Grid\n                scene.add(new THREE.GridHelper(8, 16, 0x333333, 0x222222));\n\n                // Constants - reduced distances for tighter framing\n                const CENTER = new THREE.Vector3(0, 0.75, 0);\n                const BASE_DISTANCE = 1.6;\n                const AZIMUTH_RADIUS = 2.4;\n                const ELEVATION_RADIUS = 1.8;\n\n                // State\n                let azimuthAngle = props.value?.azimuth || 0;\n                let elevationAngle = props.value?.elevation || 0;\n                let distanceFactor = props.value?.distance || 1.0;\n\n                // Mappings - reduced wide shot multiplier\n                const azimuthSteps = [0, 45, 90, 135, 180, 225, 270, 315];\n                const elevationSteps = [-30, 0, 30, 60];\n                const distanceSteps = [0.6, 1.0, 1.4];\n\n                const azimuthNames = {\n                    0: 'front view', 45: 'front-right quarter view', 90: 'right side view',\n                    135: 'back-right quarter view', 180: 'back view', 225: 'back-left quarter view',\n                    270: 'left side view', 315: 'front-left quarter view'\n                };\n                const elevationNames = { '-30': 'low-angle shot', '0': 'eye-level shot', '30': 'elevated shot', '60': 'high-angle shot' };\n                const distanceNames = { '0.6': 'close-up', '1': 'medium shot', '1.4': 'wide shot' };\n\n                function snapToNearest(value, steps) {\n                    return steps.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n                }\n\n                // Create placeholder texture (smiley face)\n                function createPlaceholderTexture() {\n                    const canvas = document.createElement('canvas');\n                    canvas.width = 256;\n                    canvas.height = 256;\n                    const ctx = canvas.getContext('2d');\n                    ctx.fillStyle = '#3a3a4a';\n                    ctx.fillRect(0, 0, 256, 256);\n                    ctx.fillStyle = '#ffcc99';\n                    ctx.beginPath();\n                    ctx.arc(128, 128, 80, 0, Math.PI * 2);\n                    ctx.fill();\n                    ctx.fillStyle = '#333';\n                    ctx.beginPath();\n                    ctx.arc(100, 110, 10, 0, Math.PI * 2);\n                    ctx.arc(156, 110, 10, 0, Math.PI * 2);\n                    ctx.fill();\n                    ctx.strokeStyle = '#333';\n                    ctx.lineWidth = 3;\n                    ctx.beginPath();\n                    ctx.arc(128, 130, 35, 0.2, Math.PI - 0.2);\n                    ctx.stroke();\n                    return new THREE.CanvasTexture(canvas);\n                }\n\n                // Target image plane\n                let currentTexture = createPlaceholderTexture();\n                const planeMaterial = new THREE.MeshBasicMaterial({ map: currentTexture, side: THREE.DoubleSide });\n                let targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n                targetPlane.position.copy(CENTER);\n                scene.add(targetPlane);\n\n                // Function to update texture from image URL\n                function updateTextureFromUrl(url) {\n                    if (!url) {\n                        // Reset to placeholder\n                        planeMaterial.map = createPlaceholderTexture();\n                        planeMaterial.needsUpdate = true;\n                        // Reset plane to square\n                        scene.remove(targetPlane);\n                        targetPlane = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 1.2), planeMaterial);\n                        targetPlane.position.copy(CENTER);\n                        scene.add(targetPlane);\n                        return;\n                    }\n\n                    const loader = new THREE.TextureLoader();\n                    loader.crossOrigin = 'anonymous';\n                    loader.load(url, (texture) => {\n                        texture.minFilter = THREE.LinearFilter;\n                        texture.magFilter = THREE.LinearFilter;\n                        planeMaterial.map = texture;\n                        planeMaterial.needsUpdate = true;\n\n                        // Adjust plane aspect ratio to match image\n                        const img = texture.image;\n                        if (img && img.width && img.height) {\n                            const aspect = img.width / img.height;\n                            const maxSize = 1.5;\n                            let planeWidth, planeHeight;\n                            if (aspect > 1) {\n                                planeWidth = maxSize;\n                                planeHeight = maxSize / aspect;\n                            } else {\n                                planeHeight = maxSize;\n                                planeWidth = maxSize * aspect;\n                            }\n                            scene.remove(targetPlane);\n                            targetPlane = new THREE.Mesh(\n                                new THREE.PlaneGeometry(planeWidth, planeHeight),\n                                planeMaterial\n                            );\n                            targetPlane.position.copy(CENTER);\n                            scene.add(targetPlane);\n                        }\n                    }, undefined, (err) => {\n                        console.error('Failed to load texture:', err);\n                    });\n                }\n\n                // Check for initial imageUrl\n                if (props.imageUrl) {\n                    updateTextureFromUrl(props.imageUrl);\n                }\n\n                // Camera model\n                const cameraGroup = new THREE.Group();\n                const bodyMat = new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 });\n                const body = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.22, 0.38), bodyMat);\n                cameraGroup.add(body);\n                const lens = new THREE.Mesh(\n                    new THREE.CylinderGeometry(0.09, 0.11, 0.18, 16),\n                    new THREE.MeshStandardMaterial({ color: 0x6699cc, metalness: 0.5, roughness: 0.3 })\n                );\n                lens.rotation.x = Math.PI / 2;\n                lens.position.z = 0.26;\n                cameraGroup.add(lens);\n                scene.add(cameraGroup);\n\n                // GREEN: Azimuth ring\n                const azimuthRing = new THREE.Mesh(\n                    new THREE.TorusGeometry(AZIMUTH_RADIUS, 0.04, 16, 64),\n                    new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.3 })\n                );\n                azimuthRing.rotation.x = Math.PI / 2;\n                azimuthRing.position.y = 0.05;\n                scene.add(azimuthRing);\n\n                const azimuthHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0x00ff88, emissive: 0x00ff88, emissiveIntensity: 0.5 })\n                );\n                azimuthHandle.userData.type = 'azimuth';\n                scene.add(azimuthHandle);\n\n                // PINK: Elevation arc\n                const arcPoints = [];\n                for (let i = 0; i <= 32; i++) {\n                    const angle = THREE.MathUtils.degToRad(-30 + (90 * i / 32));\n                    arcPoints.push(new THREE.Vector3(-0.8, ELEVATION_RADIUS * Math.sin(angle) + CENTER.y, ELEVATION_RADIUS * Math.cos(angle)));\n                }\n                const arcCurve = new THREE.CatmullRomCurve3(arcPoints);\n                const elevationArc = new THREE.Mesh(\n                    new THREE.TubeGeometry(arcCurve, 32, 0.04, 8, false),\n                    new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.3 })\n                );\n                scene.add(elevationArc);\n\n                const elevationHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0xff69b4, emissive: 0xff69b4, emissiveIntensity: 0.5 })\n                );\n                elevationHandle.userData.type = 'elevation';\n                scene.add(elevationHandle);\n\n                // ORANGE: Distance line & handle\n                const distanceLineGeo = new THREE.BufferGeometry();\n                const distanceLine = new THREE.Line(distanceLineGeo, new THREE.LineBasicMaterial({ color: 0xffa500 }));\n                scene.add(distanceLine);\n\n                const distanceHandle = new THREE.Mesh(\n                    new THREE.SphereGeometry(0.18, 16, 16),\n                    new THREE.MeshStandardMaterial({ color: 0xffa500, emissive: 0xffa500, emissiveIntensity: 0.5 })\n                );\n                distanceHandle.userData.type = 'distance';\n                scene.add(distanceHandle);\n\n                function updatePositions() {\n                    const distance = BASE_DISTANCE * distanceFactor;\n                    const azRad = THREE.MathUtils.degToRad(azimuthAngle);\n                    const elRad = THREE.MathUtils.degToRad(elevationAngle);\n\n                    const camX = distance * Math.sin(azRad) * Math.cos(elRad);\n                    const camY = distance * Math.sin(elRad) + CENTER.y;\n                    const camZ = distance * Math.cos(azRad) * Math.cos(elRad);\n\n                    cameraGroup.position.set(camX, camY, camZ);\n                    cameraGroup.lookAt(CENTER);\n\n                    azimuthHandle.position.set(AZIMUTH_RADIUS * Math.sin(azRad), 0.05, AZIMUTH_RADIUS * Math.cos(azRad));\n                    elevationHandle.position.set(-0.8, ELEVATION_RADIUS * Math.sin(elRad) + CENTER.y, ELEVATION_RADIUS * Math.cos(elRad));\n\n                    const orangeDist = distance - 0.5;\n                    distanceHandle.position.set(\n                        orangeDist * Math.sin(azRad) * Math.cos(elRad),\n                        orangeDist * Math.sin(elRad) + CENTER.y,\n                        orangeDist * Math.cos(azRad) * Math.cos(elRad)\n                    );\n                    distanceLineGeo.setFromPoints([cameraGroup.position.clone(), CENTER.clone()]);\n\n                    // Update prompt\n                    const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n                    const elSnap = snapToNearest(elevationAngle, elevationSteps);\n                    const distSnap = snapToNearest(distanceFactor, distanceSteps);\n                    const distKey = distSnap === 1 ? '1' : distSnap.toFixed(1);\n                    const prompt = '<sks> ' + azimuthNames[azSnap] + ' ' + elevationNames[String(elSnap)] + ' ' + distanceNames[distKey];\n                    promptOverlay.textContent = prompt;\n                }\n\n                function updatePropsAndTrigger() {\n                    const azSnap = snapToNearest(azimuthAngle, azimuthSteps);\n                    const elSnap = snapToNearest(elevationAngle, elevationSteps);\n                    const distSnap = snapToNearest(distanceFactor, distanceSteps);\n\n                    props.value = { azimuth: azSnap, elevation: elSnap, distance: distSnap };\n                    trigger('change', props.value);\n                }\n\n                // Raycasting\n                const raycaster = new THREE.Raycaster();\n                const mouse = new THREE.Vector2();\n                let isDragging = false;\n                let dragTarget = null;\n                let dragStartMouse = new THREE.Vector2();\n                let dragStartDistance = 1.0;\n                const intersection = new THREE.Vector3();\n\n                const canvas = renderer.domElement;\n\n                canvas.addEventListener('mousedown', (e) => {\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n\n                    raycaster.setFromCamera(mouse, camera);\n                    const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n\n                    if (intersects.length > 0) {\n                        isDragging = true;\n                        dragTarget = intersects[0].object;\n                        dragTarget.material.emissiveIntensity = 1.0;\n                        dragTarget.scale.setScalar(1.3);\n                        dragStartMouse.copy(mouse);\n                        dragStartDistance = distanceFactor;\n                        canvas.style.cursor = 'grabbing';\n                    }\n                });\n\n                canvas.addEventListener('mousemove', (e) => {\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n\n                    if (isDragging && dragTarget) {\n                        raycaster.setFromCamera(mouse, camera);\n\n                        if (dragTarget.userData.type === 'azimuth') {\n                            const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n                                if (azimuthAngle < 0) azimuthAngle += 360;\n                            }\n                        } else if (dragTarget.userData.type === 'elevation') {\n                            const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                const relY = intersection.y - CENTER.y;\n                                const relZ = intersection.z;\n                                elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n                            }\n                        } else if (dragTarget.userData.type === 'distance') {\n                            const deltaY = mouse.y - dragStartMouse.y;\n                            distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n                        }\n                        updatePositions();\n                    } else {\n                        raycaster.setFromCamera(mouse, camera);\n                        const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n                        [azimuthHandle, elevationHandle, distanceHandle].forEach(h => {\n                            h.material.emissiveIntensity = 0.5;\n                            h.scale.setScalar(1);\n                        });\n                        if (intersects.length > 0) {\n                            intersects[0].object.material.emissiveIntensity = 0.8;\n                            intersects[0].object.scale.setScalar(1.1);\n                            canvas.style.cursor = 'grab';\n                        } else {\n                            canvas.style.cursor = 'default';\n                        }\n                    }\n                });\n\n                const onMouseUp = () => {\n                    if (dragTarget) {\n                        dragTarget.material.emissiveIntensity = 0.5;\n                        dragTarget.scale.setScalar(1);\n\n                        // Snap and animate\n                        const targetAz = snapToNearest(azimuthAngle, azimuthSteps);\n                        const targetEl = snapToNearest(elevationAngle, elevationSteps);\n                        const targetDist = snapToNearest(distanceFactor, distanceSteps);\n\n                        const startAz = azimuthAngle, startEl = elevationAngle, startDist = distanceFactor;\n                        const startTime = Date.now();\n\n                        function animateSnap() {\n                            const t = Math.min((Date.now() - startTime) / 200, 1);\n                            const ease = 1 - Math.pow(1 - t, 3);\n\n                            let azDiff = targetAz - startAz;\n                            if (azDiff > 180) azDiff -= 360;\n                            if (azDiff < -180) azDiff += 360;\n                            azimuthAngle = startAz + azDiff * ease;\n                            if (azimuthAngle < 0) azimuthAngle += 360;\n                            if (azimuthAngle >= 360) azimuthAngle -= 360;\n\n                            elevationAngle = startEl + (targetEl - startEl) * ease;\n                            distanceFactor = startDist + (targetDist - startDist) * ease;\n\n                            updatePositions();\n                            if (t < 1) requestAnimationFrame(animateSnap);\n                            else updatePropsAndTrigger();\n                        }\n                        animateSnap();\n                    }\n                    isDragging = false;\n                    dragTarget = null;\n                    canvas.style.cursor = 'default';\n                };\n\n                canvas.addEventListener('mouseup', onMouseUp);\n                canvas.addEventListener('mouseleave', onMouseUp);\n                // Touch support for mobile\n                canvas.addEventListener('touchstart', (e) => {\n                    e.preventDefault();\n                    const touch = e.touches[0];\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n\n                    raycaster.setFromCamera(mouse, camera);\n                    const intersects = raycaster.intersectObjects([azimuthHandle, elevationHandle, distanceHandle]);\n\n                    if (intersects.length > 0) {\n                        isDragging = true;\n                        dragTarget = intersects[0].object;\n                        dragTarget.material.emissiveIntensity = 1.0;\n                        dragTarget.scale.setScalar(1.3);\n                        dragStartMouse.copy(mouse);\n                        dragStartDistance = distanceFactor;\n                    }\n                }, { passive: false });\n\n                canvas.addEventListener('touchmove', (e) => {\n                    e.preventDefault();\n                    const touch = e.touches[0];\n                    const rect = canvas.getBoundingClientRect();\n                    mouse.x = ((touch.clientX - rect.left) / rect.width) * 2 - 1;\n                    mouse.y = -((touch.clientY - rect.top) / rect.height) * 2 + 1;\n\n                    if (isDragging && dragTarget) {\n                        raycaster.setFromCamera(mouse, camera);\n\n                        if (dragTarget.userData.type === 'azimuth') {\n                            const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.05);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                azimuthAngle = THREE.MathUtils.radToDeg(Math.atan2(intersection.x, intersection.z));\n                                if (azimuthAngle < 0) azimuthAngle += 360;\n                            }\n                        } else if (dragTarget.userData.type === 'elevation') {\n                            const plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), -0.8);\n                            if (raycaster.ray.intersectPlane(plane, intersection)) {\n                                const relY = intersection.y - CENTER.y;\n                                const relZ = intersection.z;\n                                elevationAngle = THREE.MathUtils.clamp(THREE.MathUtils.radToDeg(Math.atan2(relY, relZ)), -30, 60);\n                            }\n                        } else if (dragTarget.userData.type === 'distance') {\n                            const deltaY = mouse.y - dragStartMouse.y;\n                            distanceFactor = THREE.MathUtils.clamp(dragStartDistance - deltaY * 1.5, 0.6, 1.4);\n                        }\n                        updatePositions();\n                    }\n                }, { passive: false });\n\n                canvas.addEventListener('touchend', (e) => {\n                    e.preventDefault();\n                    onMouseUp();\n                }, { passive: false });\n\n                canvas.addEventListener('touchcancel', (e) => {\n                    e.preventDefault();\n                    onMouseUp();\n                }, { passive: false });\n\n                // Initial update\n                updatePositions();\n\n                // Render loop\n                function render() {\n                    requestAnimationFrame(render);\n                    renderer.render(scene, camera);\n                }\n                render();\n\n                // Handle resize\n                new ResizeObserver(() => {\n                    camera.aspect = wrapper.clientWidth / wrapper.clientHeight;\n                    camera.updateProjectionMatrix();\n                    renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);\n                }).observe(wrapper);\n\n                // Store update functions for external calls\n                wrapper._updateFromProps = (newVal) => {\n                    if (newVal && typeof newVal === 'object') {\n                        azimuthAngle = newVal.azimuth ?? azimuthAngle;\n                        elevationAngle = newVal.elevation ?? elevationAngle;\n                        distanceFactor = newVal.distance ?? distanceFactor;\n                        updatePositions();\n                    }\n                };\n\n                wrapper._updateTexture = updateTextureFromUrl;\n\n                // Watch for prop changes (imageUrl and value)\n                let lastImageUrl = props.imageUrl;\n                let lastValue = JSON.stringify(props.value);\n                setInterval(() => {\n                    // Check imageUrl changes\n                    if (props.imageUrl !== lastImageUrl) {\n                        lastImageUrl = props.imageUrl;\n                        updateTextureFromUrl(props.imageUrl);\n                    }\n                    // Check value changes (from sliders)\n                    const currentValue = JSON.stringify(props.value);\n                    if (currentValue !== lastValue) {\n                        lastValue = currentValue;\n                        if (props.value && typeof props.value === 'object') {\n                            azimuthAngle = props.value.azimuth ?? azimuthAngle;\n                            elevationAngle = props.value.elevation ?? elevationAngle;\n                            distanceFactor = props.value.distance ?? distanceFactor;\n                            updatePositions();\n                        }\n                    }\n                }, 100);\n            };\n\n            initScene();\n        })();\n        \"\"\"\n\n        super().__init__(\n            value=value,\n            html_template=html_template,\n            js_on_load=js_on_load,\n            imageUrl=imageUrl,\n            **kwargs\n        )\n",
  "repo_url": "https://huggingface.co/spaces/multimodalart/qwen-image-multiple-angles-3d-camera/"
}