Project: processing-sc / Examples: Buffer.fill

Examples: Buffer.fill

A bouncing ball moves around a space corresponding to a single waveform cycle, setting ranges of values based on its y-coordinate. Holding the mouse button imposes a gravitational pull towards the cursor.

SynthDefs

SynthDef(\playbuf_1, { |bufnum = 0, outbus = 0, amp = 0.5, loop = 0,
                        pan = 0, rate = 1.0|
        var data;
        data = PlayBuf.ar(1, bufnum, BufRateScale.kr(bufnum) * rate, 0, 0, loop);
        FreeSelfWhenDone.kr(data);
        Out.ar(outbus, Pan2.ar(data, pan, amp));
}).store;

Processing Code

import supercollider.*;

float bx = width / 2,
      by = height / 2,
      vx = 0,
      vy = 0;

Buffer buffer;
Synth synth;

int [] samples;

void setup()
{
  size(1024, 512);
  frameRate(25);
  smooth();
  
  samples = new int[width];
  
  buffer = new Buffer(width, 1);
  buffer.alloc(this, "allocated");
  
  vx = random(-10, 10);
  vy = random(-10, 10);
}

void allocated (Buffer buffer)
{
  buffer.zero();
  
  synth = new Synth("playbuf_1");
  synth.set("loop", 1);
  synth.set("bufnum", buffer.index);
  synth.create();
}

void exit()
{
  synth.free();
  buffer.free();
  super.exit();
}

void draw()
{
  background(0);
  fill(255);
  noStroke();
  
  bx += vx;
  by += vy;
  
  if (bx > width - 1)
  {
    bx = width - 1;
    vx = 0 - vx;
  }
  if (bx < 0)
  {
    bx = 0;
    vx = 0 - vx;
  }
  if (by > height - 1)
  {
    by = height - 1;
    vy = 0 - vy;
  }
  if (by < 0)
  {
    by = 0;
    vy = 0 - vy;
  }
  
  if (mousePressed)
  {
    vx += (mouseX - bx) * 0.001;
    vy += (mouseY - by) * 0.001;
  }
  
  buffer.fill((int) bx, (int) abs(vx + 1), (2.0 * by / height) - 1.0);
  for (int i = 0; (i < abs(vx + 1)) && (bx + i < width - 1); i++)
  {
    samples[(int) bx + i] = (int) by;
  }
  
  for (int i = 0; i < samples.length; i++)
  {
    stroke(150);
    point(i, samples[i]);
  }
  
  if (synth != null)
  {
    synth.set("pan", (float) bx / width - 0.5);
    synth.set("rate", (float) 0.1 + 0.2 * sqrt(sq(vx) + sq(vy)));
  }
  ellipse(bx, by, 3, 3);
}