Given a center point (x0, y0, z0)
and a radius (g_radius
)
I want to use Python to generate points in a sphere in a cubic world (= Minecraft).
I’m trying to use this algorithm (I found it here on so) but it’s not precise and I have to increase the number of samples to a ridiculous huge number to get almost all the points, but it’s still not 100% accurate:
JavaScript
x
11
11
1
num_pts = 10000000
2
indices = arange(0, num_pts, dtype=float) + 0.5
3
phi = arccos(1 - 2 * indices / num_pts)
4
theta = pi * (1 + 5 ** 0.5) * indices
5
t_x, t_y, t_z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi)
6
tmp = [(g_x0 + int(x * g_radius),
7
g_y0 + int(y * g_radius) + g_radius,
8
g_z0 + int(z * g_radius))
9
for (x, y, z) in zip(t_x, t_y, t_z)]
10
final_coord_result = list(set(tmp))
11
Here’s what you get with a small radius (5
):
How would you do this?
Advertisement
Answer
This sounds like a job for raster_geometry:
JavaScript
1
16
16
1
import raster_geometry
2
from matplotlib import pyplot as plt
3
4
# define degree of rasterization
5
radius = 7.5
6
7
# create full sphere
8
sphere_coords = raster_geometry.sphere(int(2*radius), radius)
9
# make it hollow
10
sphere_coords = raster_geometry.unfill(sphere_coords)
11
12
# plot it
13
ax = plt.figure().add_subplot(111, projection='3d')
14
ax.scatter(*sphere_coords.nonzero())
15
plt.show()
16