Implement texture PImage

PShape customShape, ellipseShape;

void setup() {
  size(400, 400, P3D);
  smooth(16);

  // load texture image
  PImage img = loadImage("vv.png");

  // create custom shape
  customShape = createShape();
  customShape.beginShape(TRIANGLE_FAN);
  int numSides = 100;
  float theta = TWO_PI / numSides;
  customShape.vertex(width/2, height/2);
  for (int i=0; i<numSides+1; i++) {
    float x = sin(i * theta) * width/2 + width/2;
    float y = cos(i * theta) * width/2 + height/2;
    customShape.vertex(x, y); 
  }
  customShape.endShape();

  // create ellipse shape
  ellipseShape = createShape(ELLIPSE, 0, 0, width, height);

  // add texture and coordinates to both PShapes
  addTextureUV(customShape, img);  
  addTextureUV(ellipseShape, img);

  // check texture coordinates for customShape: OK!
//  for (int i = 0; i < customShape.getVertexCount (); i++) {
//    println(customShape.getTextureU(i) + " | " + customShape.getTextureV(i));
//  }

  // check texture coordinates for ellipseShape: there are none!
  for (int i = 0; i < ellipseShape.getVertexCount (); i++) {
    println(ellipseShape.getTextureU(i) + " | " + ellipseShape.getTextureV(i));
  }
}

void draw() {
  background(255);
  // toggle between shapes with mouse press
  shape(mousePressed ? ellipseShape : customShape);
}

void addTextureUV(PShape s, PImage img) {
  s.setStroke(false);
  s.setTexture(img);
  s.setTextureMode(NORMAL);
  for (int i = 0; i < s.getVertexCount (); i++) {
    PVector v = s.getVertex(i);
    s.setTextureUV(i, map(v.x, 0, width, 0, 1), map(v.y, 0, height, 0, 1));
  }
}
1 Like

1 Like