music-video-gen/tv-player/index.html
2025-11-13 20:39:04 +01:00

388 lines
16 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retro TV Player</title>
<!-- Load Tailwind CSS for styling --><script src="./vendor/tailwind-3.4.17.js" x-src="https://cdn.tailwindcss.com"></script>
<!-- Load Three.js for 3D rendering --><script src="./vendor/three.min.js" x-src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="./src/tailwind-config.js"></script>
<style>
/* Dark room aesthetic */
body {
background-color: #0d0d10;
margin: 0;
overflow: hidden;
font-family: 'Inter', sans-serif;
}
canvas {
display: block;
}
/* Custom styles for the Load Tape button */
.tape-button {
transition: all 0.2s;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
.tape-button:active {
transform: translateY(1px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
</style>
</head>
<body>
<!-- Hidden Video Element --><video id="video" playsinline muted class="hidden"></video>
<!-- Controls for loading video --><div id="controls" class="fixed bottom-4 left-1/2 transform -translate-x-1/2 z-20 flex flex-col items-center space-y-2">
<!-- Hidden File Input that will be triggered by the button --><input type="file" id="fileInput" accept="video/mp4" class="hidden" multiple>
<div class="flex space-x-4">
<!-- Load Tapes Button --><button id="loadTapeButton" class="tape-button px-8 py-3 bg-tape-red text-white font-bold text-lg uppercase tracking-wider rounded-lg hover:bg-red-700 transition duration-150">
Load tapes
</button>
</div>
</div>
<script src="./src/global-variables.js"></script>
<script src="./src/utils.js"></script>
<script src="./src/scene.js"></script>
<script src="./src/effects_dust.js"></script>
<script src="./src/effects_flies.js"></script>
<script src="./src/vcr-display.js"></script>
<script src="./src/init.js"></script>
<!-- 3D Canvas will be injected here by Three.js -->
<script>
// --- Initialization ---
function init() {
// 1. Scene Setup (Dark, Ambient)
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
// 2. Camera Setup
const FOV = 65;
camera = new THREE.PerspectiveCamera(FOV, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 1.5, 4);
// 3. Renderer Setup
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Enable shadows on the renderer
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Softer shadows
container.appendChild(renderer.domElement);
// 4. Lighting (Minimal and focused)
const ambientLight = new THREE.AmbientLight(0x111111);
scene.add(ambientLight);
const roomLight = new THREE.PointLight(0xffaa55, 0.05, roomSize);
roomLight.position.set(0, 1.8, 0);
scene.add(roomLight);
// 5. Build the entire scene with TV and surrounding objects
createSceneObjects();
// 6. Create the Dust Particle System
createDust();
// 7. Create the Room Walls and Ceiling
createRoomWalls();
// --- 8. Debug Visualization Helpers ---
// Visual aids for the light source positions
if (debugLight && THREE.PointLightHelper) {
const screenHelper = new THREE.PointLightHelper(screenLight, 0.1, 0xff0000); // Red for screen
scene.add(screenHelper);
// Lamp Helper will now work since lampLight is added to the scene
const lampHelperPoint = new THREE.PointLightHelper(lampLightPoint, 0.1, 0x00ff00); // Green for lamp
scene.add(lampHelperPoint);
}
// 9. Event Listeners
window.addEventListener('resize', onWindowResize, false);
fileInput.addEventListener('change', loadVideoFile);
// Button logic
loadTapeButton.addEventListener('click', () => {
fileInput.click();
});
// Auto-advance to the next video when the current one finishes.
videoElement.addEventListener('ended', playNextVideo);
// Start the animation loop
animate();
}
// --- Helper function to format seconds into MM:SS ---
function formatTime(seconds) {
if (isNaN(seconds) || seconds === Infinity || seconds < 0) return '--:--';
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.floor(seconds % 60);
const paddedMinutes = String(minutes).padStart(2, '0');
const paddedSeconds = String(remainingSeconds).padStart(2, '0');
return `${paddedMinutes}:${paddedSeconds}`;
}
// --- Play video by index ---
function playVideoByIndex(index) {
currentVideoIndex = index;
const url = videoUrls[index];
// Dispose of previous texture to free resources
if (videoTexture) {
videoTexture.dispose();
videoTexture = null;
}
if (index < 0 || index >= videoUrls.length) {
console.info('End of playlist reached. Reload tapes to start again.');
screenLight.intensity = 0.0;
tvScreen.material.dispose();
tvScreen.material = new THREE.MeshPhongMaterial({
color: 0x0a0a0a, // Deep black
shininess: 5,
specular: 0x111111
});
tvScreen.material.needsUpdate = true;
isVideoLoaded = false;
lastUpdateTime = -1; // force VCR to redraw
return;
}
videoElement.src = url;
videoElement.muted = true;
videoElement.load();
// Set loop property: only loop if it's the only video loaded
videoElement.loop = false; //videoUrls.length === 1;
videoElement.onloadeddata = () => {
// 1. Create the Three.js texture
videoTexture = new THREE.VideoTexture(videoElement);
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
videoTexture.format = THREE.RGBAFormat;
videoTexture.needsUpdate = true;
// 2. Apply the video texture to the screen mesh
tvScreen.material.dispose();
tvScreen.material = new THREE.MeshBasicMaterial({ map: videoTexture });
tvScreen.material.needsUpdate = true;
// 3. Start playback
videoElement.play().then(() => {
isVideoLoaded = true;
// Use the defined base intensity for screen glow
screenLight.intensity = originalScreenIntensity;
// Initial status message with tape count
console.info(`Playing tape ${currentVideoIndex + 1} of ${videoUrls.length}.`);
}).catch(error => {
screenLight.intensity = originalScreenIntensity * 0.5; // Dim the light if playback fails
console.error(`Playback blocked for tape ${currentVideoIndex + 1}. Click Next Tape to try again.`);
console.error('Playback Error: Could not start video playback.', error);
});
};
videoElement.onerror = (e) => {
screenLight.intensity = 0.1; // Keep minimum intensity for shadow map
console.error(`Error loading tape ${currentVideoIndex + 1}.`);
console.error('Video Load Error:', e);
};
}
// --- Cycle to the next video ---
function playNextVideo() {
// Determine the next index, cycling back to 0 if we reach the end
let nextIndex = currentVideoIndex + 1;
if (nextIndex < videoUrls.length) {
baseTime += videoElement.duration;
}
playVideoByIndex(nextIndex);
}
// --- Video Loading Logic (handles multiple files) ---
function loadVideoFile(event) {
const files = event.target.files;
if (files.length === 0) {
console.info('File selection cancelled.');
return;
}
// 1. Clear previous URLs and revoke object URLs to prevent memory leaks
videoUrls.forEach(url => URL.revokeObjectURL(url));
videoUrls = [];
// 2. Populate the new videoUrls array
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('video/')) {
videoUrls.push(URL.createObjectURL(file));
}
}
if (videoUrls.length === 0) {
console.info('No valid video files selected.');
return;
}
// 3. Start playback of the first video
console.info(`Loaded ${videoUrls.length} tapes. Starting playback...`);
loadTapeButton.classList.add("hidden");
const startDelay = 5;
console.info(`Video will start in ${startDelay} seconds.`);
setTimeout(() => { playVideoByIndex(0); }, startDelay * 1000);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
// 1. Dust animation: slow downward drift
if (dust) {
const positions = dust.geometry.attributes.position.array;
for (let i = 1; i < positions.length; i += 3) {
positions[i] -= 0.001;
if (positions[i] < -2) {
positions[i] = 8;
}
}
dust.geometry.attributes.position.needsUpdate = true;
}
// 2. Camera movement (Gentle, random hovering)
const globalTime = Date.now() * 0.00005;
const lookAtTime = Date.now() * 0.00003;
const camAmplitude = 0.7;
const lookAmplitude = 0.05;
// Base Camera Position in front of the TV
const baseX = -0.5;
const baseY = 1.5;
const baseZ = 2.5;
// Base LookAt target (Center of the screen)
const baseTargetX = -0.7;
const baseTargetY = 1.7;
const baseTargetZ = -0.3;
// Camera Position Offsets (Drift)
const camOffsetX = Math.sin(globalTime * 3.1) * camAmplitude;
const camOffsetY = Math.cos(globalTime * 2.5) * camAmplitude * 0.4;
const camOffsetZ = Math.cos(globalTime * 3.2) * camAmplitude * 1.4;
camera.position.x = baseX + camOffsetX;
camera.position.y = baseY + camOffsetY;
camera.position.z = baseZ + camOffsetZ;
// LookAt Target Offsets (Subtle Gaze Shift)
const lookOffsetX = Math.sin(lookAtTime * 1.5) * lookAmplitude;
const lookOffsetY = Math.cos(lookAtTime * 1.2) * lookAmplitude;
// Apply lookAt to the subtly shifted target
camera.lookAt(
baseTargetX + lookOffsetX,
baseTargetY + lookOffsetY,
baseTargetZ
);
// 3. Lamp Flicker Effect
const flickerChance = 0.995;
const restoreRate = 0.15;
if (Math.random() > flickerChance) {
// Flickers quickly to a dimmer random value (between 0.3 and 1.05)
let lampLightIntensity = originalLampIntensity * (0.3 + Math.random() * 0.7);
lampLightSpot.intensity = lampLightIntensity;
lampLightPoint.intensity = lampLightIntensity;
} else if (lampLightPoint.intensity < originalLampIntensity) {
// Smoothly restore original intensity
let lampLightIntensity = THREE.MathUtils.lerp(lampLightPoint.intensity, originalLampIntensity, restoreRate);
lampLightSpot.intensity = lampLightIntensity;
lampLightPoint.intensity = lampLightIntensity;
}
// 4. Screen Light Pulse and Movement Effect (Updated)
if (isVideoLoaded && screenLight.intensity > 0) {
// A. Pulse Effect (Intensity Fluctuation)
// Generate a small random fluctuation for the pulse (Range: 1.35 to 1.65 around base 1.5)
const pulseTarget = originalScreenIntensity + (Math.random() - 0.5) * screenIntensityPulse;
// Smoothly interpolate towards the new target fluctuation
screenLight.intensity = THREE.MathUtils.lerp(screenLight.intensity, pulseTarget, 0.1);
// B. Movement Effect (Subtle circle around the screen center - circling the room area)
const lightTime = Date.now() * 0.0001;
const radius = 0.01;
const centerX = 0;
const centerY = 1.5;
//const centerZ = 1.2; // Use the updated Z position of the light source
// Move the light in a subtle, erratic circle
screenLight.position.x = centerX + Math.cos(lightTime) * radius;
screenLight.position.y = centerY + Math.sin(lightTime * 1.5) * radius * 0.5; // Slightly different freq for Y
//screenLight.position.z = centerZ; // Keep Z constant at the screen light plane
}
// 5. Update video texture (essential to grab the next frame)
if (videoTexture) {
videoTexture.needsUpdate = true;
// Update time display in the animation loop
if (isVideoLoaded && videoElement.readyState >= 3) {
const currentTime = formatTime(videoElement.currentTime);
const duration = formatTime(videoElement.duration);
console.info(`Tape ${currentVideoIndex + 1} of ${videoUrls.length}. Time: ${currentTime} / ${duration}`);
}
}
updateFlies();
const currentTime = baseTime + videoElement.currentTime;
// Simulate playback time
if (Math.abs(currentTime - lastUpdateTime) > 0.1) {
updateVcrDisplay(currentTime);
lastUpdateTime = currentTime;
}
// Blink the colon every second
if (currentTime - lastBlinkToggleTime > 0.5) { // Blink every 0.5 seconds
blinkState = !blinkState;
lastBlinkToggleTime = currentTime;
}
// RENDER!
renderer.render(scene, camera);
}
// --- Window Resize Handler ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Start everything on window load
window.onload = init;
</script>
</body>
</html>
<!-- textures sourced from https://animalia-life.club/ -->