-
-
Notifications
You must be signed in to change notification settings - Fork 327
/
fastnoise.zig
1981 lines (1711 loc) · 109 KB
/
fastnoise.zig
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MIT License
//
// Copyright(c) 2023 Jordan Peck ([email protected])
// Copyright(c) 2023 Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// .'',;:cldxkO00KKXXNNWWWNNXKOkxdollcc::::::;:::ccllloooolllllllllooollc:,'... ...........',;cldxkO000Okxdlc::;;;,,;;;::cclllllll
// ..',;:ldxO0KXXNNNNNNNNXXK0kxdolcc::::::;;;,,,,,,;;;;;;;;;;:::cclllllc:;'.... ...........',;:ldxO0KXXXK0Okxdolc::;;;;::cllodddddo
// ...',:loxO0KXNNNNNXXKK0Okxdolc::;::::::::;;;,,'''''.....''',;:clllllc:;,'............''''''''',;:loxO0KXNNNNNXK0Okxdollccccllodxxxxxxd
// ....';:ldkO0KXXXKK00Okxdolcc:;;;;;::cclllcc:;;,''..... ....',;clooddolcc:;;;;,,;;;;;::::;;;;;;:cloxk0KXNWWWWWWNXKK0Okxddoooddxxkkkkkxx
// .....';:ldxkOOOOOkxxdolcc:;;;,,,;;:cllooooolcc:;'... ..,:codxkkkxddooollloooooooollcc:::::clodkO0KXNWWWWWWNNXK00Okxxxxxxxxkkkkxxx
// . ....';:cloddddo___________,,,,;;:clooddddoolc:,... ..,:ldx__00OOOkkk___kkkkkkxxdollc::::cclodkO0KXXNNNNNNXXK0OOkxxxxxxxxxxxxddd
// .......',;:cccc:| |,,,;;:cclooddddoll:;'.. ..';cox| \KKK000| |KK00OOkxdocc___;::clldxxkO0KKKKK00Okkxdddddddddddddddoo
// .......'',,,,,''| ________|',,;;::cclloooooolc:;'......___:ldk| \KK000| |XKKK0Okxolc| |;;::cclodxxkkkkxxdoolllcclllooodddooooo
// ''......''''....| | ....'',,,,;;;::cclloooollc:;,''.'| |oxk| \OOO0| |KKK00Oxdoll|___|;;;;;::ccllllllcc::;;,,;;;:cclloooooooo
// ;;,''.......... | |_____',,;;;____:___cllo________.___| |___| \xkk| |KK_______ool___:::;________;;;_______...'',;;:ccclllloo
// c:;,''......... | |:::/ ' |lo/ | | \dx| |0/ \d| |cc/ |'/ \......',,;;:ccllo
// ol:;,'..........| _____|ll/ __ |o/ ______|____ ___| | \o| |/ ___ \| |o/ ______|/ ___ \ .......'',;:clo
// dlc;,...........| |::clooo| / | |x\___ \KXKKK0| |dol| |\ \| | | | | |d\___ \..| | / / ....',:cl
// xoc;'... .....'| |llodddd| \__| |_____\ \KKK0O| |lc:| |'\ | |___| | |_____\ \.| |_/___/... ...',;:c
// dlc;'... ....',;| |oddddddo\ | |Okkx| |::;| |..\ |\ /| | | \ |... ....',;:c
// ol:,'.......',:c|___|xxxddollc\_____,___|_________/ddoll|___|,,,|___|...\_____|:\ ______/l|___|_________/...\________|'........',;::cc
// c:;'.......';:codxxkkkkxxolc::;::clodxkOO0OOkkxdollc::;;,,''''',,,,''''''''''',,'''''',;:loxkkOOkxol:;,'''',,;:ccllcc:;,'''''',;::ccll
// ;,'.......',:codxkOO0OOkxdlc:;,,;;:cldxxkkxxdolc:;;,,''.....'',;;:::;;,,,'''''........,;cldkO0KK0Okdoc::;;::cloodddoolc:;;;;;::ccllooo
// .........',;:lodxOO0000Okdoc:,,',,;:clloddoolc:;,''.......'',;:clooollc:;;,,''.......',:ldkOKXNNXX0Oxdolllloddxxxxxxdolccccccllooodddd
// . .....';:cldxkO0000Okxol:;,''',,;::cccc:;,,'.......'',;:cldxxkkxxdolc:;;,'.......';coxOKXNWWWNXKOkxddddxxkkkkkkxdoollllooddxxxxkkk
// ....',;:codxkO000OOxdoc:;,''',,,;;;;,''.......',,;:clodkO00000Okxolc::;,,''..',;:ldxOKXNWWWNNK0OkkkkkkkkkkkxxddooooodxxkOOOOO000
// ....',;;clodxkkOOOkkdolc:;,,,,,,,,'..........,;:clodxkO0KKXKK0Okxdolcc::;;,,,;;:codkO0XXNNNNXKK0OOOOOkkkkxxdoollloodxkO0KKKXXXXX
//
// VERSION: 1.1.1
// https://github.com/Auburn/FastNoiseLite
//! Developed and tested using Zig 0.12.0
const std = @import("std");
const expect = std.testing.expect;
/// A constant prime-number used in x-axis calculations.
const prime_x: i32 = 501125321;
/// A constant prime-number used in y-axis calculations.
const prime_y: i32 = 1136930381;
/// A constant prime-number used in z-axis calculations.
const prime_z: i32 = 1720413743;
/// The value of `prime_z` left-shifted by 1 bit.
const prime_x_shl1 = std.math.shl(i32, prime_x, 1);
/// The value of `prime_y` left-shifted by 1 bit. Overflow bits are truncated.
const prime_y_shl1 = std.math.shl(i32, prime_y, 1);
/// The value of `prime_z` left-shifted by 1 bit. Overflow bits are truncated.
const prime_z_shl1 = std.math.shl(i32, prime_z, 1);
/// Describes a noise-generating algorithm.
pub const NoiseType = enum {
/// Simplex is the successor of and comparable to Perlin noise, but with fewer
/// directional artifacts in higher dimensions, and a lower computational overhead.
simplex,
/// A variation of simplex (i.e. "SuperSimplex") which has a smoother output.
simplex_smooth,
/// Worley/Voronoi noise algorithm.
cellular,
/// A classic general-purpose gradient noise.
perlin,
/// A more complex variation of value noise that employs a cubic function.
value_cubic,
/// Consists of the creation of a lattice of points which are assigned random values.
value,
};
pub const RotationType = enum {
none,
improve_xy_planes,
improve_xz_planes,
};
pub const FractalType = enum {
none,
fbm,
ridged,
ping_pong,
progressive,
independent,
};
pub const CellularDistanceFunc = enum {
euclidean,
euclidean_sq,
manhattan,
hybrid,
};
pub const CellularReturnType = enum {
cell_value,
distance,
distance2,
distance2_add,
distance2_sub,
distance2_mul,
distance2_div,
};
pub const DomainWarpType = enum {
simplex,
simplex_reduced,
basic_grid,
};
/// Structure containing the noise-generater state.
///
/// The generator behaves as a state-machine, and all of its functions are "pure" in
/// the regard that that they do not modify the internal state of the generator.
/// Configuration of the generator is done via the struct's fields, which are intended
/// to be modified directly as-needed.
pub fn Noise(comptime Float: type) type {
// Compile-error if a non-float is specified
switch (@typeInfo(Float)) {
.Float => |f| switch (f.bits) {
32, 64 => {},
else => @compileError("only 32 and 64 bit types supported"),
},
else => @compileError(@typeName(Float) ++ " is not a floating-point type."),
}
// Equivalent to -ffast-math in GCC
@setFloatMode(.optimized);
const Vec4 = @Vector(4, Float);
const sqrt3: Float = comptime @sqrt(3.0);
const f2: Float = comptime 0.5 * (sqrt3 - 1.0);
const g2: Float = comptime (3.0 - sqrt3) / 6.0;
const r3: Float = comptime 2.0 / 3.0;
return struct {
/// Alias name for the current type.
const State = @This();
/// Seed used for all noise types.
///
/// Default: `1337`
seed: i32 = 1337,
/// The frequency for all noise types.
///
/// Default: `0.01`
frequency: Float = 0.01,
/// The noise algorithm to be used.
///
/// Default: `.simplex`
noise_type: NoiseType = .simplex,
/// Sets rotation type for 3D noise.
///
/// Default: `.none`
rotation_type: RotationType = .none,
/// The method used for combining octaves for all fractal noise types.
///
/// Default: `.none`
fractal_type: FractalType = .none,
/// The octave count for all fractal noise types.
///
/// Default: `3`
octaves: u32 = 3,
/// The octave lacunarity for all fractal noise types.
///
/// Default: `2.0`
lacunarity: Float = 2.0,
/// The octave gain for all fractal noise types.
///
/// Default: `0.5`
gain: Float = 0.5,
/// The octave weighting for all non domain warp fractal types.
///
/// Default: `0.0`
weighted_strength: Float = 0.0,
/// The strength of the fractal ping pong effect.
///
/// Default: `2.0`
ping_pong_strength: Float = 2.0,
/// The distance function used in cellular noise calculations.
///
/// Default: `euclidean_sq`
cellular_distance: CellularDistanceFunc = .euclidean_sq,
/// The cellular return type from cellular noise calculations.
///
/// Default: `.distance`
cellular_return: CellularReturnType = .distance,
/// The maximum distance a cellular point can move from it's grid position.
/// Setting this higher than `1.0` will cause artifacts.
///
/// Default: `1.0`
cellular_jitter_mod: Float = 1.0,
/// The warp algorithm when using domain warp.
///
/// Default: `.simplex`
domain_warp_type: DomainWarpType = .simplex,
/// The maximum warp distance from original position when using domain warp.
///
/// Default: `1.0`
domain_warp_amp: Float = 1.0,
/// Generates 2D noise at given position using the currently configured state.
/// The return value is normalized to the the range of `-1.0` to `1.0`.
pub fn genNoise2D(self: *const State, x: Float, y: Float) Float {
var ox = x;
var oy = y;
self.transformNoiseCoordinate2D(&ox, &oy);
return switch (self.fractal_type) {
.fbm => self.genFractalFBm2D(ox, oy),
.ridged => self.genFractalRidged2D(ox, oy),
.ping_pong => self.genFractalPingPong2D(ox, oy),
else => self.genNoiseSingle2D(self.seed, ox, oy),
};
}
/// Generates 2D noise at given position using the currently configured state.
/// The return value is mapped to the given range and numeric type.
pub fn genNoise2DRange(self: *const State, x: Float, y: Float, comptime T: type, min: T, max: T) T {
std.debug.assert(min < max);
// Normalize to range of 0..1
const n = 0.5 * (1.0 + @max(-1.0, @min(1.0, self.genNoise2D(x, y))));
return switch (@typeInfo(T)) {
.Int => min + @as(T, @intFromFloat(n * @as(Float, @floatFromInt(max - min)))),
.Float => min + @as(T, @floatCast(n * @as(Float, @floatCast(max - min)))),
else => @compileError(@typeName(T) ++ " is not a numeric type"),
};
}
/// Generates 2D noise at given position using the currently configured state.
/// The return value is mapped to the range of the specified numeric type.
pub fn genNoise2DAsType(self: *const State, x: Float, y: Float, comptime T: type) T {
return switch (@typeInfo(T)) {
.Int => {
const min = comptime std.math.minInt(T);
const max = comptime std.math.maxInt(T);
return genNoise2DRange(self, x, y, T, min, max);
},
.Float => @floatCast(genNoise2D(self, x, y)),
else => @compileError(@typeName(T) ++ " is not a numeric type"),
};
}
/// Warps the specified 2D coordinates.
///
/// This is typically done using two separate noise states, where one is used for
/// modiifying the coordinates, which are then used by another for generation.
pub inline fn domainWarp2D(self: *const State, x: *Float, y: *Float) void {
switch (self.fractal_type) {
.progressive => self.domainWarpFractalProgressive2D(x, y),
.independent => self.domainWarpFractalIndependent2D(x, y),
else => self.domainWarpSingle2D(x, y),
}
}
/// Generates 3D noise at given position using the currently configured state.
/// The return value is normalized to the the range of `-1.0` to `1.0`.
pub fn genNoise3D(self: *const State, x: Float, y: Float, z: Float) Float {
var ox = x;
var oy = y;
var oz = z;
self.transformNoiseCoordinate3D(&ox, &oy, &oz);
return switch (self.fractal_type) {
.fbm => self.genFractalFBm3D(ox, oy, oz),
.ridged => self.genFractalRidged3D(ox, oy, oz),
.ping_pong => self.genFractalPingPong3D(ox, oy, oz),
else => self.genNoiseSingle3D(self.seed, ox, oy, oz),
};
}
/// Generates 3D noise at given position using the currently configured state.
/// The return value is mapped to the given range and numeric type.
pub fn genNoise3DRange(self: *const State, x: Float, y: Float, z: Float, comptime T: type, min: T, max: T) T {
std.debug.assert(min < max);
// Normalize to range of 0..1
const n = 0.5 * (1.0 + @max(-1.0, @min(1.0, self.genNoise3D(x, y, z))));
return switch (@typeInfo(T)) {
.Int => min + @as(T, @intFromFloat(n * @as(Float, @floatFromInt(max - min)))),
.Float => min + @as(T, @floatCast(n * @as(Float, @floatCast(max - min)))),
else => @compileError(@typeName(T) ++ " is not a numeric type"),
};
}
/// Generates 3D noise at given position using the currently configured state.
/// The return value is mapped to the range of the specified numeric type.
pub fn genNoise3DAsType(self: *const State, x: Float, y: Float, z: Float, comptime T: type) T {
return switch (@typeInfo(T)) {
.Int => {
const min = comptime std.math.minInt(T);
const max = comptime std.math.maxInt(T);
return genNoise3DRange(self, x, y, z, T, min, max);
},
.Float => @floatCast(genNoise3D(self, x, y, z)),
else => @compileError(@typeName(T) ++ " is not a numeric type"),
};
}
/// Warps the specified 3D coordinates.
///
/// This is typically done using two separate noise states, where one is used for
/// modiifying the coordinates, which are then used by another for generation.
pub inline fn domainWarp3D(self: *const State, x: *Float, y: *Float, z: *Float) void {
switch (self.fractal_type) {
.progressive => self.domainWarpFractalProgressive3D(x, y, z),
.independent => self.domainWarpFractalIndependent3D(x, y, z),
else => self.domainWarpSingle3D(x, y, z),
}
}
// End of public API
inline fn genNoiseSingle2D(state: *const State, seed: i32, x: Float, y: Float) Float {
return switch (state.noise_type) {
.simplex => singleSimplex2D(seed, x, y),
.simplex_smooth => singleSimplexS2D(seed, x, y),
.cellular => singleCellular2D(state, seed, x, y),
.perlin => singlePerlin2D(seed, x, y),
.value_cubic => singleValueCubic2D(seed, x, y),
.value => singleValue2D(seed, x, y),
};
}
inline fn genNoiseSingle3D(state: *const State, seed: i32, x: Float, y: Float, z: Float) Float {
return switch (state.noise_type) {
.simplex => singleSimplex3D(seed, x, y, z),
.simplex_smooth => singleSimplexS3D(seed, x, y, z),
.cellular => singleCellular3D(state, seed, x, y, z),
.perlin => singlePerlin3D(seed, x, y, z),
.value_cubic => singleValueCubic3D(seed, x, y, z),
.value => singleValue3D(seed, x, y, z),
};
}
inline fn doSingleDomainWarp2D(self: *const State, seed: i32, amp: Float, freq: Float, x: Float, y: Float, xp: *Float, yp: *Float) void {
switch (self.domain_warp_type) {
.simplex => singleDomainWarpSimplexGradient(seed, amp * 38.283687591552734375, freq, x, y, xp, yp, false),
.simplex_reduced => singleDomainWarpSimplexGradient(seed, amp * 16.0, freq, x, y, xp, yp, true),
.basic_grid => singleDomainWarpBasicGrid2D(seed, amp, freq, x, y, xp, yp),
}
}
inline fn doSingleDomainWarp3D(self: *const State, seed: u32, amp: Float, freq: Float, x: Float, y: Float, z: Float, xp: *Float, yp: *Float, zp: *Float) void {
switch (self.domain_warp_type) {
.simplex => singleDomainWarpOpenSimplex2Gradient(seed, amp * 32.69428253173828125, freq, x, y, z, xp, yp, zp, false),
.simplex_reduced => singleDomainWarpOpenSimplex2Gradient(seed, amp * 7.71604938271605, freq, x, y, z, xp, yp, zp, true),
.basic_grid => singleDomainWarpBasicGrid3D(seed, amp, freq, x, y, z, xp, yp, zp),
}
}
// Utilities
inline fn fastFloor(f: Float) i32 {
return @intFromFloat(if (f >= 0) f else f - 1);
}
inline fn fastRound(f: Float) i32 {
return @intFromFloat(if (f >= 0) f + 0.5 else f - 0.5);
}
inline fn lerp(a: Float, b: Float, t: Float) Float {
return a + t * (b - a);
}
inline fn interpHermite(t: Float) Float {
return t * t * (3 - 2 * t);
}
inline fn interpQuintic(t: Float) Float {
return t * t * t * (t * (t * 6 - 15) + 10);
}
inline fn cubicLerp(a: Float, b: Float, c: Float, d: Float, t: Float) Float {
const p = (d - c) - (a - b);
return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b;
}
inline fn pingPong(t: Float) Float {
const f = t - (@floor(t * 0.5) * 2);
return if (f < 1) f else 2 - f;
}
fn calculateFractalBounding(self: *const State) Float {
const gain: Float = @abs(self.gain);
var amp = gain;
var amp_fractal: Float = 1.0;
for (0..self.octaves) |_| {
amp_fractal += amp;
amp *= gain;
}
return 1.0 / amp_fractal;
}
// Hashing
inline fn hash2D(seed: i32, x_primed: i32, y_primed: i32) i32 {
const hash: i32 = seed ^ x_primed ^ y_primed;
return hash *% 0x27D4EB2D;
}
inline fn hash3D(seed: i32, x_primed: i32, y_primed: i32, z_primed: i32) i32 {
const hash: i32 = seed ^ x_primed ^ y_primed ^ z_primed;
return hash *% 0x27D4EB2D;
}
inline fn valCoord2D(seed: i32, x_primed: i32, y_primed: i32) Float {
var hash = hash2D(seed, x_primed, y_primed);
hash *%= hash;
hash ^= std.math.shl(i32, hash, 19);
return @as(Float, @floatFromInt(hash)) * (1.0 / 2147483648.0);
}
inline fn valCoord3D(seed: i32, x_primed: i32, y_primed: i32, z_primed: i32) Float {
var hash = hash3D(seed, x_primed, y_primed, z_primed);
hash *%= hash;
hash ^= std.math.shl(i32, hash, 19);
return @as(Float, @floatFromInt(hash)) * (1.0 / 2147483648.0);
}
inline fn gradCoord2D(seed: i32, x_primed: i32, y_primed: i32, xd: Float, yd: Float) Float {
var hash = hash2D(seed, x_primed, y_primed);
hash ^= (hash >> 15);
const index: usize = @intCast(hash & (127 << 1));
return xd * gradients_2d[index] + yd * gradients_2d[index | 1];
}
inline fn gradCoord3D(seed: i32, x_primed: i32, y_primed: i32, z_primed: i32, xd: Float, yd: Float, zd: Float) Float {
var hash = hash3D(seed, x_primed, y_primed, z_primed);
hash ^= (hash >> 15);
const index: usize = @intCast(hash & (63 << 2));
return xd * gradients_3d[index] + yd * gradients_3d[index | 1] + zd * gradients_3d[index | 2];
}
inline fn gradCoordOut2D(seed: i32, x_primed: i32, y_primed: i32, xo: *Float, yo: *Float) void {
const hash: usize = @intCast(hash2D(seed, x_primed, y_primed) & (255 << 1));
xo.* = rand_2d[hash];
yo.* = rand_2d[hash | 1];
}
inline fn gradCoordOut3D(seed: i32, x_primed: i32, y_primed: i32, z_primed: i32, xo: *Float, yo: *Float, zo: *Float) void {
const hash: usize = @intCast(hash3D(seed, x_primed, y_primed, z_primed) & (255 << 2));
xo.* = rand_3d[hash];
yo.* = rand_3d[hash | 1];
zo.* = rand_3d[hash | 2];
}
inline fn gradCoordDual2D(seed: i32, x_primed: i32, y_primed: i32, xd: Float, yd: Float, xo: *Float, yo: *Float) void {
const hash = hash2D(seed, x_primed, y_primed);
const index1: usize = @intCast(hash & (127 << 1));
const index2: usize = @intCast((hash >> 7) & (255 << 1));
const xg: Float = gradients_2d[index1];
const yg: Float = gradients_2d[index1 | 1];
const value = xd * xg + yd * yg;
const xgo: Float = rand_2d[index2];
const ygo: Float = rand_2d[index2 | 1];
xo.* = value * xgo;
yo.* = value * ygo;
}
inline fn gradCoordDual3D(seed: u32, x_primed: i32, y_primed: i32, z_primed: i32, xd: Float, yd: Float, zd: Float, xo: *Float, yo: *Float, zo: *Float) void {
const hash = hash3D(seed, x_primed, y_primed, z_primed);
const index1: usize = @intCast(hash & (63 << 2));
const index2: usize = @intCast((hash >> 6) & (255 << 2));
const xg: Float = gradients_3d[index1];
const yg: Float = gradients_3d[index1 | 1];
const zg: Float = gradients_3d[index1 | 2];
const value = xd * xg + yd * yg + zd * zg;
const xgo: Float = rand_3d[index2];
const ygo: Float = rand_3d[index2 | 1];
const zgo: Float = rand_3d[index2 | 2];
xo.* = value * xgo;
yo.* = value * ygo;
zo.* = value * zgo;
}
// Noise Coordinate Transforms (frequency, and possible skew or rotation)
fn transformNoiseCoordinate2D(self: *const State, x: *Float, y: *Float) void {
x.* *= self.frequency;
y.* *= self.frequency;
switch (self.noise_type) {
.simplex, .simplex_smooth => {
const t: Float = (x.* + y.*) * f2;
x.* += t;
y.* += t;
},
else => {},
}
}
fn transformNoiseCoordinate3D(self: *const State, x: *Float, y: *Float, z: *Float) void {
x.* *= self.frequency;
y.* *= self.frequency;
z.* *= self.frequency;
switch (self.rotation_type) {
.improve_xy_planes => {
const xy: Float = x.* + y.*;
const s2: Float = xy * -0.211324865405187;
z.* *= 0.577350269189626;
x.* += s2 - z.*;
y.* = y.* + s2 - z.*;
z.* += xy * 0.577350269189626;
},
.improve_xz_planes => {
const xz: Float = x.* + z.*;
const s2: Float = xz * -0.211324865405187;
y.* *= 0.577350269189626;
x.* += s2 - y.*;
z.* += s2 - y.*;
y.* += xz * 0.577350269189626;
},
else => switch (self.noise_type) {
.simplex, .simplex_smooth => {
const r: Float = (x.* + y.* + z.*) * r3; // Rotation, not skew
x.* = r - x.*;
y.* = r - y.*;
z.* = r - z.*;
},
else => {},
},
}
}
// Domain Warp Coordinate Transforms
fn transformDomainWarpCoordinate2D(state: *const State, x: *Float, y: *Float) void {
switch (state.domain_warp_type) {
.simplex, .simplex_reduced => {
const t: Float = (x.* + y.*) * f2;
x.* += t;
y.* += t;
},
else => {},
}
}
fn transformDomainWarpCoordinate3D(state: *const State, x: *Float, y: *Float, z: *Float) void {
switch (state.rotation_type) {
.improve_xy_planes => {
const xy: Float = *x + *y;
const s2: Float = xy * -0.211324865405187;
z.* *= 0.577350269189626;
x.* += s2 - *z;
y.* = *y + s2 - *z;
z.* += xy * 0.577350269189626;
},
.improve_xz_planes => {
const xz: Float = x.* + z.*;
const s2: Float = xz * -0.211324865405187;
y.* *= 0.577350269189626;
x.* += s2 - y.*;
z.* += s2 - y.*;
y.* += xz * 0.577350269189626;
},
else => switch (state.domain_warp_type) {
.simplex, .simplex_reduced => {
const r: Float = (x.* + y.* + z.*) * r3; // Rotation, not skew
x.* = r - x.*;
y.* = r - y.*;
z.* = r - z.*;
},
else => {},
},
}
}
// Fractal FBm
fn genFractalFBm2D(state: *const State, x: Float, y: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, state.calculateFractalBounding(), 0 };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.gain, 0 };
for (0..state.octaves) |i| {
const noise = state.genNoiseSingle2D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1]);
sum += noise * vec[2];
vec[2] *= lerp(1.0, @min(noise + 1.0, 2.0) * 0.5, state.weighted_strength);
vec *= mul;
}
return sum;
}
fn genFractalFBm3D(state: *const State, x: Float, y: Float, z: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, z, state.calculateFractalBounding() };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.lacunarity, state.gain };
for (0..state.octaves) |i| {
const noise = state.genNoiseSingle3D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1], vec[2]);
sum += noise * vec[3];
vec[3] *= lerp(1.0, (noise + 1.0) * 0.5, state.weighted_strength);
vec *= mul;
}
return sum;
}
// Fractal Ridged
fn genFractalRidged2D(state: *const State, x: Float, y: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, state.calculateFractalBounding(), 0 };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.gain, 0 };
for (0..state.octaves) |i| {
const noise = @abs(state.genNoiseSingle2D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1]));
sum += (noise * -2.0 + 1.0) * vec[2];
vec[2] *= lerp(1.0, 1.0 - noise, state.weighted_strength);
vec *= mul;
}
return sum;
}
fn genFractalRidged3D(state: *const State, x: Float, y: Float, z: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, z, state.calculateFractalBounding() };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.lacunarity, state.gain };
for (0..state.octaves) |i| {
const noise = @abs(state.genNoiseSingle3D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1], vec[2]));
sum += (noise * -2 + 1) * vec[3];
vec[3] *= lerp(1.0, 1.0 - noise, state.weighted_strength);
vec *= mul;
}
return sum;
}
// Fractal PingPong
fn genFractalPingPong2D(state: *const State, x: Float, y: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, state.calculateFractalBounding(), 0 };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.gain, 0 };
for (0..state.octaves) |i| {
const noise = pingPong((state.genNoiseSingle2D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1]) + 1) * state.ping_pong_strength);
sum += (noise - 0.5) * 2.0 * vec[2];
vec[2] *= lerp(1.0, noise, state.weighted_strength);
vec *= mul;
}
return sum;
}
fn genFractalPingPong3D(state: *const State, x: Float, y: Float, z: Float) Float {
var sum: Float = 0;
var vec = Vec4{ x, y, z, state.calculateFractalBounding() };
const mul = Vec4{ state.lacunarity, state.lacunarity, state.lacunarity, state.gain };
for (0..state.octaves) |i| {
const noise = pingPong((state.genNoiseSingle3D(state.seed + @as(i32, @intCast(i)), vec[0], vec[1], vec[2]) + 1.0) * state.ping_pong_strength);
sum += (noise - 0.5) * 2.0 * vec[3];
vec[3] *= lerp(1.0, noise, state.weighted_strength);
vec *= mul;
}
return sum;
}
// Domain Warp Single Wrapper
fn domainWarpSingle2D(state: *const State, x: *Float, y: *Float) void {
const amp = state.domain_warp_amp * state.calculateFractalBounding();
var xs: Float = x.*;
var ys: Float = y.*;
state.transformDomainWarpCoordinate2D(&xs, &ys);
state.doSingleDomainWarp2D(state.seed, amp, state.frequency, xs, ys, x, y);
}
fn domainWarpSingle3D(state: *const State, x: *Float, y: *Float, z: *Float) void {
const amp = state.domain_warp_amp * state.calculateFractalBounding();
var xs: Float = x.*;
var ys: Float = y.*;
var zs: Float = z.*;
state.transformDomainWarpCoordinate3D(&xs, &ys, &zs);
state.doSingleDomainWarp3D(state.seed, amp, state.frequency, xs, ys, zs, x, y, z);
}
// Domain Warp Fractal Progressive
fn domainWarpFractalProgressive2D(state: *const State, x: *Float, y: *Float) void {
var amp = state.domain_warp_amp * state.calculateFractalBounding();
var freq = state.frequency;
for (0..state.octaves) |i| {
var xs: Float = x.*;
var ys: Float = y.*;
state.transformDomainWarpCoordinate2D(&xs, &ys);
state.doSingleDomainWarp2D(state.seed + @as(i32, @intCast(i)), amp, freq, xs, ys, x, y);
amp *= state.gain;
freq *= state.lacunarity;
}
}
fn domainWarpFractalProgressive3D(state: *const State, x: *Float, y: *Float, z: *Float) void {
var amp = state.domain_warp_amp * state.calculateFractalBounding();
var freq = state.frequency;
for (0..state.octaves) |i| {
var xs: Float = x.*;
var ys: Float = y.*;
var zs: Float = z.*;
state.transformDomainWarpCoordinate3D(&xs, &ys, &zs);
state.doSingleDomainWarp3D(state.seed + @as(i32, @intCast(i)), amp, freq, xs, ys, zs, x, y, z);
amp *= state.gain;
freq *= state.lacunarity;
}
}
// Domain Warp Fractal Independent
fn domainWarpFractalIndependent2D(state: *const State, x: *Float, y: *Float) void {
var xs: Float = x.*;
var ys: Float = y.*;
state.transformDomainWarpCoordinate2D(&xs, &ys);
const amp = state.domain_warp_amp * state.calculateFractalBounding();
const freq = state.frequency;
for (0..state.octaves) |i| {
state.doSingleDomainWarp2D(state.seed + @as(i32, @intCast(i)), amp, freq, xs, ys, x, y);
amp *= state.gain;
freq *= state.lacunarity;
}
}
fn domainWarpFractalIndependent3D(state: *const State, x: *Float, y: *Float, z: *Float) void {
var xs: Float = x.*;
var ys: Float = y.*;
var zs: Float = z.*;
state.transformDomainWarpCoordinate3D(&xs, &ys, &zs);
const amp = state.domain_warp_amp * state.calculateFractalBounding();
const freq = state.frequency;
for (0..state.octaves) |i| {
state.doSingleDomainWarp3D(state.seed + @as(i32, @intCast(i)), amp, freq, xs, ys, zs, x, y, z);
amp *= state.gain;
freq *= state.lacunarity;
}
}
// Domain Warp Basic Grid
fn singleDomainWarpBasicGrid2D(seed: i32, warp_amp: Float, frequency: Float, x: Float, y: Float, xp: *Float, yp: *Float) void {
const xf = x * frequency;
const yf = y * frequency;
var x0 = fastFloor(xf);
var y0 = fastFloor(yf);
const xs = interpHermite(xf - @as(Float, @floatFromInt(x0)));
const ys = interpHermite(yf - @as(Float, @floatFromInt(y0)));
x0 *%= prime_x;
y0 *%= prime_y;
const x1 = x0 +% prime_x;
const y1 = y0 +% prime_y;
var idx0: usize = @intCast(hash2D(seed, x0, y0) & (255 << 1));
var idx1: usize = @intCast(hash2D(seed, x1, y0) & (255 << 1));
const lx0x = lerp(rand_2d[idx0], rand_2d[idx1], xs);
const ly0x = lerp(rand_2d[idx0 | 1], rand_2d[idx1 | 1], xs);
idx0 = @intCast(hash2D(seed, x0, y1) & (255 << 1));
idx1 = @intCast(hash2D(seed, x1, y1) & (255 << 1));
const lx1x = lerp(rand_2d[idx0], rand_2d[idx1], xs);
const ly1x = lerp(rand_2d[idx0 | 1], rand_2d[idx1 | 1], xs);
xp.* += lerp(lx0x, lx1x, ys) * warp_amp;
yp.* += lerp(ly0x, ly1x, ys) * warp_amp;
}
fn singleDomainWarpBasicGrid3D(seed: i32, warp_amp: Float, frequency: Float, x: Float, y: Float, z: Float, xp: *Float, yp: *Float, zp: *Float) void {
const xf = x * frequency;
const yf = y * frequency;
const zf = z * frequency;
var x0 = fastFloor(xf);
var y0 = fastFloor(yf);
var z0 = fastFloor(zf);
const xs = interpHermite(xf - @as(Float, @floatFromInt(x0)));
const ys = interpHermite(yf - @as(Float, @floatFromInt(y0)));
const zs = interpHermite(zf - @as(Float, @floatFromInt(z0)));
x0 *%= prime_x;
y0 *%= prime_y;
z0 *%= prime_z;
const x1 = x0 +% prime_x;
const y1 = y0 +% prime_y;
const z1 = z0 +% prime_z;
var idx0: usize = @intCast(hash3D(seed, x0, y0, z0) & (255 << 2));
var idx1: usize = @intCast(hash3D(seed, x1, y0, z0) & (255 << 2));
const lx0x = lerp(rand_3d[idx0], rand_3d[idx1], xs);
const ly0x = lerp(rand_3d[idx0 | 1], rand_3d[idx1 | 1], xs);
const lz0x = lerp(rand_3d[idx0 | 2], rand_3d[idx1 | 2], xs);
idx0 = @intCast(hash3D(seed, x0, y1, z0) & (255 << 2));
idx1 = @intCast(hash3D(seed, x1, y1, z0) & (255 << 2));
var lx1x = lerp(rand_3d[idx0], rand_3d[idx1], xs);
var ly1x = lerp(rand_3d[idx0 | 1], rand_3d[idx1 | 1], xs);
var lz1x = lerp(rand_3d[idx0 | 2], rand_3d[idx1 | 2], xs);
const lx0y = lerp(lx0x, lx1x, ys);
const ly0y = lerp(ly0x, ly1x, ys);
const lz0y = lerp(lz0x, lz1x, ys);
idx0 = hash3D(seed, x0, y0, z1) & (255 << 2);
idx1 = hash3D(seed, x1, y0, z1) & (255 << 2);
lx0x = lerp(rand_3d[idx0], rand_3d[idx1], xs);
ly0x = lerp(rand_3d[idx0 | 1], rand_3d[idx1 | 1], xs);
lz0x = lerp(rand_3d[idx0 | 2], rand_3d[idx1 | 2], xs);
idx0 = hash3D(seed, x0, y1, z1) & (255 << 2);
idx1 = hash3D(seed, x1, y1, z1) & (255 << 2);
lx1x = lerp(rand_3d[idx0], rand_3d[idx1], xs);
ly1x = lerp(rand_3d[idx0 | 1], rand_3d[idx1 | 1], xs);
lz1x = lerp(rand_3d[idx0 | 2], rand_3d[idx1 | 2], xs);
xp.* += lerp(lx0y, lerp(lx0x, lx1x, ys), zs) * warp_amp;
yp.* += lerp(ly0y, lerp(ly0x, ly1x, ys), zs) * warp_amp;
zp.* += lerp(lz0y, lerp(lz0x, lz1x, ys), zs) * warp_amp;
}
// Domain Warp Simplex/OpenSimplex2
fn singleDomainWarpSimplexGradient(seed: i32, warp_amp: Float, frequency: Float, x: Float, y: Float, xr: *Float, yr: *Float, out_grad: bool) void {
const xx = x * frequency;
const yy = y * frequency;
var i = fastFloor(xx);
var j = fastFloor(yy);
const xi = xx - @as(Float, @floatFromInt(i));
const yi = yy - @as(Float, @floatFromInt(j));
const t = (xi + yi) * g2;
const x0: Float = xi - t;
const y0: Float = yi - t;
i *%= prime_x;
j *%= prime_y;
var vx: Float = 0;
var vy: Float = 0;
var xo: Float = undefined;
var yo: Float = undefined;
const a = 0.5 - x0 * x0 - y0 * y0;
if (a > 0) {
const aaaa = (a * a) * (a * a);
if (out_grad) {
gradCoordOut2D(seed, i, j, &xo, &yo);
} else {
gradCoordDual2D(seed, i, j, x0, y0, &xo, &yo);
}
vx += aaaa * xo;
vy += aaaa * yo;
}
const c = (2.0 * (1.0 - 2.0 * g2) * (1.0 / g2 - 2.0)) * t + ((-2.0 * (1.0 - 2.0 * g2) * (1.0 - 2.0 * g2)) + a);
if (c > 0) {
const x2 = x0 + (2 * g2 - 1.0);
const y2 = y0 + (2 * g2 - 1.0);
const cccc = (c * c) * (c * c);
if (out_grad) {
gradCoordOut2D(seed, i +% prime_x, j +% prime_y, &xo, &yo);
} else {
gradCoordDual2D(seed, i +% prime_x, j +% prime_y, x2, y2, &xo, &yo);
}
vx += cccc * xo;
vy += cccc * yo;
}
if (y0 > x0) {
const x1 = x0 + g2;
const y1 = y0 + (g2 - 1.0);
const b = 0.5 - x1 * x1 - y1 * y1;
if (b > 0) {
const bbbb = (b * b) * (b * b);
if (out_grad) {
gradCoordOut2D(seed, i, j +% prime_y, &xo, &yo);
} else {
gradCoordDual2D(seed, i, j +% prime_y, x1, y1, &xo, &yo);
}
vx += bbbb * xo;
vy += bbbb * yo;
}
} else {
const x1 = x0 + (g2 - 1.0);
const y1 = y0 + g2;
const b = 0.5 - x1 * x1 - y1 * y1;
if (b > 0) {
const bbbb = (b * b) * (b * b);
if (out_grad) {
gradCoordOut2D(seed, i +% prime_x, j, &xo, &yo);
} else {
gradCoordDual2D(seed, i +% prime_x, j, x1, y1, &xo, &yo);
}
vx += bbbb * xo;
vy += bbbb * yo;
}
}
xr.* += vx * warp_amp;
yr.* += vy * warp_amp;
}
fn singleDomainWarpOpenSimplex2Gradient(seed: i32, warp_amp: Float, frequency: Float, x: Float, y: Float, z: Float, xr: *Float, yr: *Float, zr: *Float, out_grad: bool) void {
const xx = x * frequency;
const yy = y * frequency;
const zz = z * frequency;
var i = fastRound(xx);
var j = fastRound(yy);
var k = fastRound(zz);
const x0 = xx - @as(Float, @floatFromInt(i));
const y0 = yy - @as(Float, @floatFromInt(j));
const z0 = zz - @as(Float, @floatFromInt(k));
var xNSign = @as(i32, @intFromFloat(-x0 - 1.0)) | 1;
var yNSign = @as(i32, @intFromFloat(-y0 - 1.0)) | 1;
var zNSign = @as(i32, @intFromFloat(-z0 - 1.0)) | 1;
const ax0 = @as(Float, @floatFromInt(xNSign)) * -x0;
const ay0 = @as(Float, @floatFromInt(yNSign)) * -y0;
const az0 = @as(Float, @floatFromInt(zNSign)) * -z0;
i *%= prime_x;
j *%= prime_y;
k *%= prime_z;
var vx: Float = 0;
var vy: Float = 0;
var vz: Float = 0;
var xo: Float = undefined;
var yo: Float = undefined;
var zo: Float = undefined;
var seed_value = seed;
const a = (0.6 - x0 * x0) - (y0 * y0 + z0 * z0);
var l: usize = 0;
while (l < 2) : (l += 1) {
const xNSignf: Float = @floatFromInt(xNSign);
const yNSignf: Float = @floatFromInt(yNSign);
const zNSignf: Float = @floatFromInt(zNSign);
if (a > 0) {
const aaaa = (a * a) * (a * a);
if (out_grad) {
gradCoordOut3D(seed_value, i, j, k, &xo, &yo, &zo);
} else {
gradCoordDual3D(seed_value, i, j, k, x0, y0, z0, &xo, &yo, &zo);
}
vx += aaaa * xo;
vy += aaaa * yo;
vz += aaaa * zo;
}
var b = a + 1.0;
var ii = i;
var jj = j;
var kk = k;
var x1 = x0;
var y1 = y0;
var z1 = z0;
if (ax0 >= ay0 and ax0 >= az0) {
x1 += xNSignf;
b -= xNSignf * 2.0 * x1;
ii -= xNSign *% prime_x;
} else if (ay0 > ax0 and ay0 >= az0) {
y1 += yNSignf;
b -= yNSignf * 2.0 * y1;
jj -= yNSign *% prime_y;
} else {
z1 += zNSignf;
b -= zNSignf * 2.0 * z1;