go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/quad/tree_test.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package quad 9 10 import ( 11 "fmt" 12 "math/rand" 13 "testing" 14 15 "go.charczuk.com/sdk/assert" 16 ) 17 18 func Test_QuadTree_Insert(t *testing.T) { 19 qt := New[string]( 20 OptMaxValuesPerQuad(255), 21 OptCenter(Point{ 22 X: 1024, 23 Y: 1024, 24 }), 25 OptHalfDimensions(Dimension{ 26 Height: 2048, 27 Width: 2048, 28 }), 29 ) 30 for x := 0; x < 1024; x++ { 31 assert.ItsEqual(t, true, qt.Insert(Point{ 32 X: rand.Float64() * 2048, 33 Y: rand.Float64() * 2048, 34 }, fmt.Sprintf("node-%d", x))) 35 } 36 37 values := qt.ValuesAll() 38 assert.ItsLen(t, values, 1024) 39 40 assert.ItsAll(t, values, func(nv PointValue[string]) bool { 41 return nv.Zone != "" 42 }) 43 44 for _, v := range values { 45 nodeValues := qt.QueryPoint(v.Point) 46 assert.ItsAny(t, nodeValues, func(nv PointValue[string]) bool { 47 return nv.Value == v.Value 48 }) 49 } 50 } 51 52 func Test_QuadTree_QueryRange(t *testing.T) { 53 qt := New[string]( 54 OptMaxValuesPerQuad(255), 55 OptCenter(Point{ 56 X: 1024, 57 Y: 1024, 58 }), 59 OptHalfDimensions(Dimension{ 60 Height: 2048, 61 Width: 2048, 62 }), 63 ) 64 for x := 0; x < 1024; x++ { 65 assert.ItsEqual(t, true, qt.Insert(Point{ 66 X: float64(x), 67 Y: float64(x), 68 }, fmt.Sprintf("node-%d", x))) 69 } 70 71 nodes := qt.QueryRange( 72 RangeFromPoints( 73 Point{512, 512}, 74 Point{1536, 1536}, 75 ), 76 ) 77 78 assert.ItsLen(t, nodes, 512) 79 } 80 81 func Test_QuadTree_QueryZone(t *testing.T) { 82 qt := New[string]( 83 OptMaxValuesPerQuad(255), 84 OptCenter(Point{ 85 X: 1024, 86 Y: 1024, 87 }), 88 OptHalfDimensions(Dimension{ 89 Height: 2048, 90 Width: 2048, 91 }), 92 ) 93 94 for x := 0; x < 1024; x++ { 95 ok := qt.Insert(Point{ 96 X: float64(x), 97 Y: float64(x), 98 }, fmt.Sprintf("node-%d", x)) 99 assert.ItsEqual(t, true, ok) 100 } 101 102 nodes := qt.QueryZone(Zone("CBBB")) 103 assert.ItsLen(t, nodes, 255) 104 105 assert.ItsAll(t, nodes, func(p PointValue[string]) bool { 106 if p.Zone != Zone("CBBB") { 107 t.Log("bad node zone! expect CBBB, got", string(p.Zone)) 108 } 109 return p.Zone == Zone("CBBB") 110 }) 111 }