Search code examples
javaopengl3dprocessingrenderer

Placing a P3D object in the default renderer


I have created an audio visualizer using the default renderer in Processing 3, now I want to implement an independent spinning 3D cube (that uses P3D) within the audio visualizer (which was created in the default renderer). Here is the code for the 3D cube:

import processing.opengl.*;

float y = 0.1;
float x = 0.1;
float z = 0.1;

void setup()
{
    size(800,600,P3D);
    smooth();
}

void draw()
{
    translate(400,300,0);
    rotateX(x);
    rotateY(y);
    rotateZ(z);
    background(255);
    fill(255,228,225);
    box(200);
    x += random(.1);
    y += random(.1);
    z += random(.1);
}

Here's a snippet from the visualizer that pertains to 3D cube:

void setup()
{
  size(800, 600);
  //fullScreen(2);
  minim = new Minim(this);
  player = minim.loadFile("/Users/samuel/Desktop/GT.mp3");
  meta = player.getMetaData();
  beat = new BeatDetect();
  player.loop();
  fft = new FFT(player.bufferSize(), player.sampleRate());
  fft.logAverages(60, 7);
  noStroke();
  w = width/fft.avgSize();
  player.play();
  background(0);
  smooth();
}

Ultimately, I'm just curious if I can integrate a 3D object without changing the size() of the visualizer to P3D.


Solution

  • You can use the createGraphics() function to create a renderer, and you can pass P3D into that renderer to allow drawing in 3D.

    However, you can't do that if your sketch is using the default renderer. You have to use either P2D or P3D in your main renderer to be able to use P3D in any createGraphics() renderers. From the reference:

    It's important to consider the renderer used with createGraphics() in relation to the main renderer specified in size(). For example, it's only possible to use P2D or P3D with createGraphics() when one of them is defined in size(). Unlike Processing 1.0, P2D and P3D use OpenGL for drawing, and when using an OpenGL renderer it's necessary for the main drawing surface to be OpenGL-based. If P2D or P3D are used as the renderer in size(), then any of the options can be used with createGraphics(). If the default renderer is used in size(), then only the default or PDF can be used with createGraphics().

    Here's a little example that uses a P2D renderer as the main renderer and P3D as a sub-renderer:

    PGraphics pg;
    
    void setup() {
      size(200, 200, P2D);
      pg = createGraphics(100, 100, P3D);
    }
    
    void draw() {
      pg.beginDraw();
      pg.background(0);
      pg.noStroke();
      pg.translate(pg.width*0.5, pg.height*0.5);
      pg.lights();
      pg.sphere(25);
      pg.endDraw();
    
      background(0, 0, 255);
      image(pg, 50, 50); 
    }