Quantcast
Channel: Processing Forum
Viewing all 1768 articles
Browse latest View live

PDF Export on mousePressed?

$
0
0
Hi, I'm new to Processing and programing in general. My apologies if this has been addressed elsewhere, but I couldn't find what I needed in the reference or other forums.  I have a basic program that is structured like this:
  1. void setup () {
  2.   // set size/background
  3. }

  4. void draw () {
  5.   // draw random shapes
  6.   noLoop ();
  7. }

  8. void mousePressed() {
  9.   saveFrame ("rs-###.jpg");
  10. }

  11. void keyPressed() {
  12.   setup();
  13.   redraw();
  14. }
The idea is that the program draws a set of random shapes.  If I press a key on the keyboard, it resets and draws a new set of random shapes.  If I get something I like, I click the mouse and it saves a JPEG.

What I'd like to do now is get a PDF in place of a JPEG when I click the mouse.  But all I can figure out is this:
  1. import processing.pdf.*;

  2. void setup () {
  3.   // set size/background
  4.   beginRecord(PDF, "rs-###.pdf");
  5. }

  6. void draw () {
  7.   // draw random shapes
  8.   noLoop ();
  9.   endRecord();
  10. }

  11. void mousePressed() {
  12.   saveFrame ("rs-###.jpg");
  13. }

  14. void keyPressed() {
  15.   setup();
  16.   redraw();
  17. }
which saves a PDF every time the draw function is run.  The problem is that I only want to save a PDF after I see what the draw function does (and would like to trigger the save with mousePressed), but it seems that I need to start recording before the draw function even runs to capture the results.  Any help would be greatly appreciated!

Thanks,

Jeff

Re : Adding PShape vertex dynamically

$
0
0
no, currently there is no way to add/remove vertices from a PShape object.

Play a sound while bouncing

$
0
0
Hi!  I have this code and and want that when the red ball bounces upon the white line (that follows mouseY) plays a sound.  But what I got is that the sound is played one time after another inmediatellly.

Any help?

