summaryrefslogtreecommitdiff
path: root/WorldlineKeepers/Assets/Scripts/Physics/Quadtree.cs
blob: bb20c7662de4e362c3aad4891ce7b8535b91f4c1 (plain)
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
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Unity.VisualScripting;
using UnityEngine;
using WK;

// https://gamedev.stackexchange.com/questions/6345/quad-tree-vs-grid-based-collision-detection

namespace mh
{

    public interface IQuadTreeObject
    {
        public Vector4 bound { get; }
    }

    /// <summary>
    /// 四叉树空间分割
    /// </summary>
    public class Quadtree
    {
        public const int kMaxObjectsPerBlock = 4;
        public const int kMaxLevel = 5;

        private int m_Level;
        private Vector4 m_Bounds; // x,y,z,w => posx,posy,width,height 
        private Quadtree[] m_SubTrees; // 从右上角开始逆时针索引
        private List<IQuadTreeObject> m_Objects; // 非叶节点的为0 
        private bool m_IsRoot;

        public Vector4 bound { get { return m_Bounds; } }
        public float x { get { return m_Bounds.x; } }
        public float y { get { return m_Bounds.y; } }
        public float w { get { return m_Bounds.z; } }
        public float h { get { return m_Bounds.w; } }
        public float halfW { get { return w / 2; } }
        public float halfH { get { return h / 2; } }
        public float left { get { return x - halfW; } }
        public float right { get { return x + halfW; } }
        public float top { get { return y + halfH; } }
        public float bottom { get { return y - halfH; } }

        public bool isRoot { get { return m_IsRoot; } }

        private static Queue<List<IQuadTreeObject>> m_QuadtreeObjPool = new Queue<List<IQuadTreeObject>>();
        private static Queue<Quadtree> m_QuadtreePool = new Queue<Quadtree>();

        private Quadtree QueryQuadtree(int level, Vector4 bounds)
        {
            if(m_QuadtreePool.Count == 0)
            {
                return new Quadtree(level, bounds);
            }
            Quadtree tree = m_QuadtreePool.Dequeue();
            tree.m_Level = level;
            tree.m_Bounds = bounds;
            if (tree.m_Objects == null)
                tree.m_Objects = QueryQuadtreeObjList();
            return tree;
        }

        private void RecycleQuadtree(ref Quadtree tree)
        {
            tree.Clear();
            m_QuadtreePool.Enqueue(tree);   
            tree = null;
        }

        private List<IQuadTreeObject> QueryQuadtreeObjList()
        {
            if(m_QuadtreeObjPool.Count == 0)
            {
                return new List<IQuadTreeObject>();
            }    
            List<IQuadTreeObject> list = m_QuadtreeObjPool.Dequeue();
            return list;
        }

        private void RecycleQuadtreeObjList(ref List<IQuadTreeObject> list)
        {
            list.Clear();
            m_QuadtreeObjPool.Enqueue(list);
            list = null;
        }

        public Quadtree(int level, Vector4 bounds, bool isRoot = false)
        {
            m_Level = level;
            m_Bounds = bounds;
            m_SubTrees = new Quadtree[4];
            m_Objects = QueryQuadtreeObjList();
            m_IsRoot = isRoot;  
        }

        /// <summary>
        /// 更改边界,只适用于最外层的tree
        /// </summary>
        /// <param name="bounds"></param>
        public void Rebound(Vector4 bounds)
        {
            if(!m_IsRoot)
            {
                LogHelper.LogError("Quadtree.Rebound()只能运用于最外层");
                return;
            }
            m_Bounds = bounds;
        }

        public void Clear(bool clearObjectList = true)
        {
            if (clearObjectList)
                RecycleQuadtreeObjList(ref m_Objects);
            else
                m_Objects.Clear();
            for (int i = 0; i < m_SubTrees.Length; i++)
            {
                if (m_SubTrees[i] != null)
                {
                    //m_SubTrees[i].Clear();
                    //m_SubTrees[i] = null;
                    RecycleQuadtree(ref m_SubTrees[i]);
                }
            }
        }

        public void Split()
        {
            float subWidth = (m_Bounds.z / 2);
            float subHeight = (m_Bounds.w / 2);
            float x = m_Bounds.x;
            float y = m_Bounds.y;
            m_SubTrees[0] = QueryQuadtree(m_Level + 1, new Vector4(x + subWidth / 2, y + subHeight / 2, subWidth, subHeight));
            m_SubTrees[1] = QueryQuadtree(m_Level + 1, new Vector4(x - subWidth / 2, y + subHeight / 2, subWidth, subHeight));
            m_SubTrees[2] = QueryQuadtree(m_Level + 1, new Vector4(x - subWidth / 2, y - subHeight / 2, subWidth, subHeight));
            m_SubTrees[3] = QueryQuadtree(m_Level + 1, new Vector4(x + subWidth / 2, y - subHeight / 2, subWidth, subHeight));
        }

