-
-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy paththree-renderer.js
More file actions
1164 lines (972 loc) · 43.1 KB
/
three-renderer.js
File metadata and controls
1164 lines (972 loc) · 43.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Three.js 3D Renderer for iPhone mockups
let threeRenderer = null;
let threeScene = null;
let threeCamera = null;
let phoneModel = null;
let phonePivot = null; // Pivot group for rotation around screen center
let screenMesh = null;
let customScreenPlane = null;
let orbitControls = null;
let isThreeJSInitialized = false;
let phoneModelLoaded = false;
let phoneModelLoading = false;
// Screen texture for the screenshot
let screenTexture = null;
// Store original model scale
let baseModelScale = 1;
// Store base position offset to keep model centered after screen alignment
let basePositionOffset = { x: 0, y: 0, z: 0 };
// Current device model type
let currentDeviceModel = 'iphone';
// Cache for loaded phone models (for rendering different devices in side previews)
let phoneModelCache = {}; // { deviceType: { model, pivot, screenPlane, baseScale, loaded } }
// Device-specific configurations
const deviceConfigs = {
iphone: {
modelPath: 'models/iphone-15-pro-max.glb',
aspectRatio: 1290 / 2796,
screenHeightFactor: 0.826,
screenOffset: { x: 0.027, y: 0.745, z: 0.098 },
positionOffsetFactor: 0.81,
cornerRadiusFactor: 0.16,
modelRotation: { x: 0, y: 0, z: 0 } // No correction needed
},
samsung: {
modelPath: 'models/samsung-galaxy-s25-ultra.glb',
aspectRatio: 1440 / 3120,
screenHeightFactor: 0.66,
screenOffset: { x: 0, y: 0.0, z: 0.08}, // Will need adjustment
positionOffsetFactor: 0.5,
cornerRadiusFactor: 0.04,
modelRotation: { x: 0, y: 0, z: 0 } // Adjust to correct model tilt (in degrees)
}
};
// Frame color presets per device (real device colors)
// Using var so it's accessible from app.js
var frameColorPresets = {
iphone: [
{ id: 'natural', label: 'Natural Titanium', swatch: '#9d927f',
materials: { backpanel: '#9d927f', metalframe: '#5f5950', gray: '#221f1b' } },
{ id: 'blue', label: 'Blue Titanium', swatch: '#3d4d5c',
materials: { backpanel: '#394d5f', metalframe: '#3a4553', gray: '#1a1f24' } },
{ id: 'white', label: 'White Titanium', swatch: '#e3ddd4',
materials: { backpanel: '#e3ddd4', metalframe: '#c4bdb4', gray: '#2a2825' } },
{ id: 'black', label: 'Black Titanium', swatch: '#3a3632',
materials: { backpanel: '#3a3632', metalframe: '#2a2725', gray: '#1a1918' } },
{ id: 'desert', label: 'Desert Titanium', swatch: '#c4a882',
materials: { backpanel: '#c4a882', metalframe: '#8a7560', gray: '#2a2218' } },
{ id: 'deep-purple', label: 'Deep Purple', swatch: '#5b4a6e',
materials: { backpanel: '#5b4a6e', metalframe: '#3d3348', gray: '#1e1825' } },
{ id: 'gold', label: 'Gold', swatch: '#e3c8a0',
materials: { backpanel: '#e3c8a0', metalframe: '#c9a96e', gray: '#2a2418' } },
{ id: 'red', label: 'Product Red', swatch: '#c1272d',
materials: { backpanel: '#c1272d', metalframe: '#8a1c20', gray: '#1a0a0a' } },
],
samsung: [
{ id: 'gray', label: 'Titanium Gray', swatch: '#8a8a8a',
materials: { back_glass: '#4c4c4c', frame: '#cdcdcd', antenna: '#707070' } },
{ id: 'black', label: 'Titanium Black', swatch: '#2a2a2a',
materials: { back_glass: '#1a1a1a', frame: '#3a3a3a', antenna: '#2a2a2a' } },
{ id: 'silverblue', label: 'Titanium Silverblue', swatch: '#a8b8c8',
materials: { back_glass: '#8a9eb0', frame: '#b8c8d4', antenna: '#7a8ea0' } },
{ id: 'whitesilver', label: 'Titanium Whitesilver', swatch: '#e8e4df',
materials: { back_glass: '#d8d4cf', frame: '#e8e4df', antenna: '#c0bcb7' } },
{ id: 'pinkgold', label: 'Titanium Pinkgold', swatch: '#d4a89a',
materials: { back_glass: '#c89888', frame: '#d4b0a0', antenna: '#b08878' } },
{ id: 'jadegreen', label: 'Titanium Jadegreen', swatch: '#9aaa9c',
materials: { back_glass: '#7a9a7c', frame: '#a8b8aa', antenna: '#6a8a6c' } },
{ id: 'jetblack', label: 'Titanium Jetblack', swatch: '#404040',
materials: { back_glass: '#2a2a2a', frame: '#484848', antenna: '#353535' } },
]
};
// Store original material colors for the current model
let originalMaterialColors = {};
// Apply a frame color preset to the phone model
function setPhoneFrameColor(presetId, deviceType) {
if (!phoneModel) return;
deviceType = deviceType || currentDeviceModel;
const presets = frameColorPresets[deviceType];
if (!presets) return;
const preset = presets.find(p => p.id === presetId);
if (!preset) return;
phoneModel.traverse((child) => {
if (child.isMesh && child.material) {
const matName = (child.material.name || '').toLowerCase();
if (preset.materials[matName]) {
child.material.color.set(preset.materials[matName]);
}
}
});
requestThreeJSRender();
}
// Apply frame color to a cached model (for side previews)
function setCachedModelFrameColor(presetId, deviceType) {
const cached = phoneModelCache[deviceType];
if (!cached?.loaded) return;
const presets = frameColorPresets[deviceType];
if (!presets) return;
const preset = presets.find(p => p.id === presetId);
if (!preset) return;
cached.model.traverse((child) => {
if (child.isMesh && child.material) {
const matName = (child.material.name || '').toLowerCase();
if (preset.materials[matName]) {
child.material.color.set(preset.materials[matName]);
}
}
});
}
// Initialize Three.js scene
function initThreeJS() {
if (isThreeJSInitialized) return;
const container = document.getElementById('threejs-container');
if (!container) return;
// Create scene with a gradient background color (we'll update this dynamically)
threeScene = new THREE.Scene();
threeScene.background = new THREE.Color(0x667eea); // Default gradient start color
// Create camera
const aspect = 400 / 700;
threeCamera = new THREE.PerspectiveCamera(35, aspect, 0.1, 1000);
threeCamera.position.set(0, 0, 6);
// Create renderer - disable antialiasing for faster interactive performance
// Quality rendering is done at export time with higher resolution
threeRenderer = new THREE.WebGLRenderer({
antialias: false, // Disable for better performance
alpha: true,
preserveDrawingBuffer: true,
powerPreference: 'high-performance'
});
threeRenderer.setSize(400, 700);
// Use device pixel ratio of 1 for fastest interactive rendering
threeRenderer.setPixelRatio(1);
threeRenderer.outputEncoding = THREE.sRGBEncoding;
threeRenderer.toneMapping = THREE.NoToneMapping;
// Disable automatic clearing - we control this manually
threeRenderer.autoClear = false;
container.appendChild(threeRenderer.domElement);
// Add lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
threeScene.add(ambientLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 0.8);
keyLight.position.set(2, 3, 4);
threeScene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xffffff, 0.4);
fillLight.position.set(-2, 1, 2);
threeScene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xffffff, 0.3);
rimLight.position.set(0, -2, -3);
threeScene.add(rimLight);
// Add orbit controls (disabled - we use custom drag handling for better performance)
// orbitControls = new THREE.OrbitControls(threeCamera, threeRenderer.domElement);
// orbitControls.enableDamping = true;
// orbitControls.dampingFactor = 0.05;
// orbitControls.enableZoom = false;
// orbitControls.enablePan = false;
// orbitControls.rotateSpeed = 0.5;
// orbitControls.minPolarAngle = Math.PI / 4;
// orbitControls.maxPolarAngle = Math.PI * 3 / 4;
// orbitControls.minAzimuthAngle = -Math.PI / 3;
// orbitControls.maxAzimuthAngle = Math.PI / 3;
isThreeJSInitialized = true;
// Load the phone model - check state for which device to use
let deviceToLoad = 'iphone';
if (typeof state !== 'undefined' && typeof getScreenshotSettings === 'function') {
const ss = getScreenshotSettings();
if (ss?.device3D) {
deviceToLoad = ss.device3D;
}
}
currentDeviceModel = deviceToLoad;
loadPhoneModel();
// Start animation loop
animateThreeJS();
}
// Load the phone 3D model based on currentDeviceModel
function loadPhoneModel() {
if (phoneModelLoading) return; // Prevent double loading
phoneModelLoading = true;
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
const loader = new THREE.GLTFLoader();
loader.load(
config.modelPath,
(gltf) => {
phoneModelLoading = false;
phoneModel = gltf.scene;
// Center and scale the model
const box = new THREE.Box3().setFromObject(phoneModel);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
// Center the model
phoneModel.position.sub(center);
// Scale to fit view (3.75 = 2.5 * 1.5 to match 2D scale at 100%)
const maxDim = Math.max(size.x, size.y, size.z);
baseModelScale = 3.75 / maxDim;
phoneModel.scale.setScalar(baseModelScale);
// Log all meshes to help identify the screen
console.log('Phone model meshes:');
let blackMeshes = [];
phoneModel.traverse((child) => {
if (child.isMesh) {
console.log(' Mesh:', child.name, '| Material:', child.material?.name);
// Look for screen mesh - in this model it's likely "black" material
const name = (child.name || '').toLowerCase();
const matName = (child.material?.name || '').toLowerCase();
if (matName === 'black') {
blackMeshes.push(child);
}
if (name.includes('screen') || name.includes('display') ||
matName.includes('screen') || matName.includes('display') ||
matName.includes('emission') || matName.includes('emissive')) {
screenMesh = child;
console.log(' -> Identified as screen mesh');
}
}
});
// Find the front glass - that's where the screen actually is
// Don't use black meshes, those are small elements like notch/dynamic island
let glassMeshes = [];
phoneModel.traverse((child) => {
if (child.isMesh) {
const matName = (child.material?.name || '').toLowerCase();
if (matName === 'glass') {
child.geometry.computeBoundingBox();
const box = child.geometry.boundingBox;
const size = new THREE.Vector3();
box.getSize(size);
const area = size.x * size.y;
glassMeshes.push({ mesh: child, area, size });
console.log(' Glass mesh:', child.name, 'size:', size.x.toFixed(3), 'x', size.y.toFixed(3), 'area:', area.toFixed(3));
}
}
});
// Use the largest glass mesh (front screen glass)
if (glassMeshes.length > 0) {
glassMeshes.sort((a, b) => b.area - a.area);
screenMesh = glassMeshes[0].mesh;
console.log(' -> Using largest glass mesh as screen:', screenMesh.name);
}
// Create a pivot group for rotation around screen center
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
const screenOffset = config.screenOffset;
phonePivot = new THREE.Group();
// Offset the phone model so the screen center is at the pivot's origin
phoneModel.position.set(
-screenOffset.x * baseModelScale,
-screenOffset.y * baseModelScale,
-screenOffset.z * baseModelScale
);
phonePivot.add(phoneModel);
threeScene.add(phonePivot);
// Create a custom screen plane overlay since the model's UV mapping may be incorrect
createScreenOverlay();
phoneModelLoaded = true;
// Apply initial settings from state
if (typeof state !== 'undefined') {
updateThreeJSBackground();
const ss = typeof getScreenshotSettings === 'function' ? getScreenshotSettings() : state.defaults?.screenshot;
const rotation3D = ss?.rotation3D || { x: 0, y: 0, z: 0 };
setThreeJSRotation(rotation3D.x, rotation3D.y, rotation3D.z);
// Apply frame color
if (ss?.frameColor) {
setPhoneFrameColor(ss.frameColor, currentDeviceModel);
}
// Apply screenshot texture
if (state.screenshots.length > 0) {
updateScreenTexture();
}
// Refresh canvas now that model is loaded (needed for side previews too)
if (typeof updateCanvas === 'function') {
updateCanvas();
}
}
console.log('Phone model loaded successfully');
},
(progress) => {
const percent = Math.round(progress.loaded / progress.total * 100);
console.log('Loading phone model... ' + percent + '%');
},
(error) => {
console.error('Error loading phone model:', error);
}
);
}
// Switch to a different phone model
function switchPhoneModel(deviceType) {
if (!deviceConfigs[deviceType]) {
console.error('Unknown device type:', deviceType);
return;
}
// Skip if same device and already loaded or loading
if (currentDeviceModel === deviceType && (phoneModelLoaded || phoneModelLoading)) {
return;
}
// Update current device type
currentDeviceModel = deviceType;
phoneModelLoading = false; // Reset so we can load the new one
// Remove current pivot (which contains the model) from scene
if (phonePivot && threeScene) {
threeScene.remove(phonePivot);
phonePivot.traverse((child) => {
if (child.isMesh) {
child.geometry?.dispose();
child.material?.dispose();
}
});
phonePivot = null;
phoneModel = null;
}
// Clean up screen plane
if (customScreenPlane) {
if (customScreenPlane.parent) {
customScreenPlane.parent.remove(customScreenPlane);
}
customScreenPlane.geometry?.dispose();
customScreenPlane.material?.dispose();
customScreenPlane = null;
}
screenMesh = null;
phoneModelLoaded = false;
// Load new model using the config
const config = deviceConfigs[currentDeviceModel];
const loader = new THREE.GLTFLoader();
loader.load(
config.modelPath,
(gltf) => {
phoneModel = gltf.scene;
// Center and scale the model
const box = new THREE.Box3().setFromObject(phoneModel);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
phoneModel.position.sub(center);
const maxDim = Math.max(size.x, size.y, size.z);
baseModelScale = 3.75 / maxDim;
phoneModel.scale.setScalar(baseModelScale);
// Create a pivot group for rotation around screen center
const screenOffset = config.screenOffset;
phonePivot = new THREE.Group();
// Offset the phone model so the screen center is at the pivot's origin
phoneModel.position.set(
-screenOffset.x * baseModelScale,
-screenOffset.y * baseModelScale,
-screenOffset.z * baseModelScale
);
phonePivot.add(phoneModel);
threeScene.add(phonePivot);
// Create screen overlay for this device
createScreenOverlay();
phoneModelLoaded = true;
// Apply settings
if (typeof state !== 'undefined') {
updateThreeJSBackground();
const ss = typeof getScreenshotSettings === 'function' ? getScreenshotSettings() : state.defaults?.screenshot;
const rotation3D = ss?.rotation3D || { x: 0, y: 0, z: 0 };
setThreeJSRotation(rotation3D.x, rotation3D.y, rotation3D.z);
// Apply frame color
if (ss?.frameColor) {
setPhoneFrameColor(ss.frameColor, currentDeviceModel);
}
if (state.screenshots.length > 0) {
updateScreenTexture();
}
// Only call updateCanvas if not suppressed (e.g., during slide transitions)
if (typeof updateCanvas === 'function' && !window.suppressSwitchModelUpdate) {
updateCanvas();
}
}
console.log(deviceType + ' model loaded successfully');
},
(progress) => {
const percent = Math.round(progress.loaded / progress.total * 100);
console.log('Loading ' + deviceType + ' model... ' + percent + '%');
},
(error) => {
console.error('Error loading ' + deviceType + ' model:', error);
}
);
}
// Load a phone model into the cache (for side preview rendering with different devices)
function loadCachedPhoneModel(deviceType) {
if (!deviceConfigs[deviceType]) return Promise.reject('Unknown device type');
// Already loaded or loading
if (phoneModelCache[deviceType]?.loaded) {
return Promise.resolve(phoneModelCache[deviceType]);
}
if (phoneModelCache[deviceType]?.loading) {
return phoneModelCache[deviceType].loadingPromise;
}
const config = deviceConfigs[deviceType];
const loader = new THREE.GLTFLoader();
phoneModelCache[deviceType] = { loading: true, loaded: false };
phoneModelCache[deviceType].loadingPromise = new Promise((resolve, reject) => {
loader.load(
config.modelPath,
(gltf) => {
const model = gltf.scene;
// Center and scale the model
const box = new THREE.Box3().setFromObject(model);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
model.position.sub(center);
const maxDim = Math.max(size.x, size.y, size.z);
const modelBaseScale = 3.75 / maxDim;
model.scale.setScalar(modelBaseScale);
// Create pivot for this model
const screenOffset = config.screenOffset;
const pivot = new THREE.Group();
model.position.set(
-screenOffset.x * modelBaseScale,
-screenOffset.y * modelBaseScale,
-screenOffset.z * modelBaseScale
);
pivot.add(model);
// Create screen plane for this model
const aspectRatio = config.aspectRatio;
const planeHeight = 4.3 * config.screenHeightFactor;
const planeWidth = planeHeight * aspectRatio;
const geometry = new THREE.PlaneGeometry(planeWidth, planeHeight);
const material = new THREE.MeshBasicMaterial({
color: 0x111111,
side: THREE.DoubleSide
});
const screenPlane = new THREE.Mesh(geometry, material);
screenPlane.position.set(screenOffset.x, screenOffset.y, screenOffset.z);
const modelRot = config.modelRotation || { x: 0, y: 0, z: 0 };
screenPlane.rotation.set(
-modelRot.x * Math.PI / 180,
-modelRot.y * Math.PI / 180,
-modelRot.z * Math.PI / 180
);
model.add(screenPlane);
phoneModelCache[deviceType] = {
model: model,
pivot: pivot,
screenPlane: screenPlane,
baseScale: modelBaseScale,
loaded: true,
loading: false
};
console.log('Cached ' + deviceType + ' model for side previews');
resolve(phoneModelCache[deviceType]);
},
undefined,
(error) => {
console.error('Error loading cached ' + deviceType + ' model:', error);
phoneModelCache[deviceType] = { loading: false, loaded: false };
reject(error);
}
);
});
return phoneModelCache[deviceType].loadingPromise;
}
// Preload all device models for side previews
function preloadAllPhoneModels() {
const deviceTypes = Object.keys(deviceConfigs);
return Promise.all(deviceTypes.map(type => loadCachedPhoneModel(type).catch(() => null)));
}
// Create a custom screen plane overlay with correct UV mapping
function createScreenOverlay() {
if (customScreenPlane) {
if (customScreenPlane.parent) {
customScreenPlane.parent.remove(customScreenPlane);
}
customScreenPlane.geometry.dispose();
customScreenPlane.material.dispose();
}
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
// Use device-specific aspect ratio and screen size
const aspectRatio = config.aspectRatio;
const planeHeight = 4.3 * config.screenHeightFactor;
const planeWidth = planeHeight * aspectRatio;
const geometry = new THREE.PlaneGeometry(planeWidth, planeHeight);
const material = new THREE.MeshBasicMaterial({
color: 0x111111,
side: THREE.DoubleSide
});
customScreenPlane = new THREE.Mesh(geometry, material);
// Position at center of phone, slightly in front of glass
const screenOffset = config.screenOffset;
customScreenPlane.position.set(screenOffset.x, screenOffset.y, screenOffset.z);
// Counter-rotate the screen to cancel out the model's base rotation
// This keeps the screen facing forward when the pivot applies the base rotation
const modelRot = config.modelRotation || { x: 0, y: 0, z: 0 };
customScreenPlane.rotation.set(
-modelRot.x * Math.PI / 180,
-modelRot.y * Math.PI / 180,
-modelRot.z * Math.PI / 180
);
// Add directly to phoneModel so it moves with it
phoneModel.add(customScreenPlane);
// basePositionOffset is no longer needed since we use pivot-based rotation
basePositionOffset.y = 0;
console.log('Created screen overlay for ' + currentDeviceModel + ' at:', customScreenPlane.position);
console.log('Plane size:', planeWidth.toFixed(4), 'x', planeHeight.toFixed(4));
}
// Create a rounded corner version of the screenshot
function createRoundedScreenImage(image, cornerRadius) {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
// Draw rounded rectangle path
const w = canvas.width;
const h = canvas.height;
const r = cornerRadius;
ctx.beginPath();
ctx.moveTo(r, 0);
ctx.lineTo(w - r, 0);
ctx.quadraticCurveTo(w, 0, w, r);
ctx.lineTo(w, h - r);
ctx.quadraticCurveTo(w, h, w - r, h);
ctx.lineTo(r, h);
ctx.quadraticCurveTo(0, h, 0, h - r);
ctx.lineTo(0, r);
ctx.quadraticCurveTo(0, 0, r, 0);
ctx.closePath();
// Clip to rounded rectangle and draw image
ctx.clip();
ctx.drawImage(image, 0, 0);
return canvas;
}
// Update the screen texture with current screenshot
function updateScreenTexture() {
if (!phoneModel) return;
if (typeof state === 'undefined' || !state.screenshots.length) return;
const screenshot = state.screenshots[state.selectedIndex];
// Use getScreenshotImage() for localized image support
const screenshotImage = typeof getScreenshotImage === 'function'
? getScreenshotImage(screenshot)
: screenshot?.image;
if (!screenshot || !screenshotImage) return;
// Create texture from screenshot
if (screenTexture) {
screenTexture.dispose();
}
// Create rounded corner version of the image using device-specific corner radius
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
const cornerRadius = Math.round(screenshotImage.width * config.cornerRadiusFactor);
const roundedImage = createRoundedScreenImage(screenshotImage, cornerRadius);
screenTexture = new THREE.Texture(roundedImage);
screenTexture.needsUpdate = true;
screenTexture.encoding = THREE.sRGBEncoding;
screenTexture.flipY = true;
// Create a material for the screen with transparency for rounded corners
const screenMaterial = new THREE.MeshBasicMaterial({
map: screenTexture,
side: THREE.FrontSide,
transparent: true
});
// Apply to custom screen plane (preferred)
if (customScreenPlane) {
customScreenPlane.material.dispose();
customScreenPlane.material = screenMaterial;
console.log('Applied rounded texture to custom screen plane');
}
// Trigger render update
requestThreeJSRender();
}
// Set 3D rotation from sliders (in degrees)
function setThreeJSRotation(rotX, rotY, rotZ) {
if (!phonePivot) return;
// Add the device's base model rotation to the user's rotation
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
const modelRot = config.modelRotation || { x: 0, y: 0, z: 0 };
console.log('setThreeJSRotation:', currentDeviceModel, 'modelRot:', modelRot, 'user:', rotX, rotY, rotZ);
// Rotate the pivot (which rotates around the screen center)
phonePivot.rotation.x = (rotX + modelRot.x) * Math.PI / 180;
phonePivot.rotation.y = (rotY + modelRot.y) * Math.PI / 180;
phonePivot.rotation.z = (rotZ + modelRot.z) * Math.PI / 180;
// Trigger render update
requestThreeJSRender();
}
// Set 3D scale
function setThreeJSScale(scale) {
if (!phoneModel) return;
phoneModel.scale.setScalar(baseModelScale * (scale / 100));
// Trigger render update
requestThreeJSRender();
}
// Render on demand instead of continuous animation loop
let renderRequested = false;
function requestThreeJSRender() {
if (renderRequested) return;
renderRequested = true;
requestAnimationFrame(() => {
renderRequested = false;
if (threeRenderer && threeScene && threeCamera) {
threeRenderer.clear();
threeRenderer.render(threeScene, threeCamera);
}
});
}
// Legacy function name for compatibility - now triggers on-demand render
function animateThreeJS() {
requestThreeJSRender();
}
// Render 3D phone only (with transparent background) to be composited
function renderThreeJSToCanvas(targetCanvas, width, height) {
if (!threeRenderer || !threeScene || !threeCamera || !phonePivot) return;
const dims = { width: width || 1290, height: height || 2796 };
// Store original values
const originalBackground = threeScene.background;
const originalPosition = phonePivot.position.clone();
const originalScale = phonePivot.scale.clone();
const originalRotation = phonePivot.rotation.clone();
// Apply position, scale, and rotation from screenshot settings
if (typeof state !== 'undefined') {
// Use getScreenshotSettings() helper if available, otherwise fall back to defaults
const ss = typeof getScreenshotSettings === 'function' ? getScreenshotSettings() : state.defaults?.screenshot;
if (ss) {
// Scale: use screenshot.scale to adjust model size
const screenshotScale = ss.scale / 100;
phonePivot.scale.setScalar(screenshotScale);
// Position: match 2D behavior where available space depends on (1 - scale)
// This ensures same percentages look the same in 2D and 3D
// X uses smaller factor (1.1) since canvas is taller than wide (400x700 aspect)
const availableSpaceY = (1 - screenshotScale) * 2;
const availableSpaceX = (1 - screenshotScale) * 0.9;
const xOffset = ((ss.x - 50) / 50) * availableSpaceX;
const yOffset = -((ss.y - 50) / 50) * availableSpaceY; // Inverted for 3D
phonePivot.position.set(
xOffset + basePositionOffset.x,
yOffset + basePositionOffset.y,
basePositionOffset.z
);
// Rotation: apply 3D rotation from current screenshot settings + model base rotation
const rotation3D = ss.rotation3D || { x: 0, y: 0, z: 0 };
const config = deviceConfigs[currentDeviceModel] || deviceConfigs.iphone;
const modelRot = config.modelRotation || { x: 0, y: 0, z: 0 };
phonePivot.rotation.set(
(rotation3D.x + modelRot.x) * Math.PI / 180,
(rotation3D.y + modelRot.y) * Math.PI / 180,
(rotation3D.z + modelRot.z) * Math.PI / 180
);
}
}
// Set transparent background for compositing
threeScene.background = null;
threeRenderer.setClearColor(0x000000, 0); // Fully transparent clear color
// Temporarily resize renderer
const oldSize = { width: 400, height: 700 };
threeRenderer.setSize(dims.width, dims.height);
threeCamera.aspect = dims.width / dims.height;
threeCamera.updateProjectionMatrix();
// Clear the renderer before drawing (ensures clean transparency)
threeRenderer.clear();
// Render with transparency
threeRenderer.render(threeScene, threeCamera);
// Draw to target canvas (compositing the 3D phone onto existing content)
const ctx = targetCanvas.getContext('2d');
ctx.drawImage(threeRenderer.domElement, 0, 0, dims.width, dims.height);
// Restore size, background, and model transforms
threeRenderer.setSize(oldSize.width, oldSize.height);
threeCamera.aspect = oldSize.width / oldSize.height;
threeCamera.updateProjectionMatrix();
threeScene.background = originalBackground;
phonePivot.position.copy(originalPosition);
phonePivot.scale.copy(originalScale);
phonePivot.rotation.copy(originalRotation);
}
// Render 3D for a specific screenshot index (used for side previews)
function renderThreeJSForScreenshot(targetCanvas, width, height, screenshotIndex) {
if (!threeRenderer || !threeScene || !threeCamera) return;
if (typeof state === 'undefined' || !state.screenshots[screenshotIndex]) return;
const screenshot = state.screenshots[screenshotIndex];
const ss = screenshot.screenshot;
const dims = { width: width || 1290, height: height || 2796 };
// Determine which device model this screenshot uses
const screenshotDeviceType = ss.device3D || 'iphone';
const config = deviceConfigs[screenshotDeviceType] || deviceConfigs.iphone;
// Check if this screenshot uses the same device as currently active
const useCurrentModel = screenshotDeviceType === currentDeviceModel && phonePivot;
// Get the model to use (either current or from cache)
let pivotToUse, screenPlaneToUse;
if (useCurrentModel) {
// Use the currently loaded model
pivotToUse = phonePivot;
screenPlaneToUse = customScreenPlane;
} else {
// Use cached model for different device
const cached = phoneModelCache[screenshotDeviceType];
if (!cached?.loaded) {
// Model not cached yet - trigger loading and skip this render
loadCachedPhoneModel(screenshotDeviceType).then(() => {
// Trigger a re-render once model is loaded
if (typeof updateCanvas === 'function') {
updateCanvas();
}
});
return;
}
pivotToUse = cached.pivot;
screenPlaneToUse = cached.screenPlane;
// Add cached pivot to scene temporarily
threeScene.add(pivotToUse);
}
// Store original values
const originalBackground = threeScene.background;
const originalPosition = pivotToUse.position.clone();
const originalScale = pivotToUse.scale.clone();
const originalRotation = pivotToUse.rotation.clone();
// Hide the current model if we're using a different one
if (!useCurrentModel && phonePivot) {
phonePivot.visible = false;
}
// Temporarily update screen texture for this screenshot
// Use getScreenshotImage() for localized image support
const screenshotImage = typeof getScreenshotImage === 'function'
? getScreenshotImage(screenshot)
: screenshot?.image;
const oldMaterial = screenPlaneToUse ? screenPlaneToUse.material : null;
if (screenshotImage && screenPlaneToUse) {
const cornerRadius = Math.round(screenshotImage.width * config.cornerRadiusFactor);
const roundedImage = createRoundedScreenImage(screenshotImage, cornerRadius);
const newTexture = new THREE.Texture(roundedImage);
newTexture.needsUpdate = true;
newTexture.encoding = THREE.sRGBEncoding;
newTexture.flipY = true;
const newMaterial = new THREE.MeshBasicMaterial({
map: newTexture,
side: THREE.FrontSide,
transparent: true
});
screenPlaneToUse.material = newMaterial;
}
// Apply frame color for this screenshot
if (ss.frameColor) {
if (useCurrentModel) {
setPhoneFrameColor(ss.frameColor, screenshotDeviceType);
} else {
setCachedModelFrameColor(ss.frameColor, screenshotDeviceType);
}
}
// Apply rotation for this screenshot + model base rotation
const rotation3D = ss.rotation3D || { x: 0, y: 0, z: 0 };
const modelRot = config.modelRotation || { x: 0, y: 0, z: 0 };
pivotToUse.rotation.set(
(rotation3D.x + modelRot.x) * Math.PI / 180,
(rotation3D.y + modelRot.y) * Math.PI / 180,
(rotation3D.z + modelRot.z) * Math.PI / 180
);
// Apply scale and position (matching 2D behavior)
const screenshotScale = ss.scale / 100;
pivotToUse.scale.setScalar(screenshotScale);
const availableSpaceY = (1 - screenshotScale) * 2;
const availableSpaceX = (1 - screenshotScale) * 0.9;
const xOffset = ((ss.x - 50) / 50) * availableSpaceX;
const yOffset = -((ss.y - 50) / 50) * availableSpaceY;
pivotToUse.position.set(
xOffset + basePositionOffset.x,
yOffset + basePositionOffset.y,
basePositionOffset.z
);
// Set transparent background for compositing
threeScene.background = null;
threeRenderer.setClearColor(0x000000, 0); // Fully transparent clear color
// Temporarily resize renderer
const oldSize = { width: 400, height: 700 };
threeRenderer.setSize(dims.width, dims.height);
threeCamera.aspect = dims.width / dims.height;
threeCamera.updateProjectionMatrix();
// Clear the renderer before drawing (ensures clean transparency)
threeRenderer.clear();
// Render with transparency
threeRenderer.render(threeScene, threeCamera);
// Draw to target canvas (composite 3D phone onto existing background)
const ctx = targetCanvas.getContext('2d');
ctx.drawImage(threeRenderer.domElement, 0, 0, dims.width, dims.height);
// Restore everything
threeRenderer.setSize(oldSize.width, oldSize.height);
threeCamera.aspect = oldSize.width / oldSize.height;
threeCamera.updateProjectionMatrix();
threeScene.background = originalBackground;
pivotToUse.position.copy(originalPosition);
pivotToUse.scale.copy(originalScale);
pivotToUse.rotation.copy(originalRotation);
// Restore original material
if (oldMaterial && screenPlaneToUse) {
// Dispose the temporary material
if (screenPlaneToUse.material !== oldMaterial) {
screenPlaneToUse.material.map?.dispose();
screenPlaneToUse.material.dispose();
}
screenPlaneToUse.material = oldMaterial;
}
// Restore frame color on current model if we changed it
if (useCurrentModel && ss.frameColor && typeof state !== 'undefined') {
const currentSS = typeof getScreenshotSettings === 'function' ? getScreenshotSettings() : null;
if (currentSS?.frameColor) {
setPhoneFrameColor(currentSS.frameColor, currentDeviceModel);
}
}
// Clean up: remove cached model from scene and restore current model visibility
if (!useCurrentModel) {
threeScene.remove(pivotToUse);
if (phonePivot) {
phonePivot.visible = true;
}
}
}
// Show/hide Three.js container
function showThreeJS(show) {
const container = document.getElementById('threejs-container');
const canvas = document.getElementById('preview-canvas');
// In 3D mode, we show the 2D canvas (which composites everything)
// The Three.js container is hidden but used for rendering
if (container) {
container.style.display = 'none'; // Always hidden - we render to 2D canvas
}
if (canvas) {
canvas.style.display = 'block'; // Always visible
}
if (show && !isThreeJSInitialized) {
initThreeJS();
}
// Apply current rotation and background
if (show && typeof state !== 'undefined') {
updateThreeJSBackground();
if (phoneModel) {
const ss = typeof getScreenshotSettings === 'function' ? getScreenshotSettings() : state.defaults?.screenshot;
const rotation3D = ss?.rotation3D || { x: 0, y: 0, z: 0 };
setThreeJSRotation(rotation3D.x, rotation3D.y, rotation3D.z);
updateScreenTexture();