import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { TransformControls } from 'three/addons/controls/TransformControls.js'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { OBJLoader } from 'three/addons/loaders/OBJLoader.js'; import { FBXLoader } from 'three/addons/loaders/FBXLoader.js'; import { STLLoader } from 'three/addons/loaders/STLLoader.js'; import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'; import { OBJExporter } from 'three/addons/exporters/OBJExporter.js'; // App State const state = { mode: 'view', tool: 'brush', brushSize: 20, brushOpacity: 1, brushColor: new THREE.Color(1, 0, 0), activeObject: null, activeFace: null, isPainting: false, lastUV: null }; // Three.js variables let scene, camera, renderer, controls, transformControls; let paintTexture, paintCanvas, paintContext; let modelGroup; // DOM elements const viewport = document.getElementById('viewport'); const loadingOverlay = document.getElementById('loading-overlay'); const dropHint = document.getElementById('drop-hint'); const faceInfo = document.getElementById('face-info'); const brushSizeInput = document.getElementById('brush-size'); const brushOpacityInput = document.getElementById('brush-opacity'); const brushColorInput = document.getElementById('brush-color'); const sizeValue = document.getElementById('size-value'); const opacityValue = document.getElementById('opacity-value'); const paintPanel = document.getElementById('paint-panel'); const materialPanel = document.getElementById('material-panel'); const importBtn = document.getElementById('import-btn'); const exportGlbBtn = document.getElementById('export-glb'); const exportObjBtn = document.getElementById('export-obj'); const importTextureBtn = document.getElementById('import-texture-btn'); const modeBtns = document.querySelectorAll('.mode-btn'); const toolBtns = document.querySelectorAll('.tool-btn'); const offsetXInput = document.getElementById('offset-x'); const offsetYInput = document.getElementById('offset-y'); const repeatXInput = document.getElementById('repeat-x'); const repeatYInput = document.getElementById('repeat-y'); const rotationInput = document.getElementById('rotation'); const mirrorXInput = document.getElementById('mirror-x'); const mirrorYInput = document.getElementById('mirror-y'); // Initialize the application init(); function init() { initThreeJS(); initPaintCanvas(); initEventListeners(); updateUI(); } function initThreeJS() { // Create scene scene = new THREE.Scene(); scene.background = new THREE.Color(0x252526); // Create camera camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(0, 2, 5); camera.lookAt(0, 0, 0); // Create renderer with sRGB encoding and antialiasing renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(viewport.clientWidth, viewport.clientHeight); renderer.outputEncoding = THREE.sRGBEncoding; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; viewport.appendChild(renderer.domElement); // Add lights const ambientLight = new THREE.AmbientLight(0x404040); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 1); directionalLight.position.set(1, 1, 1); directionalLight.castShadow = true; directionalLight.shadow.mapSize.width = 1024; directionalLight.shadow.mapSize.height = 1024; scene.add(directionalLight); // Add grid helper const gridHelper = new THREE.GridHelper(10, 10, 0x444444, 0x888888); scene.add(gridHelper); // Create controls controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.dampingFactor = 0.25; transformControls = new TransformControls(camera, renderer.domElement); transformControls.addEventListener('dragging-changed', (event) => { controls.enabled = !event.value; }); scene.add(transformControls); // Create model group modelGroup = new THREE.Group(); scene.add(modelGroup); // Start animation loop renderer.setAnimationLoop(animate); } function initPaintCanvas() { // Create a hidden canvas for painting paintCanvas = document.createElement('canvas'); paintCanvas.width = 2048; paintCanvas.height = 2048; paintContext = paintCanvas.getContext('2d'); paintContext.fillStyle = '#ffffff'; paintContext.fillRect(0, 0, paintCanvas.width, paintCanvas.height); // Create Three.js texture from canvas paintTexture = new THREE.CanvasTexture(paintCanvas); paintTexture.colorSpace = THREE.SRGBColorSpace; paintTexture.flipY = false; } function initEventListeners() { // Window events window.addEventListener('resize', onWindowResize); window.addEventListener('dragover', (e) => { e.preventDefault(); dropHint.style.display = 'flex'; }); window.addEventListener('dragleave', () => { dropHint.style.display = 'none'; }); window.addEventListener('drop', (e) => { e.preventDefault(); dropHint.style.display = 'none'; if (e.dataTransfer.files.length > 0) { handleFileDrop(e.dataTransfer.files[0]); } }); // UI event listeners importBtn.addEventListener('click', handleImport); exportGlbBtn.addEventListener('click', () => exportModel('glb')); exportObjBtn.addEventListener('click', () => exportModel('obj')); importTextureBtn.addEventListener('click', handleTextureImport); // Mode change buttons modeBtns.forEach(btn => { btn.addEventListener('click', () => { state.mode = btn.dataset.mode; updateUI(); }); }); // Tool change buttons toolBtns.forEach(btn => { btn.addEventListener('click', () => { toolBtns.forEach(b => b.classList.remove('active')); btn.classList.add('active'); state.tool = btn.dataset.tool; }); }); // Brush settings brushSizeInput.addEventListener('input', (e) => { state.brushSize = parseInt(e.target.value); sizeValue.textContent = `${state.brushSize}px`; }); brushOpacityInput.addEventListener('input', (e) => { state.brushOpacity = parseInt(e.target.value) / 100; opacityValue.textContent = `${Math.round(state.brushOpacity * 100)}%`; }); brushColorInput.addEventListener('input', (e) => { state.brushColor.setStyle(e.target.value); }); // Texture settings offsetXInput.addEventListener('input', updateTextureSettings); offsetYInput.addEventListener('input', updateTextureSettings); repeatXInput.addEventListener('input', updateTextureSettings); repeatYInput.addEventListener('input', updateTextureSettings); rotationInput.addEventListener('input', updateTextureSettings); mirrorXInput.addEventListener('input', updateTextureSettings); mirrorYInput.addEventListener('input', updateTextureSettings); // Viewport mouse events renderer.domElement.addEventListener('pointerdown', onPointerDown); renderer.domElement.addEventListener('pointermove', onPointerMove); renderer.domElement.addEventListener('pointerup', onPointerUp); } function onWindowResize() { camera.aspect = viewport.clientWidth / viewport.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(viewport.clientWidth, viewport.clientHeight); } function animate() { controls.update(); renderer.render(scene, camera); } function updateUI() { // Update mode buttons modeBtns.forEach(btn => { btn.classList.toggle('active', btn.dataset.mode === state.mode); }); // Show/hide panels based on mode paintPanel.classList.toggle('active', state.mode === 'paint'); materialPanel.classList.toggle('active', state.mode === 'uv' || state.mode === 'paint'); // Update transform controls if (state.mode === 'move' && state.activeObject) { transformControls.attach(state.activeObject); transformControls.showX = true; transformControls.showY = true; transformControls.showZ = true; } else { transformControls.detach(); } // Update cursor if (state.mode === 'paint') { renderer.domElement.style.cursor = 'crosshair'; } else if (state.mode === 'move') { renderer.domElement.style.cursor = 'move'; } else { renderer.domElement.style.cursor = 'default'; } } function handleImport() { const input = document.createElement('input'); input.type = 'file'; input.accept = '.glb,.gltf,.obj,.fbx,.stl'; input.onchange = (e) => handleFileDrop(e.target.files[0]); input.click(); } function handleTextureImport() { const input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*'; input.onchange = (e) => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = (event) => { const img = new Image(); img.onload = () => { paintContext.drawImage(img, 0, 0, paintCanvas.width, paintCanvas.height); paintTexture.needsUpdate = true; }; img.src = event.target.result; }; reader.readAsDataURL(file); }; input.click(); } function handleFileDrop(file) { if (!file) return; loadingOverlay.style.display = 'flex'; const extension = file.name.split('.').pop().toLowerCase(); const loader = getLoaderForExtension(extension); if (!loader) { alert('Unsupported file format'); loadingOverlay.style.display = 'none'; return; } const objectURL = URL.createObjectURL(file); loader.load( objectURL, (object) => onModelLoaded(object), (xhr) => { console.log((xhr.loaded / xhr.total * 100) + '% loaded'); }, (err) => { console.error('Error loading model:', err); alert('Error loading model'); loadingOverlay.style.display = 'none'; } ); } function getLoaderForExtension(ext) { switch(ext) { case 'glb': case 'gltf': return new GLTFLoader(); case 'obj': return new OBJLoader(); case 'fbx': return new FBXLoader(); case 'stl': return new STLLoader(); default: return null; } } function onModelLoaded(object) { // Clear previous model while (modelGroup.children.length > 0) { modelGroup.remove(modelGroup.children[0]); } let model; // Handle different loader types if (object.scene) { // GLTF model = object.scene; } else if (object.children) { // OBJ, FBX, etc model = new THREE.Group(); model.add(object); } else if (object.type === 'BufferGeometry') { // STL const material = new THREE.MeshStandardMaterial({ map: paintTexture, side: THREE.DoubleSide }); model = new THREE.Mesh(object, material); } // Prepare model materials model.traverse((child) => { if (child.isMesh) { if (child.material) { if (Array.isArray(child.material)) { child.material.forEach(mat => { if (mat.isMaterial) prepareMaterial(mat); }); } else if (child.material.isMaterial) { prepareMaterial(child.material); } } } }); // Add to scene modelGroup.add(model); state.activeObject = model; // Center and scale const box = new THREE.Box3().setFromObject(model); const center = box.getCenter(new THREE.Vector3()); const size = box.getSize(new THREE.Vector3()); const maxSize = Math.max(size.x, size.y, size.z); const scale = 5 / maxSize; model.position.x = -center.x * scale; model.position.y = -center.y * scale; model.position.z = -center.z * scale; model.scale.set(scale, scale, scale); // Update controls controls.reset(); updateUI(); loadingOverlay.style.display = 'none'; } function prepareMaterial(material) { // Convert to MeshStandardMaterial if (!(material instanceof THREE.MeshStandardMaterial)) { const newMaterial = new THREE.MeshStandardMaterial({ map: material.map || paintTexture, color: material.color?.getHex() || 0xffffff, roughness: 0.8, metalness: 0.2 }); material = newMaterial; } // Ensure we're using our paint texture if (!material.map) { material.map = paintTexture; } material.map.needsUpdate = true; return material; } function updateTextureSettings() { if (!paintTexture) return; const offsetX = parseFloat(offsetXInput.value); const offsetY = parseFloat(offsetYInput.value); const repeatX = parseFloat(repeatXInput.value); const repeatY = parseFloat(repeatYInput.value); const rotation = (parseFloat(rotationInput.value) * Math.PI) / 180; const mirrorX = mirrorXInput.checked; const mirrorY = mirrorYInput.checked; paintTexture.offset.set(offsetX, offsetY); paintTexture.repeat.set( mirrorX ? -repeatX : repeatX, mirrorY ? -repeatY : repeatY ); paintTexture.rotation = rotation; paintTexture.center.set(0.5, 0.5); paintTexture.needsUpdate = true; } function getCanvasPositionFromUV(uv) { if (!uv) return null; return { x: uv.x * paintCanvas.width, y: (1 - uv.y) * paintCanvas.height // Flip Y for canvas coordinates }; } function paintAtUVs(uv1, uv2) { if (!state.activeObject || state.tool === 'picker') return; const pos1 = getCanvasPositionFromUV(uv1); const pos2 = getCanvasPositionFromUV(uv2); if (!pos1 || !pos2) return; paintContext.globalCompositeOperation = 'source-over'; paintContext.globalAlpha = state.brushOpacity; if (state.tool === 'brush') { paintContext.strokeStyle = `rgb(${ Math.floor(state.brushColor.r * 255) }, ${ Math.floor(state.brushColor.g * 255) }, ${ Math.floor(state.brushColor.b * 255) })`; paintContext.lineWidth = state.brushSize; paintContext.lineCap = 'round'; paintContext.lineJoin = 'round'; paintContext.beginPath(); paintContext.moveTo(pos1.x, pos1.y); paintContext.lineTo(pos2.x, pos2.y); paintContext.stroke(); } else if (state.tool === 'eraser') { paintContext.globalCompositeOperation = 'destination-out'; paintContext.beginPath(); paintContext.arc(pos1.x, pos1.y, state.brushSize / 2, 0, Math.PI * 2); paintContext.fill(); } paintTexture.needsUpdate = true; } function pickColorFromUV(uv) { if (!uv || state.tool !== 'picker') return; const pos = getCanvasPositionFromUV(uv); const pixel = paintContext.getImageData(pos.x, pos.y, 1, 1).data; const color = `rgb(${pixel[0]}, ${pixel[1]}, ${pixel[2]})`; state.brushColor.setRGB(pixel[0] / 255, pixel[1] / 255, pixel[2] / 255); brushColorInput.value = color; } function onPointerDown(event) { if (state.mode !== 'paint') return; event.preventDefault(); state.isPainting = true; const uv = getUVFromPointer(event); if (uv) { state.lastUV = uv; pickColorFromUV(uv); paintAtUVs(uv, uv); // Dot at click position } } function onPointerMove(event) { const uv = getUVFromPointer(event); // Update face info if (uv && state.activeFace) { updateFaceOrientationInfo(state.activeFace); } // Painting if (state.isPainting && state.mode === 'paint' && uv && state.lastUV) { paintAtUVs(state.lastUV, uv); state.lastUV = uv; } } function onPointerUp(event) { state.isPainting = false; state.lastUV = null; } function getUVFromPointer(event) { if (!state.activeObject) return null; // Get mouse position in viewport coordinates const rect = renderer.domElement.getBoundingClientRect(); const mouse = { x: ((event.clientX - rect.left) / rect.width) * 2 - 1, y: -((event.clientY - rect.top) / rect.height) * 2 + 1 }; // Raycast to find intersection const raycaster = new THREE.Raycaster(); raycaster.setFromCamera(mouse, camera); const intersects = raycaster.intersectObject(state.activeObject, true); if (intersects.length > 0) { const intersect = intersects[0]; state.activeFace = intersect.face; return intersect.uv; } return null; } function updateFaceOrientationInfo(face) { if (!face || !face.normal) { faceInfo.textContent = 'No face selected'; return; } const normal = face.normal; const epsilon = 0.5; let orientation = ''; const dir = getDominantAxis(normal); switch(dir.axis) { case 'x': orientation = dir.value > 0 ? 'Right' : 'Left'; break; case 'y': orientation = dir.value > 0 ? 'Top' : 'Bottom'; break; case 'z': orientation = dir.value > 0 ? 'Front' : 'Back'; break; default: orientation = 'Unknown'; } faceInfo.textContent = `Face: ${orientation} (${normal.x.toFixed(2)}, ${normal.y.toFixed(2)}, ${normal.z.toFixed(2)})`; } function getDominantAxis(normal) { const abs = { x: Math.abs(normal.x), y: Math.abs(normal.y), z: Math.abs(normal.z) }; if (abs.x > abs.y && abs.x > abs.z) { return { axis: 'x', value: normal.x }; } else if (abs.y > abs.x && abs.y > abs.z) { return { axis: 'y', value: normal.y }; } return { axis: 'z', value: normal.z }; } function exportModel(format) { if (!state.activeObject) { alert('No model loaded'); return; } const data = format === 'glb' ? exportGLTF(state.activeObject) : exportOBJ(state.activeObject); if (!data) return; const blob = new Blob([data], { type: 'application/octet-stream' }); const url = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = `model.${format}`; anchor.click(); URL.revokeObjectURL(url); } function exportGLTF(object) { const exporter = new GLTFExporter(); let result; exporter.parse( object, (gltf) => { if (gltf instanceof ArrayBuffer) { result = gltf; } else { const json = JSON.stringify(gltf, null, 2); result = new TextEncoder().encode(json); } }, { binary: true, includeCustomExtensions: true } ); return result; } function exportOBJ(object) { const exporter = new OBJExporter(); return exporter.parse(object); }