Upload SUPER_NOVA.html
Browse files
NeuroPort/HTML+APPS/SUPER_NOVA.html
ADDED
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE html>
|
2 |
+
<html lang="ru">
|
3 |
+
<head>
|
4 |
+
<meta charset="UTF-8">
|
5 |
+
<title>Super-Nova Music Visualiser</title>
|
6 |
+
<style>
|
7 |
+
body { margin: 0; background-color: #000; overflow: hidden; cursor: default; }
|
8 |
+
canvas {
|
9 |
+
position: fixed;
|
10 |
+
top: 0;
|
11 |
+
left: 0;
|
12 |
+
z-index: 1;
|
13 |
+
}
|
14 |
+
#setup {
|
15 |
+
position: absolute; top: 50%; left: 50%;
|
16 |
+
transform: translate(-50%, -50%);
|
17 |
+
color: #fff; font-family: monospace; text-align: center;
|
18 |
+
border: 1px solid #fff; padding: 2em;
|
19 |
+
background-color: rgba(0,0,0,0.85);
|
20 |
+
max-width: 600px;
|
21 |
+
box-shadow: 0 0 20px rgba(255,255,255,0.2);
|
22 |
+
z-index: 10;
|
23 |
+
}
|
24 |
+
#setup h2 {
|
25 |
+
margin-top: 0;
|
26 |
+
font-size: 1.8em;
|
27 |
+
color: #fff;
|
28 |
+
text-shadow: 0 0 10px rgba(255,255,255,0.5);
|
29 |
+
}
|
30 |
+
#setup .description, #setup .instructions {
|
31 |
+
font-size: 0.95em;
|
32 |
+
line-height: 1.6;
|
33 |
+
text-align: left;
|
34 |
+
margin: 1.5em auto;
|
35 |
+
color: #ccc;
|
36 |
+
}
|
37 |
+
#setup h3 {
|
38 |
+
margin-top: 2em;
|
39 |
+
border-bottom: 1px solid #555;
|
40 |
+
padding-bottom: 0.5em;
|
41 |
+
color: #eee;
|
42 |
+
}
|
43 |
+
#setup strong { color: #fff; font-weight: bold; }
|
44 |
+
#setup ul {
|
45 |
+
padding-left: 20px;
|
46 |
+
text-align: left;
|
47 |
+
}
|
48 |
+
#setup li { margin-bottom: 0.5em; }
|
49 |
+
#setup select, #setup button {
|
50 |
+
display: block;
|
51 |
+
width: 100%;
|
52 |
+
margin-top: 1em;
|
53 |
+
padding: 0.8em;
|
54 |
+
background-color: #333;
|
55 |
+
color: #fff;
|
56 |
+
border: 1px solid #888;
|
57 |
+
font-family: monospace;
|
58 |
+
font-size: 1em;
|
59 |
+
cursor: pointer;
|
60 |
+
box-sizing: border-box;
|
61 |
+
transition: background-color 0.2s;
|
62 |
+
}
|
63 |
+
#setup button:hover {
|
64 |
+
background-color: #555;
|
65 |
+
}
|
66 |
+
#setup button:disabled { background-color: #222; color: #666; cursor: not-allowed; }
|
67 |
+
.button-description {
|
68 |
+
font-size: 0.8em;
|
69 |
+
color: #888;
|
70 |
+
margin-top: 0.5em;
|
71 |
+
text-align: center;
|
72 |
+
}
|
73 |
+
</style>
|
74 |
+
</head>
|
75 |
+
<body>
|
76 |
+
<div id="setup">
|
77 |
+
<h2>SUPER-NOVA VISUALISER</h2>
|
78 |
+
|
79 |
+
<!-- [ВОССТАНОВЛЕНО] Полное описание проекта -->
|
80 |
+
<div class="description">
|
81 |
+
<p>Это <strong>интерактивный аудио-визуализатор</strong>, который в реальном времени преобразует звук в динамическую 3D-сцену. Он анализирует частотный спектр аудиопотока и использует эти данные для управления анимацией:</p>
|
82 |
+
<ul>
|
83 |
+
<li><strong>Центральное ядро:</strong> Пульсирует в такт басовым частотам.</li>
|
84 |
+
<li><strong>Вращающиеся кольца:
|
85 |
+
</strong> Реагируют на средние и высокие частоты, получая импульсы вращения от резких звуков.</li>
|
86 |
+
<li><strong>Поле частиц:</strong> Его плотность и турбулентность зависят от общей громкости звука.</li>
|
87 |
+
<li><strong>Эффекты:</strong> Свечение (Bloom) и хроматическая аберрация усиливаются в зависимости от силы баса и верхов.</li>
|
88 |
+
</ul>
|
89 |
+
</div>
|
90 |
+
|
91 |
+
<!-- [ИСПРАВЛЕНО] Инструкция по использованию с учетом новой логики -->
|
92 |
+
<div class="instructions">
|
93 |
+
<h3>Инструкция по использованию</h3>
|
94 |
+
<p><strong>1. Микрофон:</strong><br>
|
95 |
+
Нажмите "Начать с микрофона". Браузер запросит доступ. Если доступ разрешен, появится список доступных микрофонов. Выберите нужный и нажмите "Подтвердить и запустить".</p>
|
96 |
+
|
97 |
+
<p><strong>2. Звук системы / вкладки:</strong><br>
|
98 |
+
Лучший вариант для музыки из YouTube, плееров и т.д.
|
99 |
+
Нажмите кнопку, и в появившемся окне браузера <strong>ОБЯЗАТЕЛЬНО ПОСТАВЬТЕ ГАЛОЧКУ</strong> "Поделиться звуком системы" (Share system audio) или "Поделиться звуком вкладки" (Share tab audio). Без этого визуализация не будет получать звук.</p>
|
100 |
+
</div>
|
101 |
+
|
102 |
+
<!-- [ИСПРАВЛЕНО] Логика выбора исто��ника с предупреждениями и двухэтапным выбором для микрофона -->
|
103 |
+
<div id="mic-step-1">
|
104 |
+
<button id="init-mic">Начать с микрофона</button>
|
105 |
+
<p class="button-description">(Браузер запросит разрешение на использование микрофона)</p>
|
106 |
+
</div>
|
107 |
+
<div id="mic-step-2" style="display: none;">
|
108 |
+
<p>Выберите устройство:</p>
|
109 |
+
<select id="mic-select"></select>
|
110 |
+
<button id="start-mic-confirm">Подтвердить и запустить</button>
|
111 |
+
</div>
|
112 |
+
|
113 |
+
<hr style="border-color: #444; margin: 2em 0;">
|
114 |
+
|
115 |
+
<div id="system-audio-step">
|
116 |
+
<button id="start-system">Начать со звука системы / вкладки</button>
|
117 |
+
<p class="button-description">(Браузер запросит разрешение на захват экрана/вкладки со звуком)</p>
|
118 |
+
</div>
|
119 |
+
</div>
|
120 |
+
|
121 |
+
<!-- Canvas будет создан здесь скриптом -->
|
122 |
+
|
123 |
+
<script type="importmap">
|
124 |
+
{
|
125 |
+
"imports": {
|
126 |
+
"three": "https://unpkg.com/[email protected]/build/three.module.js",
|
127 |
+
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
|
128 |
+
}
|
129 |
+
}
|
130 |
+
</script>
|
131 |
+
<script type="module">
|
132 |
+
import * as THREE from 'three';
|
133 |
+
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
|
134 |
+
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
|
135 |
+
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
|
136 |
+
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
|
137 |
+
|
138 |
+
let scene, camera, renderer, analyser, composer, mainObject, ringsGroup, particles;
|
139 |
+
const visualGroup = new THREE.Group();
|
140 |
+
const clock = new THREE.Clock();
|
141 |
+
let waveformData;
|
142 |
+
let micPermissionStream = null; // [ИЗМЕНЕНО] Хранит поток, полученный при первом запросе разрешения
|
143 |
+
|
144 |
+
const setupDiv = document.getElementById('setup');
|
145 |
+
const micStep1Div = document.getElementById('mic-step-1');
|
146 |
+
const micStep2Div = document.getElementById('mic-step-2');
|
147 |
+
const initMicButton = document.getElementById('init-mic');
|
148 |
+
const micSelect = document.getElementById('mic-select');
|
149 |
+
const startMicConfirmButton = document.getElementById('start-mic-confirm');
|
150 |
+
const startSystemButton = document.getElementById('start-system');
|
151 |
+
|
152 |
+
function init() {
|
153 |
+
scene = new THREE.Scene();
|
154 |
+
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
|
155 |
+
camera.position.z = 14;
|
156 |
+
renderer = new THREE.WebGLRenderer({ antialias: true });
|
157 |
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
158 |
+
document.body.appendChild(renderer.domElement);
|
159 |
+
scene.add(visualGroup);
|
160 |
+
createVisuals();
|
161 |
+
setupPostProcessing();
|
162 |
+
window.addEventListener('resize', onWindowResize);
|
163 |
+
animate();
|
164 |
+
}
|
165 |
+
|
166 |
+
function onWindowResize() {
|
167 |
+
camera.aspect = window.innerWidth / window.innerHeight;
|
168 |
+
camera.updateProjectionMatrix();
|
169 |
+
renderer.setSize(window.innerWidth, window.innerHeight);
|
170 |
+
if (composer) composer.setSize(window.innerWidth, window.innerHeight);
|
171 |
+
}
|
172 |
+
|
173 |
+
function connectAudio(stream) {
|
174 |
+
// Останавливаем все предыдущие активные потоки, чтобы избежать конфликтов и утечек
|
175 |
+
if (micPermissionStream) {
|
176 |
+
micPermissionStream.getTracks().forEach(track => track.stop());
|
177 |
+
micPermissionStream = null;
|
178 |
+
}
|
179 |
+
// Если переключаемся с системного звука, его тоже надо остановить
|
180 |
+
// (хотя getDisplayMedia обычно сам за этим следит при закрытии окна/вкладки)
|
181 |
+
// Но для надежности можно добавить логику для системного потока, если он где-то хранится.
|
182 |
+
|
183 |
+
setupDiv.style.display = 'none';
|
184 |
+
document.body.style.cursor = 'none';
|
185 |
+
|
186 |
+
const listener = new THREE.AudioListener();
|
187 |
+
const source = listener.context.createMediaStreamSource(stream);
|
188 |
+
analyser = new THREE.AudioAnalyser(new THREE.Audio(listener), 1024);
|
189 |
+
waveformData = new Uint8Array(analyser.analyser.fftSize);
|
190 |
+
source.connect(analyser.analyser);
|
191 |
+
}
|
192 |
+
|
193 |
+
// [ИСПРАВЛЕНО] Логика запроса и запуска микрофона - ОДИН запрос
|
194 |
+
initMicButton.addEventListener('click', async () => {
|
195 |
+
initMicButton.disabled = true; // Отключаем кнопку, чтобы избежать повторных кликов
|
196 |
+
|
197 |
+
try {
|
198 |
+
// [ВАЖНО] Это ЕДИНСТВЕННЫЙ вызов getUserMedia, который запросит разрешение.
|
199 |
+
// Полученный поток `stream` позволит `enumerateDevices` получить полные названия.
|
200 |
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
201 |
+
micPermissionStream = stream; // Сохраняем этот поток для дальнейшего использования
|
202 |
+
|
203 |
+
// Теперь, когда разрешение есть, получаем полный список устройств с их названиями.
|
204 |
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
205 |
+
const audioDevices = devices.filter(device => device.kind === 'audioinput');
|
206 |
+
|
207 |
+
micSelect.innerHTML = '';
|
208 |
+
if (audioDevices.length === 0) {
|
209 |
+
alert("Микрофоны не найдены.");
|
210 |
+
micPermissionStream.getTracks().forEach(track => track.stop()); // Останавливаем поток, если нечего выбрать
|
211 |
+
micPermissionStream = null;
|
212 |
+
initMicButton.disabled = false; // Включаем кнопку обратно
|
213 |
+
return;
|
214 |
+
}
|
215 |
+
|
216 |
+
// Заполняем список микрофонов
|
217 |
+
audioDevices.forEach(device => {
|
218 |
+
const option = document.createElement('option');
|
219 |
+
option.value = device.deviceId;
|
220 |
+
option.textContent = device.label || `Микрофон ${micSelect.options.length + 1}`;
|
221 |
+
micSelect.appendChild(option);
|
222 |
+
});
|
223 |
+
|
224 |
+
// Пытаемся выбрать в списке тот микрофон, который уже активен в `micPermissionStream`
|
225 |
+
const activeMicTrack = micPermissionStream.getAudioTracks()[0];
|
226 |
+
if (activeMicTrack && activeMicTrack.deviceId) {
|
227 |
+
micSelect.value = activeMicTrack.deviceId;
|
228 |
+
}
|
229 |
+
|
230 |
+
// Показываем второй шаг выбора микрофона
|
231 |
+
micStep1Div.style.display = 'none';
|
232 |
+
micStep2Div.style.display = 'block';
|
233 |
+
|
234 |
+
} catch (e) {
|
235 |
+
console.error('Ошибка доступа к микрофону:', e);
|
236 |
+
if (e.name === "NotAllowedError" || e.name === "PermissionDeniedError") {
|
237 |
+
alert("Вы не предоставили доступ к микрофону. Визуализация не сможет использовать микрофон.");
|
238 |
+
} else {
|
239 |
+
alert(`Не удалось получить доступ к микрофону. Ошибка: ${e.name}.`);
|
240 |
+
}
|
241 |
+
initMicButton.disabled = false; // Включаем кнопку обратно, если была ошибка
|
242 |
+
}
|
243 |
+
});
|
244 |
+
|
245 |
+
startMicConfirmButton.addEventListener('click', async () => {
|
246 |
+
const selectedDeviceId = micSelect.value;
|
247 |
+
const currentActiveDeviceId = micPermissionStream?.getAudioTracks()[0]?.deviceId;
|
248 |
+
|
249 |
+
if (selectedDeviceId === currentActiveDeviceId) {
|
250 |
+
// Если выбран тот же микрофон, который уже активен в micPermissionStream,
|
251 |
+
// просто используем его. Нет необходимости в новом getUserMedia().
|
252 |
+
connectAudio(micPermissionStream);
|
253 |
+
} else {
|
254 |
+
// Если выбран другой микрофон, нужно получить новый поток.
|
255 |
+
// [ВАЖНО] Разрешение уже дано, поэтому getUserMedia не будет запрашивать его повторно.
|
256 |
+
// Используем deviceId напрямую, чтобы избежать OverconstrainedError.
|
257 |
+
try {
|
258 |
+
const newStream = await navigator.mediaDevices.getUserMedia({ audio: { deviceId: selectedDeviceId } });
|
259 |
+
connectAudio(newStream);
|
260 |
+
// Важно: старый micPermissionStream уже остановлен в connectAudio
|
261 |
+
micPermissionStream = newStream; // Обновляем ссылку на текущий активный поток
|
262 |
+
} catch (e) {
|
263 |
+
console.error('Не удалось запустить с выбранного микрофона:', e);
|
264 |
+
alert(`Не удалось подключиться к выбранному микрофону. ��озможно, он занят или был отключен. Ошибка: ${e.name}.`);
|
265 |
+
|
266 |
+
// Если не удалось, возвращаем интерфейс выбора
|
267 |
+
micStep1Div.style.display = 'block';
|
268 |
+
micStep2Div.style.display = 'none';
|
269 |
+
initMicButton.disabled = false; // Включаем кнопку "Начать с микрофона"
|
270 |
+
}
|
271 |
+
}
|
272 |
+
});
|
273 |
+
|
274 |
+
startSystemButton.addEventListener('click', () => {
|
275 |
+
navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
|
276 |
+
.then(stream => {
|
277 |
+
connectAudio(stream);
|
278 |
+
})
|
279 |
+
.catch(e => {
|
280 |
+
if (e.name !== 'NotAllowedError' && e.name !== 'PermissionDeniedError') {
|
281 |
+
console.error('Не удалось захватить звук системы/вкладки:', e);
|
282 |
+
} else if (e.name === 'NotAllowedError' || e.name === 'PermissionDeniedError') {
|
283 |
+
alert('Вы не предоставили доступ к захвату экрана/вкладки. Визуализация не сможет получить звук системы.');
|
284 |
+
}
|
285 |
+
});
|
286 |
+
});
|
287 |
+
|
288 |
+
const ChromaticAberrationShader = {
|
289 |
+
uniforms: { tDiffuse: { value: null }, uAmount: { value: 0.0 } },
|
290 |
+
vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
|
291 |
+
fragmentShader: `uniform sampler2D tDiffuse; uniform float uAmount; varying vec2 vUv; void main() { vec2 offset = uAmount * 0.005 * (vUv - 0.5); vec4 cR = texture2D(tDiffuse, vUv + offset); vec4 cG = texture2D(tDiffuse, vUv); vec4 cB = texture2D(tDiffuse, vUv - offset); gl_FragColor = vec4(cR.r, cG.g, cB.b, cG.a); }`
|
292 |
+
};
|
293 |
+
|
294 |
+
function getAvg(data, start, end) {
|
295 |
+
let sum = 0; for (let i = start; i < end; i++) { sum += data[i]; }
|
296 |
+
return (sum / (end - start)) / 255;
|
297 |
+
}
|
298 |
+
|
299 |
+
function createVisuals() {
|
300 |
+
const coreMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe: true });
|
301 |
+
mainObject = new THREE.Mesh(new THREE.IcosahedronGeometry(1.5, 8), coreMaterial);
|
302 |
+
mainObject.userData.initialVertices = mainObject.geometry.attributes.position.clone();
|
303 |
+
visualGroup.add(mainObject);
|
304 |
+
|
305 |
+
const ringMaterial = new THREE.MeshBasicMaterial({ color: 0x555555, wireframe: true, transparent: true, opacity: 0.7 });
|
306 |
+
ringsGroup = new THREE.Group();
|
307 |
+
visualGroup.add(ringsGroup);
|
308 |
+
for (let i = 0; i < 4; i++) {
|
309 |
+
const ringGeo = new THREE.TorusGeometry(4.5 + i * 1.0, 0.015, 32, 200);
|
310 |
+
const ring = new THREE.Mesh(ringGeo, ringMaterial.clone());
|
311 |
+
ring.userData.initialVertices = ring.geometry.attributes.position.clone();
|
312 |
+
const pivot = new THREE.Group();
|
313 |
+
pivot.add(ring);
|
314 |
+
pivot.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, 0);
|
315 |
+
|
316 |
+
const baseSpeedMagnitude = 0.015 - i * 0.004;
|
317 |
+
const inertiaFactor = 1.0 + i * 1.5;
|
318 |
+
|
319 |
+
pivot.userData = {
|
320 |
+
baseSpeed: new THREE.Vector2(
|
321 |
+
baseSpeedMagnitude * (Math.random() > 0.5 ? 1 : -1),
|
322 |
+
baseSpeedMagnitude * 0.5 * (Math.random() > 0.5 ? 1 : -1)
|
323 |
+
),
|
324 |
+
impulseVelocity: new THREE.Vector2(),
|
325 |
+
inertia: inertiaFactor,
|
326 |
+
cooldownTimer: 0
|
327 |
+
};
|
328 |
+
ringsGroup.add(pivot);
|
329 |
+
}
|
330 |
+
|
331 |
+
const particleCount = 15000;
|
332 |
+
const particleGeo = new THREE.BufferGeometry();
|
333 |
+
const positions = new Float32Array(particleCount * 3);
|
334 |
+
const initialPositions = new Float32Array(particleCount * 3);
|
335 |
+
for (let i = 0; i < particleCount; i++) {
|
336 |
+
const r = 10 + Math.random() * 15;
|
337 |
+
const theta = Math.random() * Math.PI * 2;
|
338 |
+
const phi = Math.acos((Math.random() * 2) - 1);
|
339 |
+
const x = r * Math.sin(phi) * Math.cos(theta);
|
340 |
+
const y = r * Math.sin(phi) * Math.sin(theta);
|
341 |
+
const z = r * Math.cos(phi);
|
342 |
+
positions[i*3] = x; initialPositions[i*3] = x;
|
343 |
+
positions[i*3+1] = y; initialPositions[i*3+1] = y;
|
344 |
+
positions[i*3+2] = z; initialPositions[i*3+2] = z;
|
345 |
+
}
|
346 |
+
particleGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
|
347 |
+
particles = new THREE.Points(particleGeo, new THREE.PointsMaterial({ color: 0xaaaaaa, size: 0.03, transparent: true, opacity: 0.4, sizeAttenuation: true }));
|
348 |
+
particles.userData.initialPositions = initialPositions;
|
349 |
+
visualGroup.add(particles);
|
350 |
+
}
|
351 |
+
|
352 |
+
function setupPostProcessing() {
|
353 |
+
composer = new EffectComposer(renderer);
|
354 |
+
composer.addPass(new RenderPass(scene, camera));
|
355 |
+
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 0.4, 0.5, 0.1);
|
356 |
+
composer.addPass(bloomPass);
|
357 |
+
const chromaticPass = new ShaderPass(ChromaticAberrationShader);
|
358 |
+
composer.addPass(chromaticPass);
|
359 |
+
}
|
360 |
+
|
361 |
+
function animate() {
|
362 |
+
requestAnimationFrame(animate);
|
363 |
+
const delta = clock.getDelta();
|
364 |
+
const time = clock.getElapsedTime();
|
365 |
+
|
366 |
+
visualGroup.rotation.y += 0.0005;
|
367 |
+
visualGroup.rotation.x += 0.0002;
|
368 |
+
|
369 |
+
ringsGroup.children.forEach((pivot) => {
|
370 |
+
pivot.rotation.x += pivot.userData.baseSpeed.x * delta * 60;
|
371 |
+
pivot.rotation.y += pivot.userData.baseSpeed.y * delta * 60;
|
372 |
+
pivot.userData.impulseVelocity.multiplyScalar(0.97);
|
373 |
+
pivot.rotation.x += pivot.userData.impulseVelocity.x;
|
374 |
+
pivot.rotation.y += pivot.userData.impulseVelocity.y;
|
375 |
+
});
|
376 |
+
|
377 |
+
if (analyser) {
|
378 |
+
analyser.analyser.getByteTimeDomainData(waveformData);
|
379 |
+
const freqData = analyser.getFrequencyData();
|
380 |
+
const bass = getAvg(freqData, 0, 5);
|
381 |
+
const highs = getAvg(freqData, 100, 256);
|
382 |
+
const overall = getAvg(freqData, 0, 256);
|
383 |
+
const ringFreqs = [ getAvg(freqData, 60, 100), getAvg(freqData, 20, 50), getAvg(freqData, 6, 15), getAvg(freqData, 1, 5) ];
|
384 |
+
|
385 |
+
const corePositions = mainObject.geometry.attributes.position;
|
386 |
+
const coreInitial = mainObject.userData.initialVertices;
|
387 |
+
const noiseFactor = bass * 0.4;
|
388 |
+
for (let i = 0; i < corePositions.count; i++) {
|
389 |
+
const p = new THREE.Vector3().fromBufferAttribute(coreInitial, i);
|
390 |
+
p.add(p.clone().normalize().multiplyScalar(noiseFactor * (0.5 + Math.sin(time * 3 + i * 0.5))));
|
391 |
+
corePositions.setXYZ(i, p.x, p.y, p.z);
|
392 |
+
}
|
393 |
+
corePositions.needsUpdate = true;
|
394 |
+
|
395 |
+
ringsGroup.children.forEach((pivot, i) => {
|
396 |
+
pivot.userData.cooldownTimer = Math.max(0, pivot.userData.cooldownTimer - delta);
|
397 |
+
const freqPower = ringFreqs[i];
|
398 |
+
if (freqPower > 0.35 && pivot.userData.cooldownTimer <= 0) {
|
399 |
+
const impulseStrength = (freqPower - 0.2) * 0.22 / pivot.userData.inertia;
|
400 |
+
pivot.userData.impulseVelocity.x += impulseStrength * Math.sign(pivot.userData.baseSpeed.x);
|
401 |
+
pivot.userData.impulseVelocity.y += impulseStrength * 0.3 * (Math.random() - 0.5);
|
402 |
+
pivot.userData.cooldownTimer = 0.075;
|
403 |
+
}
|
404 |
+
const ring = pivot.children[0];
|
405 |
+
const ringPos = ring.geometry.attributes.position;
|
406 |
+
const ringInitial = ring.userData.initialVertices;
|
407 |
+
const normals = ring.geometry.attributes.normal;
|
408 |
+
for (let j = 0; j < ringPos.count; j++) {
|
409 |
+
const p = new THREE.Vector3().fromBufferAttribute(ringInitial, j);
|
410 |
+
const n = new THREE.Vector3().fromBufferAttribute(normals, j);
|
411 |
+
const uvx = ring.geometry.attributes.uv.getX(j);
|
412 |
+
const waveIndex = Math.floor(uvx * (waveformData.length - 1));
|
413 |
+
const displacement = (waveformData[waveIndex] / 128.0 - 1.0);
|
414 |
+
p.add(n.multiplyScalar(displacement * 1.0));
|
415 |
+
ringPos.setXYZ(j, p.x, p.y, p.z);
|
416 |
+
}
|
417 |
+
ringPos.needsUpdate = true;
|
418 |
+
});
|
419 |
+
|
420 |
+
particles.material.size = 0.03 + overall * 0.05;
|
421 |
+
particles.material.opacity = 0.4 + overall * 0.4;
|
422 |
+
const particlePos = particles.geometry.attributes.position;
|
423 |
+
const particleInitial = particles.userData.initialPositions;
|
424 |
+
const turbulence = overall * 1.0;
|
425 |
+
for (let i = 0; i < particlePos.count; i++) {
|
426 |
+
const i3 = i * 3;
|
427 |
+
particlePos.array[i3] = particleInitial[i3] + (Math.sin(time + i * 0.2)) * turbulence;
|
428 |
+
particlePos.array[i3+1] = particleInitial[i3+1] + (Math.cos(time + i * 0.2)) * turbulence;
|
429 |
+
}
|
430 |
+
particlePos.needsUpdate = true;
|
431 |
+
composer.passes[1].strength = 0.35 + bass * 1.5;
|
432 |
+
if (composer.passes[2].uniforms['uAmount']) {
|
433 |
+
composer.passes[2].uniforms['uAmount'].value = highs * 1.5;
|
434 |
+
}
|
435 |
+
} else {
|
436 |
+
const idlePulse = Math.pow(Math.sin(time * 0.5) * 0.5 + 0.5, 2);
|
437 |
+
const corePositions = mainObject.geometry.attributes.position;
|
438 |
+
const coreInitial = mainObject.userData.initialVertices;
|
439 |
+
const noiseFactor = idlePulse * 0.05;
|
440 |
+
for (let i = 0; i < corePositions.count; i++) {
|
441 |
+
const p = new THREE.Vector3().fromBufferAttribute(coreInitial, i);
|
442 |
+
p.add(p.clone().normalize().multiplyScalar(noiseFactor));
|
443 |
+
corePositions.setXYZ(i, p.x, p.y, p.z);
|
444 |
+
}
|
445 |
+
corePositions.needsUpdate = true;
|
446 |
+
composer.passes[1].strength = 0.35 + idlePulse * 0.2;
|
447 |
+
}
|
448 |
+
composer.render();
|
449 |
+
}
|
450 |
+
|
451 |
+
init();
|
452 |
+
</script>
|
453 |
+
</body>
|
454 |
+
</html>
|