Thanks!

  1. import ddf.minim.*;
  2. import ddf.minim.signals.*;
  3. import ddf.minim.analysis.*;
  4. import ddf.minim.effects.*;

  5. Minim minim;
  6. AudioPlayer fondo, sonidoRojo;

  7. float i;

  8. //creo las bolitas que rebotan
  9. Reboteiro rebotin01, rebotin02, rebotin03;

  10. void setup() {
  11.   size (800, 600); 
  12.   background(0);
  13.   smooth();
  14.   i = 0;
  15.   
  16.   rebotin01 = new Reboteiro(450, 0, 0, 0, 0, 35, 0.8, height, 229, 49, 68);
  17.   rebotin02 = new Reboteiro(430, -10, 0, 0, 0, 20, 0.85, height, 255, 255, 255);
  18.   rebotin03 = new Reboteiro(470, -40, 0, 0, 0, 15, 0.82, height, 113, 226, 207);
  19.   
  20.   minim = new Minim(this);
  21.   fondo = minim.loadFile("TUUUUMMMM_tunea.wav");
  22.   sonidoRojo = minim.loadFile("tonico-formado-03v2.wav");

  23. }

  24. void draw() {
  25.     background(0);
  26.   
  27.     fill(255,i+50);
  28.     
  29.     noStroke();
  30.     ellipse(width/2, height/2-100, 150+i, 150+i);
  31.     
  32.     stroke(255, 100);
  33.     noFill();
  34.     ellipse(width/2, height/2-100, 160+i, 160+i);
  35.     
  36.     stroke(255, 100);
  37.     noFill();
  38.     strokeWeight(1);
  39.     ellipse(width/2, height/2-100, 110+i, 110+i);
  40.     i++;
  41.     
  42.     if (i > 120) {
  43.       i =0;
  44.     }
  45.   
  46.   if (fondo.isPlaying() == false){
  47.      fondo.play(0); 
  48.   }
  49.   
  50.   rebotin01.dibujar();
  51.   rebotin02.dibujar();
  52.   rebotin03.dibujar();
  53.   
  54.   stroke(255, 100);
  55.   line(-2, mouseY, 802, mouseY);
  56.   
  57.   rebotin01.piso=mouseY;
  58.   rebotin02.piso=mouseY;
  59.   rebotin03.piso=mouseY;
  60.   
  61. //------>  PLAYS THE SOUND <-------
  62.   if (rebotin01.y > mouseY ){
  63.       sonidoRojo.play(0); 
  64.   }

  65. }

  66. class Reboteiro {
  67.   float x, y, speedY, speedX, gravity, movimientoX, gravit;
  68.   int diametro, piso, r, g, b, rebotadas;

  69.   Reboteiro(float x_, float y_, float speedX_, float speedY_, float movimientoX_, int diametro_, float gravit_, int piso_,
  70.             int r_, int g_, int b_ ) {
  71.     gravity = 0.5;
  72.     x = x_;
  73.     y = y_;
  74.     speedX = speedX_;
  75.     speedY = speedY_;
  76.     movimientoX = movimientoX_;
  77.     diametro = diametro_;
  78.     gravit = gravit_;
  79.     piso = piso_;
  80.     r = r_;
  81.     g = g_;
  82.     b = b_;
  83.     rebotadas = 0;

  84.   }

  85.   void dibujar() {
  86.     fill(r, g, b);
  87.     noStroke();
  88.     ellipse(x, y, diametro, diametro);

  89.     y = y + speedY; //change in position
  90.     x = x + speedX; //change in position

  91.     speedY = speedY + gravity; //acceleration

  92.     if (y - diametro > piso) {
  93.       y = piso;
  94.       speedY = speedY * (-1*gravit); //damping upon rebound

  95.       movimientoX = random(-0.05, 0.05);
  96.       
  97.       rebotadas++;
  98.       
  99.       if (rebotadas > 7){
  100.          piso+=1500; 
  101.       }
  102.     }

  103.     speedX = speedX + movimientoX;

  104.     if (x<0 || x>800) {

  105.       speedX = -speedX;
  106.     }
  107.   }
  108. }


  109. void stop() {
  110.  
  111.   fondo.close();
  112.   sonidoRojo.close();

  113.   minim.stop();
  114.   super.stop();
  115. }

Re : Different shaders for geometry, lines and text?

$
0
0
You have to specify the LINE type when calling shader(), it might sound superflous but the reason was to being able to do something like:

  1. shader(pointSh, POINT);
  2. shader(lineSh, LINE);
  3. shader(texSh); // shader(texSh, TRIANGLE) is also valid
  4. ...
  5. draw your geometry, including lines and points...
  6. ...
  7. resetShader(LINE); // only resets the LINE shader
Although, now I feel that the LINE/POINT argument might be redundant after all...

