A hashspace stores data paired with positional information in order to accelerate requests for data within a certain area.
This hashspace is implemented in lua and is restricted to 2D spaces and rectangular areas, which means that only two coordinates can be used to store the data.
The structure is - even though it is implemented in lua only - quite fast. If you have complex environments but don't want to use ODE for collision detection, you can use this class. It is very easy to use and can manage thousands of objects cheaply. You can even remove items from the space and reinsert them somewhere else while the costs for doing that are cheap.
space = Hashspace.new() -- create hashspace space:add("pawn1",5,4,10,10) -- insert pawn at 5,4 with size 10,10 space:add("pawn2",15,6,10,10) -- insert pawn at 15,6 with size 10,10 environment = Hashspace.new() -- create a hashspace for the environment for i=1,100 do -- insert now lots of small boxes scattered around randomly environment:add("obstacle "..i,math.random()*100,math.random()*100,4,4) end space:test(environment, -- test the playerspace against the environment function (a,b) -- function is called if two items from each space intersects print(a,b) -- print out intersecting items end)
obstacle 4 pawn2 obstacle 6 pawn2 obstacle 23 pawn1 obstacle 29 pawn1
inserts item (which can be any type) into the hashspace at the given coordinates. The given rectangle will be used if an intersection case is tested.
Reinserting an element if it is already present in the space will throw an error. Make sure it does not exist in that space before adding it!list = space:get(2,4,10,6) -- request area is at 2,4 with width/height=10,6 for i,item in ipairs(list) do -- iterate all items print(item) -- print out intersecting items end
Tests two hashspaces against each other and call the callback function in case of intersection with both intersecting items (function (a,b)). Testing two hashspaces against each other is much more efficient than doing all the requests by calling the get function. If you have more requests to do, you should batch all requests in another hashspace and test it then with the other space. However, if both structures must be built from scratch, the get function will be a little bit faster. It only pays out if at least one of both structures has been built before anyway.
If two spaces are tested, all items will be only be tested once against each other. However, if both spaces are the same space (for testing intercollisions), you have to ignore selfintersection of an item which will occur then.