Skip to content

Commit

Permalink
♻️ (ThreeJSAnimation.jsx): refactor ThreeJSVisualizer component to re…
Browse files Browse the repository at this point in the history
…move commented-out code and consolidate duplicate code for better maintainability and readability.
  • Loading branch information
Milan-960 committed Oct 6, 2024
1 parent ac99e0f commit e506ff7
Showing 1 changed file with 0 additions and 346 deletions.
346 changes: 0 additions & 346 deletions src/components/ThreeJSAnimation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,352 +132,6 @@
// import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// import * as Tone from "tone";

// const ThreeJSVisualizer = () => {
// const mountRef = useRef(null);
// const [isPlaying, setIsPlaying] = useState(false);
// const [toneStarted, setToneStarted] = useState(false);
// const [audioLoaded, setAudioLoaded] = useState(false); // Track if the audio is loaded
// const rendererRef = useRef(null); // To store the renderer
// const playerRef = useRef(null); // Store player instance across renders
// const animationIdRef = useRef(null); // Store animation ID
// let particles, analyser, controls;

// // Initialize Tone.js player and analyser
// useEffect(() => {
// playerRef.current = new Tone.Player({
// url: "/Baby.mp3",
// autostart: false,
// onload: () => {
// setAudioLoaded(true); // Set audio as loaded when the buffer is ready
// },
// }).toDestination();

// analyser = new Tone.Analyser("fft", 256); // Using FFT to get frequency data
// playerRef.current.connect(analyser);

// return () => {
// if (playerRef.current) {
// playerRef.current.dispose(); // Clean up player when component unmounts
// }
// };
// }, []);

// const handlePlay = async () => {
// if (!toneStarted) {
// await Tone.start(); // Ensure Tone.js is started (required in browser)
// setToneStarted(true);
// }

// // Only start playing if the audio is loaded
// if (isPlaying && audioLoaded && playerRef.current) {
// playerRef.current.start(); // Start playback
// } else if (!isPlaying && playerRef.current) {
// playerRef.current.stop(); // Stop playback
// }
// };

// useEffect(() => {
// handlePlay();
// }, [isPlaying, audioLoaded]); // Trigger handlePlay when play state changes

// // Set up Three.js scene
// useEffect(() => {
// const scene = new THREE.Scene();
// const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
// const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
// renderer.setSize(150, 150);
// renderer.setPixelRatio(window.devicePixelRatio);
// renderer.setClearColor(0x000000, 0); // Set background color to black
// mountRef.current.appendChild(renderer.domElement);
// rendererRef.current = renderer;

// // Create particle system
// const particleCount = 500;
// const geometry = new THREE.BufferGeometry();
// const positions = new Float32Array(particleCount * 3);
// const sphericalRadius = 5; // Set a spherical radius

// for (let i = 0; i < particleCount; i++) {
// // Generate random positions within a sphere
// const phi = Math.random() * Math.PI * 2;
// const theta = Math.acos(Math.random() * 2 - 1);

// positions[i * 3] = sphericalRadius * Math.sin(theta) * Math.cos(phi);
// positions[i * 3 + 1] = sphericalRadius * Math.sin(theta) * Math.sin(phi);
// positions[i * 3 + 2] = sphericalRadius * Math.cos(theta);
// }

// geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
// const material = new THREE.PointsMaterial({
// color: 0xff007f,
// size: 0.1,
// });

// particles = new THREE.Points(geometry, material);
// scene.add(particles);

// // Camera and controls
// camera.position.z = 10; // Move the camera back for better viewing of the sphere
// controls = new OrbitControls(camera, renderer.domElement);
// controls.enableZoom = false;
// controls.autoRotate = true; // Enable auto-rotation for a cooler effect
// controls.autoRotateSpeed = 1.5; // Set a reasonable speed for rotation

// // Animation loop
// const animate = () => {
// if (isPlaying && analyser) {
// const frequencyData = analyser.getValue(); // Get frequency data from Tone.js
// const positions = particles.geometry.attributes.position.array;