In any case, as things stand right now the fog sketch should look like:
  1. PShader fogColor; 
  2. PShader fogLines; 
  3. PShader fogTex; 

  4. void setup() { 
  5.   size(640, 360, P3D); 
  6.   
  7.   fogColor = loadShader("fogColor.glsl");
  8.   fogColor.set("fogNear", 0.0); 
  9.   fogColor.set("fogFar", 500.0);

  10.   fogLines = loadShader("fogLines.glsl");
  11.   fogLines.set("fogNear", 0.0); 
  12.   fogLines.set("fogFar", 500.0);

  13.   fogTex = loadShader("fogTex.glsl");
  14.   fogTex.set("fogNear", 0.0); 
  15.   fogTex.set("fogFar", 500.0);
  16.   
  17.   hint(DISABLE_DEPTH_TEST); 

  18. void draw() { 
  19.   background(0);
  20.   fill(255,0,0);
  21.   
  22.   shader(fogColor);  
  23.   noStroke(); 
  24.   translate(mouseX, mouseY, -100); 
  25.   box(200);  
  26.   box(100); 

  27.   shader(fogLines, LINES);
  28.   stroke(255, 0, 0); 
  29.   strokeWeight(10); 
  30.   line(0,0,0, width/2, height/2, 100); 
  31.   line(0,0,0, -width/2, height/2, 100);
  32.    
  33.   shader(fogTex);
  34.   text("shader", 100, 0, 100); 
  35. }

with the following shaders:

fogColor.glsl
  1. #define PROCESSING_COLOR_SHADER

  2. varying vec4 vertColor;

  3. uniform float fogNear;
  4. uniform float fogFar;

  5. void main(){
  6.     gl_FragColor = vertColor;
  7.     
  8.     vec3 fogColor = vec3(1.0,1.0,1.0);
  9.     float depth = gl_FragCoord.z / gl_FragCoord.w;
  10.     float fogFactor = smoothstep(fogNear, fogFar, depth);
  11.     gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
  12. }

fogLines.glsl:
  1. #define PROCESSING_LINE_SHADER

  2. varying vec4 vertColor;

  3. uniform float fogNear;
  4. uniform float fogFar;

  5. void main(){
  6.     gl_FragColor = vertColor;
  7.     
  8.     vec3 fogColor = vec3(1.0,1.0,1.0);
  9.     float depth = gl_FragCoord.z / gl_FragCoord.w;
  10.     float fogFactor = smoothstep(fogNear, fogFar, depth);
  11.     gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
  12. }

fogTex.glsl
  1. #define PROCESSING_TEXTURE_SHADER

  2. uniform sampler2D texture;
  3. varying vec4 vertColor;
  4. varying vec4 vertTexCoord;

  5. uniform float fogNear;
  6. uniform float fogFar;

  7. void main() {
  8.   gl_FragColor = texture2D(texture, vertTexCoord.st) * vertColor;
  9.   
  10.   vec3 fogColor = vec3(1.0,1.0,1.0);
  11.   float depth = gl_FragCoord.z / gl_FragCoord.w;
  12.   float fogFactor = smoothstep(fogNear, fogFar, depth);
  13.   gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
  14. }

Re : Different shaders for geometry, lines and text?

$
0
0
Thanks again andrés, now it's working.

Re : PDF Export on mousePressed?

$
0
0
"it seems that I need to start recording before the draw function even runs to capture the results"
Exactly. Or, more accurately, you need to record before starting the drawing operations that must be recorded.
"recorded" is the keyword, here: the PDF doesn't save a state of the drawing, like save() does, it records the drawing orders to be able to replay them.
So you need to always record the drawings even if you finally discard them.

Problem with opengl

$
0
0
Hi..
I tried to play movie in processing 2.0b7 using opengl library but it gives me error.
Please don't suggest me for processing1.5 becuase i need to play a movie when a face is detected and i am doing this by OPENCV(opencv is not compatible with processing 1.5)
Need your valuable suggestions
Thanking you in anticipation. Here is error given by processing....



Exception in thread "Animation Thread" java.lang.NoClassDefFoundError: processing/opengl/PGraphicsOpenGL$ImageCache
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.getConstructor(Class.java:1657)
at processing.core.PApplet.makeGraphics(PApplet.java:1743)
at processing.core.PApplet.size(PApplet.java:1596)
at processing.core.PApplet.size(PApplet.java:1567)
at sketch_130226c.setup(sketch_130226c.java:42)
at processing.core.PApplet.handleDraw(PApplet.java:2117)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:193)
at processing.core.PApplet.run(PApplet.java:2020)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ClassNotFoundException: processing.opengl.PGraphicsOpenGL$ImageCache
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 12 more

Re : Play a sound while bouncing


Re : Cant get my processing sketch to wait for a response from the arduino

