forked from chi-feng/colorful-fluid-dynamics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·301 lines (259 loc) · 9.95 KB
/
index.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
<html>
<head>
<style>
html, body { width: 100%; height: 100%; margin: 0px; }
body { background: #000; color: #fff; font-family: sans-serif; font-size: 12px;}
a {cursor: pointer; color: #99b; text-decoration: underline;}
#fps{top:0; left:0; padding: 5px;}
p {margin:0 5px; padding: 5px; }
h2 {font-size: 20px; margin:0 5px; padding: 5px; color: #fff;}
</style>
</head>
<body>
<div id="header"> <h1> CFD is Colorful Fluid Dynamics - Music Hack Day Boston 2013 </h1> </div>
<p><span id="fps"></span></p>
<canvas id="canvas-fluid" width="600" height="400"></canvas>
<p><span id="message"></span></p>
<h2>Info</h2>
<p>This is a fork of our project for MHD Boston 2013. The original hack by Chi Feng can be found <a href = "chifeng.scripts.mit.edu/stuff/fluid"> here</a>. This remix adds some visual tweaks and more significantly, the ability to designate the particle source image via drag and drop of local files. </p>
<p>Try it out by dragging & dropping an MP3 and/or image on to the page. Images with white or transparent background work best. Multiple images can be loaded on top of one another.</p>
<p><a id="loadSample" onclick="useSamples();">[Demo w/ Sample MP3 & Image]</a>.</p><p>Sample Audio is <a href = "https://soundcloud.com/trill-scott_heron/rhye-open-ryan-hemsworth-remix">Rhye - Open (Ryan Hemsworth Remix) Trill Scott Heron Future Screw</a>. Sample image is from <a href = "http://www.officialpsds.com/Transparent-Skull-PSD-PSD12681.html"> here </a> </p>
<h2>Options</h2>
<p>
<a onclick="display.additive=!display.additive;">Toggle blending mode</a>
<a onclick="showVelocity=!showVelocity;">Toggle velocity field</a>
<a onclick="showParticles=!showParticles;">Toggle particles</a>
<a onclick="imgSpawnX = []; imgSpawnY = [];">Clear Images</a>
</p>
<h2>References</h2>
<p><a href="http://www.dgp.toronto.edu/people/stam/reality/Research/pdf/GDC03.pdf">'Real-Time Fluid Dynamics for Games'</a> by Jos Stam</p>
<p><a href="http://airtightinteractive.com/demos/js/reactive/">Loop Music Visualizer</a> by <a href="https://twitter.com/felixturner">Felix Turner</a>.</p>
<p><a href="http://www.youtube.com/watch?feature=player_detailpage&v=fpViZkhpPHk#t=112">Particle tests 3D Music Visualizer</a> by <a href="http://www.youtube.com/user/MatthiasmVideos">MatthiasM.de</a></p>
<script src="FluidField.js"></script>
<script src="FluidDisplay.js"></script>
<script src="Music.js"></script>
<script src="BeatDetector.js"></script>
<script>
function message(msg) {
document.getElementById("message").innerHTML = msg;
}
var canvas = document.getElementById("canvas-fluid");
var field = new FluidField(canvas);
var display = new FluidDisplay(field);
var audio = null; // initialize only if on chrome
var img = null;
var imgCanvas = document.createElement("canvas");//only used if we're loading custom image for particle source
var imgCtx = null;
var imgSpawnX = [];
var imgSpawnY = [];
var detector = new BeatDetector();
var start = new Date(); // reset after each fps calculation
var initial = new Date(); // very beginning
var frames = 0; // for fps calculation
var time = 0; // time since very beginning
var offset = 0;
var interval = 5;
var n = 72000; // number of particles
var medLife = 100; //Mean Lifetime
var lifeVar = 25; //How much life is allowed to vary
//Would be cool to make lifetime dependent on the intensity of the song: the more intense, the shorter the life
//slow parts would have particles living longer
var life = medLife + lifeVar; // lifetime of particles in frames
var px = new Float32Array(n); // x coordinate of particles
var py = new Float32Array(n); // y coordinate of particles
var pc = new Float32Array(n); // color of particle (hue)
var pl = new Int16Array(n); // age of particle
var showVelocity = false;
var showParticles = true;
var theta = 0;
var velocity = 2;
var radius = 8;
var normRadius = 8;
var maxRadius = 20;
var fft_resolution = 256;
function resetParticle(i) {
if (radius == maxRadius) {
var t = i / n;
//Make it gaussian around radius
var r = radius - 6 + 3 * (Math.random() + Math.random() + Math.random() + Math.random());
px[i] = field.width * 0.5 + r * Math.cos(t * 2 * Math.PI);
py[i] = field.height * 0.5 + r * Math.sin(t * 2 * Math.PI);
pc[i] = t + (offset/20 + Math.PI)/(2*Math.PI);
pl[i] = life;
}
else if (imgSpawnX.length > 0) {
var randIdx = Math.floor(Math.random() * imgSpawnX.length);
var xPos = field.width*0.5 + imgSpawnX[randIdx];
var yPos = field.height*0.5 + imgSpawnY[randIdx];
px[i] = xPos;
py[i] = yPos;
pc[i] = ((offset/20 + Math.PI + Math.atan2(imgSpawnY[randIdx],imgSpawnX[randIdx])) / (2*Math.PI));
pl[i] = Math.random()*life;
} else {
var t = i / n;
var r = radius + Math.random();
px[i] = field.width * 0.5 + r * Math.cos(t * 2 * Math.PI);
py[i] = field.height * 0.5 + r * Math.sin(t * 2 * Math.PI);
pc[i] = t;
pl[i] = life;
}
}
function pulse(tmin, tmax) {
for (var i = 0; i < n; i++) {
if (Math.random() < 0.5 && pc[i] < tmax && pc[i] > tmin) {
pl[i] = life - Math.floor(Math.random() * life/10);
}
}
}
function updateFrame() {
var end = new Date;
time = end - initial;
offset = time * 0.005;
life = Math.sin(offset/100) * lifeVar + medLife;
frames++;
if (end - start > 500) {
document.getElementById("fps").innerHTML = "FPS: " + ((1000 * (frames) / (end - start) + 0.5) | 0);
start = end;
frames = 0;
}
if (audio.playing) {
updateVelocities();
}
field.update();
if (frames % 2 == 0) {
}
for (var i = 0; i < n; i++) {
var jitter = (1 - pl[i] / life);
var vx = 10 * field.getXVelocity(px[i], py[i]);
var vy = 10 * field.getYVelocity(px[i], py[i]);
px[i] += vx + (Math.random() - 0.5) * jitter;
py[i] += vy + (Math.random() - 0.5) * jitter;
pl[i]--;
if (pl[i] < 1 || px[i] < 1 || px[i] > field.width || py[i] < 1 || py[i] > field.height - 1) {
resetParticle(i);
}
}
display.clear();
if (showParticles)
display.renderParticles(field, px, py, pc, pl);
if (showVelocity)
display.renderVelocityField(field);
requestAnimationFrame(updateFrame);
}
function updateVelocities() {
detector.sample(audio.analyser);
// big beats
if (detector.beatChance > 1.6) {
radius = maxRadius;
} else {
radius = normRadius;
}
// jets for bins that are above threshold
for (var i = 0; i < detector.historyBins; i++) {
var theta = i / detector.historyBins * Math.PI * 2 + offset;
var x = Math.floor(field.width / 2 + radius * Math.cos(theta));
var y = Math.floor(field.height / 2 + radius * Math.sin(theta));
if (detector.binChance[i] > 1.5) {
var v = detector.binChance[i];
if (v > 3) v = 3;
var vx = field.getXVelocity(x, y) + v * Math.cos(theta);
var vy = field.getYVelocity(x, y) + v * Math.sin(theta);
field.setVelocity(x, y, vx, vy);
if (3 < detector.binChance[i] && detector.binChance[i] < 50) {
var tmin = i / detector.historyBins - 0.01;
var tmax = tmin + 0.02;
pulse(tmin, tmax);
}
}
}
}
function useSamples() {
if (audio.source) audio.source.disconnect();
imgSpawnX = []; imgSpawnY = [];//Reset default image
img = new Image();
img.src = "skull.png";
parseImage();
audio = new Audio('open_remix.m4a');
audio.loadSampleAudio();
}
function parseImage(){
if (img.complete) {
//TODO: increase contrast on images so we get a better outline
var minScale = Math.min(img.width/normRadius,img.height/normRadius);
imgCanvas.width = 10*(img.width/minScale);
imgCanvas.height = 10*(img.height/minScale);
imgCtx = imgCanvas.getContext('2d');
imgCtx.drawImage(img,0,0,imgCanvas.width,imgCanvas.height);
var scaled = imgCtx.getImageData(0,0,imgCanvas.width,imgCanvas.height);
var scaleData = scaled.data;
var weight = 0;
var idx = 0;
for (var x = 0; x < imgCanvas.width; x += 1) {
for (var y = 0; y < imgCanvas.height; y += 1) {
idx = (y*imgCanvas.width + x) * 4;
//Basically downsampling to 4 bit greyscale to get relative darkness
//Coefficients are weights for converting RGB to human-perceived greyscale
weight = scaleData[idx+3] *
(0.2989*(255-scaleData[idx]) + 0.5870*(255-scaleData[idx+1]) + 0.1140*(255-scaleData[idx+2])) / (3 * 32);
for(var i = 1; i < weight; i += 1) {
imgSpawnX.push((x - imgCanvas.width/2)/2);
imgSpawnY.push((y - imgCanvas.width/2)/2);
}
}
}
} else {
setTimeout(parseImage(), 50);
}
}
function loadImage(fileEvent) {
img = new Image();
img.src = fileEvent.target.result;
parseImage();
};
window.onload = function() {
requestAnimationFrame(updateFrame);
audio = new Audio();
document.addEventListener('drop', function(evt) {
evt.stopPropagation();
evt.preventDefault();
message("Loading files...");
var droppedFiles = evt.dataTransfer.files;
var imageType = /image.*/;
var audioType = /audio.*/;
var file;
for (var i = 0; i < droppedFiles.length; i++) {
file = droppedFiles[i];
if(file.type.match(imageType)){
message("Loading image file...");
var reader = new FileReader();
reader.onload = loadImage;
reader.readAsDataURL(file);
message("Image Loaded");
}
else if(file.type.match(audioType)){
if (audio.source) audio.source.disconnect(); // clean up previous mp3
message("Loading audio file...");
var reader = new FileReader();
reader.onload = function(fileEvent) {
var data = fileEvent.target.result;
audio.initAudio(data);
};
reader.readAsArrayBuffer(file);
}
else {
alert("Could not read file " + file.name);
}
}
}, false);
document.addEventListener('dragover', function(evt) {
evt.stopPropagation();
evt.preventDefault();
return false;
}, false);
for (var i = 0; i < n; i++) {
resetParticle(i);
pl[i] = Math.floor(Math.random() * life);
}
}
</script>
</body>