How to nicely generate a graph of a function of two variables with a restriction on the domain?

Hello,
I recently got into p5 from watching The Coding Train, and I wish to generate two-dimensional surfaces in 3D (like using WEBGL) given by a function of two variables.
If there is a function in Processing that does the job and I’m not just seeing it, then this is a Processing question. Otherwise, this could be a general question on graphing algorithms. I have no background in CS or algorithms.
My first goal is to render a surface z = x^2 + y^2 only for 0 <= z <= 20.

Here is my initial attempt:

var angleSliderX;
var rows = 30;
var cols = 30;
var s = 10;
var fcnTable = [];

//define a function to plot
function f(x, y) {
  return x ** 2 + y ** 2;
}

//create an array containing (x, y, f(x, y) ) info
for (i = -cols; i < cols; i++) {
  fcnTable.push([]);
  for (j = -rows; j < rows; j++) {
    fcnTable[i + cols].push(f(i, j));
  }
}

function mouseWheel(event) {
  s -= event.delta / 2500;
}

function setup() {
  createCanvas(400, 400, WEBGL);

  angleSliderX = createSlider(-PI / 2, PI / 2, PI / 3, 0.01);
  frameRate(30);
}

function draw() {
  background(0);
  scale(s);

  translate(0, 10, 0);
  rotateX(angleSliderX.value());

  //draw surface
  stroke(255);
  fill(100);
  for (j = -rows; j < rows; j++) {
    beginShape(TRIANGLE_STRIP);
    for (i = -cols; i < cols; i++) {
      if (f(i, j) <= 20) {
        if (f(i, j+1) <= 20) {
          vertex(i, j, fcnTable[i+cols][j+rows]);
          vertex(i, (j+1), fcnTable[i+cols][j+1+rows]);
        }
      }
    }
    endShape();
  }
}

I’m concerned that this creates jagged boundaries which I’m not so happy with. Are there known best practices to deal with such concerns without consuming too much computing power? Ideally, I wish to have a flat cut-out at z = 20 of the surface.

Thank you for your time!

1 Like

It looks like you want to solve algebraic equations in JavaScript. Instead of trying to implement your own solution, maybe try using a library? For example (untested):

https://algebra.js.org/

thx, i’ll check that out!