// // Update particle positions based on frequency data
// for (let i = 0; i < particleCount; i++) {
// // Ensure frequencyData is valid (not NaN)
// const audioFactor =
// Math.abs(frequencyData[i % frequencyData.length]) || 0; // Default to 0 if invalid
// if (!isNaN(audioFactor)) {
// positions[i * 3] += Math.sin(audioFactor) * 0.02; // Bump particles slightly
// positions[i * 3 + 1] += Math.sin(audioFactor) * 0.02;
// positions[i * 3 + 2] += Math.cos(audioFactor) * 0.02;
// }
// }

// particles.geometry.attributes.position.needsUpdate = true; // Update positions
// }

// controls.update(); // Update OrbitControls
// renderer.render(scene, camera);
// animationIdRef.current = requestAnimationFrame(animate);
// };

// animate();

// // Clean up
// return () => {
// cancelAnimationFrame(animationIdRef.current); // Cancel animation loop
// if (rendererRef.current) {
// rendererRef.current.dispose(); // Clean up renderer
// }
// };
// }, []); // Note: This runs only once

// // Toggle play/pause
// const togglePlay = () => {
// setIsPlaying(!isPlaying);
// };

// return (
// <div
// style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
// >
// <div ref={mountRef} style={{ width: "350px", height: "350px" }} />
// <button
// onClick={togglePlay}
// disabled={!audioLoaded} // Disable button until audio is loaded
// style={{
// marginTop: "10px",
// padding: "10px 20px",
// backgroundColor: audioLoaded
// ? isPlaying
// ? "#ff007f"
// : "#333"
// : "#ccc", // Adjust color if not loaded
// color: "white",
// border: "none",
// borderRadius: "5px",
// cursor: audioLoaded ? "pointer" : "not-allowed", // Disable cursor until audio is ready
// }}
// >
// {isPlaying ? "Stop" : audioLoaded ? "Play" : "Loading..."}
// </button>
// </div>
// );
// };

// export default ThreeJSVisualizer;

// import React, { useRef, useEffect, useState } from "react";
// import * as THREE from "three";
// import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// import * as Tone from "tone";

// const ThreeJSVisualizer = () => {
// const mountRef = useRef(null);
// const [isPlaying, setIsPlaying] = useState(false);
// const [toneStarted, setToneStarted] = useState(false);
// const [audioLoaded, setAudioLoaded] = useState(false); // Track if the audio is loaded
// const rendererRef = useRef(null); // To store the renderer
// const controlsRef = useRef(null); // To store OrbitControls
// const playerRef = useRef(null); // Store player instance across renders
// const animationIdRef = useRef(null); // Store animation ID
// let particles, analyser;

// // Initialize Tone.js player and analyser
// useEffect(() => {
// playerRef.current = new Tone.Player({
// url: "/Baby.mp3",
// autostart: false,
// onload: () => {
// setAudioLoaded(true); // Set audio as loaded when the buffer is ready
// },
// }).toDestination();

// analyser = new Tone.Analyser("fft", 256); // Using FFT to get frequency data
// playerRef.current.connect(analyser);

// return () => {
// if (playerRef.current) {
// playerRef.current.dispose(); // Clean up player when component unmounts
// }
// };
// }, []);

// const handlePlay = async () => {
// if (!toneStarted) {
// await Tone.start(); // Ensure Tone.js is started (required in browser)
// setToneStarted(true);
// }

// // Only start playing if the audio is loaded
// if (isPlaying && audioLoaded && playerRef.current) {
// playerRef.current.start(); // Start playback
// if (controlsRef.current) controlsRef.current.autoRotate = true; // Start rotating on play
// } else if (!isPlaying && playerRef.current) {
// playerRef.current.stop(); // Stop playback
// if (controlsRef.current) controlsRef.current.autoRotate = false; // Stop rotating on stop
// }
// };

// useEffect(() => {
// handlePlay();
// }, [isPlaying, audioLoaded]); // Trigger handlePlay when play state changes

// // Set up Three.js scene
// useEffect(() => {
// const scene = new THREE.Scene();
// const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
// const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
// renderer.setSize(150, 150);
// renderer.setPixelRatio(window.devicePixelRatio);
// renderer.setClearColor(0x000000, 0); // Set background color to black
// mountRef.current.appendChild(renderer.domElement);
// rendererRef.current = renderer;

