Resource and level streaming

Started by
5 comments, last by cr88192 10 years, 9 months ago

Hello, I'm trying to implement resource and level streaming in my engine.

And I would like some help/clarification:

1 - From what I've been reading every resource should be divided in fixed-size chunks and stored using a pool allocator. But how should the resources be divided? I need meshes and textures to be stored continuously so I can create GPU resources. The solution I found is to load the whole resource using a temporary allocator, create the GPU resource, store resource info in chunks, and clear the temporary allocator. But what if the resource info doesn't fit in a single chunk?

2 - Resources like materials are simply command groups (containing commands to bind textures to shader slots, etc), ideally they should be stored continuously in memory, but might not fit in a single chunk so how should I handle them?

3 - Is there any way to know how many chunks the pool must be able to hold? Or simply wait until a chunk is freed when the pool is full?

4 - Should I separate resource chunks and level object chunks in two pools? Each level (or section) in my engine contains a list of resource packages that must be loaded before the level. The sizes of level objects vary so I guess the chunks size should be equal to the size of the largest object (which is usually small).

Advertisement

The resource shouldn't fit in a single chunk, that would defeat the purpose of streaming. The resource is meant to be broken into multiple smaller pieces so that you can load them individually without requiring the machine to load the entire resource all at once - this is what streaming is all about.

The goal is to create your own method of maintaining resources on disk, and determining if/when a resource is needed - loading it and integrating it into your game's simulation.

In my personal opinion, streaming is best when utilized as a hierarchical LOD/resolution form of 'increasing' the data/resolution of assets.

So, for instance, every resource is loaded (that is needed for a particular simulation/session/map/level/etc) but in it's lowest-resolution form. As the player approaches areas of the game that require higher fidelity for particular resources, the streaming system then updates the resolution, loading up data to make the resolution of the asset finer.

For texturing, this is what virtual texturing is all about (eg: megatexturing) and also what a lot of GPU sparse voxel octree systems do. But I believe it is best to do it this way, storing your assets in a sort of progressive manner, so that each 'chunk' is a part of the hierarchical representation of data that forms the entire resource.

This can be applied to geometry, textures, video, etc. Virtually anything that can be downsampled can be reorganized into a hierarchical representation, and thus streamed on a basis that corresponds to what level of fidelity the state of the simulation requires for each asset/resource that is relevant to it.

I don't think things are quite so rigidly defined.

for example, I do most of my general-purpose memory allocation via a custom heap-style allocator, rather than using pool-based or region-based allocators.

typically, my loading process is also driven more by "when things come into view". like, the first time a texture is seen, or a model is drawn, or a sound is played, is when the loader loads it. one option is to make it partly asynchronous, where things to be loaded are put in a queue and a certain amount of time is allowed each frame for loading. this may introduce a slight delay between something coming into view and being fully loaded, but helps reduce the effect of long obvious loading-stalls (say as the engine tries to load it all at once).

typically, unloading works either based on distance (for world contents), or via a "stuff falls off the end of a list" strategy (for other things). for example, when a resource is accessed, it is potentially moved to the front of its respective list. if a resource hasn't been accessed recently, reaching the far end of the list, it may be safe to unload it.

some care regarding data formats may also make sense.

avoiding formats which are costly to parse or which require significant up-front processing, and probably make the engine complain about particularly slow/ugly cases (for example: textures with bad resolutions or parameters, ill-advised file-formats, ...).

arguably, this may not necessarily be the "ideal" set of solutions, but seems to "basically work".

granted, some data in my case does rely on bulk loading archive-like files. for example, to some extent my script-VM does this (using a WAD variant), and a few other parts of my engine use PAK files, ...

some other things (such as my voxel terrain), load "regions" basically as a single big glob of memory, and then decodes/encodes individual chunks on demand, and then periodically dumps the whole region image back out to disk. internally, it works similar to my memory manager, basically dividing the memory into small fixed-size cells and using a cell-bitmap to allocate and free space (as spans of cells).

pretty much any data tied to a specific part of the world then goes into specific region images (while this is mostly voxel chunks at present, it can also potentially include brush and mesh geometry, as well as entities, ...). I am also left realizing things I probably could have done differently... (made regions be perfect cubes, probably handle chunks and voxels differently, ...).

