-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
371 lines (304 loc) · 10.7 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N-Body Simulation</title>
<style>
body {
margin: 0;
}
canvas {
display: block;
}
#threeBodyButton,
#nBodyButton {
position: absolute;
bottom: 20px;
left: 240px;
z-index: 1;
padding: 10px 20px;
font-size: 14px;
background-color: rgba(255, 255, 255, 0.8);
border: none;
border-radius: 12px;
cursor: pointer;
width: 100px;
text-align: center;
}
#threeBodyButton:hover,
#nBodyButton:hover {
font-size: 16px;
transition: 0.2s;
}
#nBodyButton {
left: 350px;
}
.slider-container {
position: absolute;
bottom: 20px;
left: 10px;
z-index: 1;
background: rgba(255, 255, 255, 0.8);
padding: 10px;
border-radius: 12px;
width: 200px;
}
.slider-container label {
font-size: 14px;
}
.slider-container input {
width: 100%;
}
</style>
</head>
<body>
<button id="threeBodyButton">3-body</button>
<button id="nBodyButton">n-body</button>
<div class="slider-container">
<label for="gravitySlider">Gravity: <span id="gravityValue">1</span></label>
<input type="range" id="gravitySlider" min="0.1" max="5" step="0.1" value="1">
<label for="timeStepSlider">Time Step: <span id="timeStepValue">0.005</span></label>
<input type="range" id="timeStepSlider" min="0.001" max="0.1" step="0.001" value="0.005">
</div>
<script type="importmap">
{
"imports": {
"three": "./js/three.module.js",
"three/addons/": "./js/addons/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// CONSTANTS //
let G = 1; // Gravitational constant
let dt = 0.005; // Time step
const max_points = 500; // Max points when rendering trail effect
const n_bodies = 10; // Number of bodies to generate on random n-body button click
// SCENE SETUP //
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1;
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// Add lighting to the scene
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(0, 5, 5); // Move the light closer to the front
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 0.1;
directionalLight.shadow.camera.far = 50;
scene.add(directionalLight);
let bodies = [];
let animationId;
// Load textures to array
const textureLoader = new THREE.TextureLoader();
const textures = [
textureLoader.load('./textures/texture1.jpg'),
textureLoader.load('./textures/texture2.jpg'),
textureLoader.load('./textures/texture3.jpg'),
textureLoader.load('./textures/texture4.jpg'),
textureLoader.load('./textures/texture5.jpg'),
textureLoader.load('./textures/texture6.jpg')
];
var controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Load HDR texture
new RGBELoader()
.setPath('./textures/')
.load('HDR_space.hdr', function (texture) {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.background = texture;
scene.environment = texture;
init();
animate();
});
function init() {
document.getElementById('gravitySlider').value = G;
document.getElementById('timeStepSlider').value = dt;
document.getElementById('gravityValue').innerText = G;
document.getElementById('timeStepValue').innerText = dt;
resetScene();
random3Body();
//console.log(G);
//console.log(dt);
document.getElementById('gravitySlider').addEventListener('input', (event) => {
G = parseFloat(event.target.value);
document.getElementById('gravityValue').innerText = G;
//console.log(G);
});
document.getElementById('timeStepSlider').addEventListener('input', (event) => {
dt = parseFloat(event.target.value);
document.getElementById('timeStepValue').innerText = dt;
//console.log(dt);
});
document.getElementById('threeBodyButton').addEventListener('click', () => {
resetScene();
random3Body();
animate();
});
document.getElementById('nBodyButton').addEventListener('click', () => {
resetScene();
randomNBody();
animate();
});
}
function createBody(texture, position, velocity, mass, radius) {
// Set body geometry and material
const geometry = new THREE.SphereGeometry(radius, 32, 32);
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ map: texture, normalMap: texture }));
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
// Set trail material
var trail_mat = new THREE.LineBasicMaterial();
trail_mat.color.setRGB(Math.random(), Math.random(), Math.random());
trail_mat.flatShading = true;
// Set trail geometry
var trail_geometry = new THREE.BufferGeometry();
var trace_array = new Array(max_points * 3).fill(0);
trail_geometry.setAttribute("position", new THREE.Float32BufferAttribute(trace_array, 3));
var drawCount = 0;
var trail = new THREE.Line(trail_geometry, trail_mat);
// Add trail mesh to the scene
scene.add(trail);
// Create body
var body = {
mesh: mesh,
position: position,
velocity: velocity,
weight: mass,
radius: radius,
rotationSpeed: new THREE.Vector3(Math.random() * 0.01, Math.random() * 0.01, Math.random() * 0.01),
trace_array: trace_array,
trail: trail_geometry,
drawCount: drawCount
};
bodies.push(body);
}
function updateTrails() {
for (var body of bodies) {
body.trace_array.unshift(body.position.x, body.position.y, body.position.z);
body.trace_array.splice(max_points * 3);
body.trail.attributes.position.copyArray(body.trace_array);
body.trail.attributes.position.needsUpdate = true;
body.drawCount = THREE.MathUtils.clamp(body.drawCount, 0, max_points);
body.trail.setDrawRange(0, body.drawCount);
body.drawCount++;
}
}
function random3Body() {
const getRandomPosition = () => new THREE.Vector3(
THREE.MathUtils.randFloatSpread(2),
THREE.MathUtils.randFloatSpread(2),
THREE.MathUtils.randFloatSpread(2)
);
const getRandomVelocity = () => new THREE.Vector3(
THREE.MathUtils.randFloatSpread(0.1),
THREE.MathUtils.randFloatSpread(0.1),
THREE.MathUtils.randFloatSpread(0.1)
);
const getRandomWeight = () => THREE.MathUtils.randFloat(0.5, 2);
createBody(textures[getRandomInt(0, textures.length)], getRandomPosition(), getRandomVelocity(), getRandomWeight(), 0.2);
createBody(textures[getRandomInt(0, textures.length)], getRandomPosition(), getRandomVelocity(), getRandomWeight(), 0.2);
createBody(textures[getRandomInt(0, textures.length)], getRandomPosition(), getRandomVelocity(), getRandomWeight(), 0.2);
for (var body of bodies) {
body.mesh.position.copy(body.position);
}
}
function randomNBody() {
const getRandomPosition = () => new THREE.Vector3(
THREE.MathUtils.randFloatSpread(10),
THREE.MathUtils.randFloatSpread(10),
THREE.MathUtils.randFloatSpread(10)
);
const getRandomVelocity = () => new THREE.Vector3(
THREE.MathUtils.randFloatSpread(0.5),
THREE.MathUtils.randFloatSpread(0.5),
THREE.MathUtils.randFloatSpread(0.5)
);
const getRandomWeight = () => THREE.MathUtils.randFloat(0.5, 2);
const getRandomRadius = () => THREE.MathUtils.randFloat(0.1, 0.3);
for (var i = 0; i < n_bodies; i++) {
createBody(textures[getRandomInt(0, textures.length)], getRandomPosition(), getRandomVelocity(), getRandomWeight(), getRandomRadius());
}
for (var body of bodies) {
body.mesh.position.copy(body.position);
}
}
function computeForces() {
for (let i = 0; i < bodies.length; i++) {
let force = new THREE.Vector3(0, 0, 0);
for (let j = 0; j < bodies.length; j++) {
if (i !== j) {
const direction = new THREE.Vector3().subVectors(bodies[j].position, bodies[i].position);
const distance = Math.max(direction.length(), 0.1); // Avoid division by zero or extremely small distances
if (distance < bodies[i].radius + bodies[j].radius) { // Separate bodies on collision
const overlap = (bodies[i].radius + bodies[j].radius) - distance;
direction.normalize();
bodies[i].position.add(direction.multiplyScalar(-overlap / 2));
bodies[j].position.add(direction.multiplyScalar(overlap / 2));
} else {
const f = G * bodies[i].weight * bodies[j].weight / (distance * distance);
force.add(direction.normalize().multiplyScalar(f));
}
}
}
bodies[i].velocity.add(force.multiplyScalar(dt / bodies[i].weight));
}
}
function updatePositions() {
for (var body of bodies) {
body.position.add(body.velocity.clone().multiplyScalar(dt));
body.mesh.position.copy(body.position);
body.mesh.rotation.x += body.rotationSpeed.x;
body.mesh.rotation.y += body.rotationSpeed.y;
body.mesh.rotation.z += body.rotationSpeed.z;
// Constrain the positions to stay within the screen
body.position.clamp(new THREE.Vector3(-5, -5, -5), new THREE.Vector3(5, 5, 5));
}
updateTrails();
}
function animate() {
animationId = requestAnimationFrame(animate);
computeForces();
updatePositions();
controls.update();
renderer.render(scene, camera);
}
function resetScene() {
bodies = [];
cancelAnimationFrame(animationId);
scene.clear();
scene.add(ambientLight);
scene.add(directionalLight);
resetCamera();
}
function resetCamera() {
const initialCameraPosition = new THREE.Vector3(0, 5, 5);
const initialCameraTarget = new THREE.Vector3(0, 0, 0);
camera.position.copy(initialCameraPosition);
camera.lookAt(initialCameraTarget);
controls.target.copy(initialCameraTarget);
controls.update();
}
function getRandomInt(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // The maximum is exclusive and the minimum is inclusive
}
</script>
</body>
</html>