xxxxxxxxxx
118
let theShader;
let shaderTexture;
let NUM_PARTICLES = 20;
let posTexture;
let velTexture;
let particles = [];
function preload(){
theShader = loadShader('basic.vert', 'basic.frag');
}
function setup() {
createCanvas(400, 400, WEBGL);
// Initiate Particles
for(let i = 0; i < NUM_PARTICLES;i++){
particles.push(new Particle(i*20,i*20,0));
}
// Initialize Shader
shaderTexture = createGraphics(NUM_PARTICLES, 1, WEBGL);
shaderTexture.noStroke();
// Create Particle Texture
posTexture = createImage(NUM_PARTICLES, 1);
velTexture = createImage(NUM_PARTICLES, 1);
// Fill Particle Position Texture
posTexture.loadPixels();
for (let i = 0; i < NUM_PARTICLES; i++) {
posTexture.pixels[i*4+0] = map(particles[i].pos.x,-width,width,0,255); // R
posTexture.pixels[i*4+1] = map(particles[i].pos.y,-height,height,0,255); // G
posTexture.pixels[i*4+2] = 0; // B
posTexture.pixels[i*4+3] = 255; // A
}
posTexture.updatePixels();
// Fill Particle Position Texture
velTexture.loadPixels();
for (let i = 0; i < NUM_PARTICLES; i++) {
velTexture.pixels[i*4+0] = map(particles[i].vel.x,-width,width,0,255); // think of other way than -1 and + 1
velTexture.pixels[i*4+1] = map(particles[i].vel.y,-height,height,0,255); // G
velTexture.pixels[i*4+2] = 0; // B
velTexture.pixels[i*4+3] = 255; // A
}
velTexture.updatePixels();
}
function draw() {
translate(-width/2, -height/2);
background(255);
// Apply Texture
shaderTexture.shader(theShader); // set shader
theShader.setUniform('pos', posTexture); // send particleTexture to shader
theShader.setUniform('vel', velTexture); // send particleTexture to shader
theShader.setUniform('size', [NUM_PARTICLES, 1]);
shaderTexture.rect(0,0,NUM_PARTICLES,1); // set rect to recieve shader out
// Print Shader Output
for(let i = 0; i < NUM_PARTICLES;i++){
let newPos = shaderTexture.get(i, 0);
//print(newPos);
}
// Update and Display Particles
let cohesionForces = [];
for(let i = 0; i < NUM_PARTICLES;i++){
let data = shaderTexture.get(i, 0);
let x = map(data[0],0,255,-width,width);
let y = map(data[1],0,255,-height,height);
cohesionForces.push(createVector(x,y));
}
for(let i = 0; i < NUM_PARTICLES;i++){
particles[i].applyForce(cohesionForces[i],1);
particles[i].update();
fill(0,0,255);
circle(particles[i].pos.x, particles[i].pos.y,10);
}
// Display Visual Output of Shader in Top Left
texture(shaderTexture);
rect(0,0,100,20);
//noLoop();
}
class Particle{
constructor(x,y){
this.pos = createVector(x,y);
this.vel = createVector(random(-1,1), random(-1,-1));
this.acc = createVector(0, 0);
this.maxSpeed = 4; // how fast
this.maxForce = 0.1; // how good at turning
}
// Method to update position
update() {
this.vel.add(this.acc); // update velocity
this.vel.limit(this.maxSpeed); // limit speed
this.pos.add(this.vel); // update position
this.acc.mult(0); // reset acceleration
}
applyForce(force, coef) {
p5.Vector.mult(force,coef);
this.acc.add(force);
}
}