a lot may depend on what makes the most sense for the specific data and use-patterns in question as well.

...

(granted, I am not entirely sure what the question is asking about, FWIW...).

add, if relevant:

voxel-regions are actually more based on spatial size than memory size, and their underlying memory may be resized as-needed (generally avoided when possible).

in my case, regions are 512x512x128 meters, and chunks are 16x16x16 meters (in retrospect, I would have probably preferred 256x256x256 meter regions, but changing this would break my existing world...).

generally, voxels can't cross chunk or region boundaries by nature, so it does not matter for them.

entities or things like brushes or meshes are simply put into whichever chunk their origin happens to fall inside.

the general assumption is that things will typically be small relative to the size of the chunk or region, and typically the chunk will be loaded before whatever is inside it becomes relevant (even if it hangs out over the edge).

loading/unloading/... is mostly then driven by "how far away is it?...". say, the chunk exceeds 384 meters from the camera, or the region exceeds 768 meters, and then is unloaded. when a chunk or region is unloaded, so too is everything it contains. likewise, if a chunk is less than 192 meters away, it will be forcefully loaded (with 256 as an "optimal view distance", and providing a little slack-space between when things are more aggressively loaded or unloaded).


1 - From what I've been reading every resource should be divided in fixed-size chunks and stored using a pool allocator. But how should the resources be divided? I need meshes and textures to be stored continuously so I can create GPU resources. The solution I found is to load the whole resource using a temporary allocator, create the GPU resource, store resource info in chunks, and clear the temporary allocator. But what if the resource info doesn't fit in a single chunk?
I disagree. Every resource with a RAM cost too high should be divided, and that's a big difference.

Strangely enough, I did have streaming support in the past. I don't have it now. Why? Because right now 2GiBs are becoming commonplace... on video cards. I once estimated I could load my whole game in RAM - all the levels - and it would still fit. So there was no chance to really tune the streaming methods. Latency on real world data is a different thing. I am surprised someone just waited for textures "to become visible" to load them - that would have been unacceptable for me even with async loading.


2 - Resources like materials are simply command groups (containing commands to bind textures to shader slots, etc), ideally they should be stored continuously in memory, but might not fit in a single chunk so how should I handle them?

Define what are those things. Streaming textures might make sense but in my system the draw calls, the binding commands themselves take very little. I would be very surprised if they exceeded 512KiB. Don't look for problems at all costs, there might be no problem at all. But if you want to go ahead, run the numbers and focus where it counts.


3 - Is there any way to know how many chunks the pool must be able to hold? Or simply wait until a chunk is freed when the pool is full?

Generic pools are nonsense in my opinion. Consider streaming sounds for example: guaranteed to be consumed at an almost perfectly regular rate. In general, it is better to have small incremental releases rather than one hiccup when the pool runs out, even if the combined work happens to be more performance intensive.


4 - Should I separate resource chunks and level object chunks in two pools?

Divide as much as you need to exploit coherent, predictable behavior. Most out of core methods I've seen don't consider data to be all the same. They exploit locality of some sort in a data-specific way.

Previously "Krohm"

1 - From what I've been reading every resource should be divided in fixed-size chunks and stored using a pool allocator. But how should the resources be divided? I need meshes and textures to be stored continuously so I can create GPU resources. The solution I found is to load the whole resource using a temporary allocator, create the GPU resource, store resource info in chunks, and clear the temporary allocator. But what if the resource info doesn't fit in a single chunk?

I disagree. Every resource with a RAM cost too high should be divided, and that's a big difference.
Strangely enough, I did have streaming support in the past. I don't have it now. Why? Because right now 2GiBs are becoming commonplace... on video cards. I once estimated I could load my whole game in RAM - all the levels - and it would still fit. So there was no chance to really tune the streaming methods. Latency on real world data is a different thing. I am surprised someone just waited for textures "to become visible" to load them - that would have been unacceptable for me even with async loading.


