/
volumes.go
1685 lines (1550 loc) · 40.3 KB
/
volumes.go
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
/*
This file contains code that supports sparse and binary volumes.
*/
package dvid
import (
"bytes"
"container/list"
"encoding/binary"
"fmt"
"io"
"math"
"net/http"
"sort"
"strconv"
)
func init() {
sqrt3div3 := math.Sqrt(3.0) / 3.0
sqrt2div2 := math.Sqrt(2.0) / 2.0
// Initialize Zucker-Hummel 3x3x3 filter
// Fill in z = 0 for Z gradient kernel
zhZ[0][0][0] = -sqrt3div3
zhZ[1][0][0] = -sqrt2div2
zhZ[2][0][0] = -sqrt3div3
zhZ[0][1][0] = -sqrt2div2
zhZ[1][1][0] = -1.0
zhZ[2][1][0] = -sqrt2div2
zhZ[0][2][0] = -sqrt3div3
zhZ[1][2][0] = -sqrt2div2
zhZ[2][2][0] = -sqrt3div3
// Fill in z=1,2 for Z gradient kernel
for y := 0; y < 3; y++ {
for x := 0; x < 3; x++ {
zhZ[x][y][1] = 0.0
zhZ[x][y][2] = -zhZ[x][y][0]
}
}
// Copy Z gradient kernel to X and Y gradient kernels
for z := 0; z < 3; z++ {
for y := 0; y < 3; y++ {
for x := 0; x < 3; x++ {
zhX[z][x][y] = zhZ[x][y][z]
zhY[x][z][y] = zhZ[x][y][z]
}
}
}
}
// Sparse Volume binary encoding payload descriptors.
const (
// EncodingBinary denotes no payload bytes since binary sparse volume is
// defined by just start and run length.
EncodingBinary byte = 0x00
// EncodingGrayscale8 denotes an 8-bit grayscale payload.
EncodingGrayscale8 = 0x01
// EncodingGrayscale16 denotes a 16-bit grayscale payload.
EncodingGrayscale16 = 0x02
// EncodingNormal16 denotes 16-bit encoded normals.
EncodingNormal16 = 0x04
)
var (
zhX, zhY, zhZ [3][3][3]float64
)
// Bounding provides two levels of optional bounds (voxel and block) as well as
// whether bounds must be exact to voxel level.
type Bounds struct {
Voxel *OptionalBounds
Block *OptionalBounds
Exact bool // If false, just screen on blocks.
}
// OptionalBounds holds optional bounds in X, Y, and Z.
// This differs from Extents in allowing optional min
// and max bounds along each dimension.
type OptionalBounds struct {
minx, maxx, miny, maxy, minz, maxz *int32
}
// OptionalBoundsFromQueryString returns OptionalBounds from a set of query strings.
func OptionalBoundsFromQueryString(r *http.Request) (*OptionalBounds, error) {
bounds := new(OptionalBounds)
queryStrings := r.URL.Query()
var minx, maxx, miny, maxy, minz, maxz int32
minxStr := queryStrings.Get("minx")
if minxStr != "" {
val, err := strconv.ParseInt(minxStr, 10, 32)
if err != nil {
return nil, err
}
minx = int32(val)
bounds.minx = &minx
}
maxxStr := queryStrings.Get("maxx")
if maxxStr != "" {
val, err := strconv.ParseInt(maxxStr, 10, 32)
if err != nil {
return nil, err
}
maxx = int32(val)
bounds.maxx = &maxx
}
minyStr := queryStrings.Get("miny")
if minyStr != "" {
val, err := strconv.ParseInt(minyStr, 10, 32)
if err != nil {
return nil, err
}
miny = int32(val)
bounds.miny = &miny
}
maxyStr := queryStrings.Get("maxy")
if maxyStr != "" {
val, err := strconv.ParseInt(maxyStr, 10, 32)
if err != nil {
return nil, err
}
maxy = int32(val)
bounds.maxy = &maxy
}
minzStr := queryStrings.Get("minz")
if minzStr != "" {
val, err := strconv.ParseInt(minzStr, 10, 32)
if err != nil {
return nil, err
}
minz = int32(val)
bounds.minz = &minz
}
maxzStr := queryStrings.Get("maxz")
if maxzStr != "" {
val, err := strconv.ParseInt(maxzStr, 10, 32)
if err != nil {
return nil, err
}
maxz = int32(val)
bounds.maxz = &maxz
}
return bounds, nil
}
func nilOrInt32(p *int32) string {
if p == nil {
return "nil"
}
return fmt.Sprintf("%d", *p)
}
func (b *OptionalBounds) String() string {
text := "OptionalBounds{\n"
text += " minx: " + nilOrInt32(b.minx) + "\n"
text += " maxx: " + nilOrInt32(b.maxx) + "\n"
text += " miny: " + nilOrInt32(b.miny) + "\n"
text += " maxy: " + nilOrInt32(b.maxy) + "\n"
text += " minz: " + nilOrInt32(b.minz) + "\n"
text += " maxz: " + nilOrInt32(b.maxz) + "\n"
text += "}\n"
return text
}
func (b *OptionalBounds) SetMinX(x int32) {
b.minx = &x
}
func (b *OptionalBounds) SetMaxX(x int32) {
b.maxx = &x
}
func (b *OptionalBounds) SetMinY(y int32) {
b.miny = &y
}
func (b *OptionalBounds) SetMaxY(y int32) {
b.maxy = &y
}
func (b *OptionalBounds) SetMinZ(z int32) {
b.minz = &z
}
func (b *OptionalBounds) SetMaxZ(z int32) {
b.maxz = &z
}
// Adjust modifies the given minimum and maximum point to reflect additional
// optional bounds.
func (b *OptionalBounds) Adjust(minPt, maxPt *Point3d) {
if b == nil {
return
}
if b.minx != nil {
if *(b.minx) > (*minPt)[0] {
(*minPt)[0] = *(b.minx)
}
}
if b.maxx != nil {
if *(b.maxx) < (*maxPt)[0] {
(*maxPt)[0] = *(b.maxx)
}
}
if b.miny != nil {
if *(b.miny) > (*minPt)[1] {
(*minPt)[1] = *(b.miny)
}
}
if b.maxy != nil {
if *(b.maxy) < (*maxPt)[1] {
(*maxPt)[1] = *(b.maxy)
}
}
if b.minz != nil {
if *(b.minz) > (*minPt)[2] {
(*minPt)[2] = *(b.minz)
}
}
if b.maxz != nil {
if *(b.maxz) < (*maxPt)[2] {
(*maxPt)[2] = *(b.maxz)
}
}
}
func (b *OptionalBounds) MinX() (x int32, ok bool) {
if b == nil || b.minx == nil {
return
}
return *(b.minx), true
}
func (b *OptionalBounds) MaxX() (x int32, ok bool) {
if b == nil || b.maxx == nil {
return
}
return *(b.maxx), true
}
func (b *OptionalBounds) MinY() (y int32, ok bool) {
if b == nil || b.miny == nil {
return
}
return *(b.miny), true
}
func (b *OptionalBounds) MaxY() (y int32, ok bool) {
if b == nil || b.maxy == nil {
return
}
return *(b.maxy), true
}
func (b *OptionalBounds) MinZ() (z int32, ok bool) {
if b == nil || b.minz == nil {
return
}
return *(b.minz), true
}
func (b *OptionalBounds) MaxZ() (z int32, ok bool) {
if b == nil || b.maxz == nil {
return
}
return *(b.maxz), true
}
// Divide returns a new bounds that has all optionally set
// bounds divided by the given point.
func (b *OptionalBounds) Divide(pt Point3d) *OptionalBounds {
if b == nil {
return nil
}
newB := new(OptionalBounds)
if b.minx != nil {
newB.minx = new(int32)
*(newB.minx) = *(b.minx) / pt[0]
}
if b.maxx != nil {
newB.maxx = new(int32)
*(newB.maxx) = *(b.maxx) / pt[0]
}
if b.miny != nil {
newB.miny = new(int32)
*(newB.miny) = *(b.miny) / pt[1]
}
if b.maxy != nil {
newB.maxy = new(int32)
*(newB.maxy) = *(b.maxy) / pt[1]
}
if b.minz != nil {
newB.minz = new(int32)
*(newB.minz) = *(b.minz) / pt[2]
}
if b.maxz != nil {
newB.maxz = new(int32)
*(newB.maxz) = *(b.maxz) / pt[2]
}
return newB
}
// BoundedX returns true if there is some bound set in the X dimension
func (b *OptionalBounds) BoundedX() bool {
return b != nil && (b.minx != nil || b.maxx != nil)
}
// BoundedY returns true if there is some bound set in the Y dimension
func (b *OptionalBounds) BoundedY() bool {
return b != nil && (b.miny != nil || b.maxy != nil)
}
// BoundedZ returns true if there is some bound set in the Z dimension
func (b *OptionalBounds) BoundedZ() bool {
return b != nil && (b.minz != nil || b.maxz != nil)
}
// IsSet returns true if at least one bound in some dimension has been set.
func (b *OptionalBounds) IsSet() bool {
if b == nil {
return false
}
if b.minx != nil || b.maxx != nil || b.miny != nil || b.maxy != nil || b.minz != nil || b.maxz != nil {
return true
}
return false
}
// OutsideX returns true if the given X is outside a set X bound.
func (b *OptionalBounds) OutsideX(x int32) bool {
if b == nil {
return false
}
if b.minx != nil && x < *(b.minx) {
return true
}
if b.maxx != nil && x > *(b.maxx) {
return true
}
return false
}
// OutsideY returns true if the given Y is outside a set Y bound.
func (b *OptionalBounds) OutsideY(y int32) bool {
if b == nil {
return false
}
if b.miny != nil && y < *(b.miny) {
return true
}
if b.maxy != nil && y > *(b.maxy) {
return true
}
return false
}
// OutsideZ returns true if the given Z is outside a set Z bound.
func (b *OptionalBounds) OutsideZ(z int32) bool {
if b == nil {
return false
}
if b.minz != nil && z < *(b.minz) {
return true
}
if b.maxz != nil && z > *(b.maxz) {
return true
}
return false
}
// Outside returns true if the given chunk point is outside any set bound.
func (b *OptionalBounds) Outside(pt ChunkPoint3d) bool {
if b == nil {
return false
}
if b.minx != nil && pt[0] < *(b.minx) {
return true
}
if b.maxx != nil && pt[0] > *(b.maxx) {
return true
}
if b.miny != nil && pt[1] < *(b.miny) {
return true
}
if b.maxy != nil && pt[1] > *(b.maxy) {
return true
}
if b.minz != nil && pt[2] < *(b.minz) {
return true
}
if b.maxz != nil && pt[2] > *(b.maxz) {
return true
}
return false
}
// BeyondZ returns true if the given Z is beyond a set max Z bound.
func (b *OptionalBounds) BeyondZ(pt ChunkPoint3d) bool {
if b == nil {
return false
}
if b.maxz != nil && pt[2] > *(b.maxz) {
return true
}
return false
}
// RLE is a single run-length encoded span with a start coordinate and length along
// a coordinate (typically X).
type RLE struct {
start Point3d
length int32
}
func NewRLE(start Point3d, length int32) RLE {
return RLE{start, length}
}
// WriteTo fulfills the io.WriterTo interface.
func (rle RLE) WriteTo(w io.Writer) (n int64, err error) {
var buf [16]byte
binary.LittleEndian.PutUint32(buf[0:4], uint32(rle.start[0]))
binary.LittleEndian.PutUint32(buf[4:8], uint32(rle.start[1]))
binary.LittleEndian.PutUint32(buf[8:12], uint32(rle.start[2]))
binary.LittleEndian.PutUint32(buf[12:16], uint32(rle.length))
var numBytes int
numBytes, err = w.Write(buf[:])
n = int64(numBytes)
return
}
// MarshalBinary fulfills the encoding.BinaryMarshaler interface.
func (rle RLE) MarshalBinary() ([]byte, error) {
buf := make([]byte, 16)
binary.LittleEndian.PutUint32(buf[0:4], uint32(rle.start[0]))
binary.LittleEndian.PutUint32(buf[4:8], uint32(rle.start[1]))
binary.LittleEndian.PutUint32(buf[8:12], uint32(rle.start[2]))
binary.LittleEndian.PutUint32(buf[12:16], uint32(rle.length))
return buf, nil
}
// UnmarshalBinary fulfills the encoding.BinaryUnmarshaler interface.
func (rle *RLE) UnmarshalBinary(b []byte) error {
lenEncoding := len(b)
if lenEncoding != 16 {
return fmt.Errorf("RLE encoding # bytes is not 16: %d", len(b))
}
x := int32(binary.LittleEndian.Uint32(b[0:4]))
y := int32(binary.LittleEndian.Uint32(b[4:8]))
z := int32(binary.LittleEndian.Uint32(b[8:12]))
length := int32(binary.LittleEndian.Uint32(b[12:16]))
rle.start = Point3d{x, y, z}
rle.length = length
return nil
}
func (rle RLE) StartPt() Point3d {
return rle.start
}
func (rle RLE) Length() int32 {
return rle.length
}
func (rle *RLE) Extend(n int32) {
rle.length += n
}
func (rle RLE) String() string {
return fmt.Sprintf("dvid.NewRLE{%s, %d}", rle.start, rle.length)
}
func (rle RLE) GetRangeIZYXString() (beg, end IZYXString) {
var izyx IndexZYX
izyx[0] = rle.start[0]
izyx[1] = rle.start[1]
izyx[2] = rle.start[2]
beg = izyx.ToIZYXString()
izyx[0] += rle.length - 1
end = izyx.ToIZYXString()
return
}
func (rle RLE) Within(pt Point3d) bool {
if pt[2] != rle.start[2] || pt[1] != rle.start[1] {
return false
}
if pt[0] < rle.start[0] || pt[0] >= rle.start[0]+rle.length {
return false
}
return true
}
func (rle RLE) Intersects(rle2 RLE) bool {
if rle.start[2] != rle2.start[2] || rle.start[1] != rle2.start[1] {
return false
}
x0 := rle.start[0]
x1 := x0 + rle.length - 1
sx0 := rle2.start[0]
sx1 := sx0 + rle2.length - 1
if x0 > sx1 || x1 < sx0 {
return false
}
return true
}
// Excise returns the portion of the receiver that is not in the passed RLE.
// If the RLEs do not intersect, nil is returned. Up to two fragments can
// be generated and they will be in sorted in start X.
func (rle RLE) Excise(rle2 RLE) RLEs {
if rle.start[2] != rle2.start[2] || rle.start[1] != rle2.start[1] {
return nil
}
z := rle.start[2]
y := rle.start[1]
x0 := rle.start[0]
x1 := x0 + rle.length - 1
sx0 := rle2.start[0]
sx1 := sx0 + rle2.length - 1
if x0 > sx1 || x1 < sx0 {
return nil
}
frags := RLEs{}
if sx0 > x0 {
frags = append(frags, RLE{Point3d{x0, y, z}, sx0 - x0})
}
if sx1 < x1 {
frags = append(frags, RLE{Point3d{sx1 + 1, y, z}, x1 - sx1})
}
return frags
}
func (rle RLE) Less(rle2 RLE) bool {
if rle.start[2] < rle2.start[2] {
return true
}
if rle.start[2] > rle2.start[2] {
return false
}
if rle.start[1] < rle2.start[1] {
return true
}
if rle.start[1] > rle2.start[1] {
return false
}
return rle.start[0] < rle2.start[0]
}
// RLEs are simply a slice of RLE. Sorting only takes into account
// the start point and not the length.
type RLEs []RLE
func ReadRLEs(r io.Reader) (RLEs, error) {
if r == nil {
return nil, fmt.Errorf("nil reader given")
}
header := make([]byte, 8)
if _, err := io.ReadFull(r, header); err != nil {
return nil, err
}
if header[0] != EncodingBinary {
return nil, fmt.Errorf("sparse vol is not binary: %v", header[0])
}
var numSpans uint32
if err := binary.Read(r, binary.LittleEndian, &numSpans); err != nil {
return nil, err
}
var rles RLEs
if err := rles.UnmarshalBinaryReader(r, numSpans); err != nil {
return nil, err
}
return rles, nil
}
// Within returns a slice of indices to the given pts that are within
// the RLEs.
func (rles RLEs) Within(pts []Point3d) (in []int) {
inset := make(map[int]struct{})
for _, rle := range rles {
for i, pt := range pts {
if rle.Within(pt) {
inset[i] = struct{}{}
}
}
}
in = make([]int, len(inset))
i := 0
for k := range inset {
in[i] = k
i++
}
return
}
// Offset returns RLEs that have been offset by negative of given point.
func (rles RLEs) Offset(offset Point3d) (out RLEs) {
out = make(RLEs, len(rles))
for i, rle := range rles {
x := rle.start[0] - offset[0]
y := rle.start[1] - offset[1]
z := rle.start[2] - offset[2]
out[i] = RLE{start: Point3d{x, y, z}, length: rle.length}
}
return
}
// --- sort interface
func (rles RLEs) Len() int {
return len(rles)
}
func (rles RLEs) Swap(i, j int) {
rles[i], rles[j] = rles[j], rles[i]
}
func (rles RLEs) Less(i, j int) bool {
return rles[i].Less(rles[j])
}
// Normalize returns a sorted slice of RLEs where there are no directly adjacent RLEs along X.
func (rles RLEs) Normalize() RLEs {
if rles == nil || len(rles) == 0 {
return RLEs{}
}
// Sort the RLE
norm := make(RLEs, len(rles)) // We know # normalized RLEs <= current # RLEs
copy(norm, rles)
sort.Sort(norm)
nOrig := len(norm)
// Iterate through each (y,z) and combine adjacent spans.
var old *RLE
n := 0 // current position of normalized slice end
for o := 0; o < nOrig; o++ {
pt := norm[o].start
if old == nil {
old = &RLE{pt, norm[o].length}
} else {
// Handle new normalized RLE by saving old one.
if pt[1] != old.start[1] || pt[2] != old.start[2] || pt[0] != old.start[0]+old.length {
norm[n] = *old
n++
old.start = pt
old.length = norm[o].length
} else {
old.length += norm[o].length
}
}
}
norm[n] = *old
return norm[:n+1]
}
// Split removes RLEs, which must be a subset of current RLEs, from the receiver and returns the remainder.
func (rles RLEs) Split(splits RLEs) (RLEs, error) {
if splits == nil || len(splits) == 0 {
return rles, nil
}
// Normalize the two RLEs so they are sorted and all contiguous RLE are joined.
orles := rles.Normalize() // original RLEs
srles := splits.Normalize()
// Make a list of current RLEs
out := list.New()
for _, rle := range orles {
out.PushBack(rle)
}
orles = nil
// Perform all the splits.
e := out.Front()
for _, split := range srles {
// Fast forward until we have the intersecting RLE
for {
if e == nil {
return nil, fmt.Errorf("Split RLE %s is not contained in original RLEs", split)
}
orle := e.Value.(RLE)
frags := orle.Excise(split)
if frags == nil { // no intersection, move forward
e = e.Next()
continue
}
switch len(frags) {
case 0:
// Split fully covers. Cannot be larger than underlying RLE due to subset requirement
// and normalization.
next := e.Next()
out.Remove(e)
e = next
case 1:
// Replace the current RLE
next := out.InsertAfter(frags[0], e)
out.Remove(e)
e = next
case 2:
// There's a left and right portion. All future splits can only intersect right one
// since splits are also sorted in X.
out.InsertBefore(frags[0], e)
next := out.InsertAfter(frags[1], e)
out.Remove(e)
e = next
default:
return nil, fmt.Errorf("bad RLE excision - %d fragments for split %s by %s\n", len(frags), orle, split)
}
break
}
}
numRLEs := out.Len()
if numRLEs == 0 {
return RLEs{}, nil
}
remain := make(RLEs, numRLEs)
i := 0
for e := out.Front(); e != nil; e = e.Next() {
remain[i] = e.Value.(RLE)
i++
}
return remain, nil
}
// Partition splits RLEs up into block-sized RLEs using the given block size.
// The return is a map of RLEs with stringified ZYX block coordinate keys.
func (rles RLEs) Partition(blockSize Point3d) (BlockRLEs, error) {
brles := make(BlockRLEs, 100)
for _, rle := range rles {
// Get the block coord for starting point.
bcoord := rle.start.Chunk(blockSize).(ChunkPoint3d)
// Iterate block coord in X until block end is past span, storing fragments in block map.
bBegX := bcoord[0] * blockSize[0]
rx := rle.start[0]
remain := rle.length
for remain >= 1 {
// Store block-clipped rle
dx := bBegX + blockSize[0] - rx
if remain < dx {
brles.appendBlockRLE(bcoord, rx, rle.start[1], rle.start[2], remain)
} else {
brles.appendBlockRLE(bcoord, rx, rle.start[1], rle.start[2], dx)
}
// Go to next block
bcoord[0]++
bBegX += blockSize[0]
rx += dx
remain -= dx
}
}
return brles, nil
}
// FitToBounds returns a copy that has been adjusted to fit
// within the given optional bounds.
func (rles RLEs) FitToBounds(bounds *OptionalBounds) RLEs {
newRLEs := make(RLEs, 0, len(rles))
if bounds == nil {
copy(newRLEs, rles)
return newRLEs
}
for _, rle := range rles {
if bounds.minz != nil && rle.start[2] < *(bounds.minz) {
continue
}
if bounds.maxz != nil && rle.start[2] > *(bounds.maxz) {
continue
}
if bounds.miny != nil && rle.start[1] < *(bounds.miny) {
continue
}
if bounds.maxy != nil && rle.start[1] > *(bounds.maxy) {
continue
}
if bounds.minx != nil {
if rle.start[0]+rle.length-1 < *(bounds.minx) {
continue
}
if rle.start[0] < *(bounds.minx) {
rle.length -= *(bounds.minx) - rle.start[0]
rle.start[0] = *(bounds.minx)
}
}
if bounds.maxx != nil {
if rle.start[0] > *(bounds.maxx) {
continue
}
if rle.start[0]+rle.length-1 > *(bounds.maxx) {
rle.length = *(bounds.maxx) - rle.start[0] + 1
}
}
newRLEs = append(newRLEs, rle)
}
return newRLEs
}
//
// MarshalBinary fulfills the encoding.BinaryMarshaler interface.
func (rles RLEs) MarshalBinary() ([]byte, error) {
buf := new(bytes.Buffer)
if rles != nil {
for _, rle := range rles {
if err := binary.Write(buf, binary.LittleEndian, rle.start[0]); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.LittleEndian, rle.start[1]); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.LittleEndian, rle.start[2]); err != nil {
return nil, err
}
if err := binary.Write(buf, binary.LittleEndian, rle.length); err != nil {
return nil, err
}
}
}
return buf.Bytes(), nil
}
// UnmarshalBinary fulfills the encoding.BinaryUnmarshaler interface.
func (rles *RLEs) UnmarshalBinary(b []byte) error {
lenEncoding := len(b)
if lenEncoding%16 != 0 {
return fmt.Errorf("RLE encoding # bytes is not divisible by 16: %d", len(b))
}
buf := bytes.NewBuffer(b)
numRLEs := lenEncoding / 16
*rles = make(RLEs, numRLEs, numRLEs)
for i := 0; i < numRLEs; i++ {
if err := binary.Read(buf, binary.LittleEndian, &((*rles)[i].start[0])); err != nil {
return err
}
if err := binary.Read(buf, binary.LittleEndian, &((*rles)[i].start[1])); err != nil {
return err
}
if err := binary.Read(buf, binary.LittleEndian, &((*rles)[i].start[2])); err != nil {
return err
}
if err := binary.Read(buf, binary.LittleEndian, &((*rles)[i].length)); err != nil {
return err
}
}
return nil
}
// UnmarshalBinaryReader reads from a reader instead of a static slice of bytes.
// This will likely be more efficient for very large RLEs that are being streamed
// into the server.
func (rles *RLEs) UnmarshalBinaryReader(r io.Reader, numRLEs uint32) error {
*rles = make(RLEs, numRLEs, numRLEs)
for i := uint32(0); i < numRLEs; i++ {
if err := binary.Read(r, binary.LittleEndian, &((*rles)[i].start[0])); err != nil {
return err
}
if err := binary.Read(r, binary.LittleEndian, &((*rles)[i].start[1])); err != nil {
return err
}
if err := binary.Read(r, binary.LittleEndian, &((*rles)[i].start[2])); err != nil {
return err
}
if err := binary.Read(r, binary.LittleEndian, &((*rles)[i].length)); err != nil {
return err
}
}
return nil
}
// Add adds the given RLEs to the receiver when there's a possibility of overlapping RLEs.
// If you are guaranteed the RLEs are disjoint, e.g., the passed and receiver RLEs are in
// different subvolumes, then just concatenate the RLEs instead of calling this function.
// The returned "voxelsAdded" gives the # of non-overlapping voxels added.
// TODO: If this is a bottleneck, employ better than this brute force insertion method.
func (rles *RLEs) Add(rles2 RLEs) (voxelsAdded int64) {
for _, rle2 := range rles2 {
var found bool
for i, rle := range *rles {
// If this rle has same z and y, modify the RLE, else just add rle.
if rle.start[1] == rle2.start[1] && rle.start[2] == rle2.start[2] {
x0 := rle.start[0]
x1 := x0 + rle.length - 1
cur_x0 := rle2.start[0]
cur_x1 := cur_x0 + rle2.length - 1
if x1 < cur_x0 {
continue
}
if x0 > cur_x1 {
continue
}
if x0 > cur_x0 {
voxelsAdded += int64(x0 - cur_x0)
x0 = cur_x0
}
if x1 < cur_x1 {
voxelsAdded += int64(cur_x1 - x1)
x1 = cur_x1
}
rle.start[0] = x0
rle.length = x1 - x0 + 1
(*rles)[i] = rle
found = true
break
}
}
if !found {
*rles = append(*rles, rle2)
voxelsAdded += int64(rle2.length)
}
}
return
}
// Stats returns the total number of voxels and runs.
func (rles RLEs) Stats() (numVoxels uint64, numRuns int32) {
if rles == nil || len(rles) == 0 {
return 0, 0
}
for _, rle := range rles {
numVoxels += uint64(rle.length)
}
return numVoxels, int32(len(rles))
}
// BlockRLEs is a single label's map of block coordinates to RLEs for that label.
// The key is a string of the serialized block coordinate.
type BlockRLEs map[IZYXString]RLEs
func (brles BlockRLEs) appendBlockRLE(bcoord ChunkPoint3d, x, y, z, n int32) error {
rle := RLE{Point3d{x, y, z}, n}
idx := IndexZYX(bcoord)
s := idx.ToIZYXString()
rles, found := brles[s]
if !found || rles == nil {
brles[s] = RLEs{rle}
} else {
brles[s] = append(brles[s], rle)
}
return nil
}
// NumVoxels is the number of voxels contained within a label's block RLEs.
func (brles BlockRLEs) NumVoxels() uint64 {
var size uint64
for _, rles := range brles {
numVoxels, _ := rles.Stats()
size += uint64(numVoxels)
}
return size
}
// IZYXSlice is a typically sorted slice of IZYXString
type IZYXSlice []IZYXString
func (i IZYXSlice) Len() int { return len(i) }
func (i IZYXSlice) Swap(a, b int) { i[a], i[b] = i[b], i[a] }
func (i IZYXSlice) Less(a, b int) bool { return i[a] < i[b] }
func (i IZYXSlice) String() string {
s := "["
for _, izyxStr := range i {
s += izyxStr.String()
}
s += "]"
return s
}
// MarshalBinary implements the encoding.BinaryMarshaler interface
func (i IZYXSlice) MarshalBinary() ([]byte, error) {
buf := make([]byte, len(i)*12)
off := 0
for _, izyxStr := range i {
copy(buf[off:off+12], string(izyxStr))
off += 12
}
return buf, nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (i *IZYXSlice) UnmarshalBinary(b []byte) error {
// TODO -- the serialization is the raw data minus the slice wrapper
// yet the deserialization requires a lot of copy. Is there a way to
// simply supply the slice wrapper (ptr, len, cap) where ptr goes to