// // Create particle system
// const particleCount = 500;
// const geometry = new THREE.BufferGeometry();
// const positions = new Float32Array(particleCount * 3);
// const sphericalRadius = 5; // Set a spherical radius

// for (let i = 0; i < particleCount; i++) {
// // Generate random positions within a sphere
// const phi = Math.random() * Math.PI * 2;
// const theta = Math.acos(Math.random() * 2 - 1);

// positions[i * 3] = sphericalRadius * Math.sin(theta) * Math.cos(phi);
// positions[i * 3 + 1] = sphericalRadius * Math.sin(theta) * Math.sin(phi);
// positions[i * 3 + 2] = sphericalRadius * Math.cos(theta);
// }

// geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
// const material = new THREE.PointsMaterial({
// color: 0xff007f,
// size: 0.1,
// });

// particles = new THREE.Points(geometry, material);
// scene.add(particles);

// // Camera and controls
// camera.position.z = 10; // Move the camera back for better viewing of the sphere
// const controls = new OrbitControls(camera, renderer.domElement);
// controls.enableZoom = false;
// controls.autoRotate = false; // Rotation starts only when the song is playing
// controlsRef.current = controls; // Store controls in ref for later access

// // Animation loop
// const animate = () => {
// if (isPlaying && analyser) {
// const frequencyData = analyser.getValue(); // Get frequency data from Tone.js
// const positions = particles.geometry.attributes.position.array;

// // Update particle positions based on frequency data
// for (let i = 0; i < particleCount; i++) {
// // Ensure frequencyData is valid (not NaN)
// const audioFactor =
// Math.abs(frequencyData[i % frequencyData.length]) || 0; // Default to 0 if invalid
// if (!isNaN(audioFactor)) {
// positions[i * 3] += Math.sin(audioFactor) * 0.02; // Bump particles slightly
// positions[i * 3 + 1] += Math.sin(audioFactor) * 0.02;
// positions[i * 3 + 2] += Math.cos(audioFactor) * 0.02;
// }
// }

// particles.geometry.attributes.position.needsUpdate = true; // Update positions
// }

// controls.update(); // Update OrbitControls
// renderer.render(scene, camera);
// animationIdRef.current = requestAnimationFrame(animate);
// };

// animate();

// // Clean up
// return () => {
// cancelAnimationFrame(animationIdRef.current); // Cancel animation loop
// if (rendererRef.current) {
// rendererRef.current.dispose(); // Clean up renderer
// }
// };
// }, []); // Note: This runs only once

// // Toggle play/pause
// const togglePlay = () => {
// setIsPlaying(!isPlaying);
// };

// return (
// <div
// ref={mountRef}
// style={{
// width: "150px",
// height: "150px",
// position: "relative", // Make the container position relative for absolute child positioning
// }}
// >
// <button
// onClick={togglePlay}
// disabled={!audioLoaded} // Disable button until audio is loaded
// style={{
// position: "absolute", // Make the button positioned inside the parent div
// top: "50%", // Center vertically
// left: "50%", // Center horizontally
// transform: "translate(-50%, -50%)", // Adjust position to be truly centered
// padding: "5px 5px",
// backgroundColor: audioLoaded
// ? isPlaying
// ? "#ff007f"
// : "#333"
// : "#ccc", // Adjust color if not loaded
// color: "white",
// border: "none",
// borderRadius: "5px",
// cursor: audioLoaded ? "pointer" : "not-allowed", // Disable cursor until audio is ready
// }}
// >
// {isPlaying ? "Stop" : audioLoaded ? "Play" : "Loading..."}
// </button>
// </div>
// );
// };

// export default ThreeJSVisualizer;

// import React, { useRef, useEffect, useState } from "react";
// import * as THREE from "three";
// import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// import * as Tone from "tone";

// const ThreeJSVisualizer = () => {
// const mountRef = useRef(null);
// const [isPlaying, setIsPlaying] = useState(false);
Expand Down

0 comments on commit e506ff7

Please sign in to comment.