granted, the demand loading was mostly out of it being easier to implement (and works acceptably), even if it can't fully eliminate delays. I tried multi-threaded loading at one point, but then later found that some drivers (ATI/AMD) seem to break pretty hard with uploading via multiple threads (it was working ok with nVidia HW though), so I went back to this being single-threaded (well, along with some other parts of my engine proving to not really be sufficiently thread-safe in general).

one partial strategy used (for a fairly long time) is that many textures are split up into 2 resolution levels, with a lower resolution "base image", and higher resolution "alternate images". typically, the base image is loaded immediately, with the alternate images being delayed until there is time to load them (say, at first it loads a 128x128 version, followed later by a 512x512 or 1024x1024 version, and any normal/specular/luminance/... maps).

also, things may be pulled into memory and decoded at different times, with in some cases, data is pulled into RAM earlier, but not decoded and handed over to OpenGL or similar until it is referenced.


some of this is also related to my development of specialized codecs as well (though this is mostly more focused on things like video and similar).

video frames are typically only decoded when geometry using the texture is directly visible. this leads currently to an issue for I vs P frames, where it is a tradeoff of either wasting cycles decoding non-visible I-Frames, so that P-Frames can be decoded immediately if the video-texture comes back into view, or delaying decoding until an I-Frame has been seen.

as-is, it currently doesn't bother, leading potentially to a fraction of a second of garbled video when a texture first comes back into view.


2 - Resources like materials are simply command groups (containing commands to bind textures to shader slots, etc), ideally they should be stored continuously in memory, but might not fit in a single chunk so how should I handle them?

Define what are those things. Streaming textures might make sense but in my system the draw calls, the binding commands themselves take very little. I would be very surprised if they exceeded 512KiB. Don't look for problems at all costs, there might be no problem at all. But if you want to go ahead, run the numbers and focus where it counts.


I am not entirely sure what is meant by this.

in my case, materials are structures and most rendering is array-driven, and beyond this is mostly code directly making API calls.


3 - Is there any way to know how many chunks the pool must be able to hold? Or simply wait until a chunk is freed when the pool is full?

Generic pools are nonsense in my opinion. Consider streaming sounds for example: guaranteed to be consumed at an almost perfectly regular rate. In general, it is better to have small incremental releases rather than one hiccup when the pool runs out, even if the combined work happens to be more performance intensive.


yeah.

FWIW, it is possible to get reasonably fast allocation/freeing without needing to force everything into using fixed-size chunks.


one strategy is mostly using free-lists of various sizes of fixed-size items, then when a given size item is allocated or freed, we first either check its appropriate free-list, or return an item to that specific list size.

on allocation, if the given list is empty, then we may resort to different strategies, such as carving up an item from a bigger free-list, or falling back to a more generic allocation strategy (a personal preference here being, as-noted, bitmaps and cells).

one example breakdown of such an allocator could be (based on object size):
0-4093 bytes: objects are in terms of 1-257 x 16-byte cells;
4096-65535 bytes: objects are in terms of 1-257 x 256-byte cells;
much past this point, it makes more sense to fall back to a different allocation strategy (such as falling back to malloc and/or other OS facilities).

so, after we know the size range for an object to allocate, we may scan the bitmaps for a free span of the needed size, generally with a rover to help speed up the search.


4 - Should I separate resource chunks and level object chunks in two pools?

Divide as much as you need to exploit coherent, predictable behavior. Most out of core methods I've seen don't consider data to be all the same. They exploit locality of some sort in a data-specific way.


yeah.

main ones I think are either exploiting temporal access patterns (more generally), or spatial ones (such as for world data).


for example, for most world data, it is only really visible within a certain viewing radius.
it is fairly effective IME to simply drive the whole process effectively by distances.

some of this is mostly because unpacked voxel data can use fairly excessive amounts of RAM, and even RLE-packed still eats up a big chunk of RAM, and puts a bit of a strain on my memory-allocator performance as well (currently mostly for allocating/freeing buffers for visible chunks).


previously, audio data was showing up on memory dumps as using a lot of space (nowhere near voxel data though), so I ended up partly moving a lot of it to a customized audio codec (where it is generally kept compressed in RAM and decoded piecewise). currently, it isn't used nearly as much for on-disk storage though (though is used in conjunction with PAK files in a few cases, with a tool converting audio to the format and spitting out the PAK).


