-
Notifications
You must be signed in to change notification settings - Fork 1
/
firsttest.html
589 lines (518 loc) · 20.1 KB
/
firsttest.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
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/matter.js"></script>
<script src="js/matter-wrap.js"></script>
<style>
#playground {
border-style: solid;
}
#vectorfield {
border-style: solid;
}
</style>
<body>
<h1>Attempting to build a Ferrofluid Simulation</h1>
<p>
<label for="amount">Value (MAX Force Exponent):</label>
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div>
<div id="slider1"></div>
</div>
<div>
<button id="reset" type="button" class="btn btn-primary">Reset</button>
<button id="gravity" type="button" class="btn btn-primary">Gravity</button>
</div>
<canvas id="playground"></canvas>
<canvas id="vectorfield" width=400 height=400></canvas>
</body>
</html>
<script>
/**
* An ferrofluid plugin for matter.js.
* An attempt to make a plugin that handles force induced
* by a magnetic field computed against the whole world.
* @module MagneticFieldForce
*
* Because this is meant to model a thin sheet of ferrofluid
* affected by an external magnet, it makes a number of simplifying
* assumptions. It is probably very inaccurate, but the purpose
* is simple: to be realistic enough to explore creating a ferrofluid
* check valve.
*
* To this end, I remove polarity by treating only "attraction".
* One might imagine this is similar to gravity, but it is more complicated
* than that because ferrofluid is higly paramagnentic; that is, it
* becomes magnetic (or "attractive") in proportion to the strength
* of the field it is in (I suppose.)
*
* The basic approach here is to separate the external field from
* the induced field. The external field is created by a map of
* the magnitude of the external applied field (no polarity) at each
* point. A cylindrical magnet would thus give radial symmettry,
* Falling off quite strongly outside the circle.
*
* This field S(x,y) can be precumputed, as it is not expected to change
* within an experiment.
*
* From this scalar field, we could compute a vector field, with the
* vectors pointing in the direction of attraction. This is:
* V(x,y) = Integral over all points a,b: d^-Q * ( <x,y> - <a,b>) * S(<a,b>) * F,
* where F is an adjustable fudge factor, Q is probably 3 (or possibly 2 or 2.5),
* d is the distance between <x,y> and <a,b> . This field is also constant.
*
* Then, we dynamically compute for each object at <a,b>:
* I(a,b) = integral over all O at (x,y): d(<a,b>,<x,y>)^-Q * (<x,y>-<a,b) *V(a,b) * G
*
* The total field at any point x,y is I(<x,y>) + V(<x,y>).
*
* This is a vector that points in the direction of the force on the object.
*
*/
const WIDTH = 200;
const HEIGHT = 200;
const PIXELS_PER_MM = 2.5;
var MAX_F_EXPONENT = -3;
var MAX_F = 10**MAX_F_EXPONENT;
var GRAVITY_B = false;
var MagneticFieldForce = {
// plugin meta
name: 'magnetic-field-force', // PLUGIN_NAME
version: '0.1.1', // PLUGIN_VERSION
for: 'matter-js@^0.12.0',
S: [], // The static magnitude of external magnetism
V:[], // The static field attraction vector
F: 1.0e-5,// The fudge factor for the static attraction
G: 1.0e+3,// the fudge factor for the dynamic atrraction
MAX_F_EXPONENT : -3,
MAX_F : 10**MAX_F_EXPONENT,
MAX_F_SQUARED: MAX_F*MAX_F, // Maximum force; his is required by bugs and limitations.
distance: function distance(a,b,x,y) {
return Math.sqrt((a - x)**2 + (b - y)**2);
},
d_squared: function d_squared(a,b,x,y) {
return Math.abs((a - x)**2 + (b - y)**2);
},
set_max_f_exp: function set_max_f_exp(e) {
MagneticFieldForce.MAX_F_EXPONENT = e;
MagneticFieldForce.MAX_F = 10**MagneticFieldForce.MAX_F_EXPONENT;
MagneticFieldForce.MAX_F_SQUARED = MagneticFieldForce.MAX_F*MagneticFieldForce.MAX_F;
},
getAttractionVector: function getAttractionVector(w,h,x,y) {
var vx = 0, vy = 0;
for(var i = 0; i < w; i++) {
for(var j = 0; j < h; j++) {
const d = MagneticFieldForce.d_squared(x,y,i,j);
// if (d > 0 && d < 4900 ) {
if (d > 0 && d < 100*100 ) {
// if (d > 0) {
// console.log(d;)
// console.log(d**(-3/2));
const s = MagneticFieldForce.S[i][j]*
// -3/2 is probably the physically correct value here, but I
// want more effect, so I am lowering..
MagneticFieldForce.F*(d**(-3/2));
// MagneticFieldForce.F*(d**(-1));
if (isNaN(s)) {
console.log("problem with s!");
debugger;
}
vx += s * (i - x);
vy += s * (j - y);
}
}
}
return Matter.Vector.create(vx, vy);
},
in_main_field: function in_main_field(x,y,w,h) {
const d_p = MagneticFieldForce.d_squared(x,y,w/2,h/2);
return (d_p <= ((25.0/4) * PIXELS_PER_MM)**2);
},
initialize: function initialize() {
var w = render.bounds.max.x - render.bounds.min.x;
var h = render.bounds.max.y - render.bounds.min.y;
// This will be for a circle in the middle.
// I can't really predict this, but I'm going to call it 1.0
// in the center of the circle and have it drop off as the
// cube of distance.
// I'll use a 1/2" inch magnet, and map that 25 pixels.
for(var i = 0; i < w; i++) {
MagneticFieldForce.S[i] = [];
for(var j = 0; j < h; j++) {
var v;
if (MagneticFieldForce.in_main_field(i,j,w,h)) {
v = 1.0;
} else {
const d_p = MagneticFieldForce.distance(i,j,w/2,h/2);
v = (1.0 + (d_p - (25.0/4) * PIXELS_PER_MM))**-3;
}
MagneticFieldForce.S[i][j] = v;
}
}
console.time('computeAttraction');
for(var i = 0; i < w; i++) {
MagneticFieldForce.V[i] = [];
for(var j = 0; j < h; j++) {
var v;
// I feel it necessary to tamp down the vector inside the
// circle to prevent oscilations...I am unsure of the
// best way to do this to represent a physical uniformity
// of the field.
// const d_p = MagneticFieldForce.distance(i,j,w/2,h/2);
if (true) {
v = MagneticFieldForce.getAttractionVector(w,h,i,j);
var m = Matter.Vector.magnitude(v);
// This is unsupportable...
// v = Matter.Vector.mult(v,(m * 1e-6))
} else {
v = Matter.Vector.create(0,0);
}
MagneticFieldForce.V[i][j] = v;
// console.log(v);
}
}
debugger;
console.timeEnd('computeAttraction');
},
// installs the plugin where `base` is `Matter`
// you should not need to call this directly.
install: function install(base) {
base.after('Body.create', function () {
MagneticFieldForce.Body.init(this);
});
base.before('Engine.update', function (engine) {
MagneticFieldForce.Engine.update(engine);
});
},
Body: {
/**
* Initialises the `body` to support magneticFieldForce
* by having a magVector, defining the strength and
* direction of the magnetism defined as a (2D) vector
* This is called automatically by the plugin.
* @function MagneticFieldForce.Body.init
* @param {Matter.Body} body The body to init.
* @returns {void} No return value.
*/
init: function init(body) {
body.plugin.magVector = null;
}
},
Engine: {
/**
* Applies all attractors for all bodies in the `engine`.
* This is called automatically by the plugin.
* @function MagneticFieldForce.Engine.update
* @param {Matter.Engine} engine The engine to update.
* @returns {void} No return value.
*/
update: function update(engine) {
var world = engine.world,
bodies = Matter.Composite.allBodies(world);
// This is a local function, with access to bodies...
// I'm skating on thin ice here.
var w = render.bounds.max.x - render.bounds.min.x;
var h = render.bounds.max.y - render.bounds.min.y;
function computeInternalField(position) {
// Our actual goal here it implement a simulation across
// the whole field as if a magnet were placed out of plane
// and asserting a force every where. Addtionally,
// to simulate ferrofluid we need to simulate the
// paramagnetism of each object, that is, the fact that
// each object becomse magnetic in proportion to the strength
// of the magnetic field it is in, but thereby changes the total field.
var x = Math.max(0,Math.min(WIDTH-1,Math.floor(position.x)));
var y = Math.max(0,Math.min(HEIGHT-1,Math.floor(position.y)));
var vx = 0, vy = 0;
// This may not be right physically
const p = -2;
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i];
// I now believe that we want to exclude or decrease the attraction
// in the highly magnetized zone.
if (!body.isStatic) {
// This is untested, and seems wrong.
// if (!MagneticFieldForce.in_main_field(position.x,position.y,w,h)) {
var bx = Math.max(0,Math.min(WIDTH-1,Math.floor(body.position.x)));
var by = Math.max(0,Math.min(HEIGHT-1,Math.floor(body.position.y)));
// I will model the paramagnetism by taking whichever one has the
// greater magnetism.
var external_force = Math.max(MagneticFieldForce.S[bx][by],
MagneticFieldForce.S[bx][by]);
var f = external_force * MagneticFieldForce.G;
var d = MagneticFieldForce.d_squared(bx,by,x,y);
if (d > 0) {
var dx = f *(bx - x)*(d**p);
var dy = f *(by - y)*(d**p);
if (!Number.isNaN(dx))
vx += dx;
if (!Number.isNaN(dy))
vy += dy;
}
// }
}
}
return Matter.Vector.create( vx,
vy);
}
for (var i = 0; i < bodies.length; i += 1) {
var body = bodies[i];
if (!body.isStatic) {
var x = Math.max(0,Math.min(WIDTH-1,Math.floor(body.position.x)));
var y = Math.max(0,Math.min(HEIGHT-1,Math.floor(body.position.y)));
var external_force = MagneticFieldForce.V[x][y];
var internal_force = computeInternalField(body.position);
var total_force = Matter.Vector.create(
internal_force.x + external_force.x,
internal_force.y + external_force.y);
var tf;
var m = Matter.Vector.magnitude(total_force);
if (m > MagneticFieldForce.MAX_F) {
// tf = Matter.Vector.mult(total_force,m*MagneticFieldForce.MAX_F)
// THIS IS fragile and yet seems to make no sense, both.
tf = Matter.Vector.mult(total_force,m*MagneticFieldForce.MAX_F);
// console.log(m,MagneticFieldForce.MAX_F,m*MagneticFieldForce.MAX_F);
} else {
tf = total_force;
}
Matter.Body.applyForce(body, body.position, tf);
}
}
}
}
};
Matter.Plugin.register(MagneticFieldForce);
Matter.use('magnetic-field-force');
// END PLUGIN!!!!!
var canvas = document.getElementById('playground');
context = canvas.getContext('2d');
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.body.appendChild(canvas);
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
try {
if (typeof MatterWrap !== 'undefined') {
// either use by name from plugin registry (Browser global)
Matter.use('matter-wrap');
} else {
// or require and use the plugin directly (Node.js, Webpack etc.)
Matter.use(require('matter-wrap'));
}
} catch (e) {
// could not require the plugin or install needed
console.log(e);
}
// module aliases
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Bodies = Matter.Bodies,
Body = Matter.Body,
Common = Matter.Common,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
Composites = Matter.Composites,
Composite = Matter.Composite;
// create an engine
var engine = Engine.create();
engine.gravity.scale = 0;
engine.gravity.x = 0;
engine.gravity.y = 1;
var bounds = Matter.Bounds.create(Matter.Vertices.create([{ x: 0, y: 0 }, { x: WIDTH, y: HEIGHT }]));
// create a renderer
var render = Render.create({
element: document.body,
engine: engine,
canvas: canvas,
options: {
// bounds: bounds,
// hasBounds: true,
width: WIDTH,
height: HEIGHT,
showAngleIndicator: true,
wireframes: false,
showAngleIndicator: false,
background: 'transparent',
}
});
Matter.Render.lookAt(render, bounds);
MagneticFieldForce.initialize(render);
// create two boxes and a ground
//var boxA = Bodies.rectangle(400, 200, 80, 80);
//var boxB = Bodies.rectangle(450, 50, 80, 80);
if (false) {
Composite.add(engine.world, [
Bodies.rectangle(200, 150, WIDTH, 20, { isStatic: true, angle: Math.PI * 0.06, render: { fillStyle: '#060a19' } }),
Bodies.rectangle(500, 350, WIDTH, 20, { isStatic: true, angle: -Math.PI * 0.06, render: { fillStyle: '#060a19' } }),
Bodies.rectangle(340, 580, WIDTH, 20, { isStatic: true, angle: Math.PI * 0.04, render: { fillStyle: '#FF0a19' , strokeStyle: 'red', } })
]);
} else {
// Composite.add(engine.world, [
// Bodies.rectangle(340, 580, 200, 20, { isStatic: true, angle: Math.PI * 0.0 , render: { fillStyle: '#FF0a19' , strokeStyle: 'red', } })
// ]);
var boxA = Bodies.rectangle(0, 0, 10, 10, { isStatic: true, render: { fillStyle: '#FF0a19' , strokeStyle: 'red', } });
var boxB = Bodies.rectangle(WIDTH-1, HEIGHT-1, 10, 10, { isStatic: true, render: { fillStyle: '#FF0a19' , strokeStyle: 'red', } });
var ground = Bodies.rectangle(WIDTH/2, HEIGHT-1, WIDTH, 20, { isStatic: true });
Composite.add(engine.world, [ground,boxA,boxB]);
// Here begins my attempt to make the first valve.
// I will simulate this as an octagon. However,
// it must be an open octagon. I will then add "wings"
// to it of varying angle. Side length 2 octagon coordinates:
// (+- 1, +-(1+sqrt(2)))
const OCT_LENGTH = 30;
// For centerpoints
const x_disp = (1.65/2.0) * OCT_LENGTH;
const y_disp = (1.5/2.0) * OCT_LENGTH;
const s_h = (2.3/2.0) * OCT_LENGTH;
function draw_octagon_half(x_disp,y_disp,s_h) {
var octagon0 = Bodies.rectangle(WIDTH/2 - x_disp, HEIGHT/2 + -y_disp,OCT_LENGTH,3,
{ isStatic: true,
angle: -Math.PI/4,
render: { fillStyle: '#0000FF' , strokeStyle: 'blue', }});
var octagon1 = Bodies.rectangle(WIDTH/2 + x_disp, HEIGHT/2 + -y_disp,OCT_LENGTH,3,
{ isStatic: true,
angle: Math.PI/4,
render: { fillStyle: '#0000FF' , strokeStyle: 'blue', }});
var octagon2 = Bodies.rectangle(WIDTH/2 , HEIGHT/2 + -s_h,OCT_LENGTH,3,
{ isStatic: true,
angle: 0,
render: { fillStyle: '#0000FF' , strokeStyle: 'blue', }});
Composite.add(engine.world, [octagon0, octagon1, octagon2]);
}
draw_octagon_half(x_disp,y_disp,s_h);
draw_octagon_half(-x_disp,-y_disp,-s_h);
}
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
Composite.add(engine.world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// fit the render viewport to the scene
Render.lookAt(render, Composite.allBodies(engine.world));
// add bodies
const NUM_BODIES = 30;
var stackRed = Composites.stack(10, 10, NUM_BODIES, 1, 0, 0, function(x, y) {
return Bodies.circle(x, y, Common.random(5, 5),
{ friction: 0.0, restitution: 0.9, density: 0.001,
frictionAir: 0.95,
render: {
fillStyle: 'red',
strokeStyle: 'red',
lineWidth: 2
}
});
});
Composite.add(engine.world, stackRed);
// wrapping using matter-wrap plugin
for (var i = 0; i < stackRed.bodies.length; i += 1) {
stackRed.bodies[i].plugin.wrap = {
min: { x: render.bounds.min.x, y: render.bounds.min.y },
max: { x: render.bounds.max.x, y: render.bounds.max.y }
}
stackRed.bodies[i].plugin.magVector =
Matter.Vector.create(1.0, 1.0);
}
// Now add the debugging of showing a vector field...
function canvas_arrow(context, fromx, fromy, tox, toy) {
var headlen = 4; // length of head in pixels
var dx = tox - fromx;
var dy = toy - fromy;
var angle = Math.atan2(dy, dx);
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
context.moveTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
}
function render_V_Field()
{
var canvas = document.getElementById('vectorfield');
var ctx = canvas.getContext('2d');
const A = 10000*10;
// I'll try plotting a 10th of the field first
for(var i = 0; i < WIDTH/10; i++) {
for(var j = 0; j < HEIGHT/10; j++) {
ctx.beginPath();
var fx = i*10;
var fy = j*10;
var tx = fx + A*MagneticFieldForce.V[fx][fy].x;
var ty = fy + A*MagneticFieldForce.V[fx][fy].y;
// var tx = fx;
// var ty = fy + 3* MagneticFieldForce.S[fx][fy];
// now, I'm just doubling the size of this viewport, which is fragile,
// but should work...
canvas_arrow(ctx, fx*2, fy*2, tx*2, ty*2);
ctx.stroke();
}
}
}
render_V_Field();
// run the renderer
Render.run(render);
// create runner
var runner = Runner.create();
// run the engine
Runner.run(runner, engine);
$( function() {
$( "#slider1" ).slider({
range: true,
min: -7,
max: 7,
// value: MAX_F_EXPONENT,
step: 0.1,
value: -3,
change: function( event, ui ) {
$( "#amount" ).val( ui.value );
MAX_F_EXPONENT = ui.value;
MagneticFieldForce.set_max_f_exp(MAX_F_EXPONENT);
// $( "#slider1" ).val(MAX_F_EXPONENT);
}
}
);
$( "#slider1" ).val(MAX_F_EXPONENT);
$('#reset').on('click', function(event) {
// add bodies
const NUM_BODIES = 30;
var stackRed = Composites.stack(10, 10, NUM_BODIES, 1, 0, 0, function(x, y) {
return Bodies.circle(x, y, Common.random(5, 5),
{ friction: 0.1, restitution: 0.4, density: 0.001,
frictionAir: 0.95,
render: {
fillStyle: 'red',
strokeStyle: 'red',
lineWidth: 2
}
});
});
Composite.add(engine.world, stackRed);
});
$('#gravity').on('click', function(event) {
GRAVITY_B = !GRAVITY_B;
if (GRAVITY_B) {
engine.gravity.scale = .01;
engine.gravity.x = 1;
engine.gravity.y = 0;
} else {
engine.gravity.scale = 0;
engine.gravity.x = 0;
engine.gravity.y = 0;
}
});
});
</script>