$
0
0
There are three different examples presented in a response to "serial problem in reading a string" for Ardunio to Processing communication schemes. Maybe they can help. You have an interesting project. Now after seeing your code I am struck by the fact the plotting data is sent as consecutive data instead of as addressed data. What I mean by that is that I wonder if your plotter can actually plot to a coordinate location. Because if it can then why not send the coordinate information with the image information. For example "PL x y image data". You would be using the SerialCommand library previously mentioned. The callback function for a PL command would plot image data at x y. Incidentally this type of command structure is what HPGL plotters did back in the day and is exactly what you would see when looking at an HPGL plot file before HP adopted a compressed file format. What is interesting is that if you had the Ardunio side echo back the data to Processing then you would have created an essential piece required for the plotter to be a scanner.

Re : PDF Export on mousePressed?

$
0
0
Thanks.  My non-elegant solution was to remove the ### from the PDF file name, so that each time setup is called, it overwrites the previous PDF.  Then if I have a draw cycle I want to keep, I simply rename the PDF so that it doesn't get overwritten.

Re : Serial data is limited to signed 8-bit data???

$
0
0
One of the worst Java's implementation decisions -> signed byte primitive data-type!
Only primitive data-type which is unsigned is char, but it's 16 bits! While C's 8 bits.
You can also use 16-bit short, but it's signed!

I wonder whether it's possible to work this out.
When you read the unsigned byte from RS232 into Processing , store it in a short data-type variable.
Just before sending it back to RS232, use a (byte) cast operator upon the short variable's stored value.
    short s = 150;
    byte  b = (byte) s;
    
    println(s + "\t " + b);
    
    exit();
    

Re : Serial data is limited to signed 8-bit data???

$
0
0
Hi Matt,

Im not sure this is really what you are getting at here, I haven't worked with RS232 or really much in the way of serial data, but I did have an opportunity to work on a project that dealt with bytestreams and parsing data out of the 8bit streams. I only needed to get ints and floats out of 4-byte chunks of the stream, but it seemed to relate perhaps to what you are doing.

I would receive the data stream and then loop through it 4 numbers at a time:


  1. points = new float[(int)dataLength];
  2. for (int i = 0; i < points.length; i++) {
  3.       float value = get4ByteFloat(i*4+headerSize, data);
  4.       points[i] = value;
  5. }


and then I had three helper methods depending on the data I was expecting:
  1. long get2Bytes(int offset, byte[] data)
  2. {
  3.   return ((((int) data[offset + 1]) & 0xff) << 8 |
  4.     (((int) data[offset]) & 0xff));
  5. }

  6. long get4Bytes(int offset, byte[] data)
  7. {    
  8.   return ((((int) data[offset + 3]) & 0xff) << 24 | 
  9.     (((int) data[offset + 2]) & 0xff) << 16 |
  10.     (((int) data[offset + 1]) & 0xff) << 8 |
  11.     (((int) data[offset]) & 0xff));
  12. }
  13. float get4ByteFloat (int offset, byte[] data) {
  14.   return Float.intBitsToFloat((int)get4Bytes(offset, data));
  15. }
Hopefully that points you in the right direction, sorry if Im totally off base.

Re : Problem with opengl

$
0
0
Hi Ja_Ha,

We're going to need more info from you, to start, some code showing how you get this error would be good. Also what platform are you on? What format is the video in?

thanks,

ak

Re : Problem with opengl

$
0
0
Looking at the error I think you are trying to use the GLGraphics library with a Processing 2.0 beta. Am I right?

If so, the bad news is you can't do this because the GLGraphics library is NOT compatible with Processing 2.0. The good news is most of the opengl functionality from the GLGraphics library has been incorporated into Processing 2.0. See: http://codeanticode.wordpress.com/

Re : Serial data is limited to signed 8-bit data???

$
0
0
>> One of the worst Java's implementation decisions -> signed byte primitive data-type!

Thanks for the reply.  I didn't want to say it cause I'm new to the forum and to Java but I was definitely thinking it!!

