-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathnoise.py
More file actions
511 lines (432 loc) · 19.7 KB
/
noise.py
File metadata and controls
511 lines (432 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
"""Noise map generators are provided by this module.
The :any:`Noise.sample_mgrid` and :any:`Noise.sample_ogrid` methods perform
much better than multiple calls to :any:`Noise.get_point`.
Example::
>>> import numpy as np
>>> import tcod
>>> noise = tcod.noise.Noise(
... dimensions=2,
... algorithm=tcod.noise.Algorithm.SIMPLEX,
... seed=42,
... )
>>> samples = noise[tcod.noise.grid(shape=(5, 4), scale=0.25, offset=(0, 0))]
>>> samples # Samples are a grid of floats between -1.0 and 1.0
array([[ 0. , -0.55046356, -0.76072866, -0.7088647 , -0.68165785],
[-0.27523372, -0.7205134 , -0.74057037, -0.43919194, -0.29195625],
[-0.40398532, -0.57662135, -0.33160293, 0.12860827, 0.2864191 ],
[-0.50773406, -0.2643614 , 0.24446318, 0.6390255 , 0.5922846 ]],
dtype=float32)
>>> (samples + 1.0) * 0.5 # You can normalize samples to 0.0 - 1.0
array([[0.5 , 0.22476822, 0.11963567, 0.14556766, 0.15917107],
[0.36238313, 0.1397433 , 0.12971482, 0.28040403, 0.35402188],
[0.29800734, 0.21168932, 0.33419853, 0.5643041 , 0.6432096 ],
[0.24613297, 0.3678193 , 0.6222316 , 0.8195127 , 0.79614234]],
dtype=float32)
>>> ((samples + 1.0) * (256 / 2)).astype(np.uint8) # Or as 8-bit unsigned bytes.
array([[128, 57, 30, 37, 40],
[ 92, 35, 33, 71, 90],
[ 76, 54, 85, 144, 164],
[ 63, 94, 159, 209, 203]], dtype=uint8)
"""
from __future__ import annotations
import enum
import warnings
from typing import TYPE_CHECKING, Any, Literal
import numpy as np
import tcod.constants
import tcod.random
from tcod.cffi import ffi, lib
if TYPE_CHECKING:
from collections.abc import Sequence
from numpy.typing import ArrayLike, NDArray
class Algorithm(enum.IntEnum):
"""Libtcod noise algorithms.
.. versionadded:: 12.2
"""
PERLIN = 1
"""Perlin noise."""
SIMPLEX = 2
"""Simplex noise."""
WAVELET = 4
"""Wavelet noise."""
def __repr__(self) -> str:
"""Return the string representation for this algorithm."""
return f"tcod.noise.Algorithm.{self.name}"
class Implementation(enum.IntEnum):
"""Noise implementations.
.. versionadded:: 12.2
"""
SIMPLE = 0
"""Generate plain noise."""
FBM = 1
"""Fractional Brownian motion.
https://en.wikipedia.org/wiki/Fractional_Brownian_motion
"""
TURBULENCE = 2
"""Turbulence noise implementation."""
def __repr__(self) -> str:
"""Return the string representation for this implementation."""
return f"tcod.noise.Implementation.{self.name}"
def __getattr__(name: str) -> Implementation:
if name in Implementation.__members__:
warnings.warn(
f"'tcod.noise.{name}' is deprecated, use 'tcod.noise.Implementation.{name}' instead.",
FutureWarning,
stacklevel=2,
)
return Implementation[name]
msg = f"module {__name__} has no attribute {name}"
raise AttributeError(msg)
class Noise:
"""A configurable noise sampler.
The ``hurst`` exponent describes the raggedness of the resultant noise,
with a higher value leading to a smoother noise.
Not used with tcod.noise.SIMPLE.
``lacunarity`` is a multiplier that determines how fast the noise frequency increases for each successive octave.
Not used with tcod.noise.SIMPLE.
Args:
dimensions: Must be from 1 to 4.
algorithm: Defaults to :any:`tcod.noise.Algorithm.SIMPLEX`
implementation: Defaults to :any:`tcod.noise.Implementation.SIMPLE`
hurst: The hurst exponent. Should be in the 0.0-1.0 range.
lacunarity: The noise lacunarity.
octaves: The level of detail on fBm and turbulence implementations.
seed: A Random instance, or None.
Attributes:
noise_c (CData): A cffi pointer to a TCOD_noise_t object.
"""
def __init__( # noqa: PLR0913
self,
dimensions: int,
algorithm: int = Algorithm.SIMPLEX,
implementation: int = Implementation.SIMPLE,
hurst: float = 0.5,
lacunarity: float = 2.0,
octaves: float = 4,
seed: int | tcod.random.Random | None = None,
) -> None:
"""Initialize and seed the noise object."""
if not 0 < dimensions <= 4: # noqa: PLR2004
msg = f"dimensions must be in range 0 < n <= 4, got {dimensions}"
raise ValueError(msg)
self._seed = seed
self._random = self.__rng_from_seed(seed)
_random_c = self._random.random_c
self.noise_c = ffi.gc(
ffi.cast(
"struct TCOD_Noise*",
lib.TCOD_noise_new(dimensions, hurst, lacunarity, _random_c),
),
lib.TCOD_noise_delete,
)
self._tdl_noise_c = ffi.new("TDLNoise*", (self.noise_c, dimensions, 0, octaves))
self.algorithm = algorithm
self.implementation = implementation # sanity check
@staticmethod
def __rng_from_seed(seed: None | int | tcod.random.Random) -> tcod.random.Random:
if seed is None or isinstance(seed, int):
return tcod.random.Random(seed=seed, algorithm=tcod.random.MERSENNE_TWISTER)
return seed
def __repr__(self) -> str:
"""Return the string representation of this noise instance."""
parameters = [
f"dimensions={self.dimensions}",
f"algorithm={self.algorithm!r}",
f"implementation={Implementation(self.implementation)!r}",
]
if self.hurst != 0.5: # noqa: PLR2004 # Default value
parameters.append(f"hurst={self.hurst}")
if self.lacunarity != 2: # noqa: PLR2004 # Default value
parameters.append(f"lacunarity={self.lacunarity}")
if self.octaves != 4: # noqa: PLR2004 # Default value
parameters.append(f"octaves={self.octaves}")
if self._seed is not None:
parameters.append(f"seed={self._seed}")
return f"tcod.noise.Noise({', '.join(parameters)})"
@property
def dimensions(self) -> int:
"""Number of dimensions supported by this noise generator."""
return int(self._tdl_noise_c.dimensions)
@property
def algorithm(self) -> int:
"""Current selected algorithm. Can be changed."""
noise_type = self.noise_c.noise_type
return Algorithm(noise_type) if noise_type else Algorithm.SIMPLEX
@algorithm.setter
def algorithm(self, value: int) -> None:
lib.TCOD_noise_set_type(self.noise_c, value)
@property
def implementation(self) -> int:
"""Current selected implementation. Can be changed."""
return Implementation(self._tdl_noise_c.implementation)
@implementation.setter
def implementation(self, value: int) -> None:
if not 0 <= value < 3: # noqa: PLR2004
msg = f"{value!r} is not a valid implementation. "
raise ValueError(msg)
self._tdl_noise_c.implementation = value
@property
def hurst(self) -> float:
"""Noise hurst exponent. Can be changed."""
return float(self.noise_c.H)
@property
def lacunarity(self) -> float:
"""Noise lacunarity. Can be changed."""
return float(self.noise_c.lacunarity)
@property
def octaves(self) -> float:
"""Level of detail on fBm and turbulence implementations. Can be changed."""
return float(self._tdl_noise_c.octaves)
@octaves.setter
def octaves(self, value: float) -> None:
self._tdl_noise_c.octaves = value
def get_point(self, x: float = 0, y: float = 0, z: float = 0, w: float = 0) -> float:
"""Return the noise value at the (x, y, z, w) point.
Args:
x: The position on the 1st axis.
y: The position on the 2nd axis.
z: The position on the 3rd axis.
w: The position on the 4th axis.
"""
return float(lib.NoiseGetSample(self._tdl_noise_c, (x, y, z, w)))
def __getitem__(self, indexes: Any) -> NDArray[np.float32]:
"""Sample a noise map through NumPy indexing.
This follows NumPy's advanced indexing rules, but allows for floating point values.
.. versionadded:: 11.16
"""
if not isinstance(indexes, tuple):
indexes = (indexes,)
if len(indexes) > self.dimensions:
msg = f"This noise generator has {self.dimensions} dimensions, but was indexed with {len(indexes)}."
raise IndexError(msg)
indexes = list(np.broadcast_arrays(*indexes))
c_input = [ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL]
for i, index in enumerate(indexes):
if index.dtype.type == np.object_:
msg = "Index arrays can not be of dtype np.object_."
raise TypeError(msg)
indexes[i] = np.ascontiguousarray(index, dtype=np.float32)
c_input[i] = ffi.from_buffer("float*", indexes[i])
c_input_tuple = tuple(c_input)
assert len(c_input_tuple) == 4 # noqa: PLR2004
out: NDArray[np.float32] = np.empty(indexes[0].shape, dtype=np.float32)
if self.implementation == Implementation.SIMPLE:
lib.TCOD_noise_get_vectorized(
self.noise_c,
self.algorithm,
out.size,
*c_input_tuple,
ffi.from_buffer("float*", out),
)
elif self.implementation == Implementation.FBM:
lib.TCOD_noise_get_fbm_vectorized(
self.noise_c,
self.algorithm,
self.octaves,
out.size,
*c_input_tuple,
ffi.from_buffer("float*", out),
)
elif self.implementation == Implementation.TURBULENCE:
lib.TCOD_noise_get_turbulence_vectorized(
self.noise_c,
self.algorithm,
self.octaves,
out.size,
*c_input_tuple,
ffi.from_buffer("float*", out),
)
else:
msg = f"Unexpected {self.implementation!r}"
raise TypeError(msg)
return out
def sample_mgrid(self, mgrid: ArrayLike) -> NDArray[np.float32]:
"""Sample a mesh-grid array and return the result.
The :any:`sample_ogrid` method performs better as there is a lot of
overhead when working with large mesh-grids.
Args:
mgrid: A mesh-grid array of points to sample.
A contiguous array of type `numpy.float32` is preferred.
Returns:
An array of sampled points.
This array has the shape: ``mgrid.shape[:-1]``.
The ``dtype`` is `numpy.float32`.
"""
mgrid = np.ascontiguousarray(mgrid, np.float32)
if mgrid.shape[0] != self.dimensions:
msg = f"mgrid.shape[0] must equal self.dimensions, {mgrid.shape!r}[0] != {self.dimensions!r}"
raise ValueError(msg)
out: np.ndarray[Any, np.dtype[np.float32]] = np.ndarray(mgrid.shape[1:], np.float32)
if mgrid.shape[1:] != out.shape:
msg = f"mgrid.shape[1:] must equal out.shape, {mgrid.shape!r}[1:] != {out.shape!r}"
raise ValueError(msg)
lib.NoiseSampleMeshGrid(
self._tdl_noise_c,
out.size,
ffi.from_buffer("float*", mgrid),
ffi.from_buffer("float*", out),
)
return out
def sample_ogrid(self, ogrid: Sequence[ArrayLike]) -> NDArray[np.float32]:
"""Sample an open mesh-grid array and return the result.
Args:
ogrid: An open mesh-grid.
Returns:
An array of sampled points.
The ``shape`` is based on the lengths of the open mesh-grid arrays.
The ``dtype`` is `numpy.float32`.
"""
if len(ogrid) != self.dimensions:
msg = f"len(ogrid) must equal self.dimensions, {len(ogrid)!r} != {self.dimensions!r}"
raise ValueError(msg)
ogrids: list[NDArray[np.float32]] = [np.ascontiguousarray(array, np.float32) for array in ogrid]
out: np.ndarray[Any, np.dtype[np.float32]] = np.ndarray([array.size for array in ogrids], np.float32)
lib.NoiseSampleOpenMeshGrid(
self._tdl_noise_c,
len(ogrids),
out.shape,
[ffi.from_buffer("float*", array) for array in ogrids],
ffi.from_buffer("float*", out),
)
return out
def __getstate__(self) -> dict[str, Any]:
"""Support picking this instance."""
state = self.__dict__.copy()
if self.dimensions < 4 and self.noise_c.waveletTileData == ffi.NULL: # noqa: PLR2004
# Trigger a side effect of wavelet, so that copies will be synced.
saved_algo = self.algorithm
self.algorithm = tcod.constants.NOISE_WAVELET
self.get_point()
self.algorithm = saved_algo
waveletTileData = None # noqa: N806
if self.noise_c.waveletTileData != ffi.NULL:
waveletTileData = list(self.noise_c.waveletTileData[0 : 32 * 32 * 32]) # noqa: N806
state["_waveletTileData"] = waveletTileData
state["noise_c"] = {
"ndim": self.noise_c.ndim,
"map": list(self.noise_c.map),
"buffer": [list(sub_buffer) for sub_buffer in self.noise_c.buffer],
"H": self.noise_c.H,
"lacunarity": self.noise_c.lacunarity,
"exponent": list(self.noise_c.exponent),
"waveletTileData": waveletTileData,
"noise_type": self.noise_c.noise_type,
}
state["_tdl_noise_c"] = {
"dimensions": self._tdl_noise_c.dimensions,
"implementation": self._tdl_noise_c.implementation,
"octaves": self._tdl_noise_c.octaves,
}
return state
def __setstate__(self, state: dict[str, Any]) -> None:
"""Unpickle this instance."""
if isinstance(state, tuple): # deprecated format
return self._setstate_old(state)
# unpack wavelet tile data if it exists
if "_waveletTileData" in state:
state["_waveletTileData"] = ffi.new("float[]", state["_waveletTileData"])
state["noise_c"]["waveletTileData"] = state["_waveletTileData"]
else:
state["noise_c"]["waveletTileData"] = ffi.NULL
# unpack TCOD_Noise and link to Random instance
state["noise_c"]["rand"] = state["_random"].random_c
state["noise_c"] = ffi.new("struct TCOD_Noise*", state["noise_c"])
# unpack TDLNoise and link to libtcod noise
state["_tdl_noise_c"]["noise"] = state["noise_c"]
state["_tdl_noise_c"] = ffi.new("TDLNoise*", state["_tdl_noise_c"])
self.__dict__.update(state)
return None
def _setstate_old(self, state: tuple[Any, ...]) -> None:
self._random = state[0]
self.noise_c = ffi.new("struct TCOD_Noise*")
self.noise_c.ndim = state[3]
ffi.buffer(self.noise_c.map)[:] = state[4]
ffi.buffer(self.noise_c.buffer)[:] = state[5]
self.noise_c.H = state[6]
self.noise_c.lacunarity = state[7]
ffi.buffer(self.noise_c.exponent)[:] = state[8]
if state[9]:
# high change of this being prematurely garbage collected!
self.__waveletTileData = ffi.new("float[]", 32 * 32 * 32)
ffi.buffer(self.__waveletTileData)[:] = state[9]
self.noise_c.noise_type = state[10]
self._tdl_noise_c = ffi.new("TDLNoise*", (self.noise_c, self.noise_c.ndim, state[1], state[2]))
def grid(
shape: tuple[int, ...],
scale: tuple[float, ...] | float,
origin: tuple[float, ...] | None = None,
indexing: Literal["ij", "xy"] = "xy",
*,
offset: tuple[float, ...] | None = None,
) -> tuple[NDArray[np.number], ...]:
"""Generate a mesh-grid of sample points to use with noise sampling.
Args:
shape: The shape of the grid.
This can be any number of dimensions, but :class:`Noise` classes only support up to 4.
scale: The step size between samples.
This can be a single float, or it can be a tuple of floats with one float for each axis in `shape`.
A lower scale gives smoother transitions between noise values.
origin: The position of the first sample.
If `None` then the `origin` will be zero on each axis.
`origin` is not scaled by the `scale` parameter.
indexing: Passed to :any:`numpy.meshgrid`.
offset: The offset into the shape to generate.
Similar to `origin` but is scaled by the `scale` parameter.
Can be multiples of `shape` to index noise samples by chunk.
.. versionadded:: 19.2
Returns:
A sparse mesh-grid to be passed into a :class:`Noise` instance.
Example::
>>> noise = tcod.noise.Noise(dimensions=2, seed=42)
# Common case for ij-indexed arrays
>>> noise[tcod.noise.grid(shape=(3, 5), scale=0.25, indexing="ij")]
array([[ 0. , -0.27523372, -0.40398532, -0.50773406, -0.64945626],
[-0.55046356, -0.7205134 , -0.57662135, -0.2643614 , -0.12529983],
[-0.76072866, -0.74057037, -0.33160293, 0.24446318, 0.5346834 ]],
dtype=float32)
# Transpose an xy-indexed array to get a standard order="F" result
>>> noise[tcod.noise.grid(shape=(4, 5), scale=(0.5, 0.25), origin=(1.0, 1.0))].T
array([[ 0.52655405, 0.25038874, -0.03488023, -0.18455243, -0.16333057],
[-0.5037453 , -0.75348294, -0.73630923, -0.35063767, 0.18149695],
[-0.81221616, -0.6379566 , -0.12449139, 0.4495706 , 0.7547447 ],
[-0.7057655 , -0.5817767 , -0.22774395, 0.02399864, -0.07006818]],
dtype=float32)
# Can sample noise by chunk using the offset keyword
>>> noise[tcod.noise.grid(shape=(3, 5), scale=0.25, indexing="ij", offset=(0, 0))]
array([[ 0. , -0.27523372, -0.40398532, -0.50773406, -0.64945626],
[-0.55046356, -0.7205134 , -0.57662135, -0.2643614 , -0.12529983],
[-0.76072866, -0.74057037, -0.33160293, 0.24446318, 0.5346834 ]],
dtype=float32)
>>> noise[tcod.noise.grid(shape=(3, 5), scale=0.25, indexing="ij", offset=(3, 0))]
array([[-0.7088647 , -0.43919194, 0.12860827, 0.6390255 , 0.80402255],
[-0.68165785, -0.29195625, 0.2864191 , 0.5922846 , 0.52655405],
[-0.7841389 , -0.46131462, 0.0159424 , 0.17141782, -0.04198273]],
dtype=float32)
>>> noise[tcod.noise.grid(shape=(3, 5), scale=0.25, indexing="ij", offset=(6, 0))]
array([[-0.779634 , -0.60696834, -0.27446985, -0.23233278, -0.5037453 ],
[-0.5474089 , -0.54476213, -0.42235228, -0.49519652, -0.7101793 ],
[-0.28291094, -0.4326369 , -0.5227732 , -0.69655263, -0.81221616]],
dtype=float32)
.. versionadded:: 12.2
"""
if isinstance(scale, (int, float)):
scale = (scale,) * len(shape)
if origin is None:
origin = (0,) * len(shape)
if len(shape) != len(scale):
msg = "shape must have the same length as scale"
raise TypeError(msg)
if len(shape) != len(origin):
msg = "shape must have the same length as origin"
raise TypeError(msg)
if offset is not None:
if len(shape) != len(offset):
msg = "shape must have the same length as offset"
raise TypeError(msg)
origin = tuple(
i_origin + i_scale * i_offset for i_scale, i_offset, i_origin in zip(scale, offset, origin, strict=True)
)
indexes = (
np.arange(i_shape) * i_scale + i_origin for i_shape, i_scale, i_origin in zip(shape, scale, origin, strict=True)
)
return tuple(np.meshgrid(*indexes, copy=False, sparse=True, indexing=indexing))