From a29e6c084aaa3c059f5d5b6f627f4043213a887c Mon Sep 17 00:00:00 2001 From: Christoph Oelckers Date: Mon, 15 Nov 2021 23:34:40 +0100 Subject: [PATCH] - BFSSearch class added MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This was prompted by a bug that was recently introduced in one of the ad-hoc implementations of such a search. Let’s better use a helper class to deal with the problems and help unify memory usage. --- source/core/gamefuncs.h | 60 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/source/core/gamefuncs.h b/source/core/gamefuncs.h index 5031d779d..d2a1032fd 100644 --- a/source/core/gamefuncs.h +++ b/source/core/gamefuncs.h @@ -4,6 +4,66 @@ #include "binaryangle.h" #include "build.h" +// breadth first search, this gets used multiple times throughout the engine, mainly for iterating over sectors. +// Only works on indices, this has no knowledge of the actual objects being looked at. +// All objects of this type operate on the same shared store. Interleaved use is not allowed, nested use is fine. +class BFSSearch +{ + static inline TArray store; + + unsigned bitpos; + unsigned startpos; + unsigned curpos; + +public: + BFSSearch(unsigned datasize, unsigned startnode) + { + bitpos = store.Size(); + unsigned bitsize = (datasize + 31) >> 5; + store.Reserve(bitsize); + memset(&store[bitpos], 0, bitsize*4); + + startpos = store.Size(); + curpos = startpos; + store.Push(startnode); + } + + ~BFSSearch() + { + store.Clamp(bitpos); + } + +private: + bool Check(unsigned index) const + { + return !!(store[bitpos + (index >> 5)] & (1 << (index & 31))); + } + + void Set(unsigned index) + { + store[bitpos + (index >> 5)] |= (1 << (index & 31)); + } + +public: + unsigned GetNext() + { + curpos++; + if (curpos <= store.Size()) + return store[curpos-1]; + else + return ~0; + } + + void Add(unsigned elem) + { + if (!Check(elem)) + { + Set(elem); + store.Push(elem); + } + } +}; + extern TArray GlobalSectorList; extern int cameradist, cameraclock;