-
Notifications
You must be signed in to change notification settings - Fork 5
/
blender_magicavoxel.py
2730 lines (2470 loc) · 129 KB
/
blender_magicavoxel.py
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) 2024 https://github.com/AstrorEnales
#
# 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 script imports a MagicaVoxel VOX file to Blender.
Usage:
Run this script from "File->Import" menu and then load the desired VOX file.
Repository:
https://github.com/AstrorEnales/blender_magicavoxel
File format info:
https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox.txt
https://github.com/ephtracy/voxel-model/blob/master/MagicaVoxel-file-format-vox-extension.txt
"""
import io
import time
import bpy
import os
import math
import mathutils
import struct
from functools import cmp_to_key
from typing import IO, List, Dict, Tuple, Set
from bpy.props import (
StringProperty,
BoolProperty,
FloatProperty,
EnumProperty,
IntProperty,
)
from bpy_extras.io_utils import (
ImportHelper,
)
bl_info = {
"name": "MagicaVoxel VOX format",
"author": "AstrorEnales",
"version": (1, 5, 5),
"blender": (3, 0, 0),
"location": "File > Import-Export",
"description": "Importer for MagicaVoxel VOX files",
"category": "Import-Export",
"doc_url": "https://github.com/AstrorEnales/blender_magicavoxel",
"tracker_url": "https://github.com/AstrorEnales/blender_magicavoxel/issues",
"support": "COMMUNITY",
}
def abgr_int_to_rgba_tuple(color: int) -> Tuple[int, int, int, int]:
return (
(color >> 24) & 0xff,
(color >> 16) & 0xff,
(color >> 8) & 0xff,
color & 0xff
)
DEFAULT_PALETTE: List[Tuple[int, int, int, int]] = [
abgr_int_to_rgba_tuple(x) for x in [
0x00000000, 0xffffffff, 0xffccffff, 0xff99ffff, 0xff66ffff, 0xff33ffff,
0xff00ffff, 0xffffccff, 0xffccccff, 0xff99ccff, 0xff66ccff, 0xff33ccff,
0xff00ccff, 0xffff99ff, 0xffcc99ff, 0xff9999ff, 0xff6699ff, 0xff3399ff,
0xff0099ff, 0xffff66ff, 0xffcc66ff, 0xff9966ff, 0xff6666ff, 0xff3366ff,
0xff0066ff, 0xffff33ff, 0xffcc33ff, 0xff9933ff, 0xff6633ff, 0xff3333ff,
0xff0033ff, 0xffff00ff, 0xffcc00ff, 0xff9900ff, 0xff6600ff, 0xff3300ff,
0xff0000ff, 0xffffffcc, 0xffccffcc, 0xff99ffcc, 0xff66ffcc, 0xff33ffcc,
0xff00ffcc, 0xffffcccc, 0xffcccccc, 0xff99cccc, 0xff66cccc, 0xff33cccc,
0xff00cccc, 0xffff99cc, 0xffcc99cc, 0xff9999cc, 0xff6699cc, 0xff3399cc,
0xff0099cc, 0xffff66cc, 0xffcc66cc, 0xff9966cc, 0xff6666cc, 0xff3366cc,
0xff0066cc, 0xffff33cc, 0xffcc33cc, 0xff9933cc, 0xff6633cc, 0xff3333cc,
0xff0033cc, 0xffff00cc, 0xffcc00cc, 0xff9900cc, 0xff6600cc, 0xff3300cc,
0xff0000cc, 0xffffff99, 0xffccff99, 0xff99ff99, 0xff66ff99, 0xff33ff99,
0xff00ff99, 0xffffcc99, 0xffcccc99, 0xff99cc99, 0xff66cc99, 0xff33cc99,
0xff00cc99, 0xffff9999, 0xffcc9999, 0xff999999, 0xff669999, 0xff339999,
0xff009999, 0xffff6699, 0xffcc6699, 0xff996699, 0xff666699, 0xff336699,
0xff006699, 0xffff3399, 0xffcc3399, 0xff993399, 0xff663399, 0xff333399,
0xff003399, 0xffff0099, 0xffcc0099, 0xff990099, 0xff660099, 0xff330099,
0xff000099, 0xffffff66, 0xffccff66, 0xff99ff66, 0xff66ff66, 0xff33ff66,
0xff00ff66, 0xffffcc66, 0xffcccc66, 0xff99cc66, 0xff66cc66, 0xff33cc66,
0xff00cc66, 0xffff9966, 0xffcc9966, 0xff999966, 0xff669966, 0xff339966,
0xff009966, 0xffff6666, 0xffcc6666, 0xff996666, 0xff666666, 0xff336666,
0xff006666, 0xffff3366, 0xffcc3366, 0xff993366, 0xff663366, 0xff333366,
0xff003366, 0xffff0066, 0xffcc0066, 0xff990066, 0xff660066, 0xff330066,
0xff000066, 0xffffff33, 0xffccff33, 0xff99ff33, 0xff66ff33, 0xff33ff33,
0xff00ff33, 0xffffcc33, 0xffcccc33, 0xff99cc33, 0xff66cc33, 0xff33cc33,
0xff00cc33, 0xffff9933, 0xffcc9933, 0xff999933, 0xff669933, 0xff339933,
0xff009933, 0xffff6633, 0xffcc6633, 0xff996633, 0xff666633, 0xff336633,
0xff006633, 0xffff3333, 0xffcc3333, 0xff993333, 0xff663333, 0xff333333,
0xff003333, 0xffff0033, 0xffcc0033, 0xff990033, 0xff660033, 0xff330033,
0xff000033, 0xffffff00, 0xffccff00, 0xff99ff00, 0xff66ff00, 0xff33ff00,
0xff00ff00, 0xffffcc00, 0xffcccc00, 0xff99cc00, 0xff66cc00, 0xff33cc00,
0xff00cc00, 0xffff9900, 0xffcc9900, 0xff999900, 0xff669900, 0xff339900,
0xff009900, 0xffff6600, 0xffcc6600, 0xff996600, 0xff666600, 0xff336600,
0xff006600, 0xffff3300, 0xffcc3300, 0xff993300, 0xff663300, 0xff333300,
0xff003300, 0xffff0000, 0xffcc0000, 0xff990000, 0xff660000, 0xff330000,
0xff0000ee, 0xff0000dd, 0xff0000bb, 0xff0000aa, 0xff000088, 0xff000077,
0xff000055, 0xff000044, 0xff000022, 0xff000011, 0xff00ee00, 0xff00dd00,
0xff00bb00, 0xff00aa00, 0xff008800, 0xff007700, 0xff005500, 0xff004400,
0xff002200, 0xff001100, 0xffee0000, 0xffdd0000, 0xffbb0000, 0xffaa0000,
0xff880000, 0xff770000, 0xff550000, 0xff440000, 0xff220000, 0xff110000,
0xffeeeeee, 0xffdddddd, 0xffbbbbbb, 0xffaaaaaa, 0xff888888, 0xff777777,
0xff555555, 0xff444444, 0xff222222, 0xff111111,
]
]
DEBUG_OUTPUT = False
READ_INT_UNPACK = struct.Struct('<i').unpack
READ_FLOAT_UNPACK = struct.Struct('<f').unpack
class RectanglePacker:
"""
Rectangle packer translated from Javier Arevalo
https://www.flipcode.com/archives/Rectangle_Placement.shtml
"""
def __init__(self, packing_area_width: int, packing_area_height: int):
self.packed_rectangles: List[Tuple[int, int, int, int]] = []
self.anchors: List[Tuple[int, int]] = [(0, 0)]
self.packing_area_width = packing_area_width
self.packing_area_height = packing_area_height
self.actual_packing_area_width = 1
self.actual_packing_area_height = 1
@staticmethod
def compare_anchor_rank(a: Tuple[int, int], b: Tuple[int, int]) -> int:
return a[0] + a[1] - (b[0] + b[1])
def insert_anchor(self, anchor: Tuple[int, int]):
"""
Inserts a new anchor point into the anchor list.
This method tries to keep the anchor list ordered by ranking the anchors depending on the distance from the top
left corner in the packing area.
"""
# Find out where to insert the new anchor based on its rank (which is calculated based on the anchor's distance
# to the top left corner of the packing area).
self.anchors.append(anchor)
self.anchors.sort(key=cmp_to_key(RectanglePacker.compare_anchor_rank))
@staticmethod
def rectangles_intersect(a_x: int, a_y: int, a_width: int, a_height: int,
b_x: int, b_y: int, b_width: int, b_height: int) -> bool:
return b_x < a_x + a_width and a_x < b_x + b_width and b_y < a_y + a_height and a_y < b_y + b_height
def is_free(self, rectangle_x: int, rectangle_y: int, rectangle_width: int, rectangle_height: int,
tested_packing_area_width: int, tested_packing_area_height: int) -> bool:
leaves_packing_area = (rectangle_x < 0
or rectangle_y < 0
or rectangle_x + rectangle_width > tested_packing_area_width
or rectangle_y + rectangle_height > tested_packing_area_height)
if leaves_packing_area:
return False
# Brute-force search whether the rectangle touches any of the other rectangles already in the packing area
for index in range(0, len(self.packed_rectangles)):
other = self.packed_rectangles[index]
if self.rectangles_intersect(other[0], other[1], other[2], other[3], rectangle_x, rectangle_y,
rectangle_width, rectangle_height):
return False
return True
def find_first_free_anchor(self, rectangle_width: int, rectangle_height: int, tested_packing_area_width: int,
tested_packing_area_height: int) -> int:
# Walk over all anchors (which are ordered by their distance to the upper left corner of the packing area) until
# one is discovered that can house the new rectangle.
for index in range(0, len(self.anchors)):
if self.is_free(self.anchors[index][0], self.anchors[index][1], rectangle_width, rectangle_height,
tested_packing_area_width, tested_packing_area_height):
return index
return -1
def select_anchor_recursive(self, rectangle_width: int, rectangle_height: int,
tested_packing_area_width: int, tested_packing_area_height: int) -> int:
"""
Searches for a free anchor and recursively enlarges the packing area if none can be found.
"""
# Try to locate an anchor point where the rectangle fits in
free_anchor_index = self.find_first_free_anchor(rectangle_width, rectangle_height, tested_packing_area_width,
tested_packing_area_height)
# If the rectangle fits without resizing packing area (any further in case of a recursive call), take over the
# new packing area size and return the anchor at which the rectangle can be placed.
if free_anchor_index != -1:
self.actual_packing_area_width = tested_packing_area_width
self.actual_packing_area_height = tested_packing_area_height
return free_anchor_index
# If we reach this point, the rectangle did not fit in the current packing area and our only choice is to try
# and enlarge the packing area. For readability, determine whether the packing area can be enlarged any further
# in its width and in its height
can_enlarge_width = tested_packing_area_width < self.packing_area_width
can_enlarge_height = tested_packing_area_height < self.packing_area_height
should_enlarge_height = not can_enlarge_width or tested_packing_area_height < tested_packing_area_width
# Try to enlarge the smaller of the two dimensions first (unless the smaller dimension is already at its maximum
# size). 'shouldEnlargeHeight' is true when the height was the smaller dimension or when the width is maxed out.
if can_enlarge_height and should_enlarge_height:
# Try to double the height of the packing area
return self.select_anchor_recursive(rectangle_width, rectangle_height, tested_packing_area_width,
min(tested_packing_area_height * 2, self.packing_area_height))
if can_enlarge_width:
# Try to double the width of the packing area
return self.select_anchor_recursive(rectangle_width, rectangle_height,
min(tested_packing_area_width * 2, self.packing_area_width),
tested_packing_area_height)
return -1
def optimize_placement(self, placement: Tuple[int, int], rectangle_width: int, rectangle_height: int) \
-> Tuple[int, int]:
"""
Optimizes the rectangle's placement by moving it either left or up to fill any gaps resulting from rectangles
blocking the anchors of the most optimal placements.
"""
test_coordinate = placement[0]
# Try to move the rectangle to the left as far as possible
left_most = placement[0]
while self.is_free(test_coordinate, placement[1], rectangle_width, rectangle_height, self.packing_area_width,
self.packing_area_height):
left_most = test_coordinate
test_coordinate -= 1
# Reset rectangle to original position
test_coordinate = placement[1]
# Try to move the rectangle upwards as far as possible
top_most = placement[1]
while self.is_free(placement[0], test_coordinate, rectangle_width, rectangle_height, self.packing_area_width,
self.packing_area_height):
top_most = test_coordinate
test_coordinate -= 1
# Use the dimension in which the rectangle could be moved farther
if placement[0] - left_most > placement[1] - top_most:
return left_most, placement[1]
else:
return placement[0], top_most
def try_pack(self, rectangle_width: int, rectangle_height: int) -> Tuple[int, int] or None:
"""
Tries to allocate space for a rectangle in the packing area.
"""
# Try to find an anchor where the rectangle fits in, enlarging the packing area and repeating the search
# recursively until it fits or the maximum allowed size is exceeded.
anchor_index = self.select_anchor_recursive(rectangle_width, rectangle_height, self.actual_packing_area_width,
self.actual_packing_area_height)
# No anchor could be found at which the rectangle did fit in
if anchor_index == -1:
return None
anchor = self.anchors[anchor_index]
# Move the rectangle either to the left or to the top until it collides with a neighbouring rectangle. This is
# done to combat the effect of lining up rectangles with gaps to the left or top of them because the anchor that
# would allow placement there has been blocked by another rectangle
placement = self.optimize_placement((anchor[0], anchor[1]), rectangle_width, rectangle_height)
# Remove the used anchor and add new anchors at the upper right and lower left positions of the new rectangle.
# The anchor is only removed if the placement optimization didn't move the rectangle so far that the anchor
# isn't blocked anymore
blocks_anchor = placement[0] + rectangle_width > anchor[0] and placement[1] + rectangle_height > anchor[1]
if blocks_anchor:
del self.anchors[anchor_index]
# Add new anchors at the upper right and lower left coordinates of the rectangle
self.insert_anchor((placement[0] + rectangle_width, placement[1]))
self.insert_anchor((placement[0], placement[1] + rectangle_height))
# Finally, we can add the rectangle to our packed rectangles list
self.packed_rectangles.append((placement[0], placement[1], rectangle_width, rectangle_height))
return placement
ChildXnYnZn = 0
ChildXpYnZn = 1
ChildXnYpZn = 2
ChildXpYpZn = 3
ChildXnYnZp = 4
ChildXpYnZp = 5
ChildXnYpZp = 6
ChildXpYpZp = 7
SideLength = 4
LeafIndexXMap = [
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2,
3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3
]
LeafIndexYMap = [
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1,
1, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
]
LeafIndexZMap = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
]
SideLengthTwice = SideLength * SideLength
GridLength = SideLength * SideLength * SideLength
class Octree:
def __init__(self, size: int = 8, default_value: any = None):
self.size = 2 ** (max(8, size) - 1).bit_length()
self.size_half = self.size >> 1
self.default_value = default_value
self._root = OctreeBranchNode(self, -self.size_half, -self.size_half, -self.size_half, self.size,
self.default_value)
self.leafs: List[OctreeLeafNode] = []
@property
def is_full(self) -> bool:
return self._root.is_full
@property
def is_empty(self) -> bool:
return self._root.is_empty
@property
def is_not_empty(self) -> bool:
return self._root.is_not_empty
@property
def count(self) -> int:
return self._root.count
@property
def not_empty_bounds(self) -> Tuple[int, int, int, int, int, int]:
return self._root.not_empty_bounds
def get_value(self, x: int, y: int, z: int) -> any:
return self.default_value if self.is_outside(x, y, z) else self._root.get_value(x, y, z)
def contains(self, x: int, y: int, z: int) -> bool:
return self.is_inside(x, y, z) and self._root.contains(x, y, z)
def is_outside(self, x: int, y: int, z: int) -> bool:
return (x >= self.size_half or x < -self.size_half or y >= self.size_half or y < -self.size_half
or z >= self.size_half or z < -self.size_half)
def is_inside(self, x: int, y: int, z: int) -> bool:
# noinspection PyChainedComparisons
return (x < self.size_half and x >= -self.size_half and y < self.size_half and y >= -self.size_half
and z < self.size_half and z >= -self.size_half)
def add(self, x: int, y: int, z: int, value: any):
while self.is_outside(x, y, z):
self._expand()
self._root.add(x, y, z, value)
def _expand(self):
self.size_half <<= 1
self.size <<= 1
total_count = 0
new_root = OctreeBranchNode(self, -self.size_half, -self.size_half, -self.size_half, self.size,
self.default_value)
# Y+
child = self._root.child_nodes[ChildXpYpZp]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x, child.start_position_y, child.start_position_z,
child.size * 2, self.default_value)
new_child.child_nodes[ChildXnYnZn] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXpYpZp] = new_child
child = self._root.child_nodes[ChildXpYpZn]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x, child.start_position_y,
child.start_position_z - child.size, child.size * 2, self.default_value)
new_child.child_nodes[ChildXnYnZp] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXpYpZn] = new_child
child = self._root.child_nodes[ChildXnYpZp]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x - child.size, child.start_position_y,
child.start_position_z, child.size * 2, self.default_value)
new_child.child_nodes[ChildXpYnZn] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXnYpZp] = new_child
child = self._root.child_nodes[ChildXnYpZn]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x - child.size, child.start_position_y,
child.start_position_z - child.size, child.size * 2, self.default_value)
new_child.child_nodes[ChildXpYnZp] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXnYpZn] = new_child
# Y-
child = self._root.child_nodes[ChildXpYnZp]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x, child.start_position_y - child.size,
child.start_position_z, child.size * 2, self.default_value)
new_child.child_nodes[ChildXnYpZn] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXpYnZp] = new_child
child = self._root.child_nodes[ChildXpYnZn]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x, child.start_position_y - child.size,
child.start_position_z - child.size, child.size * 2, self.default_value)
new_child.child_nodes[ChildXnYpZp] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXpYnZn] = new_child
child = self._root.child_nodes[ChildXnYnZp]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x - child.size, child.start_position_y - child.size,
child.start_position_z, child.size * 2, self.default_value)
new_child.child_nodes[ChildXpYpZn] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXnYnZp] = new_child
child = self._root.child_nodes[ChildXnYnZn]
if child is not None:
new_child = OctreeBranchNode(self, child.start_position_x - child.size, child.start_position_y - child.size,
child.start_position_z - child.size, child.size * 2, self.default_value)
new_child.child_nodes[ChildXpYpZp] = child
new_child._count = child.count
total_count += child.count
new_child.bounds_set = child.bounds_set
new_child.min_x = child.min_x
new_child.min_y = child.min_y
new_child.min_z = child.min_z
new_child.max_x = child.max_x
new_child.max_y = child.max_y
new_child.max_z = child.max_z
new_root.child_nodes[ChildXnYnZn] = new_child
new_root._count = total_count
new_root.update_not_empty_bounds()
self._root = new_root
def _contract(self):
while (self.size > 8
and self._root.is_child_contractible(ChildXnYnZn, ChildXpYpZp)
and self._root.is_child_contractible(ChildXpYpZn, ChildXnYnZp)
and self._root.is_child_contractible(ChildXnYpZp, ChildXpYnZn)
and self._root.is_child_contractible(ChildXpYpZp, ChildXnYnZn)):
self.size >>= 1
self.size_half >>= 1
new_root = OctreeBranchNode(self, -self.size_half, -self.size_half, -self.size_half, self.size,
self.default_value)
if self._root.child_nodes[ChildXpYpZp] is not None:
# noinspection PyUnresolvedReferences
new_root.child_nodes[ChildXpYpZp] = self._root.child_nodes[ChildXpYpZp].child_nodes[ChildXnYnZn]
if self._root.child_nodes[ChildXpYpZn] is not None:
# noinspection PyUnresolvedReferences
new_root.child_nodes[ChildXpYpZn] = self._root.child_nodes[ChildXpYpZn].child_nodes[ChildXnYnZp]
if self._root.child_nodes[ChildXnYpZp] is not None:
# noinspection PyUnresolvedReferences
new_root.child_nodes[ChildXnYpZp] = self._root.child_nodes[ChildXnYpZp].child_nodes[ChildXpYnZn]
if self._root.child_nodes[ChildXnYnZn] is not None:
# noinspection PyUnresolvedReferences
new_root.child_nodes[ChildXnYnZn] = self._root.child_nodes[ChildXnYnZn].child_nodes[ChildXpYpZp]
new_root.update_not_empty_bounds()
self._root = new_root
def remove(self, x: int, y: int, z: int):
if self.is_inside(x, y, z):
self._root.remove(x, y, z)
self._contract()
class OctreeNode:
def __init__(self, parent: Octree, start_position_x: int, start_position_y: int, start_position_z: int, size: int,
default_value: any):
self.parent = parent
self.start_position_x = start_position_x
self.start_position_y = start_position_y
self.start_position_z = start_position_z
self.size = size
self.size_half = size >> 1
self.default_value = default_value
self.bounds_set = False
self.max_x = -1
self.max_y = -1
self.max_z = -1
self.min_x = -1
self.min_y = -1
self.min_z = -1
@property
def not_empty_bounds(self) -> Tuple[int, int, int, int, int, int]:
return (0, 0, 0, 1, 1, 1) if self.is_empty else \
(self.min_x, self.min_y, self.min_z, self.max_x, self.max_y, self.max_z)
@property
def is_leaf(self) -> bool:
return False
@property
def is_full(self) -> bool:
return False
@property
def count(self) -> int:
return -1
@property
def is_empty(self) -> bool:
return not self.bounds_set
@property
def is_not_empty(self) -> bool:
return self.bounds_set
def get_value(self, x: int, y: int, z: int) -> any:
pass
def contains(self, x: int, y: int, z: int) -> bool:
pass
def add(self, x: int, y: int, z: int, value: any) -> bool:
pass
def remove(self, x: int, y: int, z: int) -> bool:
pass
class OctreeBranchNode(OctreeNode):
def __init__(self, parent: Octree, start_position_x: int, start_position_y: int, start_position_z: int, size: int,
default_value: any):
OctreeNode.__init__(self, parent, start_position_x, start_position_y, start_position_z, size, default_value)
self._max_count = ((SideLength * 2) ** (math.log2(size) - 2)) * GridLength
self._center_x = start_position_x + self.size_half
self._center_y = start_position_y + self.size_half
self._center_z = start_position_z + self.size_half
self._count = 0
self.child_nodes: List[OctreeNode | None] = [None] * 8
@property
def is_leaf(self) -> bool:
return False
@property
def is_full(self) -> bool:
return self._count == self._max_count
@property
def count(self) -> int:
return self._count
def _get_index(self, x: int, y: int, z: int) -> int:
return (x >= self._center_x) + (y >= self._center_y) * 2 + (z >= self._center_z) * 4
def get_value(self, x: int, y: int, z: int) -> any:
child = self.child_nodes[self._get_index(x, y, z)]
return child.get_value(x, y, z) if child is not None else self.default_value
def contains(self, x: int, y: int, z: int) -> bool:
child = self.child_nodes[self._get_index(x, y, z)]
return child is not None and child.contains(x, y, z)
def add(self, x: int, y: int, z: int, value: any) -> bool:
node_index = self._get_index(x, y, z)
node = self.child_nodes[node_index]
if node is None:
pos_x = self.start_position_x if x < self._center_x else self._center_x
pos_y = self.start_position_y if y < self._center_y else self._center_y
pos_z = self.start_position_z if z < self._center_z else self._center_z
node = (
OctreeBranchNode(self.parent, pos_x, pos_y, pos_z, self.size_half, self.default_value)
if self.size_half > SideLength else
OctreeLeafNode(self.parent, pos_x, pos_y, pos_z, self.default_value)
)
self.child_nodes[node_index] = node
if not node.add(x, y, z, value):
return False
self._count += 1
if not self.bounds_set:
self.min_x = x
self.min_y = y
self.min_z = z
self.max_x = x + 1
self.max_y = y + 1
self.max_z = z + 1
else:
if x < self.min_x:
self.min_x = x
if y < self.min_y:
self.min_y = y
if z < self.min_z:
self.min_z = z
if x >= self.max_x:
self.max_x = x + 1
if y >= self.max_y:
self.max_y = y + 1
if z >= self.max_z:
self.max_z = z + 1
self.bounds_set = True
return True
def remove(self, x: int, y: int, z: int) -> bool:
node_index = self._get_index(x, y, z)
node = self.child_nodes[node_index]
success = False
if node is not None:
success = node.remove(x, y, z)
if node.is_empty:
if node.is_leaf:
# noinspection PyTypeChecker
self.parent.leafs.remove(node)
self.child_nodes[node_index] = None
if success:
self._count -= 1
self.update_not_empty_bounds()
return success
def update_not_empty_bounds(self):
if self._count == self._max_count:
self.min_x = self.start_position_x
self.min_y = self.start_position_y
self.min_z = self.start_position_z
self.max_x = self.start_position_x + self.size - 1
self.max_y = self.start_position_y + self.size - 1
self.max_z = self.start_position_z + self.size - 1
self.bounds_set = True
else:
self.min_x = -1
self.max_x = -1
self.min_y = -1
self.max_y = -1
self.min_z = -1
self.max_z = -1
self.bounds_set = False
for i in range(0, len(self.child_nodes)):
child = self.child_nodes[i]
if child is None or child.is_empty:
continue
if not self.bounds_set:
self.min_x = child.min_x
self.min_y = child.min_y
self.min_z = child.min_z
self.max_x = child.max_x
self.max_y = child.max_y
self.max_z = child.max_z
else:
if child.min_x < self.min_x:
self.min_x = child.min_x
if child.min_y < self.min_y:
self.min_y = child.min_y
if child.min_z < self.min_z:
self.min_z = child.min_z
if child.max_x > self.max_x:
self.max_x = child.max_x
if child.max_y > self.max_y:
self.max_y = child.max_y
if child.max_z > self.max_z:
self.max_z = child.max_z
self.bounds_set = True
def is_child_contractible(self, child_index: int, remaining_child_child_index: int) -> bool:
child = self.child_nodes[child_index]
if child is not None:
if isinstance(child, OctreeBranchNode):
for i in range(0, len(child.child_nodes)):
if i != remaining_child_child_index and child.child_nodes[i] is not None:
return False
else:
return False
return True
class OctreeLeafNode(OctreeNode):
def __init__(self, parent: Octree, start_position_x: int, start_position_y: int, start_position_z: int,
default_value: any):
OctreeNode.__init__(self, parent, start_position_x, start_position_y, start_position_z, SideLength,
default_value)
parent.leafs.append(self)
self._index_offset = start_position_x + start_position_y * SideLength + start_position_z * SideLengthTwice
self._count = 0
self._x_axis_counts: List[int] = [0] * SideLength
self._y_axis_counts: List[int] = [0] * SideLength
self._z_axis_counts: List[int] = [0] * SideLength
self.grid: List[any] = [None] * GridLength
self.grid_taken: List[bool] = [False] * GridLength
def _get_index(self, x: int, y: int, z: int) -> int:
return x + y * SideLength + z * SideLengthTwice - self._index_offset
@staticmethod
def _get_index_local(x: int, y: int, z: int) -> int:
return x + y * SideLength + z * SideLengthTwice
@property
def is_leaf(self) -> bool:
return True
@property
def is_full(self) -> bool:
return self._count == GridLength
@property
def count(self) -> int:
return self._count
def get_value(self, x: int, y: int, z: int) -> any:
index = self._get_index(x, y, z)
return self.grid[index] if self.grid_taken[index] else self.default_value
def contains(self, x: int, y: int, z: int) -> bool:
return self.grid_taken[self._get_index(x, y, z)]
def add(self, x: int, y: int, z: int, value: any) -> bool:
if not self.bounds_set:
self.min_x = x
self.min_y = y
self.min_z = z
self.max_x = x + 1
self.max_y = y + 1
self.max_z = z + 1
else:
if x < self.min_x:
self.min_x = x
if y < self.min_y:
self.min_y = y
if z < self.min_z:
self.min_z = z
if x >= self.max_x:
self.max_x = x + 1
if y >= self.max_y:
self.max_y = y + 1
if z >= self.max_z:
self.max_z = z + 1
self.bounds_set = True
x -= self.start_position_x
y -= self.start_position_y
z -= self.start_position_z
index = self._get_index_local(x, y, z)
if not self.grid_taken[index]:
self._count += 1
self.grid_taken[index] = True
self.grid[index] = value
self._x_axis_counts[x] += 1
self._y_axis_counts[y] += 1
self._z_axis_counts[z] += 1
return True
self.grid[index] = value
return False
def remove(self, x: int, y: int, z: int) -> bool:
x -= self.start_position_x
y -= self.start_position_y
z -= self.start_position_z
index = self._get_index_local(x, y, z)
if not self.grid_taken[index]:
return False
self._count -= 1
self._x_axis_counts[x] -= 1
self._y_axis_counts[y] -= 1
self._z_axis_counts[z] -= 1
self.grid_taken[index] = False
self.grid[index] = self.default_value
self._update_not_empty_bounds()
return True
def _update_not_empty_bounds(self):
self.bounds_set = False
# X axis
for i in range(0, SideLength):
if self._x_axis_counts[i] > 0:
self.min_x = i + self.start_position_x
self.bounds_set = True
break
for i in range(SideLength - 1, -1, -1):
if self._x_axis_counts[i] > 0:
self.max_x = i + self.start_position_x + 1
self.bounds_set = True
break
# Y axis
for i in range(0, SideLength):
if self._y_axis_counts[i] > 0:
self.min_y = i + self.start_position_y
self.bounds_set = True
break
for i in range(SideLength - 1, -1, -1):
if self._y_axis_counts[i] > 0:
self.max_y = i + self.start_position_y + 1
self.bounds_set = True
break
# Z axis
for i in range(0, SideLength):
if self._z_axis_counts[i] > 0:
self.min_z = i + self.start_position_z
self.bounds_set = True
break
for i in range(SideLength - 1, -1, -1):
if self._z_axis_counts[i] > 0:
self.max_z = i + self.start_position_z + 1
self.bounds_set = True
break
class OctreeIterator:
def __init__(self, octree: Octree):
self._leafs = octree.leafs.copy()
self._has_current = False
self._next_inside_leaf_index = 0
self._next_leaf_index = 0
self._current: Tuple[int, int, int, any] = (0, 0, 0, None)
@property
def current(self):
return self._current if self._has_current else None
def move_next(self) -> bool:
self._has_current = False
while self._next_leaf_index < len(self._leafs):
current_leaf = self._leafs[self._next_leaf_index]
while self._next_inside_leaf_index < GridLength:
if current_leaf.grid_taken[self._next_inside_leaf_index]:
self._current = (
LeafIndexXMap[self._next_inside_leaf_index] + current_leaf.start_position_x,
LeafIndexYMap[self._next_inside_leaf_index] + current_leaf.start_position_y,
LeafIndexZMap[self._next_inside_leaf_index] + current_leaf.start_position_z,
current_leaf.grid[self._next_inside_leaf_index]
)
self._has_current = True
self._next_inside_leaf_index += 1
break
self._next_inside_leaf_index += 1
if self._has_current:
break
self._next_leaf_index += 1
self._next_inside_leaf_index = 0
return self._has_current
def reset(self):
self._has_current = False
self._next_inside_leaf_index = 0
self._next_leaf_index = 0
class VoxelGrid:
width: int
depth: int
height: int
def __init__(self, width: int, depth: int, height: int):
self.width = width
self.depth = depth
self.height = height
@staticmethod
def reduce_voxel_grid_to_hull(voxels: Octree, outside: Octree):
if DEBUG_OUTPUT:
print('[DEBUG] reduce_voxel_grid_to_hull')
timer_start = time.time()
iterator = OctreeIterator(voxels)
while iterator.move_next():
(x, y, z, _) = iterator.current
# Left
if outside.get_value(x - 1, y, z):
continue
# Right
if outside.get_value(x + 1, y, z):
continue
# Down
if outside.get_value(x, y - 1, z):
continue
# Up
if outside.get_value(x, y + 1, z):
continue
# Back
if outside.get_value(x, y, z - 1):
continue
# Front
if outside.get_value(x, y, z + 1):
continue
# If not connected to the outside space, delete the voxel(inside hull)
voxels.remove(x, y, z)
if DEBUG_OUTPUT:
print('[DEBUG] took %s sec' % (time.time() - timer_start))
@staticmethod
def create_outside_grid(voxels: Octree) -> Octree:
if DEBUG_OUTPUT:
print('[DEBUG] create_outside_grid')
timer_start = time.time()
outside = Octree(default_value=True)
if voxels.is_not_empty:
distinct_areas = VoxelGrid.find_distinct_areas(voxels)
distinct_areas_iterator = OctreeIterator(distinct_areas)
while distinct_areas_iterator.move_next():
(x, y, z, _) = distinct_areas_iterator.current
if distinct_areas.get_value(x, y, z) != 0:
outside.add(x, y, z, False)
if DEBUG_OUTPUT:
print('[DEBUG] took %s sec' % (time.time() - timer_start))
return outside
@staticmethod
def find_distinct_areas(voxels: Octree) -> Octree:
"""
connected-component labeling (CCL) with the Hoshen–Kopelman algorithm
modified to label all voxels -1 as we're only interested in non-voxel labels
"""
if DEBUG_OUTPUT:
print('[DEBUG] find_distinct_areas')
timer_start = time.time()
labels = Octree(voxels.size, default_value=0)
label_equivalence: Dict[int, Set[int]] = {0: set()}
next_label = 1
leaf_bounds = [leaf.not_empty_bounds for leaf in voxels.leafs if leaf.is_not_empty]
leaf_bounds = [(b[0] - 1, b[1] - 1, b[2] - 1, b[3] + 1, b[4] + 1, b[5] + 1) for b in leaf_bounds]
count = -1
while count != len(leaf_bounds):
count = len(leaf_bounds)
for i in range(len(leaf_bounds) - 1, 0, -1):
b1 = leaf_bounds[i]
for j in range(i - 1, -1, -1):
b2 = leaf_bounds[j]
if not (b1[3] < b2[0] or b1[0] > b2[3] or b1[4] < b2[1] or b1[1] > b2[4] or b1[5] < b2[2]
or b1[2] > b2[5]):
leaf_bounds[j] = (
min(b1[0], b2[0]), min(b1[1], b2[1]), min(b1[2], b2[2]),
max(b1[3], b2[3]), max(b1[4], b2[4]), max(b1[5], b2[5])
)
del leaf_bounds[i]
break
for bounds in leaf_bounds:
for z in range(bounds[2], bounds[5]):
for y in range(bounds[1], bounds[4]):
for x in range(bounds[0], bounds[3]):
if voxels.get_value(x, y, z) is not None:
labels.add(x, y, z, -1)