"use client"; import { useEffect, useRef, useState, useId } from "react"; import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import { Box, RotateCcw, Layers, Ruler, Palette, Sparkles, MessageCircle, Compass, AlertTriangle, CheckCircle2 } from "lucide-react"; import { generateWhatsAppQuoteUrl } from "@/lib/whatsapp"; export type FenceType = "alambrado_curvo" | "alambrado_reto" | "alambrado_pvc" | "gradil_3d"; export type FenceColor = "galvanizado" | "verde" | "preto" | "cinza"; export type FenceHeight = "1.50m" | "1.80m" | "2.00m" | "2.50m" | "3.00m"; export type GroundType = "terra" | "grama" | "concreto"; export type FenceLayout = "1_lance" | "2_lances" | "4_lances" | "canto_l"; // Gerador de textura procedural perfeita para a malha losangular de Alambrado (Chain Link) function createChainLinkTexture(colorHex: string, wireWidth: number = 3): THREE.CanvasTexture { const canvas = document.createElement("canvas"); canvas.width = 128; canvas.height = 128; const ctx = canvas.getContext("2d"); if (ctx) { ctx.clearRect(0, 0, 128, 128); // Linha do arame com efeito metálico / degradê ctx.strokeStyle = colorHex; ctx.lineWidth = wireWidth; ctx.lineCap = "round"; ctx.lineJoin = "round"; // Desenha losango central ctx.beginPath(); ctx.moveTo(64, 0); ctx.lineTo(128, 64); ctx.lineTo(64, 128); ctx.lineTo(0, 64); ctx.closePath(); ctx.stroke(); // Linhas diagonais cruzadas nos 4 cantos para fechar o entrelaçamento contínuo ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(64, 64); ctx.moveTo(128, 0); ctx.lineTo(64, 64); ctx.moveTo(0, 128); ctx.lineTo(64, 64); ctx.moveTo(128, 128); ctx.lineTo(64, 64); ctx.stroke(); } const texture = new THREE.CanvasTexture(canvas); texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.generateMipmaps = true; texture.minFilter = THREE.LinearMipmapLinearFilter; texture.magFilter = THREE.LinearFilter; return texture; } export default function FenceViewer3D() { const containerRef = useRef(null); const canvasRef = useRef(null); // Estados const [fenceType, setFenceType] = useState("alambrado_curvo"); const [color, setColor] = useState("galvanizado"); const [height, setHeight] = useState("2.00m"); const [ground, setGround] = useState("grama"); const [layout, setLayout] = useState("2_lances"); const [hasBarbedWire, setHasBarbedWire] = useState(true); const [hasConcertina, setHasConcertina] = useState(false); const [autoRotate, setAutoRotate] = useState(false); const [webGLError, setWebGLError] = useState(false); const [isLoaded, setIsLoaded] = useState(false); const cepInputId = useId(); const [cep, setCep] = useState(""); const numericHeight = parseFloat(height.replace("m", "")); const isCurved = fenceType === "alambrado_curvo"; // Mapeamento de cores const colorMap = { galvanizado: { hex: "#b8c0c8", threeHex: 0xb8c0c8, name: "Aço Galvanizado a Fogo (Zincado)", metalness: 0.85, roughness: 0.35, postHex: 0x858990 }, verde: { hex: "#225528", threeHex: 0x225528, name: "Revestido em PVC Verde Musgo (Quadras)", metalness: 0.15, roughness: 0.45, postHex: 0x1f3621 }, preto: { hex: "#1d1f22", threeHex: 0x1d1f22, name: "Revestido em PVC Preto Nobre", metalness: 0.25, roughness: 0.5, postHex: 0x24272c }, cinza: { hex: "#5c6269", threeHex: 0x5c6269, name: "Revestido em PVC Cinza Urbano", metalness: 0.3, roughness: 0.4, postHex: 0x484b50 }, }; // Cálculo de quantitativos const getLayoutDetails = () => { switch (layout) { case "1_lance": return { meters: 2.5, posts: 2, desc: "1 Lance de Alambrado (2,50m)" }; case "2_lances": return { meters: 5.0, posts: 3, desc: "2 Lances contínuos (5,00m)" }; case "4_lances": return { meters: 10.0, posts: 5, desc: "4 Lances contínuos (10,00m)" }; case "canto_l": return { meters: 7.5, posts: 4, desc: "Canto de Esquina 90° (7,50m)" }; } }; const currentLayout = getLayoutDetails(); const estimatedRolls = Math.max(1, Math.ceil(currentLayout.meters / 25)); const wireLines = numericHeight >= 2.0 ? 4 : 3; const estimatedWireKg = Math.max(2, Math.ceil((currentLayout.meters * wireLines) / 35)); const estimatedTensioners = estimatedRolls * wireLines; // Refs de Three.js const sceneRef = useRef(null); const cameraRef = useRef(null); const rendererRef = useRef(null); const controlsRef = useRef(null); const fenceGroupRef = useRef(null); const groundMeshRef = useRef(null); // 1. Inicialização do Three.js (com reutilização segura do Canvas sem duplicação) useEffect(() => { if (!canvasRef.current || !containerRef.current) return; const canvas = canvasRef.current; let renderer: THREE.WebGLRenderer; try { renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, powerPreference: "high-performance", }); } catch (e) { console.warn("WebGL não suportado ou falhou na inicialização:", e); setWebGLError(true); return; } const width = containerRef.current.clientWidth || 800; const heightPx = containerRef.current.clientHeight || 560; renderer.setSize(width, heightPx, false); renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.2; rendererRef.current = renderer; const scene = new THREE.Scene(); scene.background = new THREE.Color(0x0a0c0e); scene.fog = new THREE.FogExp2(0x0a0c0e, 0.025); sceneRef.current = scene; const camera = new THREE.PerspectiveCamera(40, width / heightPx, 0.1, 100); camera.position.set(4.8, 3.4, 6.2); cameraRef.current = camera; const controls = new OrbitControls(camera, canvas); controls.enableDamping = true; controls.dampingFactor = 0.05; controls.maxPolarAngle = Math.PI / 2 - 0.02; controls.minDistance = 2.0; controls.maxDistance = 20.0; controls.target.set(0, 1.1, 0); controlsRef.current = controls; // Luzes const ambientLight = new THREE.AmbientLight(0xffffff, 1.0); scene.add(ambientLight); const sunLight = new THREE.DirectionalLight(0xffffff, 2.5); sunLight.position.set(7, 14, 9); sunLight.castShadow = true; sunLight.shadow.mapSize.width = 1024; sunLight.shadow.mapSize.height = 1024; sunLight.shadow.bias = -0.0005; scene.add(sunLight); const fillLight = new THREE.DirectionalLight(0xa3c745, 0.4); fillLight.position.set(-6, 4, -4); scene.add(fillLight); // Chão const groundGeo = new THREE.PlaneGeometry(40, 40); const groundMat = new THREE.MeshStandardMaterial({ color: 0x192d16, roughness: 0.95, metalness: 0.05, }); const groundMesh = new THREE.Mesh(groundGeo, groundMat); groundMesh.rotation.x = -Math.PI / 2; groundMesh.position.y = 0; groundMesh.receiveShadow = true; scene.add(groundMesh); groundMeshRef.current = groundMesh; const gridHelper = new THREE.GridHelper(26, 26, 0x334155, 0x1e293b); gridHelper.position.y = 0.005; scene.add(gridHelper); const fenceGroup = new THREE.Group(); scene.add(fenceGroup); fenceGroupRef.current = fenceGroup; setIsLoaded(true); // Loop let animId: number; const animate = () => { animId = requestAnimationFrame(animate); if (controlsRef.current) { controlsRef.current.autoRotate = autoRotate; controlsRef.current.autoRotateSpeed = 1.2; controlsRef.current.update(); } renderer.render(scene, camera); }; animate(); const handleResize = () => { if (!containerRef.current || !renderer || !camera) return; const w = containerRef.current.clientWidth; const h = containerRef.current.clientHeight || 560; camera.aspect = w / h; camera.updateProjectionMatrix(); renderer.setSize(w, h, false); }; window.addEventListener("resize", handleResize); return () => { window.removeEventListener("resize", handleResize); cancelAnimationFrame(animId); controls.dispose(); renderer.dispose(); }; }, []); // 2. Chão useEffect(() => { if (!groundMeshRef.current) return; const mat = groundMeshRef.current.material as THREE.MeshStandardMaterial; if (ground === "grama") { mat.color.setHex(0x192d16); mat.roughness = 0.95; } else if (ground === "concreto") { mat.color.setHex(0x383b42); mat.roughness = 0.7; } else { mat.color.setHex(0x38291a); mat.roughness = 0.98; } }, [ground]); // 3. Renderização da Cerca em 3D useEffect(() => { if (!fenceGroupRef.current || !sceneRef.current) return; const group = fenceGroupRef.current; while (group.children.length > 0) { const obj = group.children[0]; group.remove(obj); if ((obj as THREE.Mesh).geometry) (obj as THREE.Mesh).geometry.dispose(); } const colConfig = colorMap[color]; const wireColorHex = fenceType === "alambrado_pvc" ? "#225528" : colConfig.hex; // Material de mourão const postMat = new THREE.MeshStandardMaterial({ color: fenceType === "alambrado_curvo" ? 0x82868e : colConfig.postHex, roughness: 0.9, metalness: 0.1, }); const steelGuideMat = new THREE.MeshStandardMaterial({ color: 0x9ca3af, metalness: 0.8, roughness: 0.3, }); const spanLength = 2.5; // 2,50m entre mourões const h = numericHeight; interface PostPos { x: number; z: number; isCorner?: boolean } interface SpanPos { startX: number; startZ: number; endX: number; endZ: number } const posts: PostPos[] = []; const spans: SpanPos[] = []; if (layout === "1_lance") { posts.push({ x: -spanLength / 2, z: 0 }); posts.push({ x: spanLength / 2, z: 0 }); spans.push({ startX: -spanLength / 2, startZ: 0, endX: spanLength / 2, endZ: 0 }); } else if (layout === "2_lances") { posts.push({ x: -spanLength, z: 0 }); posts.push({ x: 0, z: 0 }); posts.push({ x: spanLength, z: 0 }); spans.push({ startX: -spanLength, startZ: 0, endX: 0, endZ: 0 }); spans.push({ startX: 0, startZ: 0, endX: spanLength, endZ: 0 }); } else if (layout === "4_lances") { posts.push({ x: -spanLength * 2, z: 0 }); posts.push({ x: -spanLength, z: 0 }); posts.push({ x: 0, z: 0 }); posts.push({ x: spanLength, z: 0 }); posts.push({ x: spanLength * 2, z: 0 }); spans.push({ startX: -spanLength * 2, startZ: 0, endX: -spanLength, endZ: 0 }); spans.push({ startX: -spanLength, startZ: 0, endX: 0, endZ: 0 }); spans.push({ startX: 0, startZ: 0, endX: spanLength, endZ: 0 }); spans.push({ startX: spanLength, startZ: 0, endX: spanLength * 2, endZ: 0 }); } else if (layout === "canto_l") { posts.push({ x: -spanLength, z: 0 }); posts.push({ x: 0, z: 0, isCorner: true }); posts.push({ x: spanLength, z: 0 }); posts.push({ x: spanLength, z: spanLength }); spans.push({ startX: -spanLength, startZ: 0, endX: 0, endZ: 0 }); spans.push({ startX: 0, startZ: 0, endX: spanLength, endZ: 0 }); spans.push({ startX: spanLength, startZ: 0, endX: spanLength, endZ: spanLength }); } // --- MOURÕES --- posts.forEach((p, idx) => { const postHeight = h + (isCurved ? 0.45 : 0.05); const postGeo = new THREE.BoxGeometry(0.10, postHeight, 0.10); const postMesh = new THREE.Mesh(postGeo, postMat); postMesh.position.set(p.x, postHeight / 2, p.z); postMesh.castShadow = true; postMesh.receiveShadow = true; group.add(postMesh); // Base sapata const baseGeo = new THREE.CylinderGeometry(0.14, 0.16, 0.08, 12); const baseMesh = new THREE.Mesh(baseGeo, postMat); baseMesh.position.set(p.x, 0.04, p.z); baseMesh.receiveShadow = true; group.add(baseMesh); // Mourão Curvo (Braço 45°) if (isCurved) { const armLength = 0.50; const armGeo = new THREE.BoxGeometry(0.08, armLength, 0.08); const armMesh = new THREE.Mesh(armGeo, postMat); armMesh.rotation.z = -Math.PI / 4; armMesh.position.set(p.x + (armLength * Math.sin(Math.PI / 4)) / 2, postHeight + 0.12, p.z); armMesh.castShadow = true; group.add(armMesh); } // Escoras nos cantos if (idx === 0 || idx === posts.length - 1 || p.isCorner) { const braceLength = h * 0.95; const braceGeo = new THREE.BoxGeometry(0.08, braceLength, 0.08); const braceMesh = new THREE.Mesh(braceGeo, postMat); braceMesh.rotation.z = idx === 0 ? -Math.PI / 4.5 : Math.PI / 4.5; braceMesh.position.set(idx === 0 ? p.x + 0.55 : p.x - 0.55, h * 0.4, p.z); braceMesh.castShadow = true; group.add(braceMesh); } }); // --- PAINÉIS DE TELA DE ALAMBRADO --- // Textura procedural ultra-leve e realista (zero crash de contexto WebGL) const meshTexture = createChainLinkTexture(wireColorHex, 3); const totalLines = h >= 2.0 ? 4 : 3; spans.forEach((span) => { const dx = span.endX - span.startX; const dz = span.endZ - span.startZ; const len = Math.sqrt(dx * dx + dz * dz); const angle = Math.atan2(dz, dx); const cx = (span.startX + span.endX) / 2; const cz = (span.startZ + span.endZ) / 2; // Fiadas horizontais de arame guia for (let l = 1; l <= totalLines; l++) { const wireY = (h / (totalLines + 0.5)) * l; const guideGeo = new THREE.CylinderGeometry(0.003, 0.003, len, 6); const guideMesh = new THREE.Mesh(guideGeo, steelGuideMat); guideMesh.rotation.z = Math.PI / 2; guideMesh.rotation.y = -angle; guideMesh.position.set(cx, wireY, cz); group.add(guideMesh); } // Fios farpados no mourão curvo if (isCurved && hasBarbedWire) { for (let b = 1; b <= 3; b++) { const barbedGeo = new THREE.CylinderGeometry(0.0025, 0.0025, len, 6); const barbedMesh = new THREE.Mesh(barbedGeo, steelGuideMat); barbedMesh.rotation.z = Math.PI / 2; barbedMesh.rotation.y = -angle; barbedMesh.position.set(cx + b * 0.09, h + 0.15 + b * 0.10, cz); group.add(barbedMesh); } } // Concertina opcional if (hasConcertina) { const concertinaRadius = 0.18; const coils = Math.floor(len * 5.5); const step = len / coils; for (let k = 0; k < coils; k++) { const torusGeo = new THREE.TorusGeometry(concertinaRadius, 0.0028, 6, 18); const torusMesh = new THREE.Mesh(torusGeo, steelGuideMat); torusMesh.rotation.y = -angle + Math.PI / 2; const px = span.startX + Math.cos(angle) * (k * step + step / 2); const pz = span.startZ + Math.sin(angle) * (k * step + step / 2); torusMesh.position.set(px, h + concertinaRadius + 0.02, pz); torusMesh.castShadow = true; group.add(torusMesh); } } // Plano da Tela de Alambrado com textura de malha losangular const spanTexture = meshTexture.clone(); spanTexture.needsUpdate = true; const diamondScale = 0.055; // 50mm por losango spanTexture.repeat.set(len / diamondScale, h / diamondScale); const planeGeo = new THREE.PlaneGeometry(len, h); const planeMat = new THREE.MeshStandardMaterial({ map: spanTexture, transparent: true, alphaTest: 0.15, side: THREE.DoubleSide, metalness: fenceType === "alambrado_pvc" ? 0.15 : 0.8, roughness: fenceType === "alambrado_pvc" ? 0.5 : 0.35, }); const planeMesh = new THREE.Mesh(planeGeo, planeMat); planeMesh.position.set(cx, h / 2, cz); planeMesh.rotation.y = -angle; planeMesh.castShadow = true; group.add(planeMesh); }); }, [fenceType, color, height, layout, hasBarbedWire, hasConcertina]); const setCameraView = (type: "geral" | "detalhe" | "topo") => { if (!cameraRef.current || !controlsRef.current) return; const cam = cameraRef.current; const ctrl = controlsRef.current; switch (type) { case "geral": cam.position.set(4.8, 3.4, 6.2); ctrl.target.set(0, 1.1, 0); break; case "detalhe": cam.position.set(0.8, 1.4, 1.5); ctrl.target.set(0, 1.2, 0); break; case "topo": cam.position.set(0.1, 8.0, 0.1); ctrl.target.set(0, 0, 0); break; } ctrl.update(); }; const whatsappUrl = generateWhatsAppQuoteUrl({ productType: fenceType, productName: fenceType === "alambrado_curvo" ? "Tela de Alambrado com Mourão de Concreto Curvo (+ Arame Farpado)" : fenceType === "alambrado_pvc" ? "Tela de Alambrado Revestida em PVC Verde (Quadras)" : fenceType === "alambrado_reto" ? "Tela de Alambrado Galvanizada com Mourão Reto" : "Gradil 3D Eletrosoldado", linearMeters: currentLayout.meters, height, finish: colorMap[color].name, postType: fenceType === "alambrado_curvo" ? "Mourão de Concreto com Ponta Curva" : "Mourão de Concreto / Aço Reto", meshSize: "2 Polegadas (50mm)", wireGauge: "BWG 12 (2,77mm) ou BWG 10", cepOrCity: cep || "A Definir", estimatedRolls, estimatedPosts: currentLayout.posts, estimatedWireKg, estimatedTensioners, notes: `Simulação no site: ${hasBarbedWire ? "Com 3 fios de arame farpado" : "Sem arame farpado"}${hasConcertina ? " + Concertina" : ""}.`, }); return (
{/* Barra de Título Superior */}
Studio 3D: Simulador de Telas de Alambrado & Mourões Foco em Alambrado