The only problem with your solution is that it doesn't solve the problem of efficiently getting data from the Serial library.  It seems the only function that take a buffer array parameter is Serial.readBytes(byteBuffer).

It seems that the only option I have is to use a loop of some kind to read out the data with readChar() or read() in the serialEvent() handler.  However now that I'm thinking about it I wonder if in reality thats what the readBytes(byteBuffer) function does in the background or some kind of memcopy.  When the serialEvent handler is called the data isn't already in the buffer I pass to the function so there is going to be overhead anyway.

For convenience I wonder if the Serial library author could add a new readChars() function - the fact that in Java the "char" or short is 16-bit wont matter because data from USART in normal mode is at max only 8-bits.

Please Use Tools- Fix the Serial Library??

$
0
0
I am not sure how to solve this problem. Any help would be greatly appreciated. I am a little new to processing but I could not find this problem in the forums. 

Find your Arduino in the list below, note its [index]:

Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
[0] "/dev/tty.Bluetooth-PDA-Sync"
[1] "/dev/cu.Bluetooth-PDA-Sync"
[2] "/dev/tty.Bluetooth-Modem"
[3] "/dev/cu.Bluetooth-Modem"
[4] "/dev/tty.usbmodem621"
[5] "/dev/cu.usbmodem621"
To use the serial library, first open
Applications -> Utilities -> Terminal.app
and enter the following:
sudo mkdir -p /var/lock
sudo chmod 777 /var/lock
Exception in thread "Animation Thread" java.lang.RuntimeException: Please use Tools ? Fix the Serial Library.
at processing.serial.Serial.<init>(Serial.java:153)
at processing.serial.Serial.<init>(Serial.java:116)
at brain_grapher.setup(brain_grapher.java:55)
at processing.core.PApplet.handleDraw(PApplet.java:2241)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:243)
at processing.core.PApplet.run(PApplet.java:2140)
at java.lang.Thread.run(Thread.java:680)

Here is the code I used. 
// Main controller / model file for the the Processing Brain Grapher.

// See README.markdown for more info.
// See http://frontiernerds.com/brain-hack for a tutorial on getting started with the Arduino Brain Library and this Processing Brain Grapher.

// Created by Eric Mika in Fall 2010, last update Spring 2012

import processing.serial.*;
import controlP5.*;

ControlP5 controlP5;
ControlFont font;

Serial serial;

Channel[] channels = new Channel[11];
Monitor[] monitors = new Monitor[10];
Graph graph;
ConnectionLight connectionLight;

int packetCount = 0;
int globalMax = 0;
String scaleMode;

void setup() {
  // Set up window
  size(1024, 768);
  frameRate(60);
  smooth();
  frame.setTitle("Processing Brain Grapher");  

  // Set up serial connection
  println("Find your Arduino in the list below, note its [index]:\n");
  println(Serial.list());
  serial = new Serial(this, Serial.list()[0], 9600);
  serial.bufferUntil(10);

  // Set up the ControlP5 knobs and dials
  controlP5 = new ControlP5(this);
  controlP5.setColorLabel(color(0));
  controlP5.setColorBackground(color(0));
  controlP5.disableShortcuts();
  controlP5.disableMouseWheel();
  controlP5.setMoveable(false);
  font = new ControlFont(createFont("DIN-MediumAlternate", 12), 12);

  // Create the channel objects
  channels[0] = new Channel("Signal Quality", color(0), "");
  channels[1] = new Channel("Attention", color(100), "");
  channels[2] = new Channel("Meditation", color(50), "");
  channels[3] = new Channel("Delta", color(219, 211, 42), "Dreamless Sleep");
  channels[4] = new Channel("Theta", color(245, 80, 71), "Drowsy");
  channels[5] = new Channel("Low Alpha", color(237, 0, 119), "Relaxed");
  channels[6] = new Channel("High Alpha", color(212, 0, 149), "Relaxed");
  channels[7] = new Channel("Low Beta", color(158, 18, 188), "Alert");
  channels[8] = new Channel("High Beta", color(116, 23, 190), "Alert");
  channels[9] = new Channel("Low Gamma", color(39, 25, 159), "Multi-sensory processing");
  channels[10] = new Channel("High Gamma", color(23, 26, 153), "???");

  // Manual override for a couple of limits.
  channels[0].minValue = 0;
  channels[0].maxValue = 200;
  channels[1].minValue = 0;
  channels[1].maxValue = 100;
  channels[2].minValue = 0;
  channels[2].maxValue = 100;
  channels[0].allowGlobal = false;
  channels[1].allowGlobal = false;
  channels[2].allowGlobal = false;

  // Set up the monitors, skip the signal quality
  for (int i = 0; i < monitors.length; i++) {
    monitors[i] = new Monitor(channels[i + 1], i * (width / 10), height / 2, width / 10, height / 2);
  }

  monitors[monitors.length - 1].w += width % monitors.length;

  // Set up the graph
  graph = new Graph(0, 0, width, height / 2);

  // Set yup the connection light
  connectionLight = new ConnectionLight(width - 98, 10, 20);
}

