Create a Bezier surface using Matplotlib

130 views Asked by At

I want to model a fluid (water) with a bezier surface. The problem is that on one axis, all the points are at the same height, which doesn't look like neither a fluid nor a bezier surface.

Here is my code:

import numpy as np
import matplotlib.pyplot as plt

n = 10 #grid size
X = np.arange(0, 1, 1/n)
Y = np.arange(0, 1, 1/n)
X, Y = np.meshgrid(X,Y)
Z = np.zeros((n,n))
#here I try to create random continuously control points to have a nice surface
Z[0] = np.random.random()
for i in range(n - 1):
    Z[i + 1] = Z[i] * (1 + 0.5 * np.random.normal())
for i in range(n):
    for j in range(n - 1):
        Z[i][j + 1] += Z[i][j] * (1 + 0.5 * np.random.normal())

d = 2*n #number of divisions (2 points per control point)

u, v = np.linspace(0, 1, d), np.linspace(0, 1, d) #variables

binome = lambda n, k : np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n - k))
bernstein = lambda n, k, t : binome(n, k) * t**k * (1 - t)**(n-k)

def bezier(X,Y,Z):
    xBezier = np.zeros((d, d))
    yBezier = np.zeros((d, d))
    zBezier = np.zeros((d, d))

    for i in range(n):
        for j in range(n): #calcul de la surface
            xBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * X[i, j]
            yBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * Y[i, j]
            zBezier += bernstein(n - 1, i, u) * bernstein(n - 1, j, v) * Z[i, j]

    return(xBezier, yBezier, zBezier)

xBezier, yBezier, zBezier = bezier(X, Y, Z)

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(xBezier.T, yBezier, zBezier, cmap=plt.cm.Blues, vmin=zBezier.min() * 0.8)
ax.scatter(X, Y, Z, edgecolors = 'face', color='tab:red')
plt.show()

I would like it to look like this: enter image description here

0

There are 0 answers