• Stars
    star
    189
  • Rank 204,649 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Poisson disk sampling in arbitrary dimensions

poisson-disk-sampling

Build Status NPM version

Poisson disk sampling in arbitrary dimensions.

Installing

With npm do:

npm install poisson-disk-sampling

With yarn do:

yarn add poisson-disk-sampling

A compiled version for web browsers is also available on a CDN:

<script src="https://cdn.jsdelivr.net/gh/kchapelier/[email protected]/build/poisson-disk-sampling.min.js"></script>

Features

  • Can be used in any dimension (1D, 2D, 3D and more).
  • Can be used with a custom RNG function.
  • Allow the configuration of the max number of tries, the minimum distance and the maximum distance between each points.
  • Allow the use of custom function to drive the density of the distribution.
  • Similar general API as fast-2d-poisson-disk-sampling and jittered-hexagonal-grid-sampling.

Basic example

var p = new PoissonDiskSampling({
    shape: [600, 300, 200],
    minDistance: 20,
    maxDistance: 30,
    tries: 10
});
var points = p.fill();

console.log(points); // array of sample points, themselves represented as simple arrays

Result as an image

Example with an image driving the distribution density

var p = new PoissonDiskSampling({
    shape: [500, 500],
    minDistance: 1,
    maxDistance: 30,
    tries: 20,
    distanceFunction: function (p) {
        return getImagePixelValueSomehow(p[0], p[1]); // value between 0 and 1
    }
});
var points = p.fill();

console.log(points); // array of sample points, themselves represented as simple arrays

Result as an image

Complete working example

Demo online | Source code

Public API

Constructor

new PoissonDiskSampling(options[, rng])

  • options :
    • shape : Size/dimensions of the grid to generate points in, required.
    • minDistance : Minimum distance between each points, required.
    • maxDistance : Maximum distance between each points, defaults to minDistance times 2.
    • tries : Maximum number of tries to generate a point, defaults to 30.
    • distanceFunction : Function to control the distance between each point depending on their position, must return a value between 0 and 1.
    • bias : When using a distanceFunction, will indicate which point constraint takes priority when evaluating two points (0 for the lowest distance, 1 for the highest distance), defaults to 0.
  • rng : A function to use as random number generator, defaults to Math.random.

The following code will allow the generation of points where both coordinates will range from 0 up to 50 (including 0, but not including 50, 0 <= c < 50).

// Poisson disk sampling in a 2D square
var pds = new PoissonDiskSampling({
    shape: [50, 50],
    minDistance: 4,
    maxDistance: 4,
    tries: 10
});
// Poisson disk sampling in a 3D volume
var pds = new PoissonDiskSampling({
    shape: [900, 400, 400],
    minDistance: 20,
    maxDistance: 25,
    tries: 10
});
// Poisson disk sampling in a 2D square using
// a custom function to drive the distance between each point
var pds = new PoissonDiskSampling({
    shape: [400, 400],
    minDistance: 4,
    maxDistance: 20,
    tries: 20,
    distanceFunction: function (point) {
        return point[0] / 400;
    },
    bias: 0
});

Method

pds.fill()

Fill the grid with random points following the distance constraint.

Returns the entirety of the points in the grid as an array of coordinate arrays. The points are sorted in their generation order.

var points = pds.fill();

console.log(points[0]);
// prints something like [30, 16]

pds.getAllPoints()

Get all the points present in the grid without trying to generate any new points.

Returns the entirety of the points in the grid as an array of coordinate arrays. The points are sorted in their generation order.

var points = pds.getAllPoints();

console.log(points[0]);
// prints something like [30, 16]

pds.getAllPointsWithDistance()

Get all the points present in the grid along with the result of the distance function.

Returns the entirety of the points in the grid as an array of coordinate + distance function result arrays. The points are sorted in their generation order.

Calling this method on an instance of PoissonDiskSampling without a distanceFunction will throw an error.

var points = pds.getAllPointsWithDistance();

console.log(points[0]);
// prints something like [30, 16, 0.4], 0.4 being the result of the distance function

pds.addRandomPoint()

Add a completely random point to the grid. There won't be any check on the distance constraint with the other points already present in the grid.

Returns the point as a coordinate array.

pds.addPoint(point)

  • point : Point represented as a coordinate array.

Add an arbitrary point to the grid. There won't be any check on the distance constraint with the other points already present in the grid.

Returns the point added to the grid.

If the point given is not of the correct dimension (i.e. inserting a 2D point in a 3D grid) or doesn't fit in the grid size, null will be returned.

pds.addPoint([20, 30, 40]);

pds.next()

Try to generate a new point in the grid following the distance constraint.

Returns a coordinate array when a point is generated, null otherwise.