void draw() {
  // Keep track of global maxima
  if (scaleMode == "Global" && (channels.length > 3)) {
    for (int i = 3; i < channels.length; i++) {
      if (channels[i].maxValue > globalMax) globalMax = channels[i].maxValue;
    }
  }

  // Clear the background
  background(255);

  // Update and draw the main graph
  graph.update();
  graph.draw();

  // Update and draw the connection light
  connectionLight.update();
  connectionLight.draw();

  // Update and draw the monitors
  for (int i = 0; i < monitors.length; i++) {
    monitors[i].update();
    monitors[i].draw();
  }
}

void serialEvent(Serial p) {
  // Split incoming packet on commas
  // See https://github.com/kitschpatrol/Arduino-Brain-Library/blob/master/README for information on the CSV packet format
  String[] incomingValues = split(p.readString(), ',');

  // Verify that the packet looks legit
  if (incomingValues.length > 1) {
    packetCount++;

    // Wait till the third packet or so to start recording to avoid initialization garbage.
    if (packetCount > 3) {
      for (int i = 0; i < incomingValues.length; i++) {
        int newValue = Integer.parseInt(incomingValues[i].trim());

        // Zero the EEG power values if we don't have a signal.
        // Can be useful to leave them in for development.
        if ((Integer.parseInt(incomingValues[0]) == 200) && (i > 2)) newValue = 0;

        channels[i].addDataPoint(newValue);
      }
    }
  }
}


// Utilities

// Extend Processing's built-in map() function to support the Long datatype
long mapLong(long x, long in_min, long in_max, long out_min, long out_max) { 
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

// Extend Processing's built-in constrain() function to support the Long datatype
long constrainLong(long value, long min_value, long max_value) {
  if (value > max_value) return max_value;
  if (value < min_value) return min_value;
  return value;
}

Multiple Files triggering Minim

$
0
0
Hi, i am trying to playback many audio files with Minim SamplePlayer but I cannot get anything after 32th sample

Any solutions?

Also do you think it is good idea to to work with JUST processing or combination of Processing + Max/MSP or Supercollider?

Re : Video Capture: Resolutions and Settings

$
0
0
Did you get this resolved? I'm looking into trying the same thing soon.

Thanks!
Bryce

Re : Please Use Tools- Fix the Serial Library??

$
0
0
In Serial.list()[0], replace [0] with [1], [2] or other, depending on the real device you use (from the displayed list).

Re : Multiple Files triggering Minim

$
0
0
Changed topic type to Question, since you ask one. And moved from Programming Question, since the question is specialized.

Perhaps there is a built-in limitation in Minim (32 is a suspiciously round (in computing terms) number), but perhaps showing how you load and play the samples can help people knowing Minim (ie. not me) to understand the problem.
Viewing all 1768 articles
Browse latest View live