About
libSeven is a library for creating "Mode 7"-style 3D worlds, using billboard sprites for objects and flat textured planes for the terrain and other effects.
Features
- A data-oriented API where you maintain a userdata of points and feed it into different functions to transform, project, sort/clip, and turn the points into batches that can be fed into draw ops like
sspr. - A higher-level, object-oriented API for convenient drawing of scenes, with most of the drawing pipeline handled for you.
- "Mode 7"-style flat 3D plane drawing, with support for height, pitch, and FOV.
- Map caching to reduce the per-pixel cost of map tline3d.
- The system maintains a cache image that is updated as the camera moves (or updated once if the entire map fits in cache).
- Nearby scanlines are drawn using the cache to save on drawing cost, while the rest is drawn using map tline for longer draw distance.
- Includes function to manually refresh parts of the cache when changing the source map tiles.
- Functions to assist with sprite object management.
- Function to get the screen height of the plane horizon for background parallax.
- Several math helpers for things like transform matrices.
- Included example scene with documentation.
Possible future stuff
Right now I'm looking forward to the release of Picotron 0.3.1, which should allow me to make further optimizations such as near clip/culling before sorting, and the ability to sort sprites above/below planes. I also want to add additional features such as plane fog and mipmapping. For a first release though, I think this library is already quite capable and can be used to make some pretty fun games.
Enjoy!
This looks really good! I might dig into it in the future, I'm curious to see your approach. I had an old racing project I wanted to make on another platform and to see such a clean-looking implementation fills me with nostalgia for it.
@Eiyeron Thanks! It's basically projecting points out to a finite distance (far clip) to determine the four coordinates making up the bounds of the plane on-screen (along with their positions in world space). It then lerps between these points for each scanline.
Doing rounding in the correct places is key to a smooth result since you need to be careful when converting between floating point world coordinates and pixel-locked screen coordinates. Also, when doing the lerp you'll want to make sure that each screen Y coordinate increments by exactly 1 pixel per scanline, or the lerped values won't map cleanly to the screen.
Have you, by any chance, read Tonc's Mode 7 tutorial? I used to read it a lot back in the past and it was probably the clearest document for me to read. Your method really reminds me of its "Ex" version, which sensibly does the same as you. Basically a whole 3D viewpoint and an affine projection of the map.
I glanced over your code and I noticed it's quite involved. Something in your todo list caught my attention. For stuff like directional sprites I had (now lost) code for that, where I roughly quantize the angle to determine the sprite among lists selected by distance. You might be able to roll that in userdata if you hardcode the same number of direction sprites per LOD or at least do partial CPU-UD pipeline if you want a lower sprite count.
I wanted to see if I could quickly hack that in your code but I lost focus once I noticed how long the code was, sorry! I'm just throwing my ideas to you in case you wanted them as kickstart for that.
(That said, there are a few free hanging fruits like avoiding indexing your library when calling your code and/or making local functions and then mapping them in your library code. I'm not fully sure that Pictron's VM remove it automatically but hey, that'd be one table index less every time you call an internal function. Free CPU cycles!)
Anyway, I like your demo quite a lot, I hope it means we'll have a M7 racing game popping in soon (because I'm sure I'll never finish mine hahahah)!
Addendum: I made a "quick" cart showing my idea with a limited scope. The core idea, transforming the rotation into frames by reading another userdata, is there. I did some ugly hacking because I'm fighting over trigonometry spaces between Pico-8/Picotron's model, Lua's and my head but other than that, it should relatively simple enough.
Cute demo! And yeah, that's the general idea for directional sprites. The reason why it's not in libSeven yet is because I'd need to figure out the right place to put it, and what the API would look like.
As you've noticed, the library is a bit involved. A big part of this is that I'm trying to make it generalized enough that people can use it for all kinds of different projects. In particular I'm striving for:
- Modular code, so that not only can you see and understand each step of the process, but pick and choose what parts of the pipeline you want to use for your application.
- Data-oriented code (for low-level operations), for performance and so that it fits well with Picotron's userdata paradigms.
- But also a high-level object layer so users can get started without worrying too much about the finer details unless they want to customize something.
- "Pay only for what you use", so the library can be used for things like large-scale particle systems.
- Separation of library responsibilities and user code. You can see this through the included
example.lua(sample user code) andseven.lua(library code).
So yeah, if you're used to how things are done over in the Pico-8 world, this might seem like a bit of a departure. There isn't really much of a need for "code golf" in Picotron, so instead I strive for whatever feels clean and convenient and provides the most options.
Right now the map caching system is probably where I fall short the most. It would have been nice to have it as a more modular low-level data-driven function, but since it's a cache, naturally it has object state that I would prefer to have coupled with whatever it needs to cache. The logic also ended up being a lot more complicated than I would have liked, since it has to do a whole bunch of wrapping at various levels, meaning the code to handle all that is a bit... hairy.
Anyway, if I were to add directional sprites to the API, I'd need to consider the following:
- In many cases you might not want directional sprites at all. For example, they'd just create unnecessary overhead for a simple particle system.
- Some games might need different numbers of directions. Eight directions is generally sufficient for a lot of games, but even Super Mario Kart needs extra angles for smoother turning. If you're doing pre-rendered 3D for your sprites you might want 16 or maybe even 32 directions! On the other hand, if you're making something like Animal Crossing and you're drawing your characters by hand, you might not want to deal with more than four directions.
- Often times you want X flipping so you don't need to make separate left/right frames. But sometimes you do want them distinct (i.e. the sword should always be in the character's left hand).
- If you're making a flying game, you might need two axes of sprite directions, which complicates things further.
Whatever I go with, it will most likely be either an (optional) aspect of the high-level API, or a low-level helper function you'd call manually to modify the sprite list userdata in place (see the code for SpriteList, maybe also the Example:move_movers function for a non-data-oriented example of changing the sprite list data).
I see your view on the library and perfectly understand where you're at. I'm also a sucker for well designed libraries and those are really hard to shape in the proper direction. I saw that you've put work on it and with your reply design thought too.
I have just one main thing about the architecture, I don't really think you can't really have your cake and eat it too. While Picotron has relaxed size constraints compared to Pico-8, you're still under CPU constraints. Adding infrastructure is never really cost-free, especially with systems like Pico-8 and Picotron where a function cost or indexing a table will cost you a fraction of your CPU budget on top of what you'll do with the function or member. Another example of that is how, in your post, you seem to struggle about the extra cost if you're considering adding directional sprites even to single-framed objects. The last example I'll draw here is the code complexity. It's a hidden cost but it's still a big friction for people who wants to platform themselves with your code or tinker it.
Still, I appreciate the idea of providing two layers of abstractions. I just have some light questions about it on would be how the higher-leveled one will fit most users' case but I think you already went through this line of thought too, didn't you? I know too well that deciding on a tool, library or a middleware's boundaries is quite harder than expected and scope creep is its own hell.
On the topic of sprites/objects, have you considered splitting off the sprite rendering into its own ad-hoc swappable system? It'd be probably more code for you but you could allow setting a specific rendering pipeline "in stone" for a specific project while staying flexible enough. Fortunately, "static" function dispatch and "dynamic" (as in either keeping the same function at a binding or replacing it with another) have the same cost, so I think a well encapsulated expandable solution could have a nifty place for this specific part. And as for flipped sprites, at least now batched sspr respects flip/pivot flags so I can say from experience it's one less headache!
Regarding the cache, I don't have much to say about it other than it looks like it works the best when up close and personal with the layers. I completely misunderstood it at the first time. I haven't looked in it yet but I'm impressed by the CPU cost reduction, nice work!
I don't know how to phrase this post but I hope my good faith and my support are showing through my words. I'm looking forward what you'll do in the future regarding this lib and maybe use it as either for a project, as reference or both. It has the plus to make me ponder a tad on architecture, it's a plus for me personally!
The reason libSeven's code is encapsulated in a table is for namespacing. If you wanted to introduce libSeven to a project that already has a round() function that works slightly differently, and libSeven weren't namespaced, you'd have a duplicate function definition. Some users might choose to resolve the conflict by deleting one of the round() implementations, resulting in subtle, hard-to-trace bugs. I suppose you could save a bit of CPU by removing the table indirection, but such micro-optimizations aren't my focus currently.
IIRC the main performance bottlenecks are:
- Large userdata operations. In particular, sorting is currently done with all active sprites, even if they are behind the camera (and thus ultimately not drawn). This is because the near clip currently requires the elements to be sorted, as there isn't a way to filter a userdata based on a column range (though that is expected to arrive with Picotron 0.3.1). You can see this for yourself by aiming the camera away from the center of the example map and pressing 3 to toggle the rotating sprite cube on/off. Transforming and sorting all these unseen sprites adds an additional 10% CPU.
- Userdata allocation costs. A recent Picotron update added a CPU cost to creating new userdata, based on how large the allocation is. This is to encourage reuse of existing userdata. Which would be fine except that some operations like
matmul3dandsortcan only operate on the entire userdata and not on selective rows. To work around this I need to use a dummy "sort buffer" large enough to hold the elements and reallocate as necessary (causing CPU time spikes). Fixing this would require additions to Picotron that have not yet been announced in any form: either the ability to do a partialmatmul3d/sortor being able tomutatea shrunken userdata back up to its original allocation size. - Per-pixel drawing costs. This is what the map caching code seeks to address by moving as much of the drawing from map tline3d to sprite tline3d as reasonable.
- Overhead from large numbers of map cache updates per frame. Unfortunately a lot of the work done here seems necessary in order for the map cache updates to work as expected (you should be able to call a function indicating a dirty tile region and it will know what parts of the map cache to update, including knowing what tiles are out of range and which ones need to be wrapped).
Hence right now I'm primarily waiting for a new Picotron before I resume work on this. There are some other aspects I could explore in the meantime, such as frustum culling of entire sprite groups via bounding boxes, but I have enough projects on my plate as is.
> On the topic of sprites/objects, have you considered splitting off the sprite rendering into its own ad-hoc swappable system? It'd be probably more code for you but you could allow setting a specific rendering pipeline "in stone" for a specific project while staying flexible enough.
I'm not sure I follow. Isn't the library already built around being able to do this sort of thing?
> The reason libSeven's code is encapsulated in a table is for namespacing
Yeah, that's completely normal. I meant the idea of structuring it like this snippet:
local function foo()
end
local function bar()
foo()
end
return {
foo=foo,
bar=bar
} |
to preserve both the ability to provide an importable table for user code, to squeeze extra CPU juice out of the library and reduce a bit the noise off the code, but fair enough, it's not that important.
I see that you have similar performance issues as my current project where I have to deal with similar sorting/filtering/rendering pipelines. All of your points echoes on my own side and sounds really familliar. The biggest change is that instead of using caches I'm chunking the sprite data spatially. Culling helps a ton, doesn't it?
> In particular, sorting is currently done with all active sprites, even if they are behind the camera (and thus ultimately not drawn)
I'm facing the same issue and I'm also looking forward the easier filtering methods incoming in the next version too. One can already do some shenanigans with :take but it's quite obtuse enough.
> I'm not sure I follow. Isn't the library already built around being able to do this sort of thing?
I'm sorry, I didn't really catch the structure when I wrote this idea. I have a clearer idea now, thanks. Gathering the lists through collections to resolve the sorting problem is pretty interesting.
[Please log in to post a comment]




