# 網格 Worley 雜訊

March 31, 2022

## 鄰近的細胞

dotSCAD 的 `nz_worley2` 函式，可以基於網格來產生 Worley 雜訊，只要指定座標位置、隨機種子以及範圍，它會自動分割網格，在每個網格中隨機散佈一個細胞核，然後計算該座標位置的 Worley 雜訊：

``````use <noise/nz_worley2.scad>

size = [100, 50];
grid_w = 10;
seed = 51;

points = [
for(y = [0:size.y - 1], x = [0:size.x - 1])
[x, y]
];

cells = [for(p = points) nz_worley2(p.x, p.y, seed, grid_w)];

max_dist = max([for(c = cells) c[2]]);
for(i = [0:len(cells) - 1]) {
c = cells[i][2] / max_dist;
color([c, c, c])
linear_extrude(cells[i][2])
translate(points[i])
square(1);
}
``````

`nz_worley2` 傳回 `[x, y, noise]`，表示某座標位置是在細胞核 `[x, y]` 的勢力範圍內，雜訊值 `noise`，從上往下看模型的話，會是長這樣：

``````use <noise/nz_worley2s.scad>

size = [100, 50];
grid_w = 10;
seed = 51;

points = [
for(y = [0:size.y - 1], x = [0:size.x - 1])
[x, y]
];

cells = nz_worley2s(points, seed, grid_w);

for(i = [0:len(cells) - 1]) {
h = norm([cells[i].x, cells[i].y]) % grid_w;
color([h, h, h] / grid_w)
linear_extrude(h)
translate(points[i])
square(1);
}
``````

## 三維的 Worley 雜訊

Worley 雜訊〉的做法，也可以擴展到三維，不過計算量龐大；網格的 Worley 雜訊做法，也可以擴展到三維，dotSCAD 的 `nz_worley3` 函式就是實現。

``````use <voxel/vx_sphere.scad>

grid_w = 10;
seed = 51;

cells = [for(p = points) nz_worley3(p.x, p.y, p.z, seed, grid_w)];

max_dist = max([for(c = cells) c[3]]);
for(i = [0:len(cells) - 1]) {
c = cells[i][3] / max_dist * 1.5;
color([c > 1 ? 1 : c, 0, 0])
translate(points[i])
cube(1);
}
``````

dotSCAD 的 `voxel` 中，提供了一些建立體素（voxel）資料的函式，`vx_sphere` 是其中之一，簡單來說，可以想像成用方塊堆出一顆球，不過 `vx_sphere` 傳回的是座標資料，你不一定要用方塊來堆就是了；以上的程式會產生：

``````use <voxel/vx_sphere.scad>

grid_w = 10;
seed = 51;

cells = nz_worley3s(points, seed, grid_w);

for(i = [0:len(cells) - 1]) {