var point;

while(point = pds.next()) {
    console.log(point); // [x, y, z]
}

pds.reset()

Reinitialize the grid as well as the internal state.

When doing multiple samplings in the same grid, it is preferable to reuse the same instance of PoissonDiskSampling instead of creating a new one for each sampling.

Usages in the wild

Implementation notes

Internally, there are two different implementations of the algorithm. The implementation is chosen depending on whether a distanceFunction is passed to the constructor. The library is designed in such a way as to keep it transparent to the end user.

In order to reduce the impact of this dependency on the size of the javascript bundle(s) in web projects, it is possible to explicitly require a given implementation.

var PoissonDiskSampling = require('poisson-disk-sampling/src/implementations/fixed-density');

or

var PoissonDiskSampling = require('poisson-disk-sampling/src/implementations/variable-density');

TypeScript definitions

TypeScripts definitions (.d.ts) provided by Aliyss are available through DefinitelyTyped. They can be installed locally using the following commands:

npm install --save-dev @types/poisson-disk-sampling

or

yarn add @types/poisson-disk-sampling --dev

History

2.3.1 (2022-06-05) :

  • Slightly better performances and point density when working with a large shape

2.3.0 (2022-05-21) :

  • Fix addPoint() erroneously accepting points on the outer bounds of the shape
  • Update dev dependencies

2.2.3 (2022-02-26) :

  • Fix outdated CDN builds, no actual changes to the code provided through npm

2.2.2 (2020-05-25) :

  • Minor performance-related tweaks for 3D and higher dimensions
  • Fix an issue causing the points to be generated in the [0, size-1] range instead of the [0, size) range

2.2.1 (2020-05-11) :

  • Minor performance-related tweaks
  • Update dev dependencies

2.2.0 (2020-02-17) :

  • Do not ignore distanceFunction anymore if minDistance and maxDistance are equal
  • Make it possible to explicitly require a specific implementation

2.1.0 (2020-02-10) :

Due to an issue on npmjs.com this version was not listed on the website even though it was available through the CLI.

  • Implement getAllPointsWithDistance()
  • Add a test suite for the variable density implementation
  • Fix an issue where the actual minDistance could be larger than the one set by the user in the variable density implementation

2.0.0 (2020-02-03) :

  • Support distance function / variable density
  • Change constructor signature, the rest of the public API is unchanged

1.0.6 (2019-09-28) :

  • Update dev dependencies

1.0.5 (2019-05-27) :

  • Fix package on npm (adding missing file)

1.0.4 (2019-05-27) :

  • Replace ndarray with a leaner custom implementation to drastically reduce the size of the package (~50%)
  • Update dev dependencies

1.0.3 (2019-01-12) :

  • Update dev dependencies
  • Change node versions tested with travis

1.0.2 (2017-09-30) :

  • Minor performance tweaks
  • Reduce npm package size
  • Update moore dep
  • Add benchmark script

1.0.1 (2017-01-06) :

  • Add some checks on the points added with addPoint()
  • Implements tests
  • Add travis support

1.0.0 (2016-09-16) :

  • Implement getAllPoints() and reset()
  • Fix incorrect handling of maxDistance when it is not set
  • Fix incorrect behavior when fill() is called several times
  • Declare the public API stable
  • API documentation
  • Remove mathp dependency

0.0.1 (2015-11-28) :

  • First release

How to contribute ?

For new features and other enhancements, please make sure to contact me beforehand, either on Twitter or through an issue on Github.

License

MIT

More Repositories

1

wavefunctioncollapse

Javascript port of https://github.com/mxgmn/WaveFunctionCollapse
JavaScript
454
star
2

procedural-generation

A mostly javascript-centric resource / links list on procedural content generation (PCG).
249
star
3

cellular-automata-voxel-shader

Generate a voxel shader (for MagicaVoxel) from a custom CA rule
JavaScript
174
star
4

pseudofractals-voxel-shader

Voxel shader (for MagicaVoxel) to generate pseudofractals volumes
90
star
5

matcap-studio

An utility to tweak matcaps, with realtime visual feedback.
JavaScript
58
star
6

convchain

Javascript port of https://github.com/mxgmn/ConvChain
JavaScript
49
star
7

procjam2018

Graph.ical, a procedural texture authoring application developed for PROCJAM 2018.
JavaScript
44
star
8

PRWM

Packed Raw WebGL Model (PRWM) specifications and implementations.
JavaScript
38
star
9

qoijs

Quite-OK Image format encoder/decoder in vanilla JavaScript.
JavaScript
38
star
10

hexagrid-relaxing

