-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.html
711 lines (611 loc) · 28.3 KB
/
client.html
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
<!DOCTYPE html>
<!--
Note: this is a single large HTML file to sidestep CORS issues.
Script is heavily based on three.js examples: https://threejs.org/examples/
-->
<html lang="en">
<head>
<title>gedankenpolizei</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
/* Styling taken from Three.js examples */
:root {
color-scheme: light dark;
--background-color: #fff;
--secondary-background-color: #f7f7f7;
--color-blue: #049EF4;
--text-color: #444;
--secondary-text-color: #9e9e9e;
--font-size: 16px;
--line-height: 26px;
--border-style: 2px solid #E8E8E8;
}
@media (prefers-color-scheme: dark) {
:root {
--background-color: #222;
--secondary-background-color: #2e2e2e;
--text-color: #bbb;
--secondary-text-color: #666;
--border-style: 2px solid #444;
}
}
body {
margin: 0;
overflow: hidden;
background-color: #000; /* Ensure this is black; otherwise lens distortion reveals a grey band (the default body background-color I guess) */
}
canvas {
display: block;
}
#overlay {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
#startButton {
font-size: calc(var(--font-size) - 1px);
padding: 10px 20px;
background-color: var(--background-color);
border: var(--border-style);
color: var(--text-color);
cursor: pointer;
border-radius: 4px;
transition: background-color 0.3s;
font-family: 'Roboto Mono', monospace;
}
#startButton:hover {
background-color: var(--secondary-background-color);
}
#infoBox {
position: absolute;
bottom: 10px;
right: 10px;
padding: 10px;
font-family: 'Roboto Mono', monospace;
font-size: calc(var(--font-size) - 2px);
color: var(--text-color);
border-radius: 5px;
border: var(--border-style);
}
#infoBox p {
margin-top: 0.3em;
margin-bottom: 0.3em;
}
#infoBox .centered {
text-align: center; /* Center the first paragraph */
}
#infoBox .aligned {
display: flex;
justify-content: space-between;
white-space: pre; /* Preserve spaces */
}
</style>
</head>
<body>
<video id="video" autoplay playsinline style="display:none"></video>
<div id="overlay">
<button id="startButton">ENTER</button>
</div>
<div id="infoBox">
<p class="centered"><strong>gedankenpolizei</strong></p>
<p class="aligned">[SPACE] (un)lock camera</p>
<p class="aligned"> [C] toggle controls</p>
<p class="aligned"> [M] (un)mute</p>
</div>
<!-- This shader transforms 2D points from the webcam texture into 3D space. It calculates depth from the texture color and positions each vertex accordingly; also sets the size of each point -->
<script id="vs" type="x-shader/x-vertex">
uniform sampler2D map;
uniform float width;
uniform float height;
uniform float nearClipping, farClipping;
uniform float pointSize;
uniform float zOffset;
varying vec2 vUv;
const float XtoZ = 1.11146;
const float YtoZ = 0.83359;
void main() {
vUv = vec2(position.x / width, position.y / height);
vec4 color = texture2D(map, vUv);
float depth = (color.r + color.g + color.b) / 3.0;
float z = (1.0 - depth) * (farClipping - nearClipping) + nearClipping;
vec4 pos = vec4(
(position.x / width - 0.5) * z * XtoZ,
(position.y / height - 0.5) * z * YtoZ,
-z + zOffset,
1.0);
gl_PointSize = pointSize;
gl_Position = projectionMatrix * modelViewMatrix * pos;
}
</script>
<!-- This shader colors each point based on the webcam texture -->
<script id="fs" type="x-shader/x-fragment">
uniform sampler2D map;
varying vec2 vUv;
void main() {
vec4 color = texture2D(map, vUv);
gl_FragColor = vec4(color.r, color.g, color.b, 0.2);
}
</script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.150.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.150.0/examples/jsm/",
"three-lens-distortion": "https://cdn.jsdelivr.net/gh/ycw/three-lens-distortion@1.0.0/src/index.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { Pass, FullScreenQuad } from "three/addons/postprocessing/Pass";
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { LuminosityShader } from 'three/addons/shaders/LuminosityShader.js';
import { SobelOperatorShader } from 'three/addons/shaders/SobelOperatorShader.js';
import { LensDistortionPassGen } from 'three-lens-distortion';
// ---------------------------------------------------------------------------
// Settings
// ---------------------------------------------------------------------------
// Scene
const INITIAL_CAMERA_Z = 1500;
// Controls GUI
let gui; // Declare gui globally
let controlsVisible = false; // Track the visibility of controls
// Webcam stream
const NEAR_CLIPPING = 2012;
const FAR_CLIPPING = 4000;
const Z_OFFSET = 706;
const POINT_SIZE = 2;
// Text display
const TEXT_CANVAS_WIDTH = 600;
const TEXT_CANVAS_HEIGHT = 480;
const FONT_SIZE = 20;
const FONT_FAMILY = 'Arial';
const TEXT_COLOR = 'rgba(255, 255, 255, 0.7)';
const LINE_HEIGHT = 24;
const TEXT_OFFSET = 50;
const FADE_HEIGHT = 0;
const MAX_TEXT_WIDTH = TEXT_CANVAS_WIDTH - 40;
// Audio
const AUDIO_GAIN = 5.0;
const CLICK_SOUND_DURATION = 80; // msec
// Websocket
const WS_VIDEO_URL = 'ws://localhost:8765';
const WS_VIDEO_FPS = 100; // msec
const WS_VIDEO_RETRY = 500; // msec
const WS_TEXT_URL = 'ws://localhost:8766';
const WS_TEXT_RETRY = 500; // msec
let scene, camera, renderer, composer, bloomPass, effectSobel, lensDistortionPass;
let mouse, center;
const initialCameraPosition = new THREE.Vector3(-63.984445903689256, 64.01760287088358, 686.1194448349208);
let targetCameraPosition = initialCameraPosition.clone();
let textMesh;
const textBuffer = []; // List of text lines
let cameraLocked = true; // Flag to lock the camera
// Variables for PositionalAudio
let listener, pinkNoise, gainNode, currentGain = AUDIO_GAIN;
let isMuted = false; // Flag to mute the sound
// Add event listener to start button
const startButton = document.getElementById('startButton');
startButton.addEventListener('click', init);
// Request webcam permission immediately
const webcamstream = navigator.mediaDevices.getUserMedia({ video: true });
// ---------------------------------------------------------------------------
// Setup scene and websockets
// ---------------------------------------------------------------------------
async function init() {
// Remove overlay after click
const overlay = document.getElementById('overlay');
overlay.remove();
const container = document.createElement('div');
document.body.appendChild(container);
// Setup camera
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.copy(initialCameraPosition);
// Setup scene and renderer
scene = new THREE.Scene();
center = new THREE.Vector3();
center.z = -1000;
renderer = renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
container.appendChild(renderer.domElement);
// Setup postprocessing
composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
// Bloom pass
bloomPass = new UnrealBloomPass(
new THREE.Vector2(window.innerWidth, window.innerHeight),
1.5, // Strength
0.4, // Radius
0.85 // Threshold
);
composer.addPass(bloomPass);
// Color to grayscale conversion
const effectGrayScale = new ShaderPass(LuminosityShader);
composer.addPass(effectGrayScale);
// Sobel operator
effectSobel = new ShaderPass(SobelOperatorShader);
effectSobel.uniforms['resolution'].value.x = window.innerWidth * window.devicePixelRatio;
effectSobel.uniforms['resolution'].value.y = window.innerHeight * window.devicePixelRatio;
effectSobel.enabled = false;
composer.addPass(effectSobel);
// Lens distortion
const LensDistortionPass = LensDistortionPassGen({ THREE, Pass, FullScreenQuad });
lensDistortionPass = new LensDistortionPass({
distortion: new THREE.Vector2(0.1, 0.1),
principalPoint: new THREE.Vector2(0.0, 0.0),
focalLength: new THREE.Vector2(1.0, 1.0),
skew: 0.0
});
composer.addPass(lensDistortionPass);
// Handle user input
mouse = new THREE.Vector3(0, 0, 1);
document.addEventListener('mousemove', onDocumentMouseMove);
document.addEventListener('mouseleave', onDocumentMouseLeave);
window.addEventListener('resize', onWindowResize);
document.addEventListener('wheel', onDocumentMouseWheel);
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
document.addEventListener('keydown', onDocumentKeyDown);
// Hide the GUI by default
gui = new GUI();
gui.hide();
// Add bloom controls to GUI
const bloomFolder = gui.addFolder('Bloom');
bloomFolder.add(bloomPass, 'strength', 0, 3, 0.01).name('Strength');
bloomFolder.add(bloomPass, 'radius', 0, 1, 0.01).name('Radius');
bloomFolder.add(bloomPass, 'threshold', 0, 1, 0.01).name('Threshold');
bloomFolder.open();
// Add Sobel edge detection enable/disable control to GUI
const sobelFolder = gui.addFolder('Sobel Edge Detection');
sobelFolder.add(effectSobel, 'enabled').name('Enable');
sobelFolder.open();
// Add lens distortion controls to GUI
const lensDistortionFolder = gui.addFolder('Lens Distortion');
lensDistortionFolder.add(lensDistortionPass.distortion, 'x', -1, 1, 0.01).name('Distortion X');
lensDistortionFolder.add(lensDistortionPass.distortion, 'y', -1, 1, 0.01).name('Distortion Y');
lensDistortionFolder.add(lensDistortionPass.principalPoint, 'x', -0.5, 0.5, 0.01).name('Principal Point X');
lensDistortionFolder.add(lensDistortionPass.principalPoint, 'y', -0.5, 0.5, 0.01).name('Principal Point Y');
lensDistortionFolder.add(lensDistortionPass.focalLength, 'x', 0, 2, 0.01).name('Focal Length X');
lensDistortionFolder.add(lensDistortionPass.focalLength, 'y', 0, 2, 0.01).name('Focal Length Y');
lensDistortionFolder.add(lensDistortionPass, 'skew', -Math.PI / 2, Math.PI / 2, 0.01).name('Skew');
lensDistortionFolder.open();
setupWebcam(webcamstream);
setupTextCanvas();
connectWebSocketVideo();
connectWebSocketText();
setupAudio();
}
function animate() {
if (!cameraLocked) {
camera.position.lerp(targetCameraPosition, 0.05);
camera.lookAt(center);
}
composer.render(); // Use composer instead of renderer
}
// ---------------------------------------------------------------------------
// Audio
// ---------------------------------------------------------------------------
function setupAudio() {
listener = new THREE.AudioListener();
camera.add(listener);
pinkNoise = createPinkNoise(listener.context);
// Create GainNode to control pinkNoise volume
gainNode = listener.context.createGain();
gainNode.gain.value = currentGain;
// Add gain control to Controls GUI
const audioFolder = gui.addFolder('Audio');
const gainControl = audioFolder.add(gainNode.gain, 'value', 0.0, AUDIO_GAIN*2, 1).name('Volume').listen();
gainControl.onChange((value) => {
if (!isMuted) {
currentGain = AUDIO_GAIN; // Update current gain value when not muted
}
});
}
function normalRandom() {
let u = 0, v = 0;
while (u === 0) u = Math.random(); // Converting [0,1) to (0,1)
while (v === 0) v = Math.random();
return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}
function createPinkNoise(audioContext) {
const bufferSize = 4096;
const node = audioContext.createScriptProcessor(bufferSize, 1, 1);
let b0, b1, b2, b3, b4, b5, b6;
b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0.0;
node.onaudioprocess = function(e) {
const output = e.outputBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
const white = normalRandom();
b0 = 0.99886 * b0 + white * 0.0555179;
b1 = 0.99332 * b1 + white * 0.0750759;
b2 = 0.96900 * b2 + white * 0.1538520;
b3 = 0.86650 * b3 + white * 0.3104856;
b4 = 0.55000 * b4 + white * 0.5329522;
b5 = -0.7616 * b5 - white * 0.0168980;
output[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362;
output[i] *= 0.11; // (roughly) compensate for gain
b6 = white * 0.115926;
output[i] /= 400; // Normalize the pink noise
output[i] /= Math.sqrt(1 - i/bufferSize); // Fade out the pink noise
}
};
return node;
}
function playClickSound() {
// Start and stop the pink noise after a short duration
pinkNoise.connect(gainNode).connect(listener.context.destination);
setTimeout(() => {
pinkNoise.disconnect();
}, CLICK_SOUND_DURATION);
}
function toggleMute(mute) {
if (mute) {
currentGain = gainNode.gain.value; // Remember the current gain
gainNode.gain.value = 0;
} else {
gainNode.gain.value = currentGain; // Restore the remembered gain
}
isMuted = mute;
}
// ---------------------------------------------------------------------------
// Setup webcam stream and transformation to 3D
// ---------------------------------------------------------------------------
async function setupWebcam(webcamstream) {
const video = document.getElementById('video');
const stream = await webcamstream
video.srcObject = stream;
video.onloadedmetadata = () => {
// Use video's native width and height
const nativeWidth = video.videoWidth;
const nativeHeight = video.videoHeight;
const texture = new THREE.VideoTexture(video);
texture.minFilter = THREE.NearestFilter;
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array(nativeWidth * nativeHeight * 3);
for (let i = 0, j = 0, l = vertices.length; i < l; i += 3, j++) {
vertices[i] = j % nativeWidth;
vertices[i + 1] = Math.floor(j / nativeWidth);
}
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
// Rest of the material and mesh setup remains the same
const material = new THREE.ShaderMaterial({
uniforms: {
'map': { value: texture },
'width': { value: TEXT_CANVAS_WIDTH },
'height': { value: TEXT_CANVAS_HEIGHT },
'nearClipping': { value: NEAR_CLIPPING },
'farClipping': { value: FAR_CLIPPING },
'pointSize': { value: POINT_SIZE },
'zOffset': { value: Z_OFFSET }
},
vertexShader: document.getElementById('vs').textContent,
fragmentShader: document.getElementById('fs').textContent,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true
});
const mesh = new THREE.Points(geometry, material);
scene.add(mesh);
const webcamFolder = gui.addFolder('Webcam');
webcamFolder.add(material.uniforms.nearClipping, 'value', 1, 10000, 1.0).name('Near Clipping');
webcamFolder.add(material.uniforms.farClipping, 'value', 1, 10000, 1.0).name('Far Clipping');
webcamFolder.add(material.uniforms.pointSize, 'value', 1, 10, 1.0).name('Point Size');
webcamFolder.add(material.uniforms.zOffset, 'value', 0, 4000, 1.0).name('Z Offset');
};
}
// ---------------------------------------------------------------------------
// Setup text canvas to display incoming text
// ---------------------------------------------------------------------------
function setupTextCanvas() {
const canvas = document.createElement('canvas');
canvas.width = TEXT_CANVAS_WIDTH;
canvas.height = TEXT_CANVAS_HEIGHT;
const context = canvas.getContext('2d');
const textTexture = new THREE.CanvasTexture(canvas);
textTexture.needsUpdate = true;
const textMaterial = new THREE.MeshBasicMaterial({
map: textTexture,
transparent: true,
});
const textGeometry = new THREE.PlaneGeometry(TEXT_CANVAS_WIDTH, TEXT_CANVAS_HEIGHT);
textMesh = new THREE.Mesh(textGeometry, textMaterial);
textMesh.position.set(0, 0, 100);
scene.add(textMesh);
}
// ---------------------------------------------------------------------------
// Setup retrying websocket for binary MJPEG out stream
// ---------------------------------------------------------------------------
function connectWebSocketVideo() {
const socket = new WebSocket(WS_VIDEO_URL);
socket.binaryType = 'arraybuffer';
socket.onopen = () => {
console.log('WebSocket connection for video opened');
setInterval(() => sendFrame(socket), WS_VIDEO_FPS);
};
socket.onclose = () => {
console.log('WebSocket connection for video closed, retrying...');
setTimeout(connectWebSocketVideo, WS_VIDEO_RETRY);
};
socket.onerror = (error) => {
console.log('WebSocket video error:', error);
socket.close();
};
}
// Send video frame through WebSocket
function sendFrame(socket) {
const video = document.getElementById('video');
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
if (socket && socket.readyState === WebSocket.OPEN) {
blob.arrayBuffer().then(buffer => {
socket.send(buffer);
});
console.log('Sent video frame');
}
}, 'image/jpeg');
}
// ---------------------------------------------------------------------------
// Setup retrying websocket for binary text in stream
// ---------------------------------------------------------------------------
function connectWebSocketText() {
const socket = new WebSocket(WS_TEXT_URL);
socket.binaryType = 'arraybuffer';
socket.onopen = () => {
console.log('WebSocket connection for text opened');
};
// Decode incoming text messages from possibly incomplete binary UTF-8 chunks
const decoder = new TextDecoder('utf-8', { stream: true });
socket.onmessage = (event) => {
const text = decoder.decode(event.data, { stream: true });
console.log('Received message:', text);
if (text) {
// Add text chunk to textBuffer (a list of lines)
const lines = text.split('\n');
lines.forEach((line, index) => {
if (index === 0) {
if (textBuffer.length > 0) {
textBuffer[textBuffer.length - 1] += line;
} else {
textBuffer.push(line);
}
} else {
textBuffer.push(line);
}
});
updateTextCanvas();
if (text.trim().length !== 0)
playClickSound();
}
};
socket.onclose = () => {
console.log('WebSocket connection for text closed, retrying...');
setTimeout(connectWebSocketText, WS_TEXT_RETRY);
};
socket.onerror = (error) => {
console.log('WebSocket text error:', error);
socket.close();
};
}
// Update the text canvas with new messages
function updateTextCanvas() {
const canvas = textMesh.material.map.image;
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = `bold ${FONT_SIZE}px ${FONT_FAMILY}`;
context.textAlign = 'left';
let currentY = TEXT_OFFSET;
let visibleText = [];
// Implement word wrapping
for (let i = 0; i < textBuffer.length; i++) {
let words = textBuffer[i].split(' ');
let currentLine = '';
words.forEach(word => {
let testLine = currentLine + word + ' ';
let testWidth = context.measureText(testLine).width;
if (testWidth > MAX_TEXT_WIDTH && currentLine !== '') {
visibleText.push(currentLine);
currentLine = word + ' ';
} else {
currentLine = testLine;
}
});
visibleText.push(currentLine);
}
while ((visibleText.length * LINE_HEIGHT) > (canvas.height - TEXT_OFFSET)) {
visibleText.shift();
}
visibleText.forEach((line, index) => {
let alpha = 1;
if (currentY < FADE_HEIGHT) {
alpha = Math.max((currentY / FADE_HEIGHT), 0);
}
context.fillStyle = `rgba(255, 255, 255, ${alpha})`;
context.fillText(line, 20, currentY);
currentY += LINE_HEIGHT;
});
textMesh.material.map.needsUpdate = true;
}
// ---------------------------------------------------------------------------
// Event handlers
// ---------------------------------------------------------------------------
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
composer.setSize(window.innerWidth, window.innerHeight); // Update composer size
effectSobel.uniforms['resolution'].value.x = window.innerWidth * window.devicePixelRatio;
effectSobel.uniforms['resolution'].value.y = window.innerHeight * window.devicePixelRatio;
}
function onDocumentMouseMove(event) {
if (!cameraLocked) {
mouse.x = (event.clientX - window.innerWidth / 2) * 8;
mouse.y = (event.clientY - window.innerHeight / 2) * 8;
targetCameraPosition.set(mouse.x, -mouse.y, camera.position.z);
}
}
function onDocumentMouseLeave(event) {
if (!cameraLocked) {
targetCameraPosition.copy(initialCameraPosition);
}
}
function onDocumentMouseWheel(event) {
camera.position.z += event.deltaY * 0.5;
}
function onDocumentTouchStart(event) {
if (event.touches.length === 1 && !cameraLocked) {
mouse.x = (event.touches[0].clientX - window.innerWidth / 2) * 8;
mouse.y = (event.touches[0].clientY - window.innerHeight / 2) * 8;
targetCameraPosition.set(mouse.x, -mouse.y, camera.position.z);
}
}
function onDocumentTouchMove(event) {
if (event.touches.length === 1 && !cameraLocked) {
mouse.x = (event.touches[0].clientX - window.innerWidth / 2) * 8;
mouse.y = (event.touches[0].clientY - window.innerHeight / 2) * 8;
targetCameraPosition.set(mouse.x, -mouse.y, camera.position.z);
}
}
function onDocumentKeyDown(event) {
if (event.code === 'Space') {
cameraLocked = !cameraLocked;
console.log('Camera (un)locked at:', camera.position);
} if (event.code === 'Delete') {
textBuffer.length = 0;
updateTextCanvas();
} else if (event.key === 'm') {
toggleMute(!isMuted);
} else if (event.key === 'c') {
controlsVisible = !controlsVisible;
if (controlsVisible) {
gui.show();
} else {
gui.hide();
}
} else if (event.key === 'h') {
const infoBox = document.getElementById('infoBox');
if (infoBox.style.display === 'none') {
infoBox.style.display = 'block';
} else {
infoBox.style.display = 'none';
}
}
}
</script>
</body>
</html>