I might eventually do similar for textures (IOW: converting all the textures into a custom codec and putting them into a big PAK file or similar). probably the engine would read in the texture PAK files in advance (similar to the sound PAKs).

Thanks for your answers.

for example, I do most of my general-purpose memory allocation via a custom heap-style allocator, rather than using pool-based or region-based allocators.


Using an heap (free list) allocator don't you have fragmentation problems? After a while of loading/unloading of different sizes the memory will most likely become fragmented, how do you deal with it?

1 - From what I've been reading every resource should be divided in fixed-size chunks and stored using a pool allocator. But how should the resources be divided? I need meshes and textures to be stored continuously so I can create GPU resources. The solution I found is to load the whole resource using a temporary allocator, create the GPU resource, store resource info in chunks, and clear the temporary allocator. But what if the resource info doesn't fit in a single chunk?

I disagree. Every resource with a RAM cost too high should be divided, and that's a big difference.
Strangely enough, I did have streaming support in the past. I don't have it now. Why? Because right now 2GiBs are becoming commonplace... on video cards. I once estimated I could load my whole game in RAM - all the levels - and it would still fit. So there was no chance to really tune the streaming methods. Latency on real world data is a different thing.


I would rather have a more flexible (streaming) solution than have to limit levels size.

I am surprised someone just waited for textures "to become visible" to load them - that would have been unacceptable for me even with async loading.


I agree. My plan is to be able to define areas in the world editor where streaming of other zones should start.

For games with large levels (open world), that use streaming, is it "ok" to limit the number of resources loaded to a fixed number? Bitsquid (for example) limits the number of units to 65k, is it usual to put limits in an engine like that? How should the limit be calculated or are there more dynamic solutions?

Having a maximum number of resources/world objects allows me to use linear arrays increasing simplicity and most likely performance.

EDIT: After thinking a bit about it limiting the number of resources shouldn't cause any issue since I would need less than 16 MiB to store the info of 1 million resources (hashed name, reference count and pointer to resource data), and it is highly unlikely that I'll ever need that many resources in memory simultaneously happy.png .

Thanks for your answers.

for example, I do most of my general-purpose memory allocation via a custom heap-style allocator, rather than using pool-based or region-based allocators.


Using an heap (free list) allocator don't you have fragmentation problems? After a while of loading/unloading of different sizes the memory will most likely become fragmented, how do you deal with it?


for the most part, I don't (I don't really try to deal with it, but it doesn't really seem to be too big of an issue either, at least vs general memory usage).


however, after a while, one may observe a pattern:
for the most part, the various sizes of free-lists will become filled with various amounts of various-sized memory objects, and (assuming that leaks are not present), will often eventually tend towards stabilizing (few or no general-purpose allocations of new memory objects in this size range, though with large numbers of allocations/frees within a given size of free-list).

typically, the existence of memory objects of various sizes (allocated and available) tends to resemble a histogram (roughly following a Gaussian distribution), with very large numbers of small objects (< 4kB), followed by progressive decreases as sizes get larger, though often with a few spikes (for example, in my engine, there is typically a fairly big spike around 32kB, which is the natural size of an uncompressed voxel chunk). larger memory objects tend to be fairly sparse.

as-is, objects < 4kB comprise around 30-40% of the total memory use in my case, with 32kB chunks and occasional large objects making up most of the rest. of these small objects, the number of objects is roughly inversely related to size (with 0-15 and 16-31 byte objects having object-counts in the millions).

objects under 64kB in-general tend to represent the majority (around 80%) of total memory use in my engine.

above this tends mostly to be largish semi-permanent data structures (such as PAK-files, video files, region files, buffers for decoded video frames, the console buffer, ...), and occasionally temporary buffers. many of these tend to range between 100s of KB and into the MB range.

granted, these dumps were usually made in cases where the engine was low on memory (typically because the available 32-bit address space was pretty much used up...).


some specific types of small memory objects are also handled specially (namely things like cons-cells and boxed-values).
a cons cell is basically a pair of tagged-pointers (traditionally called 'car' and 'cdr'), and typically boxed values are things like boxed-longs and boxed-doubles. in the former case, the MM manages these specially (they have their own heap), and boxed-values in general use slab allocation (and lack individual headers). these are not counted in the above stats (which were for the general allocator), but likewise tend to have fairly high allocation counts (also in the millions).

