Spatial.lua - A minimal spatial database.
Posted: Tue Sep 21, 2021 11:30 am
Spatial.lua is a minimal spatial database library.
Proper documentation on Github as usual.
Basic usage:
Load it
Make a database
The new function can optionally take a cell size argument. It defaults to 64
Add items to it
The insert function also returns the item back to you.
Remove items
Query the database
Note that the queryRect & queryPoint return all items that are inside the cells that the rectangle or point intersect with. This is because Spatial doesn't require that the items you put in it actually have a position. Also all query functions also return the number if items the query found.
Also also, All query functions have an optional filter argument.
About filters
A filter is just a function, That gets called for every item in the query with the following arguments:
The demo creates 1.000.000 objects and scatters them across a large area, Then uses spatial to render only the ones visible on the screen. It can take a little while to load if you're on a older machine. Or just crash because it runs out of memory. in which case sorry.
Although it runs just fine on my mid 2012 macbook pro running manjaro.
Hope someone finds this useful. If you're looking for something more comprehensive, Have a look at bump.lua, It does all the same stuff, Plus collisions!
Proper documentation on Github as usual.
Basic usage:
Load it
Code: Select all
spatial = require("spatial")
Code: Select all
data = spatial.new()
Code: Select all
data = spatial.new(64)
Code: Select all
item = {x = 100, y = 100, foo = "foo", bar = {"b", "a", "r"}}
data:insert(item.x, item.y, item)
Code: Select all
item = data:insert(item.x, item.y, item)
Code: Select all
data:remove(item)
Code: Select all
--Get all items
items = data:query()
-- Get filtered items, This will return all items with an x value greater than 100.
items = data:query(function(item) return item.x > 100 end)
-- Get items inside a rectangle
items = data:queryRect(10, 10, 100, 100)
-- Get items from a point
items = data:queryPoint(64, 64)
Code: Select all
items, len = data:query()
Code: Select all
items, len = data:queryPoint(100, 100, function(item) return item.x > 100 end)
A filter is just a function, That gets called for every item in the query with the following arguments:
- item: A reference to the item
- cell_x & cell_y: The cell the item lives in
- index: The index the item occupies inside the cell
The demo creates 1.000.000 objects and scatters them across a large area, Then uses spatial to render only the ones visible on the screen. It can take a little while to load if you're on a older machine. Or just crash because it runs out of memory. in which case sorry.
Although it runs just fine on my mid 2012 macbook pro running manjaro.
Hope someone finds this useful. If you're looking for something more comprehensive, Have a look at bump.lua, It does all the same stuff, Plus collisions!