Debian Codegraph @

examples/01-filter/perlin_noise_2d.py

raw
1 """
2 .. _perlin_noise_2d_example:
3
4 Sample Function: Perlin Noise in 2D
5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 Here we use :func:`pyvista.core.utilities.features.sample_function` to sample
7 Perlin noise over a region to generate random terrain.
8
9 Perlin noise is atype of gradient noise often used by visual effects
10 artists to increase the appearance of realism in computer graphics.
11 Source: `Perlin Noise Wikipedia <https://en.wikipedia.org/wiki/Perlin_noise>`_
12
13 The development of Perlin Noise has allowed computer graphics artists
14 to better represent the complexity of natural phenomena in visual
15 effects for the motion picture industry.
16
17 """
18
19 import pyvista as pv
20
21 # %%
22 # Generate Perlin Noise over a StructuredGrid
23 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 # Feel free to change the values of ``freq`` to change the shape of
25 # the "mountains". For example, lowering the frequency will make the
26 # terrain seem more like hills rather than mountains.
27 freq = [0.689, 0.562, 0.683]
28 noise = pv.perlin_noise(1, freq, (0, 0, 0))
29 sampled = pv.sample_function(noise, bounds=(-10, 10, -10, 10, -10, 10), dim=(500, 500, 1))
30
31
32 # %%
33 # Warp by scalar
34 # ~~~~~~~~~~~~~~
35 # Here we warp by scalar to give the terrain some height based on the
36 # value of the Perlin noise. This is necessary to the terrain its shape.
37
38 mesh = sampled.warp_by_scalar('scalars')
39 mesh = mesh.extract_surface(algorithm=None)
40
41 # clean and smooth a little to reduce Perlin noise artifacts
42 mesh = mesh.smooth(n_iter=100, inplace=False, relaxation_factor=1)
43
44 # This makes the "water" level look flat.
45 z = mesh.points[:, 2]
46 diff = z.max() - z.min()
47
48 # water level at 70% (change this to change the water level)
49 water_percent = 0.7
50 water_level = z.max() - water_percent * diff
51 mesh.points[z < water_level, 2] = water_level
52
53
54 # %%
55 # Show the terrain as a contour plot
56
57 # make the water blue
58 rng = z.max() - z.min()
59 clim = (z.max() - rng * 1.65, z.max())
60
61 pl = pv.Plotter()
62 pl.add_mesh(
63 mesh,
64 scalars=z,
65 cmap='gist_earth',
66 n_colors=10,
67 show_scalar_bar=False,
68 smooth_shading=True,
69 clim=clim,
70 )
71 pl.show()
72
73
74 # %%
75 # Show the terrain with custom lighting and shadows
76
77 pl = pv.Plotter(lighting=None)
78 pl.add_light(
79 pv.Light(
80 position=(3, 1, 0.5),
81 show_actor=True,
82 positional=True,
83 cone_angle=90,
84 intensity=1.2,
85 )
86 )
87 pl.add_mesh(
88 mesh,
89 scalars=z,
90 cmap='gist_earth',
91 show_scalar_bar=False,
92 smooth_shading=True,
93 clim=clim,
94 )
95 pl.enable_shadows = True
96 pl.show()
97 # %%
98 # .. tags:: filter