在p5.js中创建实体3D形状

问题描述

我正在尝试在p5.js中使用3D制作苹果表面,类似于this page(Ctrl + F“ Apple Surface”)上的图像:

apple surface wireframe

apple surface filled

我目前拥有的是(interactive version in p5 editor):

function setup() {
  createCanvas(500,500,WEBGL);
  setAttributes('antialias',true);
  fill(237,34,93);
  strokeWeight(3);
}

function draw() {
  background(200);
  normalMaterial();
  rotateY(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  rotateZ(frameCount * 0.01);
  apple();
}


function apple() {
  beginShape(TRIANGLE_FAN);

  size = 20;

  for (let u = 0; u < TWO_PI; u += 0.1) {
      for (let v = -PI; v < PI; v += 0.1) {
    x = cos(u) * (4 + 3.8 * cos(v))
    y = sin(u) * (4 + 3.8 * cos(v))     
    z = (cos(v) + sin(v) -1) * (1+sin(v)) * log(1-PI * v/10)+7.5 * sin(v)
    //point(size * x,size * y,size * z);
    vertex(size * x,size * z);
      }
  }

  endShape(CLOSE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

如何像上面的第二张苹果图片一样使我的形状坚实?

解决方法

只需创建三角带图元(TRIANGLE_STRIP-参见beginShape()):

0        2       4        6
 +-------+-------+-------+---
 | \     | \     | \     | \
 |   \   |   \   |   \   |   \
 |     \ |     \ |     \ |
 +-------+-------+-------+---
1        3       5        7

function setup() {
  createCanvas(500,500,WEBGL);
  setAttributes('antialias',true);
  fill(237,34,93);
  strokeWeight(3);
}

function draw() {
  background(200);
  normalMaterial();
  rotateY(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  rotateZ(frameCount * 0.01);
  apple();
}

function apple() {

  size = 20;
  for (let u = 0; u < TWO_PI; u += 0.1) {
      beginShape(TRIANGLE_STRIP);
      for (let v = -PI; v < PI; v += 0.1) {
        x = cos(u) * (4 + 3.8 * cos(v))
        y = sin(u) * (4 + 3.8 * cos(v))     
        z = (cos(v) + sin(v) -1) * (1+sin(v)) * log(1-PI * v/10)+7.5 * sin(v)
        vertex(size * x,size * y,size * z);

        x = cos(u+0.1) * (4 + 3.8 * cos(v))
        y = sin(u+0.1) * (4 + 3.8 * cos(v)) 
        vertex(size * x,size * z);
      }
      endShape(CLOSE);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>