        /// <summary>
        /// 0表示没法完全放在一个subTree: subtree交界或者整个越界
        /// </summary>
        /// <param name="bound"></param>
        /// <returns></returns>
        public int GetSubtreeIndices(Vector4 bound)
        {
            int indices = 0;
            float halfw = bound.z / 2;
            float halfh = bound.w / 2;
            float lowerx = bound.x - halfw;
            float higherx = bound.x + halfw;
            float lowery = bound.y - halfh;
            float highery = bound.y + halfh;
            bool startIsNorth = highery > y;
            bool startIsWest = lowerx < x;
            bool endIsEast = higherx > x;
            bool endIsSouth = lowery < y;
            //top-right quad
            if (startIsNorth && endIsEast)
            {
                indices |= 1;
            }

            //top-left quad
            if (startIsWest && startIsNorth)
            {
                indices |= 1 << 1;
            }

            //bottom-left quad
            if (startIsWest && endIsSouth)
            {
                indices |= 1 << 2;
            }

            //bottom-right quad
            if (endIsEast && endIsSouth)
            {
                indices |= 1 << 3;
            }

            return indices;
        }

        public void Insert(IQuadTreeObject obj)
        {
            if (m_SubTrees[0] != null)
            {
                int indices = GetSubtreeIndices(obj.bound);
                for(int i = 0; i < 4; i++)
                {
                    if((indices & (1 << i)) != 0)
                    {
                        m_SubTrees[i].Insert(obj);
                    }
                }
                return;
            }

            m_Objects.Add(obj);

            if (m_Objects.Count > kMaxObjectsPerBlock && m_Level < kMaxLevel) // 本层满了之后重新排布层内对象
            {
                if (m_SubTrees[0] == null) Split();

                for (int i = m_Objects.Count - 1; i >= 0; i--)
                {
                    int indices = GetSubtreeIndices(m_Objects[i].bound);
                    for (int j = 0; j < 4; j++)
                    {
                        if ((indices & (1 << j)) != 0)
                        {
                            m_SubTrees[j].Insert(m_Objects[i]);
                        }
                    }
                }

                m_Objects.Clear();
            }
        }

        /// <summary>
        /// 获得可能和obj碰撞的对象(不包括自己)
        /// </summary>
        /// <param name="returnObjs"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Retrieve(ref List<IQuadTreeObject> returnObjs, IQuadTreeObject obj)
        {
            for(int i = 0; i < m_Objects.Count; ++i)
            {
                if (!returnObjs.Contains(m_Objects[i]) && obj != m_Objects[i])
                {
                    returnObjs.Add(m_Objects[i]);
                }
            }
            if (m_SubTrees[0] != null)
            {
                int indices = GetSubtreeIndices(obj.bound);
                for (int i = 0; i < 4; i++)
                {
                    if ((indices & (1 << i)) != 0)
                    {
                        m_SubTrees[i].Retrieve(ref returnObjs, obj);
                    }
                }
            }
            return returnObjs.Count > 0;
        }

        /// <summary>
        /// 获得可能和obj碰撞的对象(不包括自己)
        /// </summary>
        /// <param name="returnObjs"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Retrieve(ref List<IQuadTreeObject> returnObjs, Vector4 bound)
        {
            for (int i = 0; i < m_Objects.Count; ++i) // 根节点count==0
            {
                if (!returnObjs.Contains(m_Objects[i]))
                {
                    returnObjs.Add(m_Objects[i]);
                }
            }
            if (m_SubTrees[0] != null)
            {
                int indices = GetSubtreeIndices(bound);
                for (int i = 0; i < 4; i++)
                {
                    if ((indices & (1 << i)) != 0)
                    {
                        m_SubTrees[i].Retrieve(ref returnObjs, bound);
                    }
                }
            }
            return returnObjs.Count > 0;
        }

        public void Iterate(System.Action<Quadtree> action)
        {
            action?.Invoke(this);
            m_SubTrees[0]?.Iterate(action);
            m_SubTrees[1]?.Iterate(action);
            m_SubTrees[2]?.Iterate(action);
            m_SubTrees[3]?.Iterate(action);
        }

    }
}