npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nbody-simulator-react-p5

v0.6.2

Published

A react component that simulates the n-body problem using p5.js

Downloads

18

Readme

nbody-simulator-react-p5

Description

This is an n-body simulator package made with React Typescript and p5.js.

Bodies are attracted to each other by the gravitational force and by a center attractor which is defiend by clicking on the canvas.

🚀🚀You can try it online from your browser 🚀🚀

It works on desktop and mobile as well with different controls (check the controls section).

🚀🚀 The package is available on npm 🚀🚀

Note
I also made a C++ version for WebGL2 using OpenGL ES 3.0. You can check it out here.

Note
I also made a version using Barnes-Hut algorithm. You can check it out here.

Screenshots

| Screenshot 1 | Screenshot 2 | |---------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------| | Screenshot1 | Screenshot2 |

Demo video

https://github.com/Im-Rises/nbody-simulator-react-p5/assets/59691442/20bc593e-7bd0-4d60-9470-a8caed1a45bd

Package installation

To install it type the following command in your terminal:

npm install nbody-simulator-react-p5

Then you can import it in your project with:

import NbodySimulator from 'nbody-simulator-react-p5'

Usage

To use it you can simply add the component in your project like this:

import React, {useEffect, useState} from 'react';
import NbodySimulator from 'nbody-simulator-react-p5';
import './App.css';

const App: React.FC = () => {
    const [isLoaded, setIsLoaded] = useState(false);
    const divRef = React.useRef <HTMLDivElement>(null);

    useEffect(() => {
        if (divRef.current) {
            setIsLoaded(true);
        }
    }, [divRef]);

    return (
        <div className='App'>
            <div ref={divRef}>
                {isLoaded ? (
                    <div className={'nbody-sim-canvas'}>
                        <NbodySimulator
                            parentRef={divRef}
                        />
                    </div>
                ) : (
                    <p className={'wait-sim-canvas'}>Loading...</p>
                )}
            </div>
        </div>
    );
};

export default App;

or you can change all the settings like this:

import React, {useEffect, useState} from 'react';
import NbodySimulator from 'nbody-simulator-react-p5';
import './App.css';

const App: React.FC = () => {
    const [isLoaded, setIsLoaded] = useState(false);
    const divRef = React.useRef <HTMLDivElement>(null);

    useEffect(() => {
        if (divRef.current) {
            setIsLoaded(true);
        }
    }, [divRef]);

    return (
        <div className='App'>
            <div ref={divRef}>
                {isLoaded ? (
                    <div className={'nbody-sim-canvas'}>
                        <NbodySimulator
                            parentRef={divRef}
                            nbodyCountMobile={100}
                            nbodyCountComputer={50}
                            frameRate={60}
                            fixedUpdate={60}
                            minSpawnRadius={3}
                            maxSpawnRadius={4}
                            minSpawnVelocity={5}
                            maxSpawnVelocity={10}
                            gravitationalConstant={1}
                            particlesMass={400}
                            softening={4}
                            friction={0.99}
                            centerAttractorMass={10000}
                            pixelsPerMeter={100}
                            initColor={[0, 255, 255, 200]}
                            finalColor={[255, 0, 255, 200]}
                            maxForceMagColor={30}
                            backColor={[0, 0, 0, 255]}
                        />
                    </div>
                ) : (
                    <p className={'wait-sim-canvas'}>Loading...</p>
                )}
            </div>
        </div>
    );
};

export default App;

The component takes 1 to 16 props:

  • parentRef - a reference to the parent div of the canvas. It is used to get the size of the canvas.
  • particleCountMobile - the number of particles on mobile devices.
  • particleCountComputer - the number of particles on desktop devices.
  • fixedUpdate - the number of fixed updates per second.
  • frameRate - the number of frames per second.
  • minSpawnRadius - the minimum radius of the particles when they are spawned.
  • maxSpawnRadius - the maximum radius of the particles when they are spawned.
  • minSpawnVelocity - the minimum velocity of the particles when they are spawned.
  • maxSpawnVelocity - the maximum velocity of the particles when they are spawned.
  • gravitationalConstant - the gravitational constant of the simulation.
  • particlesMass - the mass of the particles.
  • attractorMass - the mass of the attractor.
  • friction - the friction of the particles.
  • softening - the softening parameter of the gravitational force calculation.
  • pixelsPerMeter - the number of pixels to represent 1 meter.
  • initColor - the initial color of the particles (in RGB).
  • finalColor - the final color of the particles (in RGB).
  • maxVelocityMagColor - the maximum velocity of the particles at which the color will be the final color.
  • backColor - the background color of the canvas (in RGB).

This will create a canvas with 3000 particles on desktop and 1000 on mobile in fullscreen which will be resized when the window is resized.

Note The default values of the props are the same as the ones in the example above.

You can find the complete example of the project in the GitHub repository here.

Note
Be sure to do like in the example, the parent div of the canvas must be set before the p5 canvas is created.

Calculations

The calculations are made with the Newtonian mechanics equations.

$$ F = G \frac{m_1 m_2}{r^2} $$

To prevent to have a division by zero when the particles are too close to each other, we add a softening parameter $\epsilon$.

One of the real force calculation with softening could be like this:

$$ F = G \frac{m_1 m_2}{(r^2 + \epsilon^2)^\frac{3}{2}} $$

Where G is the gravitational constant, m1 and m2 are the masses of the particles, r is the distance between the particles and d is the softening parameter.

Known issues

Warning
The React-p5 dependency may have issues with the index.js file.

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App/>
    </React.StrictMode>
);

Please delete the React.StrictMode tag in the index.js file and replace it with the code below.

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <>
        <App/>
    </>
);

GitHub Actions

Node.js CI ESLint CodeQL Node.js Package

The project is set up to run the following actions:

  • node.js.yml : Runs the tests for the Node.js project.
  • eslint.yml : Runs the ESLint linter on the project.
  • codeql.yml : Runs the CodeQL linter on the project.
  • npm-publish.yml : Publishes the package to npm.

Libraries

React:
https://reactjs.org/docs/getting-started.html

Xo:
https://github.com/xojs/xo
https://github.com/xojs/eslint-config-xo-react
https://github.com/xojs/eslint-config-xo-typescript

ESLint:
https://eslint.org/docs/latest/user-guide/getting-started

GitHub gh-pages:
https://github.com/gitname/react-gh-pages

P5.js:
https://p5js.org/
https://www.npmjs.com/package/react-p5

react-device-detect:
https://www.npmjs.com/package/react-device-detect

Documentation

The Coding Challenge (math and physics):
https://www.youtube.com/watch?v=OAcXnzRNiCY
https://www.youtube.com/watch?v=GjbKsOkN1Oc

P5.js:
https://p5js.org/

P5.js React:
https://www.npmjs.com/package/react-p5

Wikipedia Barnes-Hut simulation:
https://en.wikipedia.org/wiki/Barnes–Hut_simulation

Links

Check the source code on github

Check the demo on github

Check the package on npm

Contributors

Quentin MOREL :

GitHub contributors