Gire em 360°, teste mourões retos ou curvos com arame farpado e receba a lista de rolos.

{/* Câmera Rápida */}
{/* Grid: Canvas 3D (8 cols) + Controles (4 cols) */}
{/* Canvas 3D Viewport com fallback visual garantido */}
{/* O CANVAS É DECLARATIVO E EXCLUSIVO (Zero duplicações ou broken image) */} {/* Fallback caso WebGL seja bloqueado na GPU do usuário */} {webGLError && (

Visualizador em Modo Interativo 2D

Seu navegador opera com aceleração gráfica limitada, mas todos os parâmetros e o cálculo de rolos e mourões continuam 100% funcionais abaixo!

)} {/* Dica de Interação */}
Gire 360° • Aproxime para ver a malha losangular e mourões de concreto
{/* Badge Inferior */}
{currentLayout.desc} Altura: {height} • Mourão: {isCurved ? "Ponta Curva com Arame Farpado" : "Reto"}
{/* Alternador de Solo */}
Solo:
{/* Controles Específicos para Alambrado */}
{/* 1. Tipo de Alambrado & Mourão */}
{/* 2. Altura do Alambrado */}
{(["1.50m", "1.80m", "2.00m", "2.50m", "3.00m"] as FenceHeight[]).map((h) => ( ))}
{/* 3. Acabamento do Arame */}
{[ { id: "galvanizado", label: "Galvanizado a Fogo", hex: "bg-zinc-300" }, { id: "verde", label: "Revestido em PVC Verde", hex: "bg-emerald-800" }, { id: "preto", label: "Revestido em PVC Preto", hex: "bg-zinc-950 border border-zinc-700" }, { id: "cinza", label: "Revestido em PVC Cinza", hex: "bg-zinc-600" }, ].map((c) => ( ))}
{/* 4. Módulos na Prévia 3D */}
{/* Opcionais de Segurança */}
{isCurved && ( )}
{/* Resumo de Peças para Alambrado */}
Extensão visualizada: {currentLayout.meters}m lineares
Mourões de Concreto/Aço: {currentLayout.posts} unidades
Arame Guia / Tensionador: ~{estimatedWireKg} kg
Catracas Esticadoras: {estimatedTensioners} un
setCep(e.target.value)} className="w-full bg-zinc-900 border border-zinc-700/80 rounded-lg px-3 py-1.5 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-[#a3c745]" />
Solicitar Orçamento de Alambrado no WhatsApp
); }