Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: enhance Laptop3DViewer and Phone3DViewer with outline effects and interaction handling

CristianOlivera1948d69553d24
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 2597527..0b8290f 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -376,7 +376,7 @@ function VideoCanvasInner({
if (imagePhoneZoomTimerRef.current) clearTimeout(imagePhoneZoomTimerRef.current);
imagePhoneZoomTimerRef.current = setTimeout(() => setImagePhoneZoomVisible(false), 1200);
};
-
+
useEffect(() => {
const el = previewContainerRef.current;
if (!el) return;
@@ -2459,6 +2459,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
) : activePhoneDevice === "iphone-13-pro-max" ? (
<IPhone13ProMax3DViewer
@@ -2483,6 +2484,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
) : activePhoneDevice === "iphone-17-pro-max" ? (
<IPhone17ProMax3DViewer
@@ -2507,6 +2509,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
) : activePhoneDevice === "double_iphone_13_pro" ? (
<DoubleIPhone3DViewer
@@ -2530,6 +2533,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
) : activePhoneDevice === "ipad_mini_6_2021" ? (
<IPadMini63DViewer
@@ -2553,6 +2557,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
) : (
@@ -2579,6 +2584,7 @@ function VideoCanvasInner({
environment={viewer3D.environment}
isSelected={isVideoSelected}
isHovered={isVideoHovered}
+ onSelectChange={(value) => setIsVideoSelected(value)}
/>
)}
</div>
diff --git a/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx b/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
index 32d3cd1..e2fbfb9 100644
--- a/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/DoubleIPhone3DViewer.tsx
@@ -11,13 +11,19 @@ import {
applyCropToImage,
type ImageMaskConfigLike,
parseShadowColor,
- applyTextureCover,
- getOutlineFilter,
+ applyTextureCover
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+
+const EPSILON = 0.0001;
+
export interface DoubleIPhone3DApi {
renderAt: (width: number, height: number) => void;
restorePreview: () => void;
@@ -44,6 +50,8 @@ interface Props {
environment?: EnvironmentPreset;
isSelected?: boolean;
isHovered?: boolean;
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
const DEG = Math.PI / 180;
@@ -72,12 +80,14 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 3.0,
environment = "studio",
+ isSelected = false,
+ isHovered = false,
}: Props & {
rootRef: React.MutableRefObject<THREE.Group | null>;
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
const gltf = useGLTF(MODEL_URL, DRACO_URL);
const orbitRef = useRef<OrbitControlsType | null>(null);
const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
@@ -86,6 +96,14 @@ function ModelScene({
const lastLoadedUrlRef = useRef<string | null>(null);
const lastLoadedCropKeyRef = useRef<string | null>(null);
const onApiRef = useRef(onApi);
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
+ const isUserInteractingRef = useRef(false);
+
+ const areAnglesEqual = useCallback((angles1: { x: number; y: number } | null, angles2: { x: number; y: number }) => {
+ if (!angles1) return false;
+ return Math.abs(angles1.x - angles2.x) < EPSILON && Math.abs(angles1.y - angles2.y) < EPSILON;
+ }, []);
useLayoutEffect(() => {
onApiRef.current = onApi;
@@ -100,53 +118,47 @@ function ModelScene({
useEffect(() => {
const capturedOnApi = onApiRef.current;
const RENDER_PIXEL_RATIO = 2;
-
const api: DoubleIPhone3DApi = {
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
-
const maxTexSize = gl.capabilities.maxTextureSize || 4096;
const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
-
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
-
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+
gl.render(scene, cam);
},
restorePreview: () => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
-
const freshW = gl.domElement.clientWidth;
const freshH = gl.domElement.clientHeight;
-
(cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
-
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+
+ invalidate();
},
- // Este viewer no tiene ContactShadows real en la escena — su sombra es
- // puramente CSS (drop-shadow del wrapper) y NO se captura en renderAt().
- // Si se deja en `true`, VideoCanvas.drawFrame omite el fallback 2D y el
- // export queda sin sombra.
hasBuiltInShadow: false,
};
-
capturedOnApi?.(api);
return () => capturedOnApi?.(null);
- }, [gl, scene, camera, cameraRef]);
+ }, [gl, scene, camera, cameraRef, invalidate]);
const applyTexture = useCallback(() => {
if (videoElement) return;
-
const mat = screenMatRef.current;
if (!mat) return;
@@ -193,14 +205,12 @@ function ModelScene({
lastLoadedCropKeyRef.current = cropKey;
invalidate();
};
-
img.onerror = () => {
if (mat.map) mat.map.dispose();
mat.color.set(0x111111);
mat.needsUpdate = true;
invalidate();
};
-
img.src = targetImgUrl;
}, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
@@ -226,11 +236,8 @@ function ModelScene({
}
return;
}
-
const tex = new THREE.VideoTexture(videoElement);
-
tex.flipY = true;
-
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
@@ -239,13 +246,7 @@ function ModelScene({
tex.wrapT = THREE.ClampToEdgeWrapping;
const updateTextureTransform = () => {
- applyTextureCover(
- tex,
- videoElement.videoWidth,
- videoElement.videoHeight,
- 1080,
- 2340
- );
+ applyTextureCover(tex, videoElement.videoWidth, videoElement.videoHeight, 1080, 2340);
applyVideoTextureIfReady();
};
@@ -259,7 +260,6 @@ function ModelScene({
videoTextureRef.current.dispose();
}
videoTextureRef.current = tex;
-
applyVideoTextureIfReady();
return () => {
@@ -272,7 +272,6 @@ function ModelScene({
}, [videoElement, applyVideoTextureIfReady]);
const applyTextureRef = useRef(applyTexture);
-
useEffect(() => {
applyTextureRef.current = applyTexture;
}, [applyTexture]);
@@ -285,14 +284,11 @@ function ModelScene({
let isMounted = true;
const group = gltf.scene.clone(true);
const camZ = 1.5;
-
const box = new THREE.Box3().setFromObject(group);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
-
const halfH = camZ * Math.tan((40 / 2) * DEG);
const sf = (halfH * 2 * 0.55) / size.y;
-
group.scale.setScalar(sf);
group.position.copy(center).negate().multiplyScalar(sf);
@@ -304,7 +300,6 @@ function ModelScene({
depthWrite: true,
});
screenMatRef.current = basicMat;
-
applyVideoTextureIfReady();
group.traverse((child) => {
@@ -342,14 +337,16 @@ function ModelScene({
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
useEffect(() => {
- if (
- prevRotationRef.current?.x === initialRotationX &&
- prevRotationRef.current?.y === initialRotationY
- ) {
+ if (isUserInteractingRef.current) return;
+
+ const currentAngles = { x: initialRotationX, y: initialRotationY };
+
+ if (areAnglesEqual(prevRotationRef.current, currentAngles)) {
return;
}
const id = setTimeout(() => {
+ if (isUserInteractingRef.current) return;
const orbit = orbitRef.current;
if (!orbit) return;
@@ -360,12 +357,11 @@ function ModelScene({
orbit.object.position.setFromSphericalCoords(radius, phi, theta);
orbit.update();
invalidate();
-
- prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
+ prevRotationRef.current = currentAngles;
}, 0);
return () => clearTimeout(id);
- }, [initialRotationX, initialRotationY, zoom, invalidate]);
+ }, [initialRotationX, initialRotationY, zoom, invalidate, areAnglesEqual]);
useEffect(() => {
if (rootRef.current) {
@@ -374,17 +370,65 @@ function ModelScene({
}
}, [initialRotationZ, invalidate]);
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+
+ outlinePass.edgeStrength = 8;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 3;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera, size.width, size.height, invalidate]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+
+ invalidate();
+ }, [isSelected, isHovered, invalidate, rootRef]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
+
return (
<>
- <PerspectiveCamera
- ref={cameraRef}
- makeDefault
- fov={40}
- near={0.01}
- far={100}
- position={DEFAULT_CAMERA_POS}
- zoom={zoom}
- />
+ <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={DEFAULT_CAMERA_POS} zoom={zoom} />
<OrbitControls
ref={orbitRef}
enableZoom={false}
@@ -393,19 +437,29 @@ function ModelScene({
dampingFactor={0.08}
autoRotate={autoRotate}
autoRotateSpeed={rotationSpeed}
+ onStart={() => {
+ isUserInteractingRef.current = true;
+ }}
onEnd={() => {
+ isUserInteractingRef.current = false;
const orbit = orbitRef.current;
if (!orbit || !onRotationChange) return;
+
const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
+
+ prevRotationRef.current = { x: rx, y: ry };
+
onRotationChange(rx, ry);
}}
/>
<Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
+
<ambientLight intensity={0.3} />
<directionalLight position={[3, 6, 5]} intensity={0.6} />
<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
<directionalLight position={[0, -5, 5]} intensity={0.35} />
+
<group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
<group ref={modelContainerRef} />
</group>
@@ -425,7 +479,7 @@ function CanvasWithLoader(
return (
<>
<Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
+ style={{ width: "100%", height: "100%", overflow: "visible", pointerEvents: "auto" }}
gl={{
antialias: true,
alpha: true,
@@ -449,10 +503,7 @@ function CanvasWithLoader(
</Suspense>
</Canvas>
{!loaded && (
- <div
- className="absolute inset-0 flex items-center justify-center pointer-events-none"
- style={{ zIndex: 4 }}
- >
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }} >
<div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
</div>
)}
@@ -461,18 +512,28 @@ function CanvasWithLoader(
}
export function DoubleIPhone3DViewer(props: Props) {
- const { shadowIntensity = 0, shadowColor = "#000000", imageMaskConfig = null, isSelected = false, isHovered = false } = props;
+ const {
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ imageMaskConfig = null,
+ isSelected = false,
+ onHoverChange,
+ onSelectChange
+ } = props;
+
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const canvasElRef = useRef<HTMLCanvasElement | null>(null);
+ const raycasterRef = useRef(new THREE.Raycaster());
+
const [grabbing, setGrabbing] = useState(false);
+ const [modelHovered, setModelHovered] = useState(false);
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
const computedBlur = tEased * 60;
const computedOpacity = tEased * 0.7;
- const shadowRgba = shadowColor.startsWith("#")
- ? parseShadowColor(shadowColor, computedOpacity)
- : shadowColor;
+ const shadowRgba = shadowColor.startsWith("#") ? parseShadowColor(shadowColor, computedOpacity) : shadowColor;
const hasShadow = t > 0.01;
const maskStyle = GetMediaMaskStyles(imageMaskConfig, {
@@ -481,7 +542,32 @@ export function DoubleIPhone3DViewer(props: Props) {
deviceHeight: PHONE_H,
});
- const outlineFilter = getOutlineFilter(isSelected, isHovered);
+ const hitsModel = (clientX: number, clientY: number): boolean => {
+ const canvas = canvasElRef.current;
+ const cam = cameraRef.current;
+ const model = rootRef.current;
+ if (!canvas || !cam || !model) return false;
+
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return false;
+
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycasterRef.current.setFromCamera(new THREE.Vector2(x, y), cam);
+ return raycasterRef.current.intersectObject(model, true).length > 0;
+ };
+
+ const handleCanvasMount = (canvas: HTMLCanvasElement) => {
+ canvasElRef.current = canvas;
+ props.onMount?.(canvas);
+ };
+
+ useEffect(() => {
+ const onWinPointerUp = () => setGrabbing(false);
+ window.addEventListener("pointerup", onWinPointerUp);
+ return () => window.removeEventListener("pointerup", onWinPointerUp);
+ }, []);
return (
<>
@@ -519,17 +605,47 @@ export function DoubleIPhone3DViewer(props: Props) {
inset: "-400px",
zIndex: 2,
overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: outlineFilter,
+ cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
transition: "filter 0.15s ease",
pointerEvents: "auto",
...maskStyle,
}}
- onPointerDown={() => setGrabbing(true)}
+ onPointerDownCapture={(e) => {
+ const hit = hitsModel(e.clientX, e.clientY);
+ if (!hit) {
+ onSelectChange?.(false);
+ e.stopPropagation();
+ return;
+ }
+ onSelectChange?.(true);
+ setGrabbing(true);
+ }}
+ onPointerMove={(e) => {
+ if (!grabbing) {
+ const isCurrentlyHovering = hitsModel(e.clientX, e.clientY);
+ if (isCurrentlyHovering !== modelHovered) {
+ setModelHovered(isCurrentlyHovering);
+ onHoverChange?.(isCurrentlyHovering);
+ }
+ }
+ }}
onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
+ onPointerLeave={() => {
+ setGrabbing(false);
+ if (modelHovered) {
+ setModelHovered(false);
+ onHoverChange?.(false);
+ }
+ }}
>
- <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
+ <CanvasWithLoader
+ {...props}
+ isSelected={isSelected}
+ isHovered={modelHovered}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ onMount={handleCanvasMount}
+ />
</div>
</div>
</div>
diff --git a/app/components/ui/editor/mockups-3d/IPadMini63DViewer.tsx b/app/components/ui/editor/mockups-3d/IPadMini63DViewer.tsx
index 0b76499..fe8a34f 100644
--- a/app/components/ui/editor/mockups-3d/IPadMini63DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/IPadMini63DViewer.tsx
@@ -1,20 +1,25 @@
"use client";
+
import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { PerspectiveCamera, Environment, OrbitControls, ContactShadows, useGLTF } from "@react-three/drei";
import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } from "react";
import * as THREE from "three";
-import {
- createCoverScreenCanvas,
- applyCropToImage,
- type ImageMaskConfigLike,
- parseShadowColor,
- applyTextureCover,
- getOutlineFilter,
+import {
+ createCoverScreenCanvas,
+ applyCropToImage,
+ type ImageMaskConfigLike,
+ parseShadowColor,
+ applyTextureCover
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+
export interface IPadMini63DApi {
renderAt: (width: number, height: number) => void;
restorePreview: () => void;
@@ -41,6 +46,8 @@ interface Props {
environment?: EnvironmentPreset;
isSelected?: boolean;
isHovered?: boolean;
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
const DEG = Math.PI / 180;
@@ -48,7 +55,6 @@ const PLACEHOLDER_IPAD_URL = "/images/mockups-3d/placeholder-phone.avif";
const MODEL_URL = "/models/ipad_mini_6_2021.glb";
const DRACO_URL = "/draco/";
const DEFAULT_CAMERA_POS: [number, number, number] = [0, 0, 1.5];
-
const TARGET_W = 1040;
const TARGET_H = 1500;
@@ -74,23 +80,28 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 1.0,
environment = "studio",
+ isSelected = false,
+ isHovered = false,
}: Props & {
rootRef: React.MutableRefObject<THREE.Group | null>;
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
const gltf = useGLTF(MODEL_URL, DRACO_URL);
-
+
const orbitRef = useRef<OrbitControlsType | null>(null);
const screenMatRef = useRef<THREE.MeshPhysicalMaterial | null>(null);
const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
const modelContainerRef = useRef<THREE.Group>(null!);
-
const lastLoadedUrlRef = useRef<string | null>(null);
const lastLoadedCropKeyRef = useRef<string | null>(null);
const onApiRef = useRef(onApi);
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
+ const isUserInteractingRef = useRef(false);
+
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -114,9 +125,11 @@ function ModelScene({
const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+
gl.render(scene, cam);
},
restorePreview: () => {
@@ -128,6 +141,11 @@ function ModelScene({
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+
invalidate();
},
hasBuiltInShadow: true,
@@ -180,7 +198,6 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = targetImgUrl;
lastLoadedCropKeyRef.current = cropKey;
invalidate();
@@ -192,7 +209,7 @@ function ModelScene({
invalidate();
};
img.src = targetImgUrl;
- }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
+ }, [imageUrl, cropArea, gl, videoElement, invalidate]);
const applyVideoTextureIfReady = useCallback(() => {
const mat = screenMatRef.current;
@@ -220,13 +237,10 @@ function ModelScene({
}
return;
}
-
const tex = new THREE.VideoTexture(videoElement);
-
tex.flipY = false;
tex.center.set(0.5, 0.5);
tex.rotation = Math.PI;
-
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
@@ -255,7 +269,6 @@ function ModelScene({
videoTextureRef.current.dispose();
}
videoTextureRef.current = tex;
-
applyVideoTextureIfReady();
return () => {
@@ -276,29 +289,19 @@ function ModelScene({
applyTexture();
}, [applyTexture]);
- // Lógica de centrado automático, escalado y corrección de rotación
useEffect(() => {
let isMounted = true;
const group = gltf.scene.clone(true);
-
const camZ = 1.5;
const box = new THREE.Box3().setFromObject(group);
const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
-
+ const sizeVec = box.getSize(new THREE.Vector3());
const halfH = camZ * Math.tan((40 / 2) * DEG);
- const sf = (halfH * 2 * 0.70) / size.y;
+ const sf = (halfH * 2 * 0.70) / sizeVec.y;
- // SOLUCIÓN: Creamos un wrapper para centrar y rotar 180 grados sin perder el eje
const wrapper = new THREE.Group();
-
- // 1. Centramos el grupo original restando su propio centro
group.position.copy(center).negate();
-
- // 2. Lo añadimos al wrapper
wrapper.add(group);
-
- // 3. Escalamos y giramos 180 grados (Math.PI) en el eje Y para que no salga de espaldas
wrapper.scale.setScalar(sf);
wrapper.rotation.y = Math.PI;
@@ -313,12 +316,10 @@ function ModelScene({
depthWrite: true,
});
screenMatRef.current = basicMat;
-
applyVideoTextureIfReady();
group.traverse((child) => {
if (child instanceof THREE.Mesh) {
- // SOLUCIÓN: Búsqueda flexible. GLB suele transformar "iPad Mini_Screen_0" en "iPad_Mini_Screen_0"
if (child.name.includes("Screen")) {
child.material = basicMat;
}
@@ -328,7 +329,6 @@ function ModelScene({
const container = modelContainerRef.current;
if (container) {
container.clear();
- // Añadimos el wrapper (que contiene el modelo centrado y rotado) en lugar del grupo directo
container.add(wrapper);
}
@@ -351,7 +351,10 @@ function ModelScene({
}, [gltf.scene, applyVideoTextureIfReady, onLoaded, invalidate]);
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+
useEffect(() => {
+ if (isUserInteractingRef.current) return;
+
if (
prevRotationRef.current?.x === initialRotationX &&
prevRotationRef.current?.y === initialRotationY
@@ -359,6 +362,7 @@ function ModelScene({
return;
}
const id = setTimeout(() => {
+ if (isUserInteractingRef.current) return;
const orbit = orbitRef.current;
if (!orbit) return;
const radius = 1.5;
@@ -377,7 +381,63 @@ function ModelScene({
rootRef.current.rotation.z = initialRotationZ * DEG;
invalidate();
}
- }, [initialRotationZ, invalidate]);
+ }, [initialRotationZ, rootRef, invalidate]);
+
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+
+ outlinePass.edgeStrength = 6;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 3;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera, size.width, size.height, invalidate]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+
+ invalidate();
+ }, [isSelected, isHovered, invalidate, rootRef]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
const shadowT = Math.max(0, Math.min(1, shadowIntensity));
const showContactShadow = shadowT > 0.01;
@@ -395,7 +455,11 @@ function ModelScene({
dampingFactor={0.08}
autoRotate={autoRotate}
autoRotateSpeed={rotationSpeed}
+ onStart={() => {
+ isUserInteractingRef.current = true;
+ }}
onEnd={() => {
+ isUserInteractingRef.current = false;
const orbit = orbitRef.current;
if (!orbit || !onRotationChange) return;
const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
@@ -404,12 +468,10 @@ function ModelScene({
}}
/>
<Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
-
<ambientLight intensity={0.3} />
<directionalLight position={[3, 6, 5]} intensity={0.6} />
<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
<directionalLight position={[0, -5, 5]} intensity={0.35} />
-
{showContactShadow && (
<ContactShadows
position={[0, -0.65, 0]}
@@ -421,7 +483,6 @@ function ModelScene({
resolution={512}
/>
)}
-
<group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
<group ref={modelContainerRef} />
</group>
@@ -441,7 +502,7 @@ function CanvasWithLoader(
return (
<>
<Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
+ style={{ width: "100%", height: "100%", overflow: "visible", pointerEvents: "auto" }}
gl={{
antialias: true,
alpha: true,
@@ -464,7 +525,6 @@ function CanvasWithLoader(
<ModelScene {...props} onLoaded={handleLoaded} />
</Suspense>
</Canvas>
-
{!loaded && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }}>
<div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
@@ -475,11 +535,22 @@ function CanvasWithLoader(
}
export function IPadMini63DViewer(props: Props) {
- const { shadowIntensity = 0, shadowColor = "#000000", imageMaskConfig = null, isSelected = false,
- isHovered = false } = props;
+ const {
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ imageMaskConfig = null,
+ isSelected = false,
+ onHoverChange,
+ onSelectChange
+ } = props;
+
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const canvasElRef = useRef<HTMLCanvasElement | null>(null);
+ const raycasterRef = useRef(new THREE.Raycaster());
+
const [grabbing, setGrabbing] = useState(false);
+ const [modelHovered, setModelHovered] = useState(false);
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
@@ -497,7 +568,32 @@ export function IPadMini63DViewer(props: Props) {
deviceHeight: VIEWER_H,
});
- const outlineFilter = getOutlineFilter(isSelected, isHovered);
+ const hitsModel = (clientX: number, clientY: number): boolean => {
+ const canvas = canvasElRef.current;
+ const cam = cameraRef.current;
+ const model = rootRef.current;
+ if (!canvas || !cam || !model) return false;
+
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return false;
+
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycasterRef.current.setFromCamera(new THREE.Vector2(x, y), cam);
+ return raycasterRef.current.intersectObject(model, true).length > 0;
+ };
+
+ const handleCanvasMount = (canvas: HTMLCanvasElement) => {
+ canvasElRef.current = canvas;
+ props.onMount?.(canvas);
+ };
+
+ useEffect(() => {
+ const onWinPointerUp = () => setGrabbing(false);
+ window.addEventListener("pointerup", onWinPointerUp);
+ return () => window.removeEventListener("pointerup", onWinPointerUp);
+ }, []);
return (
<>
@@ -535,17 +631,47 @@ export function IPadMini63DViewer(props: Props) {
inset: "-300px",
zIndex: 2,
overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: outlineFilter,
+ cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
transition: "filter 0.15s ease",
- pointerEvents: "auto",
- ...maskStyle
+ pointerEvents: "none",
+ ...maskStyle,
+ }}
+ onPointerDownCapture={(e) => {
+ const hit = hitsModel(e.clientX, e.clientY);
+ if (!hit) {
+ onSelectChange?.(false);
+ e.stopPropagation();
+ return;
+ }
+ onSelectChange?.(true);
+ setGrabbing(true);
+ }}
+ onPointerMove={(e) => {
+ if (!grabbing) {
+ const isCurrentlyHovering = hitsModel(e.clientX, e.clientY);
+ if (isCurrentlyHovering !== modelHovered) {
+ setModelHovered(isCurrentlyHovering);
+ onHoverChange?.(isCurrentlyHovering);
+ }
+ }
}}
- onPointerDown={() => setGrabbing(true)}
onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
+ onPointerLeave={() => {
+ setGrabbing(false);
+ if (modelHovered) {
+ setModelHovered(false);
+ onHoverChange?.(false);
+ }
+ }}
>
- <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
+ <CanvasWithLoader
+ {...props}
+ isSelected={isSelected}
+ isHovered={modelHovered}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ onMount={handleCanvasMount}
+ />
</div>
</div>
</div>
diff --git a/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx b/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
index a7c27f9..bbb5174 100644
--- a/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/IPhone13ProMax3DViewer.tsx
@@ -4,11 +4,14 @@ import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { PerspectiveCamera, useGLTF, Environment, OrbitControls } from "@react-three/drei";
import { useEffect, useRef, useState, Suspense, useLayoutEffect, useMemo } from "react";
import * as THREE from "three";
-import { createCoverScreenCanvas, applyCropToImage, type ImageMaskConfigLike, applyTextureCover, getOutlineFilter } from "@/lib/phone3d.utils";
+import { createCoverScreenCanvas, applyCropToImage, type ImageMaskConfigLike, applyTextureCover } from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
-
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
export interface IPhone13ProMax3DApi {
renderAt: (width: number, height: number) => void;
restorePreview: () => void;
@@ -37,8 +40,8 @@ interface Props {
environment?: EnvironmentPreset;
isSelected?: boolean;
isHovered?: boolean;
- onHoverChange?: (isHovered: boolean) => void; // Callback para notificar hover real
- onSelectChange?: (isSelected: boolean) => void; // 🔥 NUEVO: Callback para controlar selección exacta
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
const TEX_W = 1284 * 2;
@@ -124,6 +127,8 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 2.0,
environment = "sunset",
+ isSelected = false,
+ isHovered = false,
}: {
imageUrl: string | null;
imageMaskConfig: ImageMaskConfigLike | null;
@@ -144,8 +149,11 @@ function ModelScene({
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
+ isSelected?: boolean;
+ isHovered?: boolean;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
+
const gltf = useGLTF("/models/apple_iphone_13_pro_max.glb", DRACO_URL) as unknown as {
nodes: GLTFNodes;
materials: GLTFMaterials;
@@ -158,7 +166,8 @@ function ModelScene({
const wallpaperMatRef = useRef<THREE.MeshStandardMaterial | null>(null);
const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
const onApiRef = useRef(onApi);
-
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -196,6 +205,10 @@ function ModelScene({
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+ invalidate();
},
getVisualSize: () => {
const canvas = gl.domElement;
@@ -481,23 +494,61 @@ function ModelScene({
texture.needsUpdate = true;
return texture;
}, []);
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+ outlinePass.edgeStrength = 6;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 1.5;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+ invalidate();
+ }, [isSelected, isHovered, invalidate]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
return (
<>
- <PerspectiveCamera
- ref={cameraRef}
- makeDefault
- fov={40}
- near={0.01}
- far={100}
- position={DEFAULT_CAMERA_POS}
- zoom={zoom}
- />
- <Environment
- files={HDRI_FILES[environment as EnvironmentPreset]}
- environmentIntensity={glow}
- background={false}
- />
+ <PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={DEFAULT_CAMERA_POS} zoom={zoom} />
+ <Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
<OrbitControls
ref={orbitRef}
enableZoom={false}
@@ -520,19 +571,9 @@ function ModelScene({
<directionalLight position={[0, -5, 5]} intensity={0.35} />
{showContactShadow && (
- <mesh
- position={[-0.0, -0.203, -0.156]}
- rotation={[-Math.PI / 2, 0, 0.1]}
- scale={[0.55, 0.55, 1.5]}
- >
+ <mesh position={[-0.0, -0.203, -0.156]} rotation={[-Math.PI / 2, 0, 0.1]} scale={[0.55, 0.55, 1.5]}>
<planeGeometry args={[1, 1]} />
- <meshBasicMaterial
- color={shadowColor}
- transparent
- opacity={shadowT * 0.7}
- alphaMap={customShadowTexture}
- depthWrite={false}
- />
+ <meshBasicMaterial color={shadowColor} transparent opacity={shadowT * 0.7} alphaMap={customShadowTexture} depthWrite={false} />
</mesh>
)}
@@ -601,6 +642,8 @@ function CanvasWithLoader({
rotationSpeed,
glow,
environment,
+ isSelected,
+ isHovered,
}: {
imageUrl: string | null;
imageMaskConfig: ImageMaskConfigLike | null;
@@ -621,6 +664,8 @@ function CanvasWithLoader({
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
+ isSelected?: boolean;
+ isHovered?: boolean;
}) {
const [loaded, setLoaded] = useState(false);
return (
@@ -667,6 +712,8 @@ function CanvasWithLoader({
rotationSpeed={rotationSpeed}
glow={glow}
environment={environment}
+ isSelected={isSelected}
+ isHovered={isHovered}
/>
</Suspense>
</Canvas>
@@ -703,7 +750,7 @@ export function IPhone13ProMax3DViewer({
isSelected = false,
isHovered = false,
onHoverChange,
- onSelectChange, // 🔥 Recibimos el callback para controlar la selección exacta
+ onSelectChange,
}: Props) {
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
@@ -723,9 +770,6 @@ export function IPhone13ProMax3DViewer({
deviceHeight: 1000,
});
- // 🔥 CAMBIO: El filtro de Outline ahora depende únicamente de "modelHovered" y no de "isHovered"
- const outlineFilter = getOutlineFilter(isSelected, modelHovered);
-
const hitsModel = (clientX: number, clientY: number): boolean => {
const canvas = canvasElRef.current;
const cam = cameraRef.current;
@@ -770,23 +814,21 @@ export function IPhone13ProMax3DViewer({
zIndex: 2,
overflow: "visible",
cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
- filter: outlineFilter,
+ filter: "none",
transition: "filter 0.15s ease",
pointerEvents: "none",
...maskStyle,
}}
onPointerDownCapture={(e) => {
const hit = hitsModel(e.clientX, e.clientY);
-
+
if (!hit) {
- // 🔥 Hizo click fuera del modelo (en el contenedor invisible)
- onSelectChange?.(false); // Le dice al padre que deseleccione
- e.stopPropagation(); // Evita que la cámara gire y frena que se vuelva a seleccionar
+ onSelectChange?.(false);
+ e.stopPropagation();
return;
}
-
- // 🔥 Hizo click directamente en el modelo
- onSelectChange?.(true); // Le dice al padre que seleccione el modelo
+
+ onSelectChange?.(true);
setGrabbing(true);
}}
onPointerMove={(e) => {
@@ -827,6 +869,8 @@ export function IPhone13ProMax3DViewer({
rotationSpeed={rotationSpeed}
glow={glow}
environment={environment}
+ isSelected={isSelected}
+ isHovered={modelHovered}
/>
</div>
</div>
diff --git a/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx b/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx
index 31d777d..774b2aa 100644
--- a/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/IPhone17ProMax3DViewer.tsx
@@ -4,11 +4,22 @@ import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { PerspectiveCamera, useGLTF, Environment, OrbitControls, ContactShadows } from "@react-three/drei";
import { useEffect, useRef, useState, Suspense, useLayoutEffect, useMemo, useCallback } from "react";
import * as THREE from "three";
-import { createCoverScreenCanvas, applyCropToImage, parseShadowColor, type ImageMaskConfigLike, applyTextureCover, getOutlineFilter } from "@/lib/phone3d.utils";
+import {
+ createCoverScreenCanvas,
+ applyCropToImage,
+ parseShadowColor,
+ type ImageMaskConfigLike,
+ applyTextureCover
+} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+
export interface IPhone17ProMax3DApi {
renderAt: (width: number, height: number) => void;
restorePreview: () => void;
@@ -36,6 +47,8 @@ interface Props {
environment?: EnvironmentPreset;
isSelected?: boolean;
isHovered?: boolean;
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
const TEX_W = 1284 * 2;
@@ -66,6 +79,8 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 1.0,
environment = "studio",
+ isSelected = false,
+ isHovered = false,
}: {
imageUrl: string | null;
imageMaskConfig: ImageMaskConfigLike | null;
@@ -86,8 +101,10 @@ function ModelScene({
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
+ isSelected?: boolean;
+ isHovered?: boolean;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
const gltf = useGLTF("/models/iphone-17-pro-max.glb", DRACO_URL);
const clonedScene = useMemo(() => gltf.scene.clone(true), [gltf.scene]);
@@ -98,8 +115,11 @@ function ModelScene({
const lastLoadedCropKeyRef = useRef<string | null>(null);
const wallpaperMatRef = useRef<THREE.MeshPhysicalMaterial | null>(null);
const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
-
const onApiRef = useRef(onApi);
+
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
+
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -136,6 +156,7 @@ function ModelScene({
useEffect(() => {
const capturedOnApi = onApiRef.current;
const RENDER_PIXEL_RATIO = 2;
+
const api: IPhone17ProMax3DApi = {
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
@@ -146,9 +167,11 @@ function ModelScene({
const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
+
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+
gl.render(scene, cam);
},
restorePreview: () => {
@@ -160,6 +183,11 @@ function ModelScene({
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+
invalidate();
},
hasBuiltInShadow: true,
@@ -180,7 +208,6 @@ function ModelScene({
}
return;
}
-
const tex = new THREE.VideoTexture(videoElement);
tex.flipY = false;
tex.colorSpace = THREE.SRGBColorSpace;
@@ -215,19 +242,15 @@ function ModelScene({
const applyVideoTex = () => {
const mat = wallpaperMatRef.current;
if (!mat) return;
-
if (mat.map && mat.map !== tex) {
mat.map.dispose();
}
-
mat.map = tex;
mat.color.set(0xffffff);
mat.needsUpdate = true;
if (mat.map) mat.map.needsUpdate = true;
-
invalidate();
};
-
applyVideoTex();
return () => {
@@ -242,7 +265,6 @@ function ModelScene({
useEffect(() => {
const mat = wallpaperMatRef.current;
if (!mat) return;
-
if (videoElement) return;
const maskKey = imageMaskConfig ? JSON.stringify(imageMaskConfig) : null;
@@ -261,9 +283,7 @@ function ModelScene({
mat.map = null;
}
const tex = new THREE.CanvasTexture(cover);
-
tex.flipY = false;
-
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
@@ -304,14 +324,13 @@ function ModelScene({
img.onload = () => {
const sourceImage = cropArea ? applyCropToImage(img, cropArea) : img;
const cover = createCoverScreenCanvas(sourceImage, TEX_W, TEX_H, 0, imageMaskConfig);
+
if (mat.map) {
mat.map.dispose();
mat.map = null;
}
const tex = new THREE.CanvasTexture(cover);
-
tex.flipY = false;
-
tex.colorSpace = THREE.SRGBColorSpace;
tex.generateMipmaps = true;
tex.minFilter = THREE.LinearMipmapLinearFilter;
@@ -321,7 +340,6 @@ function ModelScene({
mat.map = tex;
mat.color.set(0xffffff);
mat.needsUpdate = true;
-
invalidate();
lastLoadedImageUrlRef.current = imageUrl;
@@ -340,8 +358,10 @@ function ModelScene({
}, []);
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+
useEffect(() => {
if (prevRotationRef.current?.x === initialRotationX && prevRotationRef.current?.y === initialRotationY) return;
+
const id = setTimeout(() => {
const orbit = orbitRef.current;
if (!orbit) return;
@@ -365,6 +385,62 @@ function ModelScene({
}
}, [initialRotationZ, invalidate]);
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+
+ outlinePass.edgeStrength = 8;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 3;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+
+ invalidate();
+ }, [isSelected, isHovered, invalidate]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
+
const shadowT = Math.max(0, Math.min(1, shadowIntensity));
const showContactShadow = shadowT > 0.01;
const contactOpacity = shadowT * 0.65;
@@ -374,19 +450,37 @@ function ModelScene({
<>
<PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={DEFAULT_CAMERA_POS} zoom={zoom} />
<Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
- <OrbitControls ref={orbitRef} enableZoom={false} enablePan={false} enableDamping dampingFactor={0.08} autoRotate={autoRotate} autoRotateSpeed={rotationSpeed} onEnd={() => {
- const orbit = orbitRef.current;
- if (!orbit || !onRotationChange) return;
- const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
- const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
- onRotationChange(rx, ry);
- }} />
+ <OrbitControls
+ ref={orbitRef}
+ enableZoom={false}
+ enablePan={false}
+ enableDamping
+ dampingFactor={0.08}
+ autoRotate={autoRotate}
+ autoRotateSpeed={rotationSpeed}
+ onEnd={() => {
+ const orbit = orbitRef.current;
+ if (!orbit || !onRotationChange) return;
+ const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
+ const rx = (Math.PI / 2 - orbit.getPolarAngle()) * (180 / Math.PI);
+ onRotationChange(rx, ry);
+ }}
+ />
<ambientLight intensity={0.3} />
<directionalLight position={[3, 6, 5]} intensity={0.6} />
<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
<directionalLight position={[0, -5, 5]} intensity={0.35} />
+
{showContactShadow && (
- <ContactShadows position={[0, -0.55, 0]} opacity={contactOpacity} scale={3} blur={contactBlur} far={4} color={shadowColor} resolution={512} />
+ <ContactShadows
+ position={[0, -0.55, 0]}
+ opacity={contactOpacity}
+ scale={3}
+ blur={contactBlur}
+ far={4}
+ color={shadowColor}
+ resolution={512}
+ />
)}
<group ref={rootRef} rotation={[0, 0, 0]} scale={1} dispose={null}>
@@ -416,6 +510,8 @@ function CanvasWithLoader({
rotationSpeed,
glow,
environment,
+ isSelected,
+ isHovered,
}: {
imageUrl: string | null;
imageMaskConfig: ImageMaskConfigLike | null;
@@ -436,19 +532,33 @@ function CanvasWithLoader({
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
+ isSelected?: boolean;
+ isHovered?: boolean;
}) {
const [loaded, setLoaded] = useState(false);
const handleLoaded = useCallback(() => setLoaded(true), []);
return (
<>
- <Canvas style={{ width: "100%", height: "100%", overflow: "visible" }} gl={{ antialias: true, alpha: true, preserveDrawingBuffer: true, powerPreference: "high-performance" }} dpr={3} frameloop={videoElement ? "always" : "demand"} resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }} onCreated={({ gl, scene }) => {
- gl.outputColorSpace = THREE.SRGBColorSpace;
- gl.toneMapping = THREE.NeutralToneMapping;
- gl.toneMappingExposure = 1.0;
- scene.environmentIntensity = 1.6;
- onMount?.(gl.domElement);
- }} >
+ <Canvas
+ style={{ width: "100%", height: "100%", overflow: "visible" }}
+ gl={{
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance"
+ }}
+ dpr={3}
+ frameloop={videoElement ? "always" : "demand"}
+ resize={{ scroll: false, debounce: { scroll: 0, resize: 0 } }}
+ onCreated={({ gl, scene }) => {
+ gl.outputColorSpace = THREE.SRGBColorSpace;
+ gl.toneMapping = THREE.NeutralToneMapping;
+ gl.toneMappingExposure = 1.0;
+ scene.environmentIntensity = 1.6;
+ onMount?.(gl.domElement);
+ }}
+ >
<Suspense fallback={null}>
<ModelScene
imageUrl={imageUrl}
@@ -470,6 +580,8 @@ function CanvasWithLoader({
rotationSpeed={rotationSpeed}
glow={glow}
environment={environment}
+ isSelected={isSelected}
+ isHovered={isHovered}
/>
</Suspense>
</Canvas>
@@ -502,10 +614,16 @@ export function IPhone17ProMax3DViewer({
environment,
isSelected = false,
isHovered = false,
+ onHoverChange,
+ onSelectChange,
}: Props) {
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const canvasElRef = useRef<HTMLCanvasElement | null>(null);
+ const raycasterRef = useRef(new THREE.Raycaster());
+
const [grabbing, setGrabbing] = useState(false);
+ const [modelHovered, setModelHovered] = useState(false);
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
@@ -520,30 +638,102 @@ export function IPhone17ProMax3DViewer({
deviceHeight: 1000,
});
- const outlineFilter = getOutlineFilter(isSelected, isHovered);
+ const hitsModel = (clientX: number, clientY: number): boolean => {
+ const canvas = canvasElRef.current;
+ const cam = cameraRef.current;
+ const model = rootRef.current;
+ if (!canvas || !cam || !model) return false;
+
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return false;
+
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycasterRef.current.setFromCamera(new THREE.Vector2(x, y), cam);
+ return raycasterRef.current.intersectObject(model, true).length > 0;
+ };
+
+ const handleCanvasMount = (canvas: HTMLCanvasElement) => {
+ canvasElRef.current = canvas;
+ onMount?.(canvas);
+ };
+
+ useEffect(() => {
+ const onWinPointerUp = () => setGrabbing(false);
+ window.addEventListener("pointerup", onWinPointerUp);
+ return () => window.removeEventListener("pointerup", onWinPointerUp);
+ }, []);
return (
<>
- <div style={{ display: "inline-block", transformOrigin: "top center", width: 480, height: 1000 + (hasShadow ? computedBlur * 0.8 : 0), marginTop: "100px", marginLeft: "170px" }}>
+ <div
+ style={{
+ display: "inline-block",
+ transformOrigin: "top center",
+ width: 480,
+ height: 1000 + (hasShadow ? computedBlur * 0.8 : 0),
+ marginTop: "100px",
+ marginLeft: "170px"
+ }}
+ >
<div style={{ position: "relative", width: 480, height: 1000 }}>
{hasShadow && (
- <div aria-hidden style={{ position: "absolute", bottom: -(computedBlur * 0.5), left: `${20 + tEased * 5}%`, width: `${60 - tEased * 10}%`, height: Math.max(4, computedBlur * 0.55), borderRadius: "50%", background: shadowRgba, filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`, zIndex: 0, pointerEvents: "none" }} />
+ <div
+ aria-hidden
+ style={{
+ position: "absolute",
+ bottom: -(computedBlur * 0.5),
+ left: `${20 + tEased * 5}%`,
+ width: `${60 - tEased * 10}%`,
+ height: Math.max(4, computedBlur * 0.55),
+ borderRadius: "50%",
+ background: shadowRgba,
+ filter: `blur(${Math.max(2, computedBlur * 0.6)}px)`,
+ zIndex: 0,
+ pointerEvents: "none"
+ }}
+ />
)}
+
<div
style={{
position: "absolute",
inset: "-400px",
zIndex: 2,
overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: outlineFilter,
+ cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
transition: "filter 0.15s ease",
- pointerEvents: "auto",
+ pointerEvents: "none",
...maskStyle,
}}
- onPointerDown={() => setGrabbing(true)}
+ onPointerDownCapture={(e) => {
+ const hit = hitsModel(e.clientX, e.clientY);
+ if (!hit) {
+ onSelectChange?.(false);
+ e.stopPropagation();
+ return;
+ }
+ onSelectChange?.(true);
+ setGrabbing(true);
+ }}
+ onPointerMove={(e) => {
+ if (!grabbing) {
+ const isCurrentlyHovering = hitsModel(e.clientX, e.clientY);
+ if (isCurrentlyHovering !== modelHovered) {
+ setModelHovered(isCurrentlyHovering);
+ onHoverChange?.(isCurrentlyHovering);
+ }
+ }
+ }}
onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
+ onPointerLeave={() => {
+ setGrabbing(false);
+ if (modelHovered) {
+ setModelHovered(false);
+ onHoverChange?.(false);
+ }
+ }}
>
<CanvasWithLoader
imageUrl={imageUrl}
@@ -557,7 +747,7 @@ export function IPhone17ProMax3DViewer({
cameraRef={cameraRef}
zoom={zoom}
onApi={onApi}
- onMount={onMount}
+ onMount={handleCanvasMount}
videoElement={videoElement}
shadowIntensity={shadowIntensity}
shadowColor={shadowColor}
@@ -565,6 +755,8 @@ export function IPhone17ProMax3DViewer({
rotationSpeed={rotationSpeed}
glow={glow}
environment={environment}
+ isSelected={isSelected}
+ isHovered={modelHovered}
/>
</div>
</div>
diff --git a/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx b/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
index 7d02bc4..a157529 100644
--- a/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/Laptop3DViewer.tsx
@@ -5,18 +5,22 @@ import { PerspectiveCamera, Environment, OrbitControls } from "@react-three/drei
import { useEffect, useRef, useState, Suspense, useCallback, useLayoutEffect } from "react";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
-import {
- createCoverScreenCanvas,
- applyCropToImage,
- parseShadowColor,
- type ImageMaskConfigLike,
- applyTextureCover,
- getOutlineFilter,
+import {
+ createCoverScreenCanvas,
+ applyCropToImage,
+ parseShadowColor,
+ type ImageMaskConfigLike,
+ applyTextureCover
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+
THREE.Cache.enabled = true;
const LAPTOP_W = 1500;
@@ -31,7 +35,6 @@ const LID_CLOSED_X = Math.PI * 0.5;
const LID_OPEN_X = -0.2 * Math.PI;
const DEG = Math.PI / 180;
const PLACEHOLDER_LAPTOP_URL = "/images/mockups-3d/placeholder-laptop.avif";
-
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export interface Laptop3DApi {
@@ -60,12 +63,13 @@ interface Props {
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
- isHovered: boolean;
- isSelected: boolean;
+ isHovered?: boolean;
+ isSelected?: boolean;
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
let gltfCachePromise: Promise<THREE.Group> | null = null;
-
function loadLaptopGltf(): Promise<THREE.Group> {
if (!gltfCachePromise) {
gltfCachePromise = new Promise<THREE.Group>((resolve, reject) =>
@@ -99,13 +103,16 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 1.0,
environment = "forest",
+ isSelected = false,
+ isHovered = false,
}: Props & {
rootRef: React.MutableRefObject<THREE.Group | null>;
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
const orbitRef = useRef<OrbitControlsType | null>(null);
+
const [modelGroup, setModelGroup] = useState<THREE.Group | null>(null);
const lidGroupRef = useRef<THREE.Group | null>(null);
const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
@@ -114,6 +121,10 @@ function ModelScene({
const lastLoadedCropKeyRef = useRef<string | null>(null);
const onApiRef = useRef(onApi);
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
+ const isUserInteractingRef = useRef(false);
+
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -130,46 +141,44 @@ function ModelScene({
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
-
const RENDER_PIXEL_RATIO = 2;
const maxTexSize = gl.capabilities.maxTextureSize || 4096;
const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
-
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
-
+
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
-
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+
gl.render(scene, cam);
},
restorePreview: () => {
const cam = cameraRef.current ?? camera;
if (!cam) return;
-
const freshW = gl.domElement.clientWidth;
const freshH = gl.domElement.clientHeight;
-
(cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
-
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+
invalidate();
},
hasBuiltInShadow: true,
};
-
capturedOnApi?.(api);
return () => capturedOnApi?.(null);
}, [gl, scene, camera, cameraRef, invalidate]);
const applyTexture = useCallback(() => {
if (videoElement) return;
-
const mat = screenMatRef.current;
if (!mat) return;
@@ -184,7 +193,6 @@ function ModelScene({
img.onload = () => {
const currentMat = screenMatRef.current;
if (!currentMat) return;
-
const TEX_W = RENDER_W;
const TEX_H = RENDER_H;
const cover = createCoverScreenCanvas(img, TEX_W, TEX_H, 0, null);
@@ -192,7 +200,6 @@ function ModelScene({
if (currentMat.map) {
currentMat.map.dispose();
}
-
const tex = new THREE.CanvasTexture(cover);
tex.flipY = false;
tex.wrapS = THREE.RepeatWrapping;
@@ -210,7 +217,6 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = placeholderKey;
lastLoadedCropKeyRef.current = null;
invalidate();
@@ -235,7 +241,6 @@ function ModelScene({
img.onload = () => {
const currentMat = screenMatRef.current;
if (!currentMat) return;
-
const TEX_W = RENDER_W;
const TEX_H = RENDER_H;
const cropped = applyCropToImage(img, cropArea);
@@ -244,7 +249,6 @@ function ModelScene({
if (currentMat.map) {
currentMat.map.dispose();
}
-
const tex = new THREE.CanvasTexture(cover);
tex.flipY = false;
tex.wrapS = THREE.RepeatWrapping;
@@ -262,7 +266,6 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = imageUrl;
lastLoadedCropKeyRef.current = cropKey;
invalidate();
@@ -272,7 +275,7 @@ function ModelScene({
lastLoadedCropKeyRef.current = cropKey;
};
img.src = imageUrl;
- }, [imageUrl, imageMaskConfig, cropArea, gl, videoElement, invalidate]);
+ }, [imageUrl, cropArea, gl, videoElement, invalidate]);
const applyVideoTextureIfReady = useCallback(() => {
const mat = screenMatRef.current;
@@ -296,7 +299,6 @@ function ModelScene({
}
return;
}
-
const tex = new THREE.VideoTexture(videoElement);
tex.flipY = false;
tex.colorSpace = THREE.SRGBColorSpace;
@@ -327,7 +329,6 @@ function ModelScene({
videoTextureRef.current.dispose();
}
videoTextureRef.current = tex;
-
applyVideoTextureIfReady();
return () => {
@@ -350,11 +351,18 @@ function ModelScene({
useEffect(() => {
let isMounted = true;
-
- const darkPlasticMaterial = new THREE.MeshStandardMaterial({ color: 0x000000, roughness: 0.9, metalness: 0.9 });
+ const darkPlasticMaterial = new THREE.MeshStandardMaterial({
+ color: 0x000000,
+ roughness: 0.9,
+ metalness: 0.9
+ });
const cameraMaterial = new THREE.MeshBasicMaterial({ color: 0x333333 });
const logoMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
- const baseMetalMaterial = new THREE.MeshStandardMaterial({ color: 0xcecfd3, roughness: 0.25, metalness: 0.85 });
+ const baseMetalMaterial = new THREE.MeshStandardMaterial({
+ color: 0xcecfd3,
+ roughness: 0.25,
+ metalness: 0.85
+ });
const tStart = Math.max(0, Math.min(1, openingProgress));
const screenMaterial = new THREE.MeshBasicMaterial({
@@ -369,8 +377,11 @@ function ModelScene({
applyVideoTextureIfReady();
const textLoader = new THREE.TextureLoader();
- const keyboardMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, toneMapped: false });
-
+ const keyboardMaterial = new THREE.MeshBasicMaterial({
+ color: 0xffffff,
+ transparent: true,
+ toneMapped: false
+ });
textLoader.load("/images/pages/keyboard-overlay.png", (tex) => {
tex.anisotropy = gl.capabilities.getMaxAnisotropy();
keyboardMaterial.alphaMap = tex;
@@ -414,7 +425,8 @@ function ModelScene({
if (!(obj instanceof THREE.Mesh)) return;
const m = obj as THREE.Mesh;
if (m.name === "base") m.material = baseMetalMaterial;
- else if (["legs", "keyboard", "inner"].includes(m.name)) m.material = darkPlasticMaterial;
+ else if (["legs", "keyboard", "inner"].includes(m.name))
+ m.material = darkPlasticMaterial;
});
}
});
@@ -423,17 +435,26 @@ function ModelScene({
root.add(bottomGroup);
lidGroupRef.current = lidGroup;
- const screenMesh = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), screenMaterial);
+ const screenMesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(screenSize[0], screenSize[1]),
+ screenMaterial
+ );
screenMesh.position.set(0, 10.5, -0.11);
screenMesh.rotation.set(Math.PI, 0, 0);
lidGroup.add(screenMesh);
- const darkScreen = new THREE.Mesh(new THREE.PlaneGeometry(screenSize[0], screenSize[1]), darkPlasticMaterial);
+ const darkScreen = new THREE.Mesh(
+ new THREE.PlaneGeometry(screenSize[0], screenSize[1]),
+ darkPlasticMaterial
+ );
darkScreen.position.set(0, 10.5, -0.111);
darkScreen.rotation.set(Math.PI, Math.PI, 0);
lidGroup.add(darkScreen);
- const keyboardKeys = new THREE.Mesh(new THREE.PlaneGeometry(27.7, 11.6), keyboardMaterial);
+ const keyboardKeys = new THREE.Mesh(
+ new THREE.PlaneGeometry(27.7, 11.6),
+ keyboardMaterial
+ );
keyboardKeys.rotation.set(-0.5 * Math.PI, 0, 0);
keyboardKeys.position.set(0, 0.045, 7.21);
bottomGroup.add(keyboardKeys);
@@ -458,29 +479,28 @@ function ModelScene({
}, [openingProgress, applyVideoTextureIfReady, onLoaded, gl, invalidate]);
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
+
useEffect(() => {
+ if (isUserInteractingRef.current) return;
+
if (
prevRotationRef.current?.x === initialRotationX &&
prevRotationRef.current?.y === initialRotationY
) {
return;
}
-
const id = setTimeout(() => {
+ if (isUserInteractingRef.current) return;
const orbit = orbitRef.current;
if (!orbit) return;
-
const radius = CAM_RADIUS / zoom;
const phi = Math.PI / 2 - initialRotationX * DEG;
const theta = initialRotationY * DEG;
-
orbit.object.position.setFromSphericalCoords(radius, phi, theta);
orbit.update();
invalidate();
-
prevRotationRef.current = { x: initialRotationX, y: initialRotationY };
}, 0);
-
return () => clearTimeout(id);
}, [initialRotationX, initialRotationY, zoom, invalidate]);
@@ -501,6 +521,62 @@ function ModelScene({
invalidate();
}, [openingProgress, modelGroup, invalidate]);
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+
+ outlinePass.edgeStrength = 6;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 2;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera, size.width, size.height, invalidate]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+
+ invalidate();
+ }, [isSelected, isHovered, invalidate, rootRef]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
+
return (
<>
<PerspectiveCamera ref={cameraRef} makeDefault fov={CAM_FOV} near={10} far={1000} position={[0, 0, CAM_RADIUS / zoom]} />
@@ -512,7 +588,11 @@ function ModelScene({
dampingFactor={0.08}
autoRotate={autoRotate}
autoRotateSpeed={rotationSpeed}
+ onStart={() => {
+ isUserInteractingRef.current = true;
+ }}
onEnd={() => {
+ isUserInteractingRef.current = false;
const orbit = orbitRef.current;
if (!orbit || !onRotationChange) return;
const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
@@ -521,6 +601,7 @@ function ModelScene({
}}
/>
<Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
+
<ambientLight intensity={3.2} />
<group>
<pointLight position={[0, 5, 50]} intensity={0.8} color="#fff5e1" />
@@ -528,6 +609,7 @@ function ModelScene({
<directionalLight position={[4, 8, 7]} intensity={2.6} />
<directionalLight position={[-5, -2, 4]} intensity={0.8} color="#aabbff" />
<directionalLight position={[0, -6, 6]} intensity={1.3} />
+
<group ref={rootRef} rotation={[0, 0, initialRotationZ * DEG]}>
{modelGroup && <primitive object={modelGroup} />}
</group>
@@ -547,7 +629,7 @@ function CanvasWithLoader(
return (
<>
<Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
+ style={{ width: "100%", height: "100%", overflow: "visible", pointerEvents: "auto" }}
gl={{
antialias: true,
alpha: true,
@@ -579,10 +661,22 @@ function CanvasWithLoader(
}
export function Laptop3DViewer(props: Props) {
- const { shadowIntensity = 0, shadowColor = "#000000", imageMaskConfig = null, isHovered = false, isSelected = false } = props;
+ const {
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ imageMaskConfig = null,
+ isSelected = false,
+ onHoverChange,
+ onSelectChange
+ } = props;
+
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const canvasElRef = useRef<HTMLCanvasElement | null>(null);
+ const raycasterRef = useRef(new THREE.Raycaster());
+
const [grabbing, setGrabbing] = useState(false);
+ const [modelHovered, setModelHovered] = useState(false);
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
@@ -598,7 +692,32 @@ export function Laptop3DViewer(props: Props) {
deviceHeight: LAPTOP_H,
});
- const outlineFilter = getOutlineFilter(isSelected, isHovered);
+ const hitsModel = (clientX: number, clientY: number): boolean => {
+ const canvas = canvasElRef.current;
+ const cam = cameraRef.current;
+ const model = rootRef.current;
+ if (!canvas || !cam || !model) return false;
+
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return false;
+
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycasterRef.current.setFromCamera(new THREE.Vector2(x, y), cam);
+ return raycasterRef.current.intersectObject(model, true).length > 0;
+ };
+
+ const handleCanvasMount = (canvas: HTMLCanvasElement) => {
+ canvasElRef.current = canvas;
+ props.onMount?.(canvas);
+ };
+
+ useEffect(() => {
+ const onWinPointerUp = () => setGrabbing(false);
+ window.addEventListener("pointerup", onWinPointerUp);
+ return () => window.removeEventListener("pointerup", onWinPointerUp);
+ }, []);
return (
<>
@@ -611,12 +730,12 @@ export function Laptop3DViewer(props: Props) {
marginTop: "250px",
}}
>
- <div
- style={{
- position: "relative",
- width: LAPTOP_W,
- height: LAPTOP_H,
- overflow: "visible",
+ <div
+ style={{
+ position: "relative",
+ width: LAPTOP_W,
+ height: LAPTOP_H,
+ overflow: "visible",
willChange: "transform",
}}
>
@@ -646,16 +765,47 @@ export function Laptop3DViewer(props: Props) {
height: LAPTOP_H,
overflow: "visible",
zIndex: 2,
- cursor: grabbing ? "grabbing" : "grab",
- filter: outlineFilter,
+ cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
transition: "filter 0.15s ease",
+ pointerEvents: "none",
...maskStyle,
}}
- onPointerDown={() => setGrabbing(true)}
+ onPointerDownCapture={(e) => {
+ const hit = hitsModel(e.clientX, e.clientY);
+ if (!hit) {
+ onSelectChange?.(false);
+ e.stopPropagation();
+ return;
+ }
+ onSelectChange?.(true);
+ setGrabbing(true);
+ }}
+ onPointerMove={(e) => {
+ if (!grabbing) {
+ const isCurrentlyHovering = hitsModel(e.clientX, e.clientY);
+ if (isCurrentlyHovering !== modelHovered) {
+ setModelHovered(isCurrentlyHovering);
+ onHoverChange?.(isCurrentlyHovering);
+ }
+ }
+ }}
onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
+ onPointerLeave={() => {
+ setGrabbing(false);
+ if (modelHovered) {
+ setModelHovered(false);
+ onHoverChange?.(false);
+ }
+ }}
>
- <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
+ <CanvasWithLoader
+ {...props}
+ isSelected={isSelected}
+ isHovered={modelHovered}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ onMount={handleCanvasMount}
+ />
</div>
</div>
</div>
diff --git a/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx b/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
index e6fa36b..dec37e1 100644
--- a/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
+++ b/app/components/ui/editor/mockups-3d/Phone3DViewer.tsx
@@ -16,13 +16,17 @@ import {
cloneGroup,
type ImageMaskConfigLike,
parseShadowColor,
- applyTextureCover,
- getOutlineFilter,
+ applyTextureCover
} from "@/lib/phone3d.utils";
import type { OrbitControls as OrbitControlsType } from 'three-stdlib';
import { EnvironmentPreset, HDRI_FILES } from "@/lib/viewer-controls3d";
import { GetMediaMaskStyles } from "@/lib/media-mask.utils";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+
THREE.Cache.enabled = true;
export interface Phone3DApi {
@@ -51,8 +55,10 @@ interface Props {
rotationSpeed?: number;
glow?: number;
environment?: EnvironmentPreset;
- isHovered: boolean;
- isSelected: boolean;
+ isHovered?: boolean;
+ isSelected?: boolean;
+ onHoverChange?: (isHovered: boolean) => void;
+ onSelectChange?: (isSelected: boolean) => void;
}
const DEG = Math.PI / 180;
@@ -117,12 +123,14 @@ function ModelScene({
rotationSpeed = 3.5,
glow = 1.0,
environment = "studio",
+ isSelected = false,
+ isHovered = false,
}: Props & {
rootRef: React.MutableRefObject<THREE.Group | null>;
cameraRef: React.MutableRefObject<THREE.PerspectiveCamera | null>;
onLoaded?: () => void;
}) {
- const { gl, scene, camera, invalidate } = useThree();
+ const { gl, scene, camera, invalidate, size } = useThree();
const orbitRef = useRef<OrbitControlsType | null>(null);
const screenMatRef = useRef<THREE.MeshBasicMaterial | null>(null);
const videoTextureRef = useRef<THREE.VideoTexture | null>(null);
@@ -134,6 +142,10 @@ function ModelScene({
const flipYRef = useRef<boolean>(false);
const onApiRef = useRef(onApi);
+ const composerRef = useRef<EffectComposer | null>(null);
+ const outlinePassRef = useRef<OutlinePass | null>(null);
+ const isUserInteractingRef = useRef(false);
+
useLayoutEffect(() => {
onApiRef.current = onApi;
});
@@ -147,7 +159,6 @@ function ModelScene({
useEffect(() => {
const capturedOnApi = onApiRef.current;
const RENDER_PIXEL_RATIO = 2;
-
const api: Phone3DApi = {
renderAt: (w, h) => {
const cam = cameraRef.current ?? camera;
@@ -156,13 +167,13 @@ function ModelScene({
const maxDim = Math.floor(maxTexSize / RENDER_PIXEL_RATIO) - 1;
const safeW = Math.max(1, Math.min(Math.round(w), maxDim));
const safeH = Math.max(1, Math.min(Math.round(h), maxDim));
-
(cam as THREE.PerspectiveCamera).aspect = safeW / safeH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
gl.setPixelRatio(RENDER_PIXEL_RATIO);
gl.setSize(safeW, safeH, false);
if (videoTextureRef.current) videoTextureRef.current.needsUpdate = true;
+
gl.render(scene, cam);
},
restorePreview: () => {
@@ -170,30 +181,33 @@ function ModelScene({
if (!cam) return;
const freshW = gl.domElement.clientWidth;
const freshH = gl.domElement.clientHeight;
-
(cam as THREE.PerspectiveCamera).aspect = freshW / freshH;
(cam as THREE.PerspectiveCamera).updateProjectionMatrix();
-
gl.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1);
gl.setSize(freshW, freshH, false);
+
+ composerRef.current?.setSize(freshW, freshH);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(freshW, freshH);
+
+ invalidate();
},
hasBuiltInShadow: true,
};
-
capturedOnApi?.(api);
return () => capturedOnApi?.(null);
- }, [gl, scene, camera, cameraRef]);
+ }, [gl, scene, camera, cameraRef, invalidate]);
const applyTexture = useCallback(() => {
if (videoElement) return;
-
const mat = screenMatRef.current;
if (!mat) return;
-
const cropKey = cropArea ? JSON.stringify(cropArea) : null;
+
if (!imageUrl) {
const placeholderKey = `__placeholder__:${PLACEHOLDER_PHONE_URL}`;
if (lastLoadedUrlRef.current === placeholderKey) return;
+
const device = getDeviceFromModelUrl(modelUrl);
const deviceConfig = deviceConfigs[device];
const isDefaultPhone = device === "phone";
@@ -203,7 +217,6 @@ function ModelScene({
img.onload = () => {
const currentMat = screenMatRef.current;
if (!currentMat) return;
-
let TARGET_W = 2048;
let TARGET_H = 0;
let cornerRadius = 0;
@@ -235,7 +248,6 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = placeholderKey;
lastLoadedCropKeyRef.current = null;
invalidate();
@@ -273,7 +285,6 @@ function ModelScene({
img.onload = () => {
const currentMat = screenMatRef.current;
if (!currentMat) return;
-
let TARGET_W = 2048;
let TARGET_H = 0;
let cornerRadius = 0;
@@ -313,7 +324,6 @@ function ModelScene({
currentMat.map = tex;
currentMat.color.set(0xffffff);
currentMat.needsUpdate = true;
-
lastLoadedUrlRef.current = imageUrl;
lastLoadedCropKeyRef.current = cropKey;
invalidate();
@@ -360,10 +370,8 @@ function ModelScene({
}
return;
}
-
const device = getDeviceFromModelUrl(modelUrl);
const isDefaultPhone = device === "phone";
-
const tex = new THREE.VideoTexture(videoElement);
tex.flipY = !isDefaultPhone;
tex.colorSpace = THREE.SRGBColorSpace;
@@ -376,7 +384,6 @@ function ModelScene({
const updateTextureTransform = () => {
let TARGET_W = 2048;
let TARGET_H = 0;
-
if (isDefaultPhone) {
TARGET_W = PHONE_W * 4;
TARGET_H = Math.round(TARGET_W / screenAspectRef.current);
@@ -384,7 +391,6 @@ function ModelScene({
const deviceConfig = deviceConfigs[device];
TARGET_H = Math.round(TARGET_W / deviceConfig.aspectRatio);
}
-
applyTextureCover(
tex,
videoElement.videoWidth,
@@ -392,7 +398,6 @@ function ModelScene({
TARGET_W,
TARGET_H
);
-
applyVideoTextureIfReady();
};
@@ -406,7 +411,6 @@ function ModelScene({
videoTextureRef.current.dispose();
}
videoTextureRef.current = tex;
-
applyVideoTextureIfReady();
return () => {
@@ -452,9 +456,7 @@ function ModelScene({
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const halfH = camZ * Math.tan((40 / 2) * DEG);
-
const sf = (halfH * 2 * 0.72) / size.y;
-
group.scale.setScalar(sf);
group.position.copy(center).negate().multiplyScalar(sf);
@@ -463,10 +465,12 @@ function ModelScene({
const mat = Array.isArray(child.material) ? child.material[0] : child.material;
const matName = (mat as THREE.Material)?.name ?? "";
const isScreen = matName === "Screen.editable" || child.name === "Screen";
+
if (isScreen) {
const meshBox = new THREE.Box3().setFromObject(child);
const meshSize = meshBox.getSize(new THREE.Vector3());
if (meshSize.x > 0 && meshSize.y > 0) screenAspectRef.current = meshSize.x / meshSize.y;
+
const basicMat = new THREE.MeshBasicMaterial({
color: 0x111111,
side: THREE.FrontSide,
@@ -494,7 +498,6 @@ function ModelScene({
const size = box.getSize(new THREE.Vector3());
const halfH = camZ * Math.tan((40 / 2) * DEG);
const sf = (halfH * 2 * 0.6) / size.y;
-
group.scale.setScalar(sf);
group.position.copy(center).negate().multiplyScalar(sf);
@@ -545,7 +548,6 @@ function ModelScene({
);
plane.renderOrder = 10;
group.add(plane);
-
finalizeSetup(group);
});
}
@@ -557,6 +559,8 @@ function ModelScene({
const prevRotationRef = useRef<{ x: number; y: number } | null>(null);
useEffect(() => {
+ if (isUserInteractingRef.current) return;
+
if (
prevRotationRef.current?.x === initialRotationX &&
prevRotationRef.current?.y === initialRotationY
@@ -564,11 +568,10 @@ function ModelScene({
return;
}
const id = setTimeout(() => {
+ if (isUserInteractingRef.current) return;
const orbit = orbitRef.current;
if (!orbit) return;
-
const radius = 1.5;
-
const phi = Math.PI / 2 - initialRotationX * DEG;
const theta = initialRotationY * DEG;
orbit.object.position.setFromSphericalCoords(radius, phi, theta);
@@ -586,10 +589,65 @@ function ModelScene({
}
}, [initialRotationZ, invalidate]);
+ useEffect(() => {
+ const composer = new EffectComposer(gl);
+ composer.addPass(new RenderPass(scene, camera));
+
+ const outlinePass = new OutlinePass(
+ new THREE.Vector2(size.width, size.height),
+ scene,
+ camera
+ );
+
+ outlinePass.edgeStrength = 8;
+ outlinePass.edgeGlow = 0;
+ outlinePass.edgeThickness = 3;
+ outlinePass.pulsePeriod = 0;
+ outlinePass.visibleEdgeColor.set(0xffffff);
+ outlinePass.hiddenEdgeColor.set(0xffffff);
+
+ composer.addPass(outlinePass);
+ composer.addPass(new OutputPass());
+
+ composerRef.current = composer;
+ outlinePassRef.current = outlinePass;
+ invalidate();
+
+ return () => {
+ outlinePass.dispose();
+ composer.dispose();
+ composerRef.current = null;
+ outlinePassRef.current = null;
+ };
+ }, [gl, scene, camera, size.width, size.height, invalidate]);
+
+ useEffect(() => {
+ composerRef.current?.setSize(size.width, size.height);
+ composerRef.current?.setPixelRatio(gl.getPixelRatio());
+ outlinePassRef.current?.resolution.set(size.width, size.height);
+ invalidate();
+ }, [size, gl, invalidate]);
+
+ useEffect(() => {
+ const outlinePass = outlinePassRef.current;
+ if (!outlinePass) return;
+
+ const showOutline = isSelected || isHovered;
+ outlinePass.selectedObjects = showOutline && rootRef.current ? [rootRef.current] : [];
+ const color = isSelected ? 0x3b82f6 : 0xffffff;
+ outlinePass.visibleEdgeColor.set(color);
+ outlinePass.hiddenEdgeColor.set(color);
+
+ invalidate();
+ }, [isSelected, isHovered, invalidate, rootRef]);
+
+ useFrame(() => {
+ composerRef.current?.render();
+ }, 1);
+
return (
<>
<PerspectiveCamera ref={cameraRef} makeDefault fov={40} near={0.01} far={100} position={[0, 0, 1.5]} zoom={zoom} />
-
<OrbitControls
ref={orbitRef}
enableZoom={false}
@@ -598,7 +656,11 @@ function ModelScene({
dampingFactor={0.08}
autoRotate={autoRotate}
autoRotateSpeed={rotationSpeed}
+ onStart={() => {
+ isUserInteractingRef.current = true;
+ }}
onEnd={() => {
+ isUserInteractingRef.current = false;
const orbit = orbitRef.current;
if (!orbit || !onRotationChange) return;
const ry = orbit.getAzimuthalAngle() * (180 / Math.PI);
@@ -607,6 +669,7 @@ function ModelScene({
}}
/>
<Environment files={HDRI_FILES[environment as EnvironmentPreset]} environmentIntensity={glow} background={false} />
+
<ambientLight intensity={0.3} />
<directionalLight position={[3, 6, 5]} intensity={0.6} />
<directionalLight position={[-4, -2, 3]} intensity={0.25} color="#c8d8ff" />
@@ -631,7 +694,7 @@ function CanvasWithLoader(
return (
<>
<Canvas
- style={{ width: "100%", height: "100%", overflow: "visible" }}
+ style={{ width: "100%", height: "100%", overflow: "visible", pointerEvents: "auto" }}
gl={{
antialias: true,
alpha: true,
@@ -655,10 +718,7 @@ function CanvasWithLoader(
</Suspense>
</Canvas>
{!loaded && (
- <div
- className="absolute inset-0 flex items-center justify-center pointer-events-none"
- style={{ zIndex: 4 }}
- >
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none" style={{ zIndex: 4 }} >
<div className="w-6 h-6 border-2 border-white/20 border-t-white/60 rounded-full animate-spin" />
</div>
)}
@@ -667,14 +727,25 @@ function CanvasWithLoader(
}
export function Phone3DViewer(props: Props) {
- const { shadowIntensity = 0, shadowColor = "#000000", imageMaskConfig = null, isHovered = false, isSelected = false } = props;
+ const {
+ shadowIntensity = 0,
+ shadowColor = "#000000",
+ imageMaskConfig = null,
+ isSelected = false,
+ onHoverChange,
+ onSelectChange
+ } = props;
+
const rootRef = useRef<THREE.Group | null>(null);
const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
+ const canvasElRef = useRef<HTMLCanvasElement | null>(null);
+ const raycasterRef = useRef(new THREE.Raycaster());
+
const [grabbing, setGrabbing] = useState(false);
+ const [modelHovered, setModelHovered] = useState(false);
const t = Math.max(0, Math.min(1, shadowIntensity));
const tEased = t * t;
-
const computedBlur = tEased * 60;
const computedOpacity = tEased * 0.7;
const shadowRgba = shadowColor.startsWith("#") ? parseShadowColor(shadowColor, computedOpacity) : shadowColor;
@@ -686,7 +757,32 @@ export function Phone3DViewer(props: Props) {
deviceHeight: PHONE_H,
});
- const outlineFilter = getOutlineFilter(isSelected, isHovered);
+ const hitsModel = (clientX: number, clientY: number): boolean => {
+ const canvas = canvasElRef.current;
+ const cam = cameraRef.current;
+ const model = rootRef.current;
+ if (!canvas || !cam || !model) return false;
+
+ const rect = canvas.getBoundingClientRect();
+ if (!rect.width || !rect.height) return false;
+
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((clientY - rect.top) / rect.height) * 2 + 1;
+
+ raycasterRef.current.setFromCamera(new THREE.Vector2(x, y), cam);
+ return raycasterRef.current.intersectObject(model, true).length > 0;
+ };
+
+ const handleCanvasMount = (canvas: HTMLCanvasElement) => {
+ canvasElRef.current = canvas;
+ props.onMount?.(canvas);
+ };
+
+ useEffect(() => {
+ const onWinPointerUp = () => setGrabbing(false);
+ window.addEventListener("pointerup", onWinPointerUp);
+ return () => window.removeEventListener("pointerup", onWinPointerUp);
+ }, []);
return (
<>
@@ -718,7 +814,6 @@ export function Phone3DViewer(props: Props) {
}}
/>
)}
-
<div
style={{
position: "absolute",
@@ -729,17 +824,47 @@ export function Phone3DViewer(props: Props) {
transform: "translate(-50%, -50%)",
zIndex: 2,
overflow: "visible",
- cursor: grabbing ? "grabbing" : "grab",
- filter: outlineFilter,
+ cursor: grabbing ? "grabbing" : modelHovered ? "grab" : "default",
transition: "filter 0.15s ease",
pointerEvents: "auto",
...maskStyle
}}
- onPointerDown={() => setGrabbing(true)}
+ onPointerDownCapture={(e) => {
+ const hit = hitsModel(e.clientX, e.clientY);
+ if (!hit) {
+ onSelectChange?.(false);
+ e.stopPropagation();
+ return;
+ }
+ onSelectChange?.(true);
+ setGrabbing(true);
+ }}
+ onPointerMove={(e) => {
+ if (!grabbing) {
+ const isCurrentlyHovering = hitsModel(e.clientX, e.clientY);
+ if (isCurrentlyHovering !== modelHovered) {
+ setModelHovered(isCurrentlyHovering);
+ onHoverChange?.(isCurrentlyHovering);
+ }
+ }
+ }}
onPointerUp={() => setGrabbing(false)}
- onPointerLeave={() => setGrabbing(false)}
+ onPointerLeave={() => {
+ setGrabbing(false);
+ if (modelHovered) {
+ setModelHovered(false);
+ onHoverChange?.(false);
+ }
+ }}
>
- <CanvasWithLoader {...props} rootRef={rootRef} cameraRef={cameraRef} />
+ <CanvasWithLoader
+ {...props}
+ isSelected={isSelected}
+ isHovered={modelHovered}
+ rootRef={rootRef}
+ cameraRef={cameraRef}
+ onMount={handleCanvasMount}
+ />
</div>
</div>
</div>
diff --git a/lib/phone3d.utils.ts b/lib/phone3d.utils.ts
index 8d0c960..a346061 100644
--- a/lib/phone3d.utils.ts
+++ b/lib/phone3d.utils.ts
@@ -301,18 +301,4 @@ function createOptimalCanvas(width: number, height: number) {
canvas.width = width;
canvas.height = height;
return canvas;
-}
-
-export function getOutlineFilter(isSelected: boolean = false, isHovered: boolean = false): string {
- const showOutline = isSelected || isHovered;
-
- if (!showOutline) return "none";
-
- const outlineColor = isSelected ? "#3b82f6" : "#ffffff";
-
- if (isSelected) {
- return `drop-shadow(1.5px 0 0.1px ${outlineColor}) drop-shadow(-1.5px 0 0.1px ${outlineColor}) drop-shadow(0 1.5px 0.1px ${outlineColor}) drop-shadow(0 -1.5px 0.1px ${outlineColor})`;
- } else {
- return `drop-shadow(0.75px 0 0px ${outlineColor}) drop-shadow(-0.75px 0 0px ${outlineColor}) drop-shadow(0 0.75px 0px ${outlineColor}) drop-shadow(0 -0.75px 0px ${outlineColor})`;
- }
}
\ No newline at end of file