forked from vplesko/libwfc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwfc.h
2104 lines (1786 loc) · 68.7 KB
/
wfc.h
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 Vladimir Pleskonjic
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.
*/
/*
This is a single-header library for the Wave Function Collapse algorithm (WFC).
WFC accepts a sample image, analyzes it, and generates a larger image that
resembles the input. It is a procedural image generation algorithm.
The easiest way to make use of this code is to use the provided CLI and GUI. If
you want to use the library itself, include it like this:
#define WFC_IMPLEMENTATION
#include "wfc.h"
You can then include it in other translation units by omitting the define
directive.
Run WFC with:
wfc_generate(
// pattern width and height, 3 is a good starting value
n,
// options to control WFC, 0 if you don't want to enable any
wfc_optFlipH | wfc_optFlipV | wfc_optRotate,
// byte size of a single pixel value
4,
// dimensions and bytes of the input image
srcW, srcH, (unsigned char*)src,
// dimensions and bytes of the output image
dstW, dstH, (unsigned char*)dst);
This library does NOT handle file input/output and does NOT do backtracking on
its own. CLI and GUI do provide that, you may look at their code to see one
possible implementation.
You can also run WFC step-by-step like this:
struct wfc_State *state = wfc_init(
n, wfc_optFlipH | wfc_optFlipV | wfc_optRotate, 4,
srcW, srcH, (unsigned char*)src,
dstW, dstH);
assert(state != NULL);
while (!wfc_step(state));
assert(wfc_status(state) > 0);
int code = wfc_blit(state, (unsigned char*)src, (unsigned char*)dst);
assert(code == 0);
wfc_free(state);
wfc_clone() can be used to deep-copy a state object. You can use it to implement
your own backtracking behaviour.
WFC works by first gathering unique NxN patterns from the input image. You can
get the total number of patterns gathered with wfc_patternCount(). Use
wfc_patternPresentAt() to check if a pattern is still present at a particular
point. Use wfc_modifiedAt() to check if, during the previous step, a particular
point was modified, ie. its set of present patterns was reduced. Use
wfc_collapsedCount() to get the number of wave points collapsed to a single
pattern. Use wfc_pixelToBlitAt() to get a pointer to pixel bytes corresponding
to a particular pattern.
If you do not want to use standard C functions, you can define these macros
before including this header:
#define WFC_ASSERT(ctx, cond) ...
#define WFC_MALLOC(ctx, sz) ...
#define WFC_FREE(ctx, p) ...
// should yield a float value between 0 (inclusive) and 1 (exclusive)
#define WFC_RAND(ctx) ...
All macros accept a user context pointer as the first argument. If you want it
to have a value other than null, you will need to supply that value by using
wfc_generateEx() or wfc_initEx().
*/
#ifndef INCLUDE_WFC_H
#define INCLUDE_WFC_H
#include <stdbool.h>
// @TODO Allow different values of N for different dimensions.
// @TODO Implement 3D WFC, with GUI support.
#ifdef __cplusplus
extern "C" {
#endif
enum {
// Status code that signifies that WFC has successfully completed.
wfc_completed = 1,
// Status code that signifies that WFC has failed due to running into a
// contradiction.
wfc_failed = -1,
// Status code that signifies that there was an error in provided arguments.
wfc_callerError = -2
};
enum {
// Enable this option to allow horizontal flipping of patterns (think of
// y-axis as the mirror).
wfc_optFlipH = 1 << 1,
// Enable this option to allow vertical flipping of patterns (think of
// x-axis as the mirror).
wfc_optFlipV = 1 << 0,
// This is a combination of wfc_optFlipH and wfc_optFlipV.
wfc_optFlip = wfc_optFlipH | wfc_optFlipV,
// Enable this option to allow rotating of patterns (by 90, 180, and 270
// degrees).
// @TODO Introduce separate rotation options for different angles.
wfc_optRotate = 1 << 2,
// Enable this option to fix left and right edges of input image so that
// patterns may not wrap around them.
wfc_optEdgeFixH = 1 << 4,
// Enable this option to fix top and bottom edges of input image so that
// patterns may not wrap around them.
wfc_optEdgeFixV = 1 << 3,
// This is a combination of wfc_optEdgeFixH and wfc_optEdgeFixV.
wfc_optEdgeFix = wfc_optEdgeFixH | wfc_optEdgeFixV
};
// An opaque struct containing the WFC state. You should only interact with it
// through a pointer.
typedef struct wfc_State wfc_State;
/**
* Runs WFC on the provided source image and blits to the destination.
*
* \param n Pattern size will be n by n pixels. Must be positive and not greater
* than any dimension of source and destination images.
*
* \param options Bitmask determining how WFC will run. This should be a
* bitwise-or of wfc_opt* values or zero.
*
* \param bytesPerPixel Determines the byte size of a single pixel value in
* source and destination images. These values will be compared with a simple
* memcmp, so make sure that all unused bits are set to zero. Must be positive.
*
* \param srcW Width in pixels of the source image. Must be positive.
*
* \param srcH Height in pixels of the source image. Must be positive.
*
* \param src Pointer to a row-major array of pixels comprising the source
* image. Must not be null.
*
* \param dstW Width in pixels of the destination image. Must be positive.
*
* \param dstH Height in pixels of the destination image. Must be positive.
*
* \param dst Pointer to a row-major array of pixels comprising the destination
* image. WFC output will be blitted here.
*
* \return Returns the status code of WFC, which is one of:
*
* \li wfc_completed (positive) in case of success;
* \li wfc_failed (negative) in case of contradiction;
* \li wfc_callerError (negative) in case of argument error.
*
* On success, the generated image will be written to dst.
*/
int wfc_generate(
int n, int options, int bytesPerPixel,
int srcW, int srcH, const unsigned char *src,
int dstW, int dstH, unsigned char *dst);
/**
* Runs WFC on the provided source image and blits to the destination. Same as
* wfc_generate() except that it provides more capabilities.
*
* \param n Pattern size will be n by n pixels. Must be positive and not greater
* than any dimension of source and destination images.
*
* \param options Bitmask determining how WFC will run. This should be a
* bitwise-or of wfc_opt* values or zero.
*
* \param bytesPerPixel Determines the size in bytes of a single value in source
* and destination images. These values will be compared with a simple memcmp,
* so make sure that all unused bits are set to zero. Must be positive.
*
* \param srcW Width in pixels of the source image. Must be positive.
*
* \param srcH Height in pixels of the source image. Must be positive.
*
* \param src Pointer to a row-major array of pixels comprising the source
* image. Must not be null.
*
* \param dstW Width in pixels of the destination image. Must be positive.
*
* \param dstH Height in pixels of the destination image. Must be positive.
*
* \param dst Pointer to a row-major array of pixels comprising the destination
* image. WFC output will be blitted here. If keep is non-null then this must
* not be null.
*
* \param ctx User context that will be passed to WFC_ASSERT(), WFC_MALLOC(),
* WFC_FREE(), and WFC_RAND().
*
* \param keep If non-null, signifies that some values in dst are pre-determined
* and that WFC should not modify them. WFC will attempt to generate the rest of
* the output image, while keeping these values as they are. If non-null, must
* be of the same dimensions as dst - true means keep that pixel value
* unchanged.
*
* \return Returns the status code of WFC, which is one of:
*
* \li wfc_completed (positive) in case of success;
* \li wfc_failed (negative) in case of contradiction;
* \li wfc_callerError (negative) in case of argument error.
*
* On success, the generated image will be written to dst.
*/
int wfc_generateEx(
int n, int options, int bytesPerPixel,
int srcW, int srcH, const unsigned char *src,
int dstW, int dstH, unsigned char *dst,
void *ctx,
bool *keep);
/**
* Allocates and initializes a state object for WFC. This is a first step
* towards running WFC, you will likely be using wfc_step() after.
*
* Consider using wfc_generate() instead if you don't need any custom handling
* of individual steps.
*
* \param n Pattern size will be n by n pixels. Must be positive and not greater
* than any dimension of source and destination images.
*
* \param options Bitmask determining how WFC will run. This should be a
* bitwise-or of wfc_opt* values or zero.
*
* \param bytesPerPixel Determines the size in bytes of a single value in source
* and destination images. These values will be compared with a simple memcmp,
* so make sure that all unused bits are set to zero. Must be positive.
*
* \param srcW Width in pixels of the source image. Must be positive.
*
* \param srcH Height in pixels of the source image. Must be positive.
*
* \param src Pointer to a row-major array of pixels comprising the source
* image. Must not be null.
*
* \param dstW Width in pixels of the destination image. Must be positive.
*
* \param dstH Height in pixels of the destination image. Must be positive.
*
* \return Returns an allocated state object to be passed to further WFC
* functions. This object should be deallocated using wfc_free().
*
* In case of error, returns null.
*/
wfc_State* wfc_init(
int n, int options, int bytesPerPixel,
int srcW, int srcH, const unsigned char *src,
int dstW, int dstH);
/**
* Allocates and initializes a state object for WFC. This is a first step
* towards running WFC, you will likely be using wfc_step() after. Same as
* wfc_init() except that it provides more capabilities.
*
* Consider using wfc_generate() instead if you don't need any custom handling
* of individual steps.
*
* \param n Pattern size will be n by n pixels. Must be positive and not greater
* than any dimension of source and destination images.
*
* \param options Bitmask determining how WFC will run. This should be a
* bitwise-or of wfc_opt* values or zero.
*
* \param bytesPerPixel Determines the size in bytes of a single value in source
* and destination images. These values will be compared with a simple memcmp,
* so make sure that all unused bits are set to zero. Must be positive.
*
* \param srcW Width in pixels of the source image. Must be positive.
*
* \param srcH Height in pixels of the source image. Must be positive.
*
* \param src Pointer to a row-major array of pixels comprising the source
* image. Must not be null.
*
* \param dstW Width in pixels of the destination image. Must be positive.
*
* \param dstH Height in pixels of the destination image. Must be positive.
*
* \param dst Pointer to a row-major array of pixels comprising the destination
* image. During initialization, destination image is only used for the sake of
* images to be kept (see the keep parameter). If keep is non-null then this
* must not be null.
*
* \param ctx User context that will be passed to WFC_ASSERT(), WFC_MALLOC(),
* WFC_FREE(), and WFC_RAND().
*
* \param keep If non-null, signifies that some values in dst are pre-determined
* and that WFC should not modify them. WFC will attempt to generate the rest of
* the output image, while keeping these values as they are. If non-null, must
* be of the same dimensions as dst - true means keep that pixel value
* unchanged.
*
* \return Returns an allocated state object to be passed to further WFC
* functions. This object should be deallocated using wfc_free().
*
* In case of error, returns null.
*/
wfc_State* wfc_initEx(
int n, int options, int bytesPerPixel,
int srcW, int srcH, const unsigned char *src,
int dstW, int dstH, const unsigned char *dst,
void *ctx,
bool *keep);
/**
* Returns the current status code for this WFC state.
*
* \param state State object pointer for which to query status. Must not be
* null.
*
* \return Returns the current status code, which is one of:
*
* \li 0 (zero) in case that WFC has not completed yet (you can keep calling
* wfc_step());
* \li wfc_completed (positive) in case that WFC has completed successfully;
* \li wfc_failed (negative) in case that WFC has reached a contradiction and
* failed to complete;
* \li wfc_callerError (negative) in case state was null.
*/
int wfc_status(const wfc_State *state);
/**
* Performs one iteration of the WFC algorithm, observing one wave point and
* propagating constraints. After WFC completes, you will likely be calling
* wfc_blit() next.
*
* \param state State object pointer on which to perform the iteration. Must not
* be null.
*
* \return Returns the status code after calling wfc_step(), which is one of:
*
* \li 0 (zero) in case that WFC has not completed yet (you can keep calling
* wfc_step());
* \li wfc_completed (positive) in case that WFC has completed successfully;
* \li wfc_failed (negative) in case that WFC has reached a contradiction and
* failed to complete;
* \li wfc_callerError (negative) in case state was null.
*/
int wfc_step(wfc_State *state);
/**
* Blits (aka. renders) the generated image to dst by copying in the pixel
* values. Should be called after WFC completes successfully (after wfc_step()
* has returned wfc_completed).
*
* \param state State object pointer. Must not be null. Must be in the completed
* state.
*
* \param src Pointer to pixels comprising the source image. Must not be null.
* Must be of the same dimensions as the image that was passed to wfc_init().
*
* \param dst Pointer to pixels comprising the destination image. Must not be
* null. Must be of the dimensions that were specified in wfc_init().
*
* \return Returns zero on success or wfc_callerError if there was an error in
* the arguments.
*/
int wfc_blit(
const wfc_State *state,
const unsigned char *src, unsigned char *dst);
/**
* Allocates a new state object as a deep-copy of the provided one. The new
* object is completely independent of the old one - you can call wfc_step() on
* it and both objects need to be deallocated with wfc_free().
*
* \param state Pointer to the state object to be cloned.
*
* \return Returns a new state object that is a copy of the provided one. If
* state is null, null is returned instead.
*/
wfc_State* wfc_clone(const wfc_State *state);
/**
* Deallocates the state object and all data owned by it. The state pointer
* should not be used after this function is called.
*
* \param state Pointer to the state object to deallocate.
*/
void wfc_free(wfc_State *state);
/**
* Returns the number of wave points collapsed to a single pattern.
*
* If a wave point has been reduced to a single pattern at some step, but at a
* later step reduced to zero patterns (meaning WFC has failed), it will still
* register towards this count.
*
* \param state State object pointer for which to query the number of collapsed
* wave points. Must not be null.
*
* \return Returns the number of collapsed wave points. Returns wfc_callerError
* (a negative value) if state is null.
*/
int wfc_collapsedCount(const wfc_State *state);
/**
* Returns the number of unique patterns gathered from the input image when the
* provided state object was being initialized.
*
* \param state State object pointer for which to query the number of unique
* patterns. Must not be null.
*
* \return Returns the number of unique patterns gathered from the input image.
* Returns wfc_callerError (a negative value) if state is null.
*/
int wfc_patternCount(const wfc_State *state);
/**
* Returns whether a particular pattern is still present at the wave point with
* the given coordinates. As WFC iterates, patterns from wave points get removed
* as points are observed and constraints are propagated - this function lets
* you know which patterns are still left at specific points.
*
* When calling this, you need to provide a valid pattern index. Valid pattern
* indexes are in the range from zero (inclusive) to pattern count (exclusive).
* You can get the pattern count by calling wfc_patternCount().
*
* \param state State object pointer containing the wave point to be queried.
* Must not be null.
*
* \param patt Pattern index whose presence is being queried. Must be a valid
* index.
*
* \param x x coordinate of the destination image. Must be a valid x coordinate
* for the image being generated.
*
* \param y y coordinate of the destination image. Must be a valid y coordinate
* for the image being generated.
*
* \return Returns:
*
* \li 0 if the pattern is not present at that wave point;
* \li 1 if the pattern is present at that wave point;
* \li wfc_callerError (a negative value) if there was an error in the
* arguments.
*/
int wfc_patternPresentAt(const wfc_State *state, int patt, int x, int y);
/**
* Returns whether the wave point with the given coordinates has been modified
* during the previous round of observation and propagations in wfc_step(). As
* WFC iterates, patterns from wave points get removed as points are observed
* and constraints are propagated - this function lets you know which points had
* their set of remaining patterns reduced.
*
* If called before any calls to wfc_step() had been made, responds as if all
* wave points have been modified.
*
* \param state State object pointer containing the wave point to be queried.
* Must not be null.
*
* \param x x coordinate of the destination image. Must be a valid x coordinate
* for the image being generated.
*
* \param y y coordinate of the destination image. Must be a valid y coordinate
* for the image being generated.
*
* \return Returns:
*
* \li 0 if the wave point was not recently modified;
* \li 1 if the wave point was modified during the previous round of observation
* and propagations in wfc_step() or if no calls to wfc_step() have yet been
* made;
* \li wfc_callerError (a negative value) if there was an error in the
* arguments.
*/
int wfc_modifiedAt(const wfc_State *state, int x, int y);
/**
* Returns a pointer to the bytes of the pixel value that would be blitted to a
* destination image at the given coordinates if the given pattern was the one
* chosen for the corresponding wave point.
*
* In other words, since WFC may rotate/flip/etc. the patterns it gathers (and
* pattern order is not guaranteed), this function tells you what pixel would
* end up at a destination image pixel for a specific pattern.
*
* When calling this, you need to provide a valid pattern index. Valid pattern
* indexes are in the range from zero (inclusive) to pattern count (exclusive).
* You can get the pattern count by calling wfc_patternCount().
*
* \param state State object pointer containing the wave point to be queried.
* Must not be null.
*
* \param src Pointer to pixels comprising the source image. Must not be null.
* Must be of the same dimensions as the image that was passed to wfc_init().
*
* \param patt Pattern index whose presence is being queried. Must be a valid
* index.
*
* \param x x coordinate of the destination image. Must be a valid x coordinate
* for the image being generated.
*
* \param y y coordinate of the destination image. Must be a valid y coordinate
* for the image being generated.
*
* \return Returns a pointer to the bytes within src for the corresponding
* pixel value. Returns null if there was an error in the arguments.
*/
const unsigned char* wfc_pixelToBlitAt(
const wfc_State *state, const unsigned char *src,
int patt, int x, int y);
#ifdef __cplusplus
}
#endif
#endif // INCLUDE_WFC_H
// IMPLEMENTATION
#ifdef WFC_IMPLEMENTATION
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef WFC_ASSERT
#include <assert.h>
#define WFC_ASSERT(ctx, cond) assert(cond)
#endif
#ifndef WFC_MALLOC
#define WFC_MALLOC(ctx, sz) malloc(sz)
#endif
#ifndef WFC_FREE
#define WFC_FREE(ctx, p) free(p)
#endif
// This macro should return a float in [0, 1).
#ifndef WFC_RAND
#define WFC_RAND(ctx) wfc__rand()
#endif
// basic utility
int wfc__min_i(int a, int b) {
return a < b ? a : b;
}
int wfc__max_i(int a, int b) {
return a < b ? b : a;
}
float wfc__min_f(float a, float b) {
return a < b ? a : b;
}
// Counts the number of 1 bits in a value.
int wfc__popcount_u(unsigned n) {
int cnt = 0;
for (; n != 0; ++cnt) n &= n - 1;
return cnt;
}
int wfc__roundUpToDivBy(int n, int div) {
return ((n + div - 1) / div) * div;
}
// a and b must be non-negative.
// Assumes IEEE 754 representation of float on the system.
bool wfc__approxEqNonNeg_f(float a, float b) {
const int ulpsDiff = 8;
// Reinterpret floats as 32-bit ints in a standard compliant way.
int32_t ai, bi;
memcpy(&ai, &a, sizeof(a));
memcpy(&bi, &b, sizeof(b));
// Check that bit representations are close to each other.
return abs(ai - bi) < ulpsDiff;
}
// Approximates log2(x), where x is positive
// and not NaN, infinity, nor a subnormal.
// Assumes IEEE 754 representation of float on the system.
float wfc__log2f(float x) {
// IEEE 754 representation constants.
const int32_t mantissaLen = 23;
const int32_t mantissaMask = (1 << mantissaLen) - 1;
const int32_t baseExponent = -127;
// Reinterpret x as int in a standard compliant way.
int32_t xi;
memcpy(&xi, &x, sizeof(xi));
// Calculate exponent of x.
float e = (float)((xi >> mantissaLen) + baseExponent);
// Calculate mantissa of x. It will be in range [1, 2).
float m;
int32_t mxi = (xi & mantissaMask) | ((-baseExponent) << mantissaLen);
memcpy(&m, &mxi, sizeof(m));
// Use Remez algorithm-generated 3rd degree approximation polynomial
// for log2(a) where a is in range [1, 2].
float l = 0.15824871f;
l = l * m + -1.051875f;
l = l * m + 3.0478842f;
l = l * m + -2.1536207f;
// Add exponent to the calculation.
// Final log is log2(m*2^e)=log2(m)+e.
l += e;
return l;
}
// RNG utility
// [0, 1)
float wfc__rand(void) {
return (float)rand() / ((float)RAND_MAX + 1.0f);
}
// [0, n)
int wfc__rand_i(void *ctx, int n) {
(void)ctx;
return (int)(WFC_RAND(ctx) * (float)n);
}
// Wraps ind into range [0, sz).
int wfc__indWrap(int ind, int sz) {
if (ind >= 0) return ind % sz;
return sz + ind % sz;
}
// multi-dimensional array utility
#define WFC__A2D_DEF(type, abbrv) \
struct wfc__A2d_##abbrv { \
int d02, d12; \
type *a; \
}
#define WFC__A2D_LEN(arr) ((arr).d02 * (arr).d12)
#define WFC__A2D_SIZE(arr) ((size_t)WFC__A2D_LEN(arr) * sizeof(*(arr).a))
#define WFC__A2D_GET(arr, c0, c1) \
((arr).a[ \
(c0) * (arr).d12 + \
(c1)])
#define WFC__A2D_GET_WRAP(arr, c0, c1) \
((arr).a[ \
wfc__indWrap(c0, (arr).d02) * (arr).d12 + \
wfc__indWrap(c1, (arr).d12)])
#define WFC__A3D_DEF(type, abbrv) \
struct wfc__A3d_##abbrv { \
int d03, d13, d23; \
type *a; \
}
#define WFC__A3D_LEN(arr) ((arr).d03 * (arr).d13 * (arr).d23)
#define WFC__A3D_SIZE(arr) ((size_t)WFC__A3D_LEN(arr) * sizeof(*(arr).a))
#define WFC__A3D_GET(arr, c0, c1, c2) \
((arr).a[ \
(c0) * (arr).d13 * (arr).d23 + \
(c1) * (arr).d23 + \
(c2)])
#define WFC__A3D_GET_WRAP(arr, c0, c1, c2) \
((arr).a[ \
wfc__indWrap(c0, (arr).d03) * (arr).d13 * (arr).d23 + \
wfc__indWrap(c1, (arr).d13) * (arr).d23 + \
wfc__indWrap(c2, (arr).d23)])
#define WFC__A4D_DEF(type, abbrv) \
struct wfc__A4d_##abbrv { \
int d04, d14, d24, d34; \
type *a; \
}
#define WFC__A4D_LEN(arr) ((arr).d04 * (arr).d14 * (arr).d24 * (arr).d34)
#define WFC__A4D_SIZE(arr) ((size_t)WFC__A4D_LEN(arr) * sizeof(*(arr).a))
#define WFC__A4D_GET(arr, c0, c1, c2, c3) \
((arr).a[ \
(c0) * (arr).d14 * (arr).d24 * (arr).d34 + \
(c1) * (arr).d24 * (arr).d34 + \
(c2) * (arr).d34 + \
(c3)])
#define WFC__A4D_GET_WRAP(arr, c0, c1, c2, c3) \
((arr).a[ \
wfc__indWrap(c0, (arr).d04) * (arr).d14 * (arr).d24 * (arr).d34 + \
wfc__indWrap(c1, (arr).d14) * (arr).d24 * (arr).d34 + \
wfc__indWrap(c2, (arr).d24) * (arr).d34 + \
wfc__indWrap(c3, (arr).d34)])
void wfc__indToCoords2d(int d1, int ind, int *c0, int *c1) {
int c0_ = ind / d1;
ind -= c0_ * d1;
int c1_ = ind;
if (c0 != NULL) *c0 = c0_;
if (c1 != NULL) *c1 = c1_;
}
int wfc__coords2dToInd(int d1, int c0, int c1) {
return c0 * d1 + c1;
}
// WFC code
enum {
// Some loop calculations are split into striped channels
// that each calculate their part of the result,
// which is then aggregated into the final result.
// This improves CPU instruction-level parallelism.
wfc__loopChannels = 4
};
// H and V are used in public API, prefer to use C0/1/... in private code.
enum {
wfc__optFlipC0 = wfc_optFlipV,
wfc__optFlipC1 = wfc_optFlipH,
wfc__optEdgeFixC0 = wfc_optEdgeFixV,
wfc__optEdgeFixC1 = wfc_optEdgeFixH
};
// Transformations for patterns are encoded in a bitmask.
// @TODO Some combinations are equivalent, so work in gathering patterns gets
// duplicated. Optimize by removing that work duplication.
enum {
wfc__tfFlipC0 = 1 << 0,
wfc__tfFlipC1 = 1 << 1,
wfc__tfRot90 = 1 << 2,
wfc__tfRot180 = 1 << 3,
// Rotating by 270 is a combination of rotation by 90 and 180.
wfc__tfRot270 = wfc__tfRot90 | wfc__tfRot180,
wfc__tfCnt = 1 << 4
};
enum wfc__Dir {
wfc__dirC0Less,
wfc__dirC0More,
wfc__dirC1Less,
wfc__dirC1More,
wfc__dirCnt
};
void wfc__dirToOffsets(void *ctx, enum wfc__Dir dir, int *offC0, int *offC1) {
(void)ctx;
int offC0_ = 0, offC1_ = 0;
if (dir == wfc__dirC0Less) {
offC0_ = -1;
} else if (dir == wfc__dirC0More) {
offC0_ = +1;
} else if (dir == wfc__dirC1Less) {
offC1_ = -1;
} else if (dir == wfc__dirC1More) {
offC1_ = +1;
} else {
WFC_ASSERT(ctx, false);
}
if (offC0 != NULL) *offC0 = offC0_;
if (offC1 != NULL) *offC1 = offC1_;
}
enum wfc__Dir wfc__dirOpposite(void *ctx, enum wfc__Dir dir) {
(void)ctx;
if (dir == wfc__dirC0Less) {
return wfc__dirC0More;
} else if (dir == wfc__dirC0More) {
return wfc__dirC0Less;
} else if (dir == wfc__dirC1Less) {
return wfc__dirC1More;
} else if (dir == wfc__dirC1More) {
return wfc__dirC1Less;
} else {
WFC_ASSERT(ctx, false);
}
// Unreachable.
return (enum wfc__Dir)0;
}
void wfc__coords2dPlusDir(
void *ctx, int c0, int c1, enum wfc__Dir dir, int *rC0, int *rC1) {
int offC0, offC1;
wfc__dirToOffsets(ctx, dir, &offC0, &offC1);
int rC0_ = c0 + offC0;
int rC1_ = c1 + offC1;
if (rC0 != NULL) *rC0 = rC0_;
if (rC1 != NULL) *rC1 = rC1_;
}
// uint8_ts are used instead of bools for performance concerns.
WFC__A2D_DEF(bool, b);
WFC__A2D_DEF(uint8_t, u8);
WFC__A2D_DEF(int, i);
WFC__A2D_DEF(float, f);
WFC__A3D_DEF(uint8_t, u8);
WFC__A3D_DEF(const uint8_t, cu8);
WFC__A3D_DEF(unsigned, u);
int wfc__bitPackLen(int cnt) {
const int uSzBits = (int)sizeof(unsigned) * 8;
return wfc__roundUpToDivBy(cnt, uSzBits) / uSzBits;
}
bool wfc__getBit(const unsigned *a, int ind) {
const int uSzBits = (int)sizeof(unsigned) * 8;
const unsigned bitMask = 1u << (unsigned)(ind % uSzBits);
return a[ind / uSzBits] & bitMask;
}
void wfc__setBit(unsigned *a, int ind, bool val) {
const int uSzBits = (int)sizeof(unsigned) * 8;
const unsigned bitMask = 1u << (unsigned)(ind % uSzBits);
if (val) a[ind / uSzBits] |= bitMask;
else a[ind / uSzBits] &= ~bitMask;
}
bool wfc__getBitA3d(
const struct wfc__A3d_u arr, int c0, int c1, int c2) {
return wfc__getBit(&WFC__A3D_GET(arr, c0, c1, 0), c2);
}
void wfc__setBitA3d(
const struct wfc__A3d_u arr, int c0, int c1, int c2, bool val) {
wfc__setBit(&WFC__A3D_GET(arr, c0, c1, 0), c2, val);
}
// Bit packs may have surplus bit positions that need to equal 0.
// That is why a function to set all bits to 1 is not provided
// as it would be easy to make the mistake of setting surplus bits to 1.
void wfc__clearBitPackA3d(
const struct wfc__A3d_u arr, int c0, int c1) {
memset(&WFC__A3D_GET(arr, c0, c1, 0), 0, (size_t)arr.d23 * sizeof(*arr.a));
}
int wfc__popcountBitPackA3d(
const struct wfc__A3d_u arr, int c0, int c1) {
int cnt = 0;
for (int i = 0; i < arr.d23; ++i) {
cnt += wfc__popcount_u(WFC__A3D_GET(arr, c0, c1, i));
}
return cnt;
}
struct wfc__Pattern {
// Coordinates of the top-left pixel in the source image.
int c0, c1;
// Bitmask for transformation done to produce this pattern.
int tf;
// Whether this pattern may be placed along a particular edge in output.
bool edgeC0Lo, edgeC0Hi, edgeC1Lo, edgeC1Hi;
// How often this pattern appeared in different places in the source image.
int freq;
};
void wfc__coordsPattToSrc(
int n,
struct wfc__Pattern patt, int pC0, int pC1,
int sD0, int sD1, int *sC0, int *sC1) {
int tfC0 = pC0;
int tfC1 = pC1;
// Map from pattern space to source space.
{
if (patt.tf & wfc__tfFlipC0) tfC0 = n - 1 - tfC0;
if (patt.tf & wfc__tfFlipC1) tfC1 = n - 1 - tfC1;
// Rot-270 is rot-90 plus rot-180 both in bitmask and as transformation.
if (patt.tf & wfc__tfRot90) {
int tmpC0 = tfC0;
int tmpC1 = tfC1;
tfC0 = tmpC1;
tfC1 = n - 1 - tmpC0;
}
if (patt.tf & wfc__tfRot180) {
tfC0 = n - 1 - tfC0;
tfC1 = n - 1 - tfC1;
}
}
int sC0_ = wfc__indWrap(patt.c0 + tfC0, sD0);
int sC1_ = wfc__indWrap(patt.c1 + tfC1, sD1);
if (sC0 != NULL) *sC0 = sC0_;
if (sC1 != NULL) *sC1 = sC1_;
}
// Fill in edge info in a pattern.
void wfc__fillPattEdges(
int n, int sD0, int sD1,
struct wfc__Pattern *patt) {
bool edgeC0Lo = patt->c0 == 0;
bool edgeC0Hi = patt->c0 + n == sD0;
bool edgeC1Lo = patt->c1 == 0;
bool edgeC1Hi = patt->c1 + n == sD1;
// Map from source space to pattern space.
// Note that this is the inverse of what is done in wfc__coordsPattToSrc().
{
// Rot-270 is rot-90 plus rot-180 both in bitmask and as transformation.
if (patt->tf & wfc__tfRot180) {
bool tmpC0Lo = edgeC0Lo;
bool tmpC0Hi = edgeC0Hi;
bool tmpC1Lo = edgeC1Lo;
bool tmpC1Hi = edgeC1Hi;
edgeC0Lo = tmpC0Hi;
edgeC0Hi = tmpC0Lo;
edgeC1Lo = tmpC1Hi;
edgeC1Hi = tmpC1Lo;
}
if (patt->tf & wfc__tfRot90) {
bool tmpC0Lo = edgeC0Lo;
bool tmpC0Hi = edgeC0Hi;
bool tmpC1Lo = edgeC1Lo;
bool tmpC1Hi = edgeC1Hi;
edgeC0Lo = tmpC1Hi;
edgeC0Hi = tmpC1Lo;
edgeC1Lo = tmpC0Lo;
edgeC1Hi = tmpC0Hi;
}
if (patt->tf & wfc__tfFlipC1) {
bool tmp = edgeC1Lo;
edgeC1Lo = edgeC1Hi;
edgeC1Hi = tmp;
}
if (patt->tf & wfc__tfFlipC0) {
bool tmp = edgeC0Lo;
edgeC0Lo = edgeC0Hi;
edgeC0Hi = tmp;
}
}
patt->edgeC0Lo = edgeC0Lo;
patt->edgeC0Hi = edgeC0Hi;
patt->edgeC1Lo = edgeC1Lo;
patt->edgeC1Hi = edgeC1Hi;
}
// Maps from destination coordinates to wave coordinates.
// When edges are fixed, wave may be shorter and/or narrower than destination,
// so multiple destination points will map to the same wave point,
// but with different offsets.
void wfc__coordsDstToWave(