most other things are mostly things like strings and various small structures and similar.


having all objects in a given free list be the same size also helps some.
if each object has to be an exact number of bytes, this creates a mess.
however, with a given number of cells, the same object may hold a certain range of memory-object sizes.

say, we have a 17x16-cell object:
it can hold an allocation anywhere from 240-256 bytes.

typically, after a little while, one then hits a plateau of the number of objects of that given size range.


fragmentation is potentially still an issue for larger objects, but luckily these are relatively uncommon.

a lot of this is likely to depend a lot on the specific engine though.

ADD (specifics):

while each free list contains fixed size objects, there are a fair number of free lists:

256 free-lists for small objects (in increments of 16 bytes);

256 free-lists for medium objects (in increments of 256 bytes);

...

small/medium objects, as noted, can have their background memory managed by by cells and bitmaps;

large objects are generally managed by sorted arrays (managed via binary searches and positional inserts).

there is actually a fairly involved set of algorithms responsible for dealing with the case where the relevant free-list is empty, and linearly scanning for a sufficient span of free cells fails to find free memory (it tries to reclaim memory from other free-lists, considers trying to expand the heap, ...).

in a few cases, "memory usage probes" are used by some logic to evaluate some decisions, like whether or not to load voxel-chunks, as well as temporarily reducing the view radius (to try to reduce memory pressure by forcing distant chunks to be unloaded). this basically means, for example, that if memory-usage exceeds 65% of maximum, then the view radius drops to 192 meters, and then to 128 meters at 70%.

this policy was itself fairly effective in helping reduce the problem the engine running out of memory.

note that the (combined) heap limit for 32-bit processes is currently limited to around 2GB (though this is partly subdivided between the different kinds of heap memory). the remaining address space is left for "pretty much everything else".

1 - From what I've been reading every resource should be divided in fixed-size chunks and stored using a pool allocator. But how should the resources be divided? I need meshes and textures to be stored continuously so I can create GPU resources. The solution I found is to load the whole resource using a temporary allocator, create the GPU resource, store resource info in chunks, and clear the temporary allocator. But what if the resource info doesn't fit in a single chunk?

I disagree. Every resource with a RAM cost too high should be divided, and that's a big difference.
Strangely enough, I did have streaming support in the past. I don't have it now. Why? Because right now 2GiBs are becoming commonplace... on video cards. I once estimated I could load my whole game in RAM - all the levels - and it would still fit. So there was no chance to really tune the streaming methods. Latency on real world data is a different thing.


I would rather have a more flexible (streaming) solution than have to limit levels size.


likewise.

then again, I am using voxels, which if handled naively can use up all the RAM within a fairly short view radius.

if the worlds were Quake style, you could probably actually fit a "pretty damn big world" in a single giant BSP, and would more likely run into floating-point precision issues before running into memory issues. not that this would necessarily be practical though (there are likely to be other limiting factors before this, namely performance and map-creation issues, and dividing the world into a regular grid would probably make more sense).


I am surprised someone just waited for textures "to become visible" to load them - that would have been unacceptable for me even with async loading.


I agree. My plan is to be able to define areas in the world editor where streaming of other zones should start.


For games with large levels (open world), that use streaming, is it "ok" to limit the number of resources loaded to a fixed number? Bitsquid (for example) limits the number of units to 65k, is it usual to put limits in an engine like that? How should the limit be calculated or are there more dynamic solutions?

Having a maximum number of resources/world objects allows me to use linear arrays increasing simplicity and most likely performance.

EDIT: After thinking a bit about it limiting the number of resources shouldn't cause any issue since I would need less than 16 MiB to store the info of 1 million resources (hashed name, reference count and pointer to resource data), and it is highly unlikely that I'll ever need that many resources in memory simultaneously happy.png .


yeah, as long as the limit is higher than what is likely to be needed, and doesn't pose some strict architectural limit (IOW: like say using 16-bits in a file-format for something that may need more bits later and can't be easily expanded), it typically doesn't matter too much.

This topic is closed to new replies.

Advertisement