JavaScript port of Cedric Guillemet's implementation of Oskar StΓ₯lberg's irregular grid in a hexagon.
JavaScript
28
star
11

convchain-gpu

Javascript/WebGL2 port of https://github.com/mxgmn/ConvChain
JavaScript
26
star
12

fast-2d-poisson-disk-sampling

Fast 2D Poisson Disk Sampling based on a modified Bridson algorithm
JavaScript
21
star
13

cellular-automata

Cellular automata runner
JavaScript
17
star
14

voxelShaders

Small collection of Voxel Shaders for MagicaVoxel
15
star
15

ngram-word-generator

Word generation based on n-gram models, and a cli utility to generate said models.
JavaScript
14
star
16

SimpleMidiInput.js

Abstraction over the MIDI input. Does all the byte crunching and exposes a straightforward event API with MIDI learn capability.
JavaScript
12
star
17

node-glitch

Glitched stream for intentional data corruption.
JavaScript
11
star
18

cellular-automata-gpu

GPU-based cellular automata runner
JavaScript
11
star
19

decode-dxt

Decoder for the DXT texture formats.
JavaScript
10
star
20

node-mathp

Math utility for node
JavaScript
9
star
21

jittered-hexagonal-grid-sampling

Jittered Hexagonal Grid Sampling
JavaScript
7
star
22

ndarray-to-vox

Convert a 3D ndarray to a vox file (Magica Voxel format)
JavaScript
6
star
23

gpx

[STALLED] Javascript library to write GPX files
JavaScript
6
star
24

Aural.js

An attempt at aggregating all my previous work on audio in a single library.
JavaScript
6
star
25

in-browser-language

Get the language of the browser
JavaScript
5
star
26

ti-selector

Simple selector for Titanium's native view elements.
JavaScript
5
star
27

stochastemes

Second entry for PROCJAM 2015
JavaScript
4
star
28

procjam2015

JavaScript
4
star
29

node-datafilter

Simple filtering for collections of objects
JavaScript
4
star
30

aural-sfz

A codec for SFZ soundfont files.
JavaScript
4
star
31

cellular-automata-rule-parser

Parser for S/B, S/B/C and R/T/C/N cellular automata rule formats.
JavaScript
4
star
32

microsound

JavaScript
4
star
33

in-browser-download

JavaScript
4
star
34

aural-interpolation

Interpolation library, aimed for audio-related processing.
JavaScript
3
star
35

procjam2016

Inund, a short contemplative game for PROCJAM2016
JavaScript
2
star
36

aural-scala

Codec of Scala scale files
JavaScript
2
star
37

node-get-source-map-consumer

Get an instance of SourceMapConsumer, when a sourcemap is available, for a given script.
JavaScript
2
star
38

mpc-hd-shaders

HLSL effects for MPC-HD
HLSL
2
star
39

grunt-glitch

A grunt task you shouldn't use.
JavaScript
2
star
40

procjam2020-smb3

SMB3 Procedural ROM Hack
JavaScript
2
star
41

migl-input

Micro Game Library : Input (keyboard and gamepads)
JavaScript
1
star
42

cellular-automata-playground

JavaScript
1
star
43

imgproc

An experimental and unpolished image processing utility for the command line
JavaScript
1
star
44

gist-load

Load the content of a Gist file in the browser
JavaScript
1
star
45

files2json

A simple cli tool to concat multiple files into a single json file.
JavaScript
1
star
46

procjam2014

Black Sea, a #procjam 2014 experiment
JavaScript
1
star
47

unicode

http://www.kchapelier.com/unicode/ | Simple tool to retrieve information on arbitrary UTF-8 characters
JavaScript
1
star
48

hexview

Experiment viewing the hexadecimal content of large files
JavaScript
1
star
49

jsstg2015

Repo for js➀stg 2015 - http://jp.wgld.org/jsstg/2015f/
JavaScript
1
star
50

algorithmicsynthjs

[on hold] Algorithmic Synth
JavaScript
1
star
51

BNDL

BNDL (binary bundle for arbitrary files) specifications and implementations.
JavaScript
1
star
52

geometricmusicjs

Remix of the Geometric Music app in javascript
JavaScript
1
star
53

procjam2019

PROCJAM 2019 - Generation of vintage engravings of leaves
1
star
54

cellular-automata-gpu-playground

⚠ Work in progress, purely experimental, do not use, highly explosive ⚠
JavaScript
1
star
55

ya-base62

Yet Another Base62, first and foremost designed to encode to and decode from structured strings.
JavaScript
1
star
56

von-neumann

Generates Von Neumann neighborhoods of any range/dimension
JavaScript
1
star
57

migl-rng

Micro Game Library : Random number generator (using seedrandom and noisejs)
JavaScript
1
star