mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-12-02 07:22:42 +01:00
Merge pull request #555 from MaSzyna-EU07/feat/eu07m-geometry-streaming
feat(render): the geometry of the scenery models and the data of the textures streamed, on by default
This commit is contained in:
@@ -400,6 +400,7 @@ set(SOURCES
|
||||
"utilities/headtrack.cpp"
|
||||
"utilities/hardwareprobe.cpp"
|
||||
"rendering/geometrybank.cpp"
|
||||
"rendering/geometrystreamer.cpp"
|
||||
"simulation/simulationsounds.cpp"
|
||||
"rendering/openglcamera.cpp"
|
||||
|
||||
@@ -433,6 +434,8 @@ set(SOURCES
|
||||
"rendering/common/scenewalk.cpp"
|
||||
"rendering/common/scenewalkindirect.cpp"
|
||||
"rendering/common/walksync.cpp"
|
||||
"rendering/common/modelprefetch.cpp"
|
||||
"rendering/common/memoryreport.cpp"
|
||||
"rendering/common/instancecull.cpp"
|
||||
"rendering/common/shadowfit.cpp"
|
||||
"rendering/common/localshadows.cpp"
|
||||
@@ -871,6 +874,7 @@ set(CORE_SOURCES
|
||||
"model/eu07m/eu07m_dump.cpp"
|
||||
"model/eu07m/eu07m_store.cpp"
|
||||
"model/eu07m/eu07m_pack.cpp"
|
||||
"model/eu07m/eu07m_geometry.cpp"
|
||||
"model/skinning.cpp"
|
||||
"model/clip.cpp"
|
||||
"${DEPS_DIR}/zstd/zstd.c"
|
||||
|
||||
@@ -23,6 +23,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "utilities/dictionary.h"
|
||||
#include "scene/sceneeditor.h"
|
||||
#include "rendering/renderer.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/modelprefetch.h"
|
||||
#include "application/uilayer.h"
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/logfiles.h"
|
||||
@@ -77,6 +79,18 @@ ui_layer uilayerstaticinitializer;
|
||||
|
||||
namespace
|
||||
{
|
||||
// gfx.textures.streaming not set in eu07.ini: the textures are streamed with the vulkan renderer, which was measured with it, and
|
||||
// read whole with opengl as before
|
||||
void default_texture_streaming()
|
||||
{
|
||||
if (Global.gfx_texture_streaming_set)
|
||||
return;
|
||||
Global.gfx_texture_streaming = (Global.GfxRenderer == "vulkan");
|
||||
// the settings were logged before the renderer was chosen
|
||||
if (Global.gfx_texture_streaming)
|
||||
WriteLog("gfx.textures.streaming yes: the default of the vulkan renderer");
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// windows wakes a sleeping thread of a process which didn't ask for a finer timer in steps of up to ~15.6 ms.
|
||||
// the wait of fpslimit sleeps, so a 10 ms frame slot of fpslimit 100 ended ~15.6 ms later, the pacer made it up
|
||||
@@ -836,6 +850,15 @@ int eu07_application::run()
|
||||
EditorTerrain.update(Global.pCamera.Pos);
|
||||
Timer::subsystem.loop_terrain.stop();
|
||||
|
||||
// the geometry of the streamed scenery models (modelstreaming): asked for around the camera ahead of its drawing, handed to the
|
||||
// banks it was read for, and let go of where it's unused
|
||||
if ((Global.modelstreaming && GfxRenderer->Streams_Geometry()) || GfxRenderer->Prefetches_Textures())
|
||||
{
|
||||
if (simulation::is_ready)
|
||||
gfx::model_prefetch::instance().update(Global.pCamera.Pos, false);
|
||||
gfx::geometry_streamer::instance().update();
|
||||
}
|
||||
|
||||
Timer::subsystem.loop_tasks.start();
|
||||
m_taskqueue.update();
|
||||
m_screenqueue.update();
|
||||
@@ -1604,6 +1627,7 @@ void eu07_application::select_gfx_backend()
|
||||
{
|
||||
m_gfxbackend = factory->backend("modern");
|
||||
}
|
||||
default_texture_streaming();
|
||||
|
||||
crashreport_add_info("gfxrenderer", Global.GfxRenderer);
|
||||
WriteLog("renderer: " + (m_gfxbackend != nullptr ? m_gfxbackend->name : std::string("none")));
|
||||
@@ -1686,6 +1710,7 @@ int eu07_application::fallback_to_opengl(std::string const &Reason)
|
||||
crashreport_add_info("gfxrenderer_fallback", Reason);
|
||||
Global.GfxRenderer = "default";
|
||||
m_gfxbackend = gfx_renderer_factory::get_instance()->backend("modern");
|
||||
default_texture_streaming();
|
||||
crashreport_add_info("gfxrenderer", Global.GfxRenderer);
|
||||
WriteLog("renderer: " + (m_gfxbackend != nullptr ? m_gfxbackend->name : std::string("none")));
|
||||
|
||||
@@ -1748,6 +1773,8 @@ int eu07_application::init_gfx()
|
||||
// the reason is in the log already
|
||||
GfxRenderer->Shutdown();
|
||||
GfxRenderer.reset();
|
||||
// the shutdown of the vulkan renderer stopped the streaming of the geometry; opengl streams it too
|
||||
gfx::geometry_streamer::instance().resume();
|
||||
if (fallback_to_opengl("the renderer failed to start") != 0)
|
||||
{
|
||||
return -1;
|
||||
|
||||
@@ -28,12 +28,15 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "model/AnimModel.h"
|
||||
#include "model/Model3d.h"
|
||||
#include "rendering/renderer.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/modelprefetch.h"
|
||||
#include "world/Sweep.h"
|
||||
#include "input/keyboardinput.h"
|
||||
#include "launcher/textures_scanner.h"
|
||||
#include <glm/gtc/matrix_transform.hpp>
|
||||
#include <glm/gtc/type_ptr.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include "editor/editorFormat.hpp"
|
||||
#include "editor/editorAlignmentStore.hpp"
|
||||
#include "editor/editorSwitchStore.hpp"
|
||||
@@ -708,6 +711,34 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm
|
||||
WriteLog(format("SELFTEST clip %s %s: %s", node.c_str(), name.c_str(), started ? "playing" : "no such clip"));
|
||||
return selftest_result::handled;
|
||||
}
|
||||
if (command == "memory")
|
||||
{
|
||||
// what the process and its parts keep in memory (rendering/common/memoryreport.h), a line of the log for each part
|
||||
std::string label;
|
||||
words >> label;
|
||||
for (auto const &line : GfxRenderer->Memory_Report())
|
||||
WriteLog(std::format("SELFTEST memory {}: {}", label, line));
|
||||
return selftest_result::handled;
|
||||
}
|
||||
if (command == "modelstream")
|
||||
{
|
||||
// the streaming of the geometry (modelstreaming): evict lets go of the geometry of every streamed model which isn't kept for
|
||||
// good, as if they were unused for long, wait hands over the loads asked for, stats tells what the streamer holds
|
||||
std::string action;
|
||||
words >> action;
|
||||
auto &streamer{gfx::geometry_streamer::instance()};
|
||||
if (action == "evict")
|
||||
WriteLog(std::format("SELFTEST modelstream evict: {} banks let go of", streamer.evict_all()));
|
||||
else if (action == "wait")
|
||||
WriteLog(std::format("SELFTEST modelstream wait: {} loads left", streamer.finish(std::chrono::seconds{30})));
|
||||
auto const prefetch{gfx::model_prefetch::instance().take_timing()};
|
||||
WriteLog(std::format("SELFTEST modelstream {}: prefetch {} passes, {:.1f} ms in all, the longest {:.2f} ms, textures asked for {} instances", action, prefetch.passes,
|
||||
prefetch.total, prefetch.longest, prefetch.textures));
|
||||
auto const stats{streamer.stats()};
|
||||
WriteLog(std::format("SELFTEST modelstream {}: {} banks with {} bytes, {} pending, {} loaded, {} let go of, {} failed", action, stats.resident, stats.bytes, stats.pending, stats.loaded,
|
||||
stats.evicted, stats.failed));
|
||||
return selftest_result::handled;
|
||||
}
|
||||
if (command == "animate")
|
||||
{
|
||||
std::string node;
|
||||
|
||||
@@ -18,6 +18,9 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "application/application.h"
|
||||
#include "application/scenarioloaderuilayer.h"
|
||||
#include "rendering/renderer.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/modelprefetch.h"
|
||||
#include "vehicle/DynObj.h"
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/translation.h"
|
||||
#include "audio/audiorenderer.h"
|
||||
@@ -48,6 +51,9 @@ bool scenarioloader_mode::update() {
|
||||
m_userinterface->set_progress( static_cast<float>( done ) * 100.f / static_cast<float>( total ), 0.f );
|
||||
return true;
|
||||
}
|
||||
if( false == geometry_ready() ) {
|
||||
return true;
|
||||
}
|
||||
m_closing = 0;
|
||||
Application.pop_mode();
|
||||
Application.push_mode( eu07_application::mode::driver );
|
||||
@@ -122,6 +128,43 @@ bool scenarioloader_mode::update() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// the geometry of the streamed models around the start (modelstreaming) loaded with the loading screen kept, so the simulation starts with
|
||||
// them drawn; two minutes at most, the rest comes as it's drawn
|
||||
bool scenarioloader_mode::geometry_ready() {
|
||||
auto const geometry { Global.modelstreaming && GfxRenderer->Streams_Geometry() };
|
||||
if( ( false == geometry ) && ( false == GfxRenderer->Prefetches_Textures() ) ) {
|
||||
return true;
|
||||
}
|
||||
auto &streamer { gfx::geometry_streamer::instance() };
|
||||
if( false == m_geometryasked ) {
|
||||
m_geometryasked = true;
|
||||
m_geometrystart = std::chrono::steady_clock::now();
|
||||
// where the simulation starts: the vehicle of the player, or the free camera
|
||||
auto const *vehicle { Global.local_start_vehicle != "ghostview" ? simulation::Vehicles.find( Global.local_start_vehicle ) : nullptr };
|
||||
auto const start { vehicle != nullptr ? vehicle->GetPosition() : glm::dvec3 { Global.FreeCameraInit[ 0 ] } };
|
||||
GfxRenderer->Collect_Start_Textures( true );
|
||||
gfx::model_prefetch::instance().update( start, true );
|
||||
GfxRenderer->Collect_Start_Textures( false );
|
||||
m_geometrytotal = streamer.pending();
|
||||
}
|
||||
// the geometry handed to the banks, the data of the textures read by their workers, then the textures made on the gpu
|
||||
auto left { streamer.finish( std::chrono::milliseconds { 50 } ) + GfxRenderer->Textures_Being_Read() };
|
||||
if( left == 0 ) {
|
||||
left = GfxRenderer->Make_Start_Textures();
|
||||
}
|
||||
if( m_geometrytotal < left ) {
|
||||
m_geometrytotal = left;
|
||||
}
|
||||
if( ( left == 0 ) || ( std::chrono::steady_clock::now() - m_geometrystart > std::chrono::minutes { 2 } ) ) {
|
||||
WriteLog( std::format( "Geometry of the streamed models around the start loaded, {} of {} in {} ms", m_geometrytotal - std::min( left, m_geometrytotal ), m_geometrytotal,
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - m_geometrystart ).count() ) );
|
||||
return true;
|
||||
}
|
||||
auto const done { m_geometrytotal - std::min( left, m_geometrytotal ) };
|
||||
m_userinterface->set_progress( static_cast<float>( done ) * 100.f / static_cast<float>( std::max<std::size_t>( m_geometrytotal, 1 ) ), 0.f );
|
||||
return false;
|
||||
}
|
||||
|
||||
bool scenarioloader_mode::is_command_processor() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,13 @@ class scenarioloader_mode : public application_mode {
|
||||
std::chrono::system_clock::time_point timestart;
|
||||
// the scenery is loaded: the loading screen kept while the renderer prepares the programs (gfx_renderer::Prewarm_Shaders())
|
||||
int m_closing{0};
|
||||
// the geometry of the streamed models around the start asked for, when, and how many loads it took (modelstreaming)
|
||||
bool m_geometryasked{false};
|
||||
std::chrono::steady_clock::time_point m_geometrystart;
|
||||
std::size_t m_geometrytotal{0};
|
||||
|
||||
// the geometry of the streamed models around the start loaded before the simulation starts. returns: whether it's done
|
||||
bool geometry_ready();
|
||||
|
||||
public:
|
||||
// constructors
|
||||
|
||||
@@ -459,6 +459,46 @@ own. It applies to EU07M and E3D models alike.
|
||||
- Measured (Vulkan, 200 heads `s4ipcpb_dd`): with `gfx.gpucull 0` the frame 9.2 ms → 1.5–2.5 ms and 2400 → 16 draw calls, with
|
||||
`gfx.gpucull 1` 9.1 ms → 3.0 ms and 2410 → 26 draw calls.
|
||||
|
||||
### Streaming of the geometry
|
||||
|
||||
With `modelstreaming yes` in `eu07.ini` (the default; `no` turns it off), and `modelformat ng3d`, the vertex and index streams of the larger scenery
|
||||
models are read when the models are about to be drawn and let go of when they're unused for a while. The table of sections makes it
|
||||
possible: the loading of the scenery reads only the structure of such a model (everything but `VPOS VATT VSKN VSKW VUSR VBND IDX2
|
||||
IDX4`, one read of the beginning of the file), and the streams are read later from the same file, with the blocks of the store
|
||||
(`GREF`). The format doesn't change for it.
|
||||
|
||||
- **Which models.** A scenery model (`node … model`) of an `.ng3d` file of at least `modelstreaming.minsize` KiB (default 256),
|
||||
without skins, stars and texts of E3D, with `BNDS`. The size of the file decides, so a smaller model is read once, whole, as
|
||||
without the streaming. Vehicles, cabs, loads and every other model are loaded whole, as
|
||||
before. A streamed model asked for by anything else than the scenery (a vehicle of the same file) has its geometry loaded and kept.
|
||||
- **What stays.** The nodes, the materials, the components, the clips and the channels are loaded with the model and stay: the
|
||||
animations, the lights, the `.mmd`, `GetFromName` and the events work on a model without its geometry. The geometry bank of the
|
||||
model keeps its chunks, empty (`gfx::residency` in `rendering/geometrybank.h`).
|
||||
- **Loading.** A bank without its data draws nothing and is asked of the streamer (`rendering/geometrystreamer.h`): its threads read
|
||||
and unpack the streams, nearest first, and the main thread hands them to the banks, at most 64 MB or 3 ms in a frame. The cells
|
||||
around the camera are gone through ahead of the drawing (`rendering/common/modelprefetch.h`, the draw range and 500 m), and the
|
||||
loading screen waits, for two minutes at most, for the models around the start, the data of their textures and, in Vulkan, the
|
||||
images of those textures made on the gpu.
|
||||
- **Animations and events.** The walk of the scene goes through an instance without its geometry as through any other: its
|
||||
animations, lights, clips and channels are worked out (`RaAnimate()`, `RaPrepare()`), only its draws are left out. The animations
|
||||
with an event at their end (`evDone`) go on also when the model isn't drawn at all, as before. So the timing of the animations and
|
||||
the events is the same as without the streaming.
|
||||
- **Letting go.** A bank not drawn nor asked for within the prefetch for `modelstreaming.evictafter` seconds (default 30) lets go of
|
||||
its data in memory and on the GPU. Above `modelstreaming.budget` MB (default 0, no limit) the banks unused for 2 seconds go sooner.
|
||||
- **Reading the vertices.** What reads the vertices of a model (the picking, the editor, the occlusion of the sky) gets them: a bank
|
||||
without its data loads it at once, on the thread which asks.
|
||||
- **Bounds.** The radius of a streamed model and the bounds of its branches (the texture variants) come from `BNDS`, the corners of
|
||||
the bounds of its nodes taken through their transforms, not from the vertices. The radius is so the true bound of the model around
|
||||
its origin, which may differ a little from the one the vertices give.
|
||||
- **Textures.** With `gfx.textures.streaming yes` (now the default; `no` keeps the copies of the data of the textures in memory, as
|
||||
before) the same pass through the cells has the data of the textures of every instance in
|
||||
reach read ahead by the workers of the textures (Vulkan; the OpenGL renderer has its own pass, `Update_Texture_Prefetch()`), and the
|
||||
data is let go of after the upload, as the streaming of the textures does. The data read ahead and not drawn for 5 minutes, or
|
||||
read for a place the camera went far from, is let go of too.
|
||||
- The self-test commands `modelstream evict` (the geometry of every streamed model let go of), `modelstream wait` and
|
||||
`modelstream stats`, and `memory <label>`: what the process and its parts keep in memory (`rendering/common/memoryreport.h`).
|
||||
- A file changed on the disk since the model was loaded isn't read for it: its geometry stays out, with `Bad model` in the log.
|
||||
|
||||
## Backward compatibility
|
||||
|
||||
E3D and T3D are read as before. An `.ng3d` file is loaded only when it exists, behind the switch `modelformat ng3d` in
|
||||
|
||||
+2
-1
@@ -297,7 +297,8 @@ bool TAnimModel::Init(std::string const &asName, std::string const &asReplacable
|
||||
// TODO: redo the random timer initialization
|
||||
// fBlinkTimer = Random() * ( fOnTime + fOffTime );
|
||||
|
||||
pModel = TModelsManager::GetModel( asName );
|
||||
// the geometry of a scenery model may be streamed (modelstreaming)
|
||||
pModel = TModelsManager::GetModel( asName, false, true, 0, true );
|
||||
return pModel != nullptr;
|
||||
}
|
||||
|
||||
|
||||
@@ -147,6 +147,13 @@ public:
|
||||
TModel3d *
|
||||
Model() const {
|
||||
return pModel; }
|
||||
// whether the data of the textures of the instance was read ahead (gfx.textures.streaming, rendering/common/modelprefetch.h)
|
||||
bool
|
||||
textures_prefetched() const {
|
||||
return m_texturesprefetched; }
|
||||
void
|
||||
textures_prefetched( bool const Value ) {
|
||||
m_texturesprefetched = Value; }
|
||||
inline
|
||||
void
|
||||
Angles( glm::vec3 const &Angles ) {
|
||||
|
||||
+10
-5
@@ -23,9 +23,10 @@ http://mozilla.org/MPL/2.0/.
|
||||
|
||||
// wczytanie modelu do kontenerka
|
||||
TModel3d *
|
||||
TMdlContainer::LoadModel(std::string const &Name, bool const Dynamic) {
|
||||
TMdlContainer::LoadModel(std::string const &Name, bool const Dynamic, bool const Streamable) {
|
||||
|
||||
Model = std::make_shared<TModel3d>();
|
||||
Model->m_streamable = Streamable;
|
||||
if( true == Model->LoadFromFile( Name, Dynamic ) ) {
|
||||
m_name = Name;
|
||||
return Model.get();
|
||||
@@ -65,10 +66,10 @@ TModelsManager::memory() {
|
||||
|
||||
// wczytanie modelu do tablicy
|
||||
TModel3d *
|
||||
TModelsManager::LoadModel(std::string const &Name, std::string const &virtualName, bool dynamic) {
|
||||
TModelsManager::LoadModel(std::string const &Name, std::string const &virtualName, bool dynamic, bool const Streamable) {
|
||||
|
||||
m_models.emplace_back();
|
||||
auto model = m_models.back().LoadModel( Name, dynamic );
|
||||
auto model = m_models.back().LoadModel( Name, dynamic, Streamable );
|
||||
if( model != nullptr ) {
|
||||
m_modelsmap.try_emplace( virtualName, m_models.size() - 1 );
|
||||
}
|
||||
@@ -80,7 +81,7 @@ TModelsManager::LoadModel(std::string const &Name, std::string const &virtualNam
|
||||
}
|
||||
|
||||
TModel3d *
|
||||
TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const Logerrors, int uid )
|
||||
TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const Logerrors, int uid, bool const Streamable )
|
||||
{ // model może być we wpisie "node...model" albo "node...dynamic", a także być dodatkowym w dynamic
|
||||
// (kabina, wnętrze, ładunek)
|
||||
// dla "node...dynamic" mamy podaną ścieżkę w "\dynamic\" i musi być co najmniej 1 poziom, zwkle
|
||||
@@ -122,13 +123,17 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const
|
||||
TModel3d *model { banklookupmodel };
|
||||
if( true == banklookupfound ) {
|
||||
Global.asCurrentTexturePath = buftp;
|
||||
// a model streamed for the scenery, wanted now by something which reads its vertices (a vehicle): its geometry kept for good
|
||||
if( ( model != nullptr ) && ( false == Streamable ) ) {
|
||||
model->pin_geometry();
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
// first load attempt, check if it's on disk
|
||||
|
||||
if( std::string disklookup { find_on_disk( filename ) }; false == disklookup.empty() ) {
|
||||
model = LoadModel( disklookup, disklookup + postfix, Dynamic ); // model nie znaleziony, to wczytać
|
||||
model = LoadModel( disklookup, disklookup + postfix, Dynamic, Streamable ); // model nie znaleziony, to wczytać
|
||||
}
|
||||
else {
|
||||
// there's nothing matching in the databank nor on the disk, report failure...
|
||||
|
||||
+5
-3
@@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/.
|
||||
|
||||
class TMdlContainer {
|
||||
friend class TModelsManager;
|
||||
TModel3d *LoadModel( std::string const &Name, bool const Dynamic );
|
||||
TModel3d *LoadModel( std::string const &Name, bool const Dynamic, bool const Streamable );
|
||||
std::shared_ptr<TModel3d> Model { nullptr };
|
||||
std::string m_name;
|
||||
};
|
||||
@@ -22,7 +22,9 @@ class TMdlContainer {
|
||||
class TModelsManager {
|
||||
public:
|
||||
// McZapkie: dodalem sciezke, notabene Path!=Patch :)
|
||||
static TModel3d *GetModel(std::string const &Name, bool const dynamic = false, bool const Logerrors = true , int uid = 0);
|
||||
// Streamable: a scenery model, whose geometry may be streamed (modelstreaming). a streamed model asked for by anything else has its
|
||||
// geometry loaded and kept for good
|
||||
static TModel3d *GetModel(std::string const &Name, bool const dynamic = false, bool const Logerrors = true , int uid = 0, bool const Streamable = false);
|
||||
// what the loaded models keep in memory, for the debug panel: models, submodels with the bytes of their own copies of the
|
||||
// geometry (vertices, user data, indices; the gpu gets theirs from the geometry banks)
|
||||
struct memory_data {
|
||||
@@ -39,7 +41,7 @@ private:
|
||||
static modelcontainer_sequence m_models;
|
||||
static stringmodelcontainerindex_map m_modelsmap;
|
||||
// methods:
|
||||
static TModel3d *LoadModel(std::string const &Name, const std::string &virtualName, bool const Dynamic );
|
||||
static TModel3d *LoadModel(std::string const &Name, const std::string &virtualName, bool const Dynamic, bool const Streamable );
|
||||
static std::pair<bool, TModel3d *> find_in_databank( std::string const &Name );
|
||||
// checks whether specified file exists. returns name of the located file, or empty string.
|
||||
static std::string find_on_disk( std::string const &Name );
|
||||
|
||||
+75
-2
@@ -2758,6 +2758,15 @@ void TModel3d::finish_binary(bool const dynamic, bool const hastangents)
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (m_streamed)
|
||||
{
|
||||
// a submodel of a streamed model: an empty chunk, filled with the data of the bank when it's drawn or read
|
||||
if (Root[i].m_geometry.vertex_count > 0)
|
||||
{
|
||||
Root[i].m_geometry.handle = GfxRenderer->Insert_Streamed(m_geometrybank, type);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (false == Root[i].CompactPositions.empty())
|
||||
{
|
||||
// a submodel of an EU07M model: its compact streams as they are, the renderer keeps them or makes basic_vertex of them
|
||||
@@ -3066,12 +3075,38 @@ void mark_variant_group(TSubModel *Submodel, int const Group, bool const Include
|
||||
}
|
||||
}
|
||||
|
||||
// the corners of the bounds of the node of a submodel of a streamed model, in the space of the model
|
||||
std::array<glm::vec3, 8> model_corners(TSubModel const &Submodel)
|
||||
{
|
||||
float4x4 parentmatrix;
|
||||
Submodel.ParentMatrix(&parentmatrix);
|
||||
auto const transformationmatrix{glm::make_mat4(parentmatrix.readArray())};
|
||||
auto const &bounds{*Submodel.m_nodebounds};
|
||||
std::array<glm::vec3, 8> corners;
|
||||
for (std::size_t idx = 0; idx < corners.size(); ++idx)
|
||||
{
|
||||
glm::vec3 const corner{bounds[idx & 1].x, bounds[(idx >> 1) & 1].y, bounds[(idx >> 2) & 1].z};
|
||||
corners[idx] = glm::vec3{transformationmatrix * glm::vec4{corner, 1.f}};
|
||||
}
|
||||
return corners;
|
||||
}
|
||||
|
||||
// expands provided bounding area to cover geometry carried by the submodel and all of its children
|
||||
void accumulate_mesh_bounds(TSubModel const *Submodel, glm::vec3 &Minimum, glm::vec3 &Maximum, bool &Isempty, bool const Includesiblings)
|
||||
{
|
||||
while (Submodel != nullptr)
|
||||
{
|
||||
if (auto const &vertices{(Submodel->m_geometry.handle != null_handle ? GfxRenderer->Vertices(Submodel->m_geometry.handle) : Submodel->Vertices)};
|
||||
if ((Submodel->m_nodebounds != nullptr) && (Submodel->m_geometry.handle != null_handle))
|
||||
{
|
||||
// a submodel of a streamed model, whose vertices may not be there: the corners of the bounds of its node
|
||||
for (auto const &corner : model_corners(*Submodel))
|
||||
{
|
||||
Minimum = glm::min(Minimum, corner);
|
||||
Maximum = glm::max(Maximum, corner);
|
||||
}
|
||||
Isempty = false;
|
||||
}
|
||||
else if (auto const &vertices{(Submodel->m_geometry.handle != null_handle ? GfxRenderer->Vertices(Submodel->m_geometry.handle) : Submodel->Vertices)};
|
||||
false == vertices.empty())
|
||||
{
|
||||
// the transformation chain can still hold a rotation, so the vertices go through it
|
||||
@@ -3152,6 +3187,39 @@ void TModel3d::assign_variant_groups()
|
||||
}
|
||||
}
|
||||
|
||||
// the bounding radius of a streamed model from the bounds of its nodes: the farthest corner of them from the origin of the model.
|
||||
// TSubModel::create_geometry() takes it from the vertices, which a streamed model doesn't read at its load
|
||||
void TModel3d::bounds_from_nodes()
|
||||
{
|
||||
if (Root == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
float squaredradius{0.f};
|
||||
for (int idx = 0; idx < iSubModelsCount; ++idx)
|
||||
{
|
||||
auto const &submodel{Root[idx]};
|
||||
if ((submodel.m_nodebounds == nullptr) || (submodel.m_geometry.handle == null_handle))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (auto const &corner : model_corners(submodel))
|
||||
{
|
||||
squaredradius = std::max(squaredradius, glm::length2(corner));
|
||||
}
|
||||
}
|
||||
Root->m_boundingradius = std::max(Root->m_boundingradius, std::sqrt(squaredradius));
|
||||
}
|
||||
|
||||
// the geometry of a streamed model loaded now and kept for good
|
||||
void TModel3d::pin_geometry()
|
||||
{
|
||||
if (m_streamed && (m_geometrybank != null_handle))
|
||||
{
|
||||
GfxRenderer->Pin_Bank(m_geometrybank);
|
||||
}
|
||||
}
|
||||
|
||||
void TModel3d::Init()
|
||||
{ // obrócenie początkowe układu współrzędnych, dla
|
||||
// pojazdów wykonywane po analizie animacji
|
||||
@@ -3167,7 +3235,12 @@ void TModel3d::Init()
|
||||
Root->InitialRotate(true);
|
||||
}
|
||||
iFlags |= Root->FlagsCheck() | 0x8000; // flagi całego modelu
|
||||
if (m_vertexcount)
|
||||
if (m_streamed)
|
||||
{
|
||||
// the vertices of a streamed model aren't read at its load: its radius comes from the bounds of its nodes
|
||||
bounds_from_nodes();
|
||||
}
|
||||
else if (m_vertexcount)
|
||||
{
|
||||
if (m_geometrybank == null_handle)
|
||||
{
|
||||
|
||||
@@ -56,6 +56,9 @@ class shape_node;
|
||||
}
|
||||
|
||||
class TModel3d;
|
||||
namespace eu07m {
|
||||
struct model;
|
||||
}
|
||||
namespace eu07m::payload {
|
||||
struct light;
|
||||
}
|
||||
@@ -177,6 +180,9 @@ public: // chwilowo
|
||||
std::shared_ptr<skinning::skinned_geometry> m_skin;
|
||||
glm::mat4 m_clipanimation{1.f}; // applied after the matrix of the submodel (at_Clip)
|
||||
float m_boundingradius { 0 };
|
||||
// of a submodel of a streamed EU07M model (modelstreaming): the bounds of its node, minimum and maximum, in its space, taken in
|
||||
// place of the vertices, which may not be there (the bounding radius, the bounds of the branches)
|
||||
std::array<glm::vec3, 2> const *m_nodebounds { nullptr };
|
||||
std::uintptr_t iAnimOwner{ 0 }; // roboczy numer egzemplarza, który ustawił animację
|
||||
TAnimType b_aAnim{ TAnimType::at_None }; // kody animacji oddzielnie, bo zerowane
|
||||
std::shared_ptr<float4x4> mAnimMatrix; // macierz do animacji kwaternionowych
|
||||
@@ -334,16 +340,31 @@ private:
|
||||
std::vector<skinning::skin> m_skins; // of an EU07M model, the skinned submodels refer to them
|
||||
std::vector<animation::clip> m_clips; // of an EU07M model, the nodes are the submodels of the same index
|
||||
std::vector<animation::channel> m_channels; // of an EU07M model
|
||||
bool m_streamed { false }; // the geometry is streamed (modelstreaming)
|
||||
std::vector<std::array<glm::vec3, 2>> m_nodebounds; // of a streamed EU07M model, for TSubModel::m_nodebounds
|
||||
|
||||
void finish_binary( bool dynamic, bool hastangents );
|
||||
// the bounding radius of a streamed model from the bounds of its nodes, in place of TSubModel::create_geometry()
|
||||
void bounds_from_nodes();
|
||||
// the geometry bank of an EU07M model made streamed, the bounds of the nodes kept (model/eu07m/eu07m_load.cpp)
|
||||
void stream_geometry( std::string const &FileName, eu07m::model const &Model, std::uint64_t const Hash );
|
||||
// the flags of the submodel tree worked out again after the editor changed it, and the renderer told
|
||||
void submodels_changed();
|
||||
std::vector<std::unique_ptr<TSubModel>> m_editorsubmodels; // added by the editor, linked into the tree
|
||||
std::vector<std::unique_ptr<float4x4>> m_editormatrices; // given by the editor to submodels which had none
|
||||
|
||||
public:
|
||||
// the geometry of the model may be streamed (modelstreaming): set by who asks for the model before it's loaded
|
||||
// (TModelsManager::GetModel()), for the scenery models
|
||||
bool m_streamable { false };
|
||||
|
||||
TModel3d() = default;
|
||||
~TModel3d();
|
||||
// the geometry is streamed: its banks get their data when they're drawn and let go of it when unused
|
||||
bool streamed() const {
|
||||
return m_streamed; }
|
||||
// the geometry of a streamed model loaded now and kept for good: the model is wanted by something which reads its vertices (a vehicle)
|
||||
void pin_geometry();
|
||||
float bounding_radius() const {
|
||||
return Root ? Root->m_boundingradius : 0.f; }
|
||||
inline TSubModel * GetSMRoot() { return Root; };
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
|
||||
#include "model/eu07m/eu07m_geometry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <span>
|
||||
|
||||
namespace eu07m {
|
||||
|
||||
std::vector<std::uint32_t> drawn_primitives(model const &Model) {
|
||||
std::vector<std::uint32_t> primitives;
|
||||
for (auto const &node : Model.nodes) {
|
||||
if (node.mesh < 0 || static_cast<std::size_t>(node.mesh) >= Model.meshes.size())
|
||||
continue;
|
||||
auto const &mesh{Model.meshes[node.mesh]};
|
||||
if (mesh.primitive_count == 0 || mesh.primitive_first >= Model.primitives.size())
|
||||
continue;
|
||||
if (Model.primitives[mesh.primitive_first].vertex_count > 0)
|
||||
primitives.push_back(mesh.primitive_first);
|
||||
}
|
||||
return primitives;
|
||||
}
|
||||
|
||||
std::string_view not_streamable(model const &Model) {
|
||||
if (false == Model.skins.empty())
|
||||
return "it has skins";
|
||||
if (std::ranges::any_of(Model.components, [](component_record const &Record) { return Record.type == component::legacy_stars || Record.type == component::legacy_text; }))
|
||||
return "it has stars or texts";
|
||||
if (Model.bounds.size() != Model.nodes.size() + 1)
|
||||
return "it has no bounds of its nodes";
|
||||
return {};
|
||||
}
|
||||
|
||||
primitive_geometry geometry_of(model const &Model, std::uint32_t const Primitive) {
|
||||
primitive_geometry geometry;
|
||||
if (Primitive >= Model.primitives.size())
|
||||
return geometry;
|
||||
auto const &primitive{Model.primitives[Primitive]};
|
||||
if (std::uint64_t{primitive.base_vertex} + primitive.vertex_count > Model.vertex_count() || Model.vertex_attributes.size() != Model.vertex_count())
|
||||
return geometry;
|
||||
auto const positions{std::span{Model.positions}.subspan(primitive.base_vertex, primitive.vertex_count)};
|
||||
auto const attributes{std::span{Model.vertex_attributes}.subspan(primitive.base_vertex, primitive.vertex_count)};
|
||||
geometry.positions.assign(positions.begin(), positions.end());
|
||||
geometry.vertex_attributes.assign(attributes.begin(), attributes.end());
|
||||
if (Model.vertex_userdata.size() == Model.vertex_count()) {
|
||||
auto const userdata{std::span{Model.vertex_userdata}.subspan(primitive.base_vertex, primitive.vertex_count)};
|
||||
geometry.vertex_userdata.assign(userdata.begin(), userdata.end());
|
||||
}
|
||||
if ((primitive.flags & primitive_flags::indexed) == 0)
|
||||
return geometry;
|
||||
if ((primitive.flags & primitive_flags::index32) != 0) {
|
||||
if (std::uint64_t{primitive.first_index} + primitive.index_count <= Model.indices32.size()) {
|
||||
auto const source{std::span{Model.indices32}.subspan(primitive.first_index, primitive.index_count)};
|
||||
geometry.indices.assign(source.begin(), source.end());
|
||||
}
|
||||
}
|
||||
else if (std::uint64_t{primitive.first_index} + primitive.index_count <= Model.indices16.size()) {
|
||||
auto const source{std::span{Model.indices16}.subspan(primitive.first_index, primitive.index_count)};
|
||||
geometry.indices.assign(source.begin(), source.end());
|
||||
}
|
||||
return geometry;
|
||||
}
|
||||
|
||||
} // namespace eu07m
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// the geometry of an EU07M model as the game draws it: one chunk of the geometry bank of the model for each node with a mesh, made of
|
||||
// the first primitive of the mesh (a submodel of E3D has one geometry), in the order of the nodes, for the primitives with vertices.
|
||||
// TModel3d::LoadFromEU07M() makes the chunks in this order, and the streaming of the geometry (modelstreaming) fills them in it
|
||||
|
||||
#include "model/eu07m/eu07m_model.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace eu07m {
|
||||
|
||||
// the primitives which become the chunks, in their order
|
||||
std::vector<std::uint32_t> drawn_primitives(model const &Model);
|
||||
|
||||
// what keeps the streams of the model from being loaded after the rest of it (modelstreaming); empty when nothing does: the skins
|
||||
// (their bind pose goes to the gpu with the model), the stars and the texts of E3D (made of the vertices at load), a node without
|
||||
// its bounds (the radius and the bounds of the model are taken from them instead of from the vertices)
|
||||
std::string_view not_streamable(model const &Model);
|
||||
|
||||
// the vertices and the indices of a drawn primitive, as the geometry bank takes them
|
||||
struct primitive_geometry {
|
||||
std::vector<std::uint32_t> indices; // local to the primitive; empty for a primitive without indices
|
||||
std::vector<position> positions;
|
||||
std::vector<attributes> vertex_attributes;
|
||||
std::vector<userdata> vertex_userdata; // empty when the model has none
|
||||
};
|
||||
primitive_geometry geometry_of(model const &Model, std::uint32_t Primitive);
|
||||
|
||||
} // namespace eu07m
|
||||
+125
-29
@@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/.
|
||||
|
||||
#include "model/eu07m/eu07m_io.h"
|
||||
#include "model/eu07m/eu07m_dump.h"
|
||||
#include "utilities/wholefile.h"
|
||||
|
||||
#include "meshoptimizer.h"
|
||||
#include "zstd.h"
|
||||
@@ -346,14 +347,30 @@ constexpr std::uint64_t section_size_limit{std::uint64_t{1} << 30};
|
||||
// and the most all the sections of a model may unpack to together
|
||||
constexpr std::uint64_t model_size_limit{std::uint64_t{2} << 30};
|
||||
|
||||
bool is_vertex_stream(std::uint32_t Id);
|
||||
|
||||
class file_reader {
|
||||
public:
|
||||
file_reader(std::span<std::byte const> const File, read_options const &Options) : m_file(File), m_options(Options) {}
|
||||
// the whole file in memory
|
||||
file_reader(std::span<std::byte const> const File, read_options const &Options) : m_file(File), m_size(File.size()), m_options(Options) {}
|
||||
// a part of a file of Size bytes: Window holds the bytes from Base on
|
||||
file_reader(std::span<std::byte const> const Window, std::uint64_t const Base, std::uint64_t const Size, read_options const &Options)
|
||||
: m_file(Window), m_base(Base), m_size(Size), m_options(Options) {}
|
||||
read_result run(model &Model);
|
||||
// the file at Path, of which only the parts with the sections the options ask for are read
|
||||
static read_result run_file(std::string const &Path, model &Model, read_options const &Options);
|
||||
|
||||
private:
|
||||
bool read_header(file_header &Header);
|
||||
bool read_entries(file_header const &Header, std::vector<section_entry> &Entries);
|
||||
read_result read_sections(file_header const &Header, std::vector<section_entry> const &Sections, model &Model);
|
||||
// whether the reader holds the bytes of the section, and the bytes
|
||||
bool holds(section_entry const &Entry) const {
|
||||
return Entry.offset >= m_base && Entry.offset - m_base <= m_file.size() && Entry.stored_size <= m_file.size() - (Entry.offset - m_base);
|
||||
}
|
||||
std::span<std::byte const> stored_bytes(section_entry const &Entry) const {
|
||||
return m_file.subspan(static_cast<std::size_t>(Entry.offset - m_base), static_cast<std::size_t>(Entry.stored_size));
|
||||
}
|
||||
bool unpack(section_entry const &Entry, std::vector<std::byte> &Storage, std::span<std::byte const> &Bytes);
|
||||
bool dispatch(section_entry const &Entry, section_bytes const &Section, model &Model);
|
||||
bool vertex_stream(section_entry const &Entry, model &Model, bool &Handled);
|
||||
@@ -367,23 +384,27 @@ class file_reader {
|
||||
}
|
||||
|
||||
std::span<std::byte const> m_file;
|
||||
std::uint64_t m_base{0}; // where m_file starts in the file
|
||||
std::uint64_t m_size{0}; // of the whole file
|
||||
read_options m_options;
|
||||
std::string m_error;
|
||||
};
|
||||
|
||||
// the header, from the start of the file the reader holds
|
||||
bool file_reader::read_header(file_header &Header) {
|
||||
if (m_file.size() < sizeof(file_header))
|
||||
if (m_base != 0 || m_file.size() < sizeof(file_header))
|
||||
return fail("the file is shorter than the header");
|
||||
std::memcpy(&Header, m_file.data(), sizeof(file_header));
|
||||
if (Header.magic != file_header{}.magic)
|
||||
return fail("the file isn't an EU07M model");
|
||||
if (Header.major != version_major)
|
||||
return fail(std::format("the model has version {}.{}, this program reads version {}", Header.major, Header.minor, version_major));
|
||||
if (Header.file_size > m_file.size())
|
||||
return fail(std::format("the file is cut short: {} bytes of {}", m_file.size(), Header.file_size));
|
||||
if (Header.file_size > m_size)
|
||||
return fail(std::format("the file is cut short: {} bytes of {}", m_size, Header.file_size));
|
||||
if (Header.file_size < sizeof(file_header))
|
||||
return fail(std::format("the file claims {} bytes, less than its header", Header.file_size));
|
||||
m_file = m_file.first(Header.file_size);
|
||||
m_size = Header.file_size;
|
||||
m_file = m_file.first(static_cast<std::size_t>(std::min<std::uint64_t>(m_file.size(), m_size)));
|
||||
if (m_options.verify_hash && hash_bytes(m_file.subspan(sizeof(file_header))) != Header.content_hash)
|
||||
return fail("the content of the file doesn't match its hash");
|
||||
return true;
|
||||
@@ -391,16 +412,18 @@ bool file_reader::read_header(file_header &Header) {
|
||||
|
||||
bool file_reader::read_entries(file_header const &Header, std::vector<section_entry> &Entries) {
|
||||
auto const tablesize{std::uint64_t{Header.section_count} * sizeof(section_entry)};
|
||||
if (Header.toc_offset > m_file.size() || tablesize > m_file.size() - Header.toc_offset)
|
||||
if (Header.toc_offset > m_size || tablesize > m_size - Header.toc_offset)
|
||||
return fail("the list of the sections lies outside the file");
|
||||
if (Header.toc_offset < m_base || Header.toc_offset - m_base > m_file.size() || tablesize > m_file.size() - (Header.toc_offset - m_base))
|
||||
return fail("the list of the sections isn't in the part of the file read");
|
||||
Entries.resize(Header.section_count);
|
||||
if (false == Entries.empty())
|
||||
std::memcpy(Entries.data(), m_file.data() + Header.toc_offset, tablesize);
|
||||
std::memcpy(Entries.data(), m_file.data() + (Header.toc_offset - m_base), tablesize);
|
||||
std::unordered_set<std::uint32_t> seen;
|
||||
seen.reserve(Entries.size());
|
||||
std::uint64_t total{0};
|
||||
for (auto const &entry : Entries) {
|
||||
if (entry.offset > m_file.size() || entry.stored_size > m_file.size() - entry.offset)
|
||||
if (entry.offset > m_size || entry.stored_size > m_size - entry.offset)
|
||||
return fail(std::format("section {} lies outside the file", fourcc_name(entry.id)));
|
||||
if (entry.size > section_size_limit)
|
||||
return fail(std::format("section {} claims {} bytes", fourcc_name(entry.id), entry.size));
|
||||
@@ -414,7 +437,7 @@ bool file_reader::read_entries(file_header const &Header, std::vector<section_en
|
||||
}
|
||||
|
||||
bool file_reader::unpack(section_entry const &Entry, std::vector<std::byte> &Storage, std::span<std::byte const> &Bytes) {
|
||||
auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)};
|
||||
auto const stored{stored_bytes(Entry)};
|
||||
if ((Entry.flags & section_flags::meshopt) != 0)
|
||||
return fail(std::format("section {} is in a codec only the vertex and index streams may be in", fourcc_name(Entry.id)));
|
||||
if ((Entry.flags & section_flags::zstd) == 0) {
|
||||
@@ -436,7 +459,7 @@ bool file_reader::unpack(section_entry const &Entry, std::vector<std::byte> &Sto
|
||||
|
||||
// the zstd frame of the section, of at most Limit bytes
|
||||
bool file_reader::unzstd(section_entry const &Entry, std::size_t const Limit, std::vector<std::byte> &Output) {
|
||||
auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)};
|
||||
auto const stored{stored_bytes(Entry)};
|
||||
auto const size{ZSTD_getFrameContentSize(stored.data(), stored.size())};
|
||||
if (size == ZSTD_CONTENTSIZE_UNKNOWN || size == ZSTD_CONTENTSIZE_ERROR || size > Limit)
|
||||
return fail(std::format("section {} doesn't unpack to a size its codec can have", fourcc_name(Entry.id)));
|
||||
@@ -461,7 +484,7 @@ bool file_reader::decode(section_entry const &Entry, std::span<std::byte const>
|
||||
template <typename Type_> bool file_reader::unpack_into(section_entry const &Entry, std::vector<Type_> &Output, stream_codec const Codec) {
|
||||
if (Entry.size % sizeof(Type_) != 0)
|
||||
return fail(std::format("section {} of {} bytes isn't a whole number of elements of {} bytes", fourcc_name(Entry.id), Entry.size, sizeof(Type_)));
|
||||
auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)};
|
||||
auto const stored{stored_bytes(Entry)};
|
||||
if ((Entry.flags & section_flags::meshopt) != 0) {
|
||||
auto const count{static_cast<std::size_t>(Entry.size) / sizeof(Type_)};
|
||||
// the result of the codec is never larger than its bound, which caps what a broken zstd frame can claim
|
||||
@@ -537,7 +560,7 @@ bool file_reader::read_streams(std::vector<section_entry> const &Sections, model
|
||||
// of its own would end the program
|
||||
auto const unpack_one{[this, &streams, &errors, &Model](std::size_t const Index) {
|
||||
try {
|
||||
file_reader worker{m_file, m_options};
|
||||
file_reader worker{m_file, m_base, m_size, m_options};
|
||||
bool handled{false};
|
||||
if (false == worker.vertex_stream(streams[Index], Model, handled)) // NOSONAR: S2259 false positive, worker is a local object and no pointer is null here
|
||||
errors[Index] = std::move(worker.m_error);
|
||||
@@ -631,15 +654,25 @@ read_result file_reader::run(model &Model) {
|
||||
std::vector<section_entry> sections;
|
||||
if (false == read_header(header) || false == read_entries(header, sections))
|
||||
return {false, m_error};
|
||||
Model.flags = header.flags;
|
||||
Model.source_hash = header.source_hash;
|
||||
return read_sections(header, sections, Model);
|
||||
}
|
||||
|
||||
read_result file_reader::read_sections(file_header const &Header, std::vector<section_entry> const &Sections, model &Model) {
|
||||
Model.flags = Header.flags;
|
||||
Model.source_hash = Header.source_hash;
|
||||
read_result result{true, {}, Header.content_hash, 0};
|
||||
for (auto const &entry : Sections) {
|
||||
if (is_vertex_stream(entry.id))
|
||||
result.stream_bytes += entry.size;
|
||||
}
|
||||
std::vector<std::byte> storage;
|
||||
if (false == read_streams(sections, Model)) {
|
||||
if (m_options.streams && false == read_streams(Sections, Model)) {
|
||||
Model = model{};
|
||||
return {false, m_error};
|
||||
}
|
||||
for (auto const &entry : sections) {
|
||||
if (is_vertex_stream(entry.id))
|
||||
for (auto const &entry : Sections) {
|
||||
// a section the reader hasn't the bytes of wasn't asked for (read_file())
|
||||
if (is_vertex_stream(entry.id) || false == holds(entry))
|
||||
continue;
|
||||
if (false == known_section(entry.id)) {
|
||||
// a section this reader doesn't know: one the model needs is refused before its codec is looked at; one it can
|
||||
@@ -659,21 +692,73 @@ read_result file_reader::run(model &Model) {
|
||||
}
|
||||
}
|
||||
for (auto const required : {section::strings, section::nodes, section::meshes, section::primitives, section::positions, section::attributes, section::materials}) {
|
||||
if (std::ranges::none_of(sections, [required](section_entry const &Entry) { return Entry.id == required; })) {
|
||||
if (std::ranges::none_of(Sections, [required](section_entry const &Entry) { return Entry.id == required; })) {
|
||||
Model = model{};
|
||||
return {false, std::format("the model has no section {}", fourcc_name(required))};
|
||||
}
|
||||
}
|
||||
// the geometry kept in the store of the family goes back in its place in the streams
|
||||
if (std::string error; false == insert_blocks(Model, m_options.blocks, error, m_options.verify_hash)) {
|
||||
if (std::string error; m_options.streams && false == insert_blocks(Model, m_options.blocks, error, m_options.verify_hash)) {
|
||||
Model = model{};
|
||||
return {false, error};
|
||||
}
|
||||
if (auto const faults{validate(Model, 1)}; false == faults.empty()) {
|
||||
if (auto const faults{validate(Model, 1, m_options.streams ? validate_scope::whole : validate_scope::structure)}; false == faults.empty()) {
|
||||
Model = model{};
|
||||
return {false, faults.front()};
|
||||
}
|
||||
return {true, {}};
|
||||
return result;
|
||||
}
|
||||
|
||||
// whether read_file() reads the section: the streams when they're asked for, and the sections it knows or keeps or has to refuse
|
||||
bool wanted_section(section_entry const &Entry, read_options const &Options) {
|
||||
if (is_vertex_stream(Entry.id))
|
||||
return Options.streams;
|
||||
return known_section(Entry.id) || Options.keep_unknown || (Entry.flags & section_flags::required) != 0;
|
||||
}
|
||||
|
||||
read_result file_reader::run_file(std::string const &Path, model &Model, read_options const &Options) {
|
||||
Model = model{};
|
||||
file_parts file{Path};
|
||||
if (false == file.is_open())
|
||||
return {false, "the file can't be opened"};
|
||||
// a part of the file can't be checked with the hash of the whole content
|
||||
auto options{Options};
|
||||
options.verify_hash = false;
|
||||
std::array<std::byte, sizeof(file_header)> head{};
|
||||
auto const headsize{static_cast<std::size_t>(std::min<std::uint64_t>(file.size(), head.size()))};
|
||||
if (false == file.read(0, headsize, head.data()))
|
||||
return {false, "the file can't be read"};
|
||||
file_reader start{std::span<std::byte const>{head}.first(headsize), 0, file.size(), options};
|
||||
file_header header;
|
||||
if (false == start.read_header(header))
|
||||
return {false, start.m_error};
|
||||
auto const tablesize{std::uint64_t{header.section_count} * sizeof(section_entry)};
|
||||
if (header.toc_offset > header.file_size || tablesize > header.file_size - header.toc_offset)
|
||||
return {false, "the list of the sections lies outside the file"};
|
||||
std::vector<std::byte> table(static_cast<std::size_t>(tablesize));
|
||||
if (false == file.read(header.toc_offset, table.size(), table.data()))
|
||||
return {false, "the file can't be read"};
|
||||
file_reader list{table, header.toc_offset, header.file_size, options};
|
||||
std::vector<section_entry> sections;
|
||||
if (false == list.read_entries(header, sections))
|
||||
return {false, list.m_error};
|
||||
// one read of the part of the file which holds the sections wanted; the sections lie in the order they're written, the structure
|
||||
// first and the streams after it, so without the streams the part is a small one
|
||||
auto first{std::numeric_limits<std::uint64_t>::max()};
|
||||
std::uint64_t last{0};
|
||||
for (auto const &entry : sections) {
|
||||
if (false == wanted_section(entry, options))
|
||||
continue;
|
||||
first = std::min(first, entry.offset);
|
||||
last = std::max(last, entry.offset + entry.stored_size);
|
||||
}
|
||||
if (first > last)
|
||||
first = last;
|
||||
std::vector<std::byte> window(static_cast<std::size_t>(last - first));
|
||||
if (false == file.read(first, window.size(), window.data()))
|
||||
return {false, "the file can't be read"};
|
||||
file_reader reader{window, first, header.file_size, options};
|
||||
return reader.read_sections(header, sections, Model);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
@@ -854,7 +939,7 @@ bool valid_payload(model const &Model, component_record const &Record, std::span
|
||||
|
||||
class validator {
|
||||
public:
|
||||
validator(model const &Model, std::size_t const Limit) : m_model(Model), m_limit(Limit) {}
|
||||
validator(model const &Model, std::size_t const Limit, validate_scope const Scope) : m_model(Model), m_limit(Limit), m_streams(Scope == validate_scope::whole) {}
|
||||
std::vector<std::string> run();
|
||||
|
||||
private:
|
||||
@@ -889,6 +974,7 @@ class validator {
|
||||
|
||||
model const &m_model;
|
||||
std::size_t m_limit;
|
||||
bool m_streams; // the streams are there to check against (validate_scope::whole)
|
||||
std::vector<std::string> m_faults;
|
||||
};
|
||||
|
||||
@@ -976,7 +1062,7 @@ void validator::skinned(std::uint32_t const Index, primitive_record const &Primi
|
||||
}
|
||||
|
||||
void validator::primitive(std::uint32_t const Index, primitive_record const &Primitive) {
|
||||
if (std::uint64_t{Primitive.base_vertex} + Primitive.vertex_count > m_model.vertex_count()) {
|
||||
if (m_streams && std::uint64_t{Primitive.base_vertex} + Primitive.vertex_count > m_model.vertex_count()) {
|
||||
fault(std::format("primitive {} has vertices out of range", Index));
|
||||
return;
|
||||
}
|
||||
@@ -986,12 +1072,16 @@ void validator::primitive(std::uint32_t const Index, primitive_record const &Pri
|
||||
fault(std::format("primitive {} belongs to node {}, which isn't there", Index, Primitive.node));
|
||||
if (Primitive.material != no_index && Primitive.material >= m_model.materials.size())
|
||||
fault(std::format("primitive {} has material {} out of range", Index, Primitive.material));
|
||||
if ((Primitive.flags & primitive_flags::indexed) != 0)
|
||||
indices(Index, Primitive);
|
||||
if ((Primitive.flags & primitive_flags::indexed) != 0) {
|
||||
if (m_streams)
|
||||
indices(Index, Primitive);
|
||||
}
|
||||
else if (std::uint64_t{Primitive.first_index} + Primitive.index_count > Primitive.vertex_count)
|
||||
fault(std::format("primitive {} draws vertices past its own", Index));
|
||||
if (Primitive.skin < -1 || Primitive.skin >= static_cast<std::int64_t>(m_model.skins.size()))
|
||||
fault(std::format("primitive {} has skin {} out of range", Index, Primitive.skin));
|
||||
else if (false == m_streams)
|
||||
return; // the joints and the light slots of the vertices are in the streams
|
||||
else if ((Primitive.flags & primitive_flags::rigid_joints) != 0)
|
||||
bound(Index, Primitive);
|
||||
else if (Primitive.skin >= 0 && m_model.weights.size() != m_model.vertex_count() && m_model.weights_wide.size() != m_model.vertex_count())
|
||||
@@ -1034,6 +1124,8 @@ void validator::primitives() {
|
||||
}
|
||||
|
||||
void validator::streams() {
|
||||
if (false == m_streams)
|
||||
return;
|
||||
auto const count{m_model.vertex_count()};
|
||||
if (m_model.vertex_attributes.size() != count)
|
||||
fault(std::format("VATT has {} vertices, VPOS {}", m_model.vertex_attributes.size(), count));
|
||||
@@ -1085,7 +1177,7 @@ void validator::vertex_groups() {
|
||||
}
|
||||
if ((group.flags & vertex_group_flags::weighted) != 0 && end > m_model.vertex_group_weights.size())
|
||||
fault(std::format("vertex group {} has weights out of range", idx));
|
||||
for (auto item = std::size_t{group.item_first}; item < end; item += itemsize) {
|
||||
for (auto item = std::size_t{group.item_first}; m_streams && item < end; item += itemsize) {
|
||||
auto const last{ranges ? std::uint64_t{m_model.vertex_group_items[item]} + m_model.vertex_group_items[item + 1] : std::uint64_t{m_model.vertex_group_items[item]} + 1};
|
||||
if (last > m_model.vertex_count()) {
|
||||
fault(std::format("vertex group {} has vertices out of range", idx));
|
||||
@@ -1212,7 +1304,7 @@ void validator::geometry_references() {
|
||||
auto const indices{(primitive.flags & primitive_flags::indexed) != 0 ? primitive.index_count : 0u};
|
||||
if (reference.vertex_count != primitive.vertex_count || reference.index_count != indices)
|
||||
fault(std::format("the geometry reference of primitive {} has other counts than the primitive", reference.primitive));
|
||||
else if (false == shareable(m_model, reference.primitive))
|
||||
else if (m_streams && false == shareable(m_model, reference.primitive))
|
||||
fault(std::format("primitive {} is in the geometry store, and shares its vertices or indices with another one", reference.primitive));
|
||||
}
|
||||
}
|
||||
@@ -1288,8 +1380,12 @@ read_result read(std::span<std::byte const> const File, model &Model, read_optio
|
||||
return file_reader{File, Options}.run(Model);
|
||||
}
|
||||
|
||||
std::vector<std::string> validate(model const &Model, std::size_t const Limit) {
|
||||
return validator{Model, Limit}.run();
|
||||
std::vector<std::string> validate(model const &Model, std::size_t const Limit, validate_scope const Scope) {
|
||||
return validator{Model, Limit, Scope}.run();
|
||||
}
|
||||
|
||||
read_result read_file(std::string const &Path, model &Model, read_options const &Options) {
|
||||
return file_reader::run_file(Path, Model, Options);
|
||||
}
|
||||
|
||||
} // namespace eu07m
|
||||
|
||||
+15
-1
@@ -38,17 +38,31 @@ struct read_options {
|
||||
// the blocks of the geometry store a model refers to (GREF), put back in its streams; a model with references and no source
|
||||
// is refused
|
||||
block_source blocks;
|
||||
// the vertex and index streams (VPOS VATT VSKN VSKW VUSR VBND IDX2 IDX4) and the blocks of the store. without them the model
|
||||
// has the rest, its structure, checked without what needs the streams (validate_scope::structure); the game reads the
|
||||
// streams of a streamed model later (modelstreaming)
|
||||
bool streams{true};
|
||||
};
|
||||
|
||||
struct read_result {
|
||||
bool ok{false};
|
||||
std::string error; // what is wrong with the file, when not ok
|
||||
std::uint64_t content_hash{0}; // from the header: the same file read again has the same one
|
||||
std::uint64_t stream_bytes{0}; // the vertex and index streams unpacked, as the file has them (without the blocks of the store)
|
||||
};
|
||||
|
||||
// reads the file into the model and checks it with validate(). a file which fails leaves the model empty
|
||||
read_result read(std::span<std::byte const> File, model &Model, read_options const &Options = {});
|
||||
// the same from the file at Path, reading only the parts of the file the options ask for: without the streams the structure
|
||||
// alone, a small part of a large model. the hash of the content isn't verified
|
||||
read_result read_file(std::string const &Path, model &Model, read_options const &Options = {});
|
||||
|
||||
enum class validate_scope {
|
||||
whole,
|
||||
structure, // what can be checked without the streams: their counts and ranges aren't
|
||||
};
|
||||
|
||||
// the faults of the model, each a line of text; empty when it can be used. stops after Limit faults
|
||||
std::vector<std::string> validate(model const &Model, std::size_t Limit = 16);
|
||||
std::vector<std::string> validate(model const &Model, std::size_t Limit = 16, validate_scope Scope = validate_scope::whole);
|
||||
|
||||
} // namespace eu07m
|
||||
|
||||
+149
-14
@@ -12,8 +12,10 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "model/Model3d.h"
|
||||
|
||||
#include "model/eu07m/eu07m_build.h"
|
||||
#include "model/eu07m/eu07m_geometry.h"
|
||||
#include "model/eu07m/eu07m_io.h"
|
||||
#include "rendering/renderer.h"
|
||||
#include "utilities/Globals.h"
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/utilities.h"
|
||||
#include "utilities/wholefile.h"
|
||||
@@ -23,6 +25,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
@@ -505,29 +509,137 @@ animation::channel make_channel(eu07m::model const &Model, std::uint32_t const C
|
||||
return channel;
|
||||
}
|
||||
|
||||
// the vertex and index streams of a streamed EU07M model (modelstreaming), read again from its file when its geometry bank needs them:
|
||||
// the chunks in the order of eu07m::drawn_primitives(), as LoadFromEU07M() makes them
|
||||
class streamed_geometry : public gfx::geometry_source {
|
||||
public:
|
||||
streamed_geometry(std::string Path, std::uint64_t const Hash, std::vector<unsigned int> Types) : m_path(std::move(Path)), m_hash(Hash), m_types(std::move(Types)) {}
|
||||
|
||||
bool load(gfx::bank_data &Data, bool const Plain, std::string &Error) const override {
|
||||
eu07m::model model;
|
||||
eu07m::read_options options{false, false};
|
||||
options.blocks = eu07m::store_source(eu07m::family_store(m_path));
|
||||
auto const result{eu07m::read_file(m_path, model, options)};
|
||||
if (false == result.ok) {
|
||||
Error = result.error;
|
||||
return false;
|
||||
}
|
||||
if (result.content_hash != m_hash) {
|
||||
Error = "the file changed since the model was loaded";
|
||||
return false;
|
||||
}
|
||||
auto const primitives{eu07m::drawn_primitives(model)};
|
||||
if (primitives.size() != m_types.size()) {
|
||||
Error = "the file has other parts than when the model was loaded";
|
||||
return false;
|
||||
}
|
||||
Data.clear();
|
||||
Data.resize(primitives.size());
|
||||
for (std::size_t idx = 0; idx < primitives.size(); ++idx)
|
||||
fill_chunk(model, primitives[idx], m_types[idx], Plain, Data[idx]);
|
||||
return true;
|
||||
}
|
||||
std::string const &name() const override {
|
||||
return m_path;
|
||||
}
|
||||
|
||||
private:
|
||||
// the chunk as finish_binary() makes it: the compact streams as they are (Insert_Compact()), or the vertices made of them, as a
|
||||
// renderer which draws basic_vertex only makes them
|
||||
static void fill_chunk(eu07m::model const &Model, std::uint32_t const Primitive, unsigned int const Type, bool const Plain, gfx::chunk_data &Chunk) {
|
||||
auto geometry{eu07m::geometry_of(Model, Primitive)};
|
||||
Chunk.indices = std::move(geometry.indices);
|
||||
Chunk.positions.resize(geometry.positions.size());
|
||||
Chunk.attributes.resize(geometry.vertex_attributes.size());
|
||||
if (false == geometry.positions.empty()) {
|
||||
std::memcpy(Chunk.positions.data(), geometry.positions.data(), geometry.positions.size() * sizeof(glm::vec3));
|
||||
std::memcpy(Chunk.attributes.data(), geometry.vertex_attributes.data(), geometry.vertex_attributes.size() * sizeof(gfx::compact_attributes));
|
||||
}
|
||||
Chunk.userdata.reserve(geometry.vertex_userdata.size());
|
||||
for (auto const &data : geometry.vertex_userdata)
|
||||
Chunk.userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}});
|
||||
if (false == Plain)
|
||||
return;
|
||||
Chunk.vertices = gfx::decode_compact(Chunk.positions, Chunk.attributes);
|
||||
gfx::position_array().swap(Chunk.positions);
|
||||
gfx::compact_array().swap(Chunk.attributes);
|
||||
// the opengl renderer works the tangents out anew for a chunk without indices (opengl46_renderer::Insert())
|
||||
if (Chunk.indices.empty())
|
||||
gfx::calculate_tangents(Chunk.vertices, gfx::index_array(), static_cast<int>(Type));
|
||||
}
|
||||
|
||||
std::string m_path;
|
||||
std::uint64_t m_hash;
|
||||
std::vector<unsigned int> m_types; // of the chunks
|
||||
};
|
||||
|
||||
// the kind of geometry of the chunk of a submodel, as finish_binary() gives it
|
||||
unsigned int chunk_type(TSubModel const &Submodel) {
|
||||
if (Submodel.eType == TP_FREESPOTLIGHT || Submodel.eType == TP_STARS)
|
||||
return GL_POINTS;
|
||||
return static_cast<unsigned int>(Submodel.eType);
|
||||
}
|
||||
|
||||
// what read_model() made of the file
|
||||
struct model_read {
|
||||
bool ok{false};
|
||||
bool streamed{false}; // only the structure was read, the streams are read when the model is drawn (modelstreaming)
|
||||
std::uint64_t hash{0}; // of the content of the file, which the reads of the streams check
|
||||
};
|
||||
|
||||
// the model read from its file: whole, or a scenery model of a file large enough (modelstreaming) by its structure alone. the size of
|
||||
// the file decides, so a smaller model is read once, whole, as without the streaming. returns: not ok with the reason in the log
|
||||
model_read read_model(std::string const &FileName, bool const Streamable, eu07m::model &Model) {
|
||||
model_read result;
|
||||
// the game has no use for the sections it doesn't know; the geometry shared by the family comes from the store of the folder
|
||||
eu07m::read_options options{false, false};
|
||||
options.blocks = eu07m::store_source(eu07m::family_store(FileName));
|
||||
std::error_code sizeerror;
|
||||
auto const filesize{std::filesystem::file_size(FileName, sizeerror)};
|
||||
auto const largeenough{(false == bool(sizeerror)) && (filesize >= static_cast<std::uint64_t>(std::max(0, Global.modelstreaming_minsize)) * 1024)};
|
||||
if (Streamable && largeenough && GfxRenderer->Streams_Geometry()) {
|
||||
auto structure{options};
|
||||
structure.streams = false;
|
||||
auto const structureread{eu07m::read_file(FileName, Model, structure)};
|
||||
if (false == structureread.ok) {
|
||||
ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + structureread.error, logtype::model);
|
||||
return result;
|
||||
}
|
||||
result.hash = structureread.content_hash;
|
||||
result.streamed = eu07m::not_streamable(Model).empty();
|
||||
if (result.streamed) {
|
||||
result.ok = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
auto const file{read_whole_file(FileName)};
|
||||
if (file.data == nullptr) {
|
||||
ErrorLog("Bad model: can't read \"" + FileName + "\"", logtype::model);
|
||||
return result;
|
||||
}
|
||||
if (auto const whole{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), Model, options)}; false == whole.ok) {
|
||||
ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + whole.error, logtype::model);
|
||||
return result;
|
||||
}
|
||||
result.ok = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) {
|
||||
WriteLog("Loading EU07M model data from \"" + FileName + "\"...", logtype::model);
|
||||
auto const file{read_whole_file(FileName)};
|
||||
if (file.data == nullptr) {
|
||||
ErrorLog("Bad model: can't read \"" + FileName + "\"", logtype::model);
|
||||
return false;
|
||||
}
|
||||
eu07m::model model;
|
||||
// the game has no use for the sections it doesn't know; the geometry shared by the family comes from the store of the folder
|
||||
model_read read;
|
||||
try {
|
||||
eu07m::read_options options{false, false};
|
||||
options.blocks = eu07m::store_source(eu07m::family_store(FileName));
|
||||
if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, options)}; false == result.ok) {
|
||||
ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + result.error, logtype::model);
|
||||
return false;
|
||||
}
|
||||
read = read_model(FileName, m_streamable, model);
|
||||
}
|
||||
catch (std::exception const &Error) {
|
||||
ErrorLog("Bad model: \"" + FileName + "\" can't be read: " + Error.what(), logtype::model);
|
||||
return false;
|
||||
}
|
||||
if (false == read.ok)
|
||||
return false;
|
||||
if (model.nodes.empty()) {
|
||||
ErrorLog("Bad model: \"" + FileName + "\" has no nodes", logtype::model);
|
||||
return false;
|
||||
@@ -546,7 +658,10 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) {
|
||||
try {
|
||||
for (std::uint32_t idx = 0; idx < model.nodes.size(); ++idx)
|
||||
builder.build(idx, Root[idx]);
|
||||
builder.fill_geometry();
|
||||
if (read.streamed)
|
||||
stream_geometry(FileName, model, read.hash);
|
||||
else
|
||||
builder.fill_geometry();
|
||||
}
|
||||
catch (std::exception const &Error) {
|
||||
// nothing of the model is kept, so its .e3d / .t3d is loaded in its place
|
||||
@@ -595,10 +710,30 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) {
|
||||
m_indexcount += builder.index_count;
|
||||
// the tangents come with the vertices
|
||||
finish_binary(dynamic, true);
|
||||
WriteLog("Finished loading EU07M model data from \"" + FileName + "\"", logtype::model);
|
||||
WriteLog(std::format("Finished loading EU07M model data from \"{}\"{}", FileName, m_streamed ? ", its geometry streamed" : ""), logtype::model);
|
||||
return true;
|
||||
}
|
||||
|
||||
// the geometry bank of the model takes the data of its chunks from the file when it's drawn (modelstreaming); the bounds of the nodes stand
|
||||
// for the vertices meanwhile
|
||||
void TModel3d::stream_geometry(std::string const &FileName, eu07m::model const &Model, std::uint64_t const Hash) {
|
||||
m_nodebounds.clear();
|
||||
m_nodebounds.reserve(Model.nodes.size());
|
||||
for (std::size_t idx = 0; idx < Model.nodes.size(); ++idx) {
|
||||
auto const &record{Model.bounds[idx]};
|
||||
std::array<glm::vec3, 2> const bounds{glm::vec3{record.min[0], record.min[1], record.min[2]}, glm::vec3{record.max[0], record.max[1], record.max[2]}};
|
||||
m_nodebounds.push_back(bounds);
|
||||
}
|
||||
std::vector<unsigned int> types;
|
||||
for (std::size_t idx = 0; idx < Model.nodes.size(); ++idx) {
|
||||
Root[idx].m_nodebounds = &m_nodebounds[idx];
|
||||
if (Root[idx].m_geometry.vertex_count > 0)
|
||||
types.push_back(chunk_type(Root[idx]));
|
||||
}
|
||||
GfxRenderer->Stream_Bank(m_geometrybank, std::make_shared<streamed_geometry>(FileName, Hash, std::move(types)));
|
||||
m_streamed = true;
|
||||
}
|
||||
|
||||
void TModel3d::ApplyEU07MLight(TSubModel &Submodel, eu07m::payload::light const &Light) {
|
||||
submodel_builder::light(Light, Submodel);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/common/memoryreport.h"
|
||||
|
||||
#include "audio/audiorenderer.h"
|
||||
#include "model/AnimModel.h"
|
||||
#include "model/MdlMngr.h"
|
||||
#include "model/Texture.h"
|
||||
#include "world/Track.h"
|
||||
#include "rendering/geometrybank.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "scene/scene.h"
|
||||
#include "simulation/simulation.h"
|
||||
#include "utilities/memorystats.h"
|
||||
|
||||
#include <format>
|
||||
|
||||
namespace gfx {
|
||||
|
||||
namespace {
|
||||
|
||||
double megabytes( std::uint64_t const Bytes ) {
|
||||
|
||||
return static_cast<double>( Bytes ) / ( 1024.0 * 1024.0 );
|
||||
}
|
||||
|
||||
// the world space vertices the shapes and the lines of the scenery keep, the transforms of the sleepers, the model instances
|
||||
struct scenery_memory {
|
||||
memory_count shapes;
|
||||
memory_count lines;
|
||||
memory_count sleepers;
|
||||
std::uint64_t instances { 0 };
|
||||
};
|
||||
|
||||
void count_cell( scene::basic_cell const &Cell, scenery_memory &Memory ) {
|
||||
|
||||
for( auto const *list : { &Cell.m_shapesopaque, &Cell.m_shapestranslucent } ) {
|
||||
for( auto const &shape : *list ) {
|
||||
++Memory.shapes.count;
|
||||
Memory.shapes.bytes += memory_of( shape.data().vertices ) + memory_of( shape.data().userdata );
|
||||
}
|
||||
}
|
||||
for( auto const &line : Cell.m_lines ) {
|
||||
++Memory.lines.count;
|
||||
Memory.lines.bytes += memory_of( line.data().vertices );
|
||||
}
|
||||
for( auto const *track : Cell.m_paths ) {
|
||||
if( track->m_sleeper_local_transforms.empty() ) { continue; }
|
||||
++Memory.sleepers.count;
|
||||
Memory.sleepers.bytes += memory_of( track->m_sleeper_local_transforms );
|
||||
}
|
||||
Memory.instances += Cell.m_instancesopaque.size() + Cell.m_instancetranslucent.size();
|
||||
}
|
||||
|
||||
scenery_memory count_scenery() {
|
||||
|
||||
scenery_memory memory;
|
||||
if( simulation::Region == nullptr ) { return memory; }
|
||||
for( auto const *section : simulation::Region->m_sections ) {
|
||||
if( section == nullptr ) { continue; }
|
||||
for( auto const &shape : section->m_shapes ) {
|
||||
++memory.shapes.count;
|
||||
memory.shapes.bytes += memory_of( shape.data().vertices ) + memory_of( shape.data().userdata );
|
||||
}
|
||||
for( auto const &cell : section->m_cells ) {
|
||||
count_cell( cell, memory );
|
||||
}
|
||||
}
|
||||
return memory;
|
||||
}
|
||||
|
||||
void report_heap( std::uint64_t const Committed, std::vector<std::string> &Lines ) {
|
||||
|
||||
if( false == heap_counting() ) {
|
||||
Lines.emplace_back( "heap: not counted (debug.memorystats yes)" );
|
||||
return;
|
||||
}
|
||||
auto const heap { query_heap_memory() };
|
||||
Lines.emplace_back( std::format( "heap: {:.1f} MB taken with new in {} blocks, the rest of the private memory {:.1f} MB (drivers, libraries)", megabytes( heap.bytes ), heap.blocks,
|
||||
megabytes( Committed > heap.bytes ? Committed - heap.bytes : 0 ) ) );
|
||||
auto const large { query_large_blocks() };
|
||||
std::size_t constexpr shown { 20 };
|
||||
for( std::size_t index = 0; ( index < large.sites.size() ) && ( index < shown ); ++index ) {
|
||||
auto const &site { large.sites[ index ] };
|
||||
Lines.emplace_back( std::format( " large blocks {:.1f} MB in {}: {}", megabytes( site.bytes ), site.blocks, site.place ) );
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<std::string> memory_report( texture_bank const *Textures, geometrybank_manager const &Geometry ) {
|
||||
|
||||
std::vector<std::string> lines;
|
||||
auto const process { query_process_memory() };
|
||||
if( process.valid ) {
|
||||
lines.emplace_back( std::format( "process: {:.1f} MB private, {:.1f} MB resident (peak {:.1f} MB)", megabytes( process.committed ), megabytes( process.resident ),
|
||||
megabytes( process.peak ) ) );
|
||||
}
|
||||
std::uint64_t accounted { 0 };
|
||||
if( Textures != nullptr ) {
|
||||
auto const textures { Textures->memory() };
|
||||
accounted += textures.cpu.bytes + textures.readahead.bytes;
|
||||
lines.emplace_back( std::format( "textures: {} keep their data in ram, {:.1f} MB; {} on the card, ~{:.1f} MB; read ahead {} {:.1f} MB, {} being read, {} not read till needed",
|
||||
textures.cpu.count, megabytes( textures.cpu.bytes ), textures.gpu.count, megabytes( textures.gpu.bytes ), textures.readahead.count, megabytes( textures.readahead.bytes ),
|
||||
textures.reading, textures.waiting ) );
|
||||
}
|
||||
auto const geometry { Geometry.memory() };
|
||||
accounted += geometry.vertices.bytes + geometry.indices.bytes + geometry.userdata.bytes;
|
||||
lines.emplace_back( std::format( "geometry banks: {}, {} chunks: vertices {:.1f} MB, indices {:.1f} MB, user data {:.1f} MB", geometry.banks, geometry.vertices.count,
|
||||
megabytes( geometry.vertices.bytes ), megabytes( geometry.indices.bytes ), megabytes( geometry.userdata.bytes ) ) );
|
||||
auto const streamed { geometry_streamer::instance().stats() };
|
||||
lines.emplace_back( std::format( " of them streamed: {} banks with their data, {:.1f} MB", streamed.resident, megabytes( streamed.bytes ) ) );
|
||||
auto const models { TModelsManager::memory() };
|
||||
accounted += models.submodels.bytes;
|
||||
lines.emplace_back( std::format( "models: {}, {} submodels, their own geometry {:.1f} MB", models.models, models.submodels.count, megabytes( models.submodels.bytes ) ) );
|
||||
auto const scenery { count_scenery() };
|
||||
accounted += scenery.shapes.bytes + scenery.lines.bytes + scenery.sleepers.bytes + scenery.instances * sizeof( TAnimModel );
|
||||
lines.emplace_back( std::format( "scenery: {} shapes {:.1f} MB, {} lines {:.1f} MB, sleepers of {} tracks {:.1f} MB, {} model instances {:.1f} MB", scenery.shapes.count,
|
||||
megabytes( scenery.shapes.bytes ), scenery.lines.count, megabytes( scenery.lines.bytes ), scenery.sleepers.count, megabytes( scenery.sleepers.bytes ), scenery.instances,
|
||||
megabytes( scenery.instances * sizeof( TAnimModel ) ) ) );
|
||||
auto const sounds { audio::renderer.buffers_memory() };
|
||||
accounted += sounds.bytes;
|
||||
lines.emplace_back( std::format( "sounds: {} buffers {:.1f} MB", sounds.count, megabytes( sounds.bytes ) ) );
|
||||
if( process.valid ) {
|
||||
lines.emplace_back( std::format( "counted above: {:.1f} MB of {:.1f} MB private, the rest {:.1f} MB", megabytes( accounted ), megabytes( process.committed ),
|
||||
megabytes( process.committed > accounted ? process.committed - accounted : 0 ) ) );
|
||||
}
|
||||
report_heap( process.committed, lines );
|
||||
return lines;
|
||||
}
|
||||
|
||||
} // namespace gfx
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// what the process and its parts keep in memory, in lines of text: the process as the system counts it, the copies of the textures
|
||||
// and of the geometry kept in the process, the models, the scenery, the sounds, and with debug.memorystats what the program took
|
||||
// with new and the places which took the large blocks. for the self-test (memory) of both renderers
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class texture_bank;
|
||||
|
||||
namespace gfx {
|
||||
|
||||
class geometrybank_manager;
|
||||
|
||||
std::vector<std::string> memory_report( texture_bank const *Textures, geometrybank_manager const &Geometry );
|
||||
|
||||
} // namespace gfx
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/common/modelprefetch.h"
|
||||
|
||||
#include "model/AnimModel.h"
|
||||
#include "model/Model3d.h"
|
||||
#include "world/Track.h"
|
||||
#include "rendering/renderer.h"
|
||||
#include "scene/scene.h"
|
||||
#include "simulation/simulation.h"
|
||||
#include "utilities/Globals.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
|
||||
namespace gfx {
|
||||
|
||||
namespace {
|
||||
|
||||
// the way the data has to arrive from, before the model is drawn (m)
|
||||
constexpr double prefetch_margin { 500.0 };
|
||||
// the cells gone through at a frame
|
||||
constexpr std::size_t cells_per_frame { 32 };
|
||||
constexpr std::size_t cells_per_section { ( scene::EU07_SECTIONSIZE / scene::EU07_CELLSIZE ) * ( scene::EU07_SECTIONSIZE / scene::EU07_CELLSIZE ) };
|
||||
|
||||
// what the instance will need when it's drawn from within the margin: the geometry of a streamed model, asked for by its distance, and
|
||||
// with Textures the data of its textures, read once until the instance is out of reach again
|
||||
bool prefetch_instance( TAnimModel &Instance, glm::dvec3 const &Camera, double const Drawrange, bool const Textures ) {
|
||||
|
||||
auto *model { Instance.Model() };
|
||||
if( ( model == nullptr ) || ( false == Instance.visible() ) ) { return false; }
|
||||
// as far as the walk of the scene draws it (scene_walk::Render( TAnimModel * )), and the margin
|
||||
auto const reach { std::min( std::sqrt( Instance.m_rangesquaredmax * Global.fDistanceFactor ), Drawrange ) + prefetch_margin };
|
||||
auto const distance { glm::length( Instance.location() - Camera ) };
|
||||
if( distance > reach ) {
|
||||
// out of reach the data may be let go of: read again the next time
|
||||
if( Textures && ( distance > reach + prefetch_margin ) ) {
|
||||
Instance.textures_prefetched( false );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if( model->streamed() ) {
|
||||
GfxRenderer->Touch_Bank( model->m_geometrybank, static_cast<float>( distance ) );
|
||||
}
|
||||
if( ( false == Textures ) || Instance.textures_prefetched() ) { return false; }
|
||||
Instance.textures_prefetched( true );
|
||||
GfxRenderer->Prefetch_Textures( model, Instance.Material(), Camera );
|
||||
return true;
|
||||
}
|
||||
|
||||
// the textures of the shapes and the tracks of the cell read ahead (gfx.textures.streaming), as the opengl renderer has them read
|
||||
// (Update_Texture_Prefetch()); asked for each time the cell is gone through, which costs nothing for the data read already
|
||||
void prefetch_scenery( scene::basic_cell const &Cell, glm::dvec3 const &Camera ) {
|
||||
|
||||
for( auto const *list : { &Cell.m_shapesopaque, &Cell.m_shapestranslucent } ) {
|
||||
for( auto const &shape : *list ) {
|
||||
GfxRenderer->Prefetch_Material( shape.data().material, Camera );
|
||||
}
|
||||
}
|
||||
for( auto const *track : Cell.m_paths ) {
|
||||
GfxRenderer->Prefetch_Material( track->m_material1, Camera );
|
||||
GfxRenderer->Prefetch_Material( track->m_material2, Camera );
|
||||
GfxRenderer->Prefetch_Material( track->m_sleeper_skin, Camera );
|
||||
if( track->SwitchExtension != nullptr ) {
|
||||
GfxRenderer->Prefetch_Material( track->SwitchExtension->m_material3, Camera );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// returns: the instances whose textures were asked for
|
||||
std::uint64_t prefetch_instances( scene::basic_cell::instance_sequence const &Instances, glm::dvec3 const &Camera, double const Drawrange, bool const Textures ) {
|
||||
|
||||
std::uint64_t textures { 0 };
|
||||
for( auto *instance : Instances ) {
|
||||
if( ( instance != nullptr ) && prefetch_instance( *instance, Camera, Drawrange, Textures ) ) {
|
||||
++textures;
|
||||
}
|
||||
}
|
||||
return textures;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
model_prefetch &
|
||||
model_prefetch::instance() {
|
||||
|
||||
static model_prefetch prefetch;
|
||||
return prefetch;
|
||||
}
|
||||
|
||||
void
|
||||
model_prefetch::update( glm::dvec3 const &Camera, bool const Whole ) {
|
||||
|
||||
auto *region { simulation::Region };
|
||||
if( region == nullptr ) { return; }
|
||||
auto const start { std::chrono::steady_clock::now() };
|
||||
// as far as the walk draws anything (scene_walk::Render( TAnimModel * )): the draw range and the 250 m it adds
|
||||
auto const drawrange { static_cast<double>( Global.BaseDrawRange ) * Global.fDistanceFactor + 250.0 };
|
||||
auto const range { drawrange + prefetch_margin };
|
||||
region->sections( Camera, static_cast<float>( range ), m_sections );
|
||||
auto const cellcount { m_sections.size() * cells_per_section };
|
||||
if( cellcount == 0 ) { return; }
|
||||
auto const steps { Whole ? cellcount : std::min( cells_per_frame, cellcount ) };
|
||||
auto const textures { GfxRenderer->Prefetches_Textures() };
|
||||
for( std::size_t step = 0; step < steps; ++step, ++m_cursor ) {
|
||||
auto const index { m_cursor % cellcount };
|
||||
auto *section { m_sections[ index / cells_per_section ] };
|
||||
if( section == nullptr ) { continue; }
|
||||
if( textures && ( index % cells_per_section == 0 ) && ( glm::length( section->m_area.center - Camera ) - section->m_area.radius <= range ) ) {
|
||||
// the shapes of the section, the terrain
|
||||
for( auto const &shape : section->m_shapes ) {
|
||||
GfxRenderer->Prefetch_Material( shape.data().material, Camera );
|
||||
}
|
||||
}
|
||||
auto const &cell { section->m_cells[ index % cells_per_section ] };
|
||||
if( ( false == cell.m_active ) || ( glm::length( cell.m_area.center - Camera ) - cell.m_area.radius > range ) ) { continue; }
|
||||
if( textures ) {
|
||||
prefetch_scenery( cell, Camera );
|
||||
}
|
||||
m_timing.textures += prefetch_instances( cell.m_instancesopaque, Camera, drawrange, textures );
|
||||
m_timing.textures += prefetch_instances( cell.m_instancetranslucent, Camera, drawrange, textures );
|
||||
}
|
||||
auto const spent { std::chrono::duration<double, std::milli>( std::chrono::steady_clock::now() - start ).count() };
|
||||
++m_timing.passes;
|
||||
m_timing.total += spent;
|
||||
m_timing.longest = std::max( m_timing.longest, spent );
|
||||
}
|
||||
|
||||
model_prefetch::timing
|
||||
model_prefetch::take_timing() {
|
||||
|
||||
auto const result { m_timing };
|
||||
m_timing = {};
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace gfx
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// the geometry of the streamed scenery models around the camera asked of the streamer ahead of their drawing, and kept while they're
|
||||
// near (modelstreaming, rendering/geometrystreamer.h): the cells within the draw range and a margin are gone through, a part of them
|
||||
// at a frame, and every model whose instance would be drawn from within the margin is asked for, the nearer the sooner. with
|
||||
// gfx.textures.streaming the data of the textures of the instances is read ahead too, where the renderer has it read so
|
||||
// (gfx_renderer::Prefetches_Textures())
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include <glm/vec3.hpp>
|
||||
|
||||
namespace scene {
|
||||
class basic_section;
|
||||
}
|
||||
|
||||
namespace gfx {
|
||||
|
||||
class model_prefetch {
|
||||
|
||||
public:
|
||||
static auto instance() -> model_prefetch &;
|
||||
// a part of the cells around the camera gone through, Whole: all of them at once (the start of the scenario). the main thread
|
||||
void update( glm::dvec3 const &Camera, bool const Whole );
|
||||
|
||||
// what the passes cost the main thread since the last call: passes, their time and the longest, in ms (the self-test)
|
||||
struct timing {
|
||||
std::uint64_t passes { 0 };
|
||||
double total { 0.0 };
|
||||
double longest { 0.0 };
|
||||
std::uint64_t textures { 0 }; // instances whose textures were asked for
|
||||
};
|
||||
auto take_timing() -> timing;
|
||||
|
||||
private:
|
||||
std::size_t m_cursor { 0 };
|
||||
timing m_timing;
|
||||
std::vector<scene::basic_section *> m_sections;
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
@@ -542,6 +542,8 @@ class scene_walk
|
||||
};
|
||||
std::unordered_map<scene::basic_cell::instance_bucket_key, walk_record, scene::basic_cell::instance_bucket_key_hash> m_walkrecords;
|
||||
int m_walkrankcutoff{0}; // Global.gfx_shadow_rank_cutoff the walks were made with
|
||||
// how many times the streamer had given banks their data when the walks were made (gfx::geometry_streamer::adoptions())
|
||||
std::uint64_t m_streamadoptions{0};
|
||||
// what the walks of the frame did, for the panel: walks made, of them not kept, walks taken from earlier frames, and the cpu time
|
||||
// of the walks and of putting the draws in order with their blocks uploaded
|
||||
struct walk_counts
|
||||
|
||||
@@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/.
|
||||
// queueing of buckets, the walks of the submodel trees of the culled groups and the order of the recorded draws
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/scenewalk.h"
|
||||
#include "rendering/common/walksync.h"
|
||||
|
||||
@@ -421,6 +422,12 @@ void scene_walk::Walk_Indirect_Draws(gfx::instance_cull const &Cull, bool const
|
||||
m_walkrecords.clear();
|
||||
m_walkrankcutoff = Global.gfx_shadow_rank_cutoff;
|
||||
}
|
||||
// and when a streamed model got its geometry (modelstreaming): a walk made while it hadn't it left its draws out
|
||||
if (auto const adoptions{gfx::geometry_streamer::instance().adoptions()}; adoptions != m_streamadoptions)
|
||||
{
|
||||
m_walkrecords.clear();
|
||||
m_streamadoptions = adoptions;
|
||||
}
|
||||
if (walkcache && ((m_framestamp % 256) == 0))
|
||||
{
|
||||
// the groups not drawn for a while
|
||||
|
||||
+236
-1
@@ -9,6 +9,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/geometrybank.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/walksync.h"
|
||||
#include "model/vertex.h"
|
||||
|
||||
#include "scene/sn_utils.h"
|
||||
@@ -493,6 +495,8 @@ geometry_bank::release() {
|
||||
index_array const &
|
||||
geometry_bank::indices( gfx::geometry_handle const &Geometry ) const {
|
||||
|
||||
// the data of a streamed bank is loaded for those who read it
|
||||
if( state() != residency::resident ) { load_now( false ); }
|
||||
return geometry_bank::chunk( Geometry ).indices;
|
||||
}
|
||||
|
||||
@@ -518,6 +522,7 @@ geometry_bank::positions( gfx::geometry_handle const &Geometry ) const {
|
||||
vertex_array const &
|
||||
geometry_bank::vertices( gfx::geometry_handle const &Geometry ) const {
|
||||
|
||||
if( state() != residency::resident ) { load_now( false ); }
|
||||
auto const &chunk { geometry_bank::chunk( Geometry ) };
|
||||
// made from the compact streams the first time something reads them (the simulation, the editor, the picking). under the lock
|
||||
// also for a chunk which isn't compact (any more): make_plain() may be turning it into basic_vertex on a thread drawing the bank
|
||||
@@ -549,9 +554,189 @@ geometry_bank::primitive( gfx::geometry_handle const &Geometry ) const {
|
||||
userdata_array const &
|
||||
geometry_bank::userdata( gfx::geometry_handle const &Geometry ) const {
|
||||
|
||||
if( state() != residency::resident ) { load_now( false ); }
|
||||
return geometry_bank::chunk( Geometry ).userdata;
|
||||
}
|
||||
|
||||
// the streaming of the geometry
|
||||
|
||||
void
|
||||
geometry_bank::stream_from( std::shared_ptr<geometry_source const> Source ) {
|
||||
|
||||
m_source = std::move( Source );
|
||||
m_residency.store( m_source != nullptr ? residency::absent : residency::resident, std::memory_order_release );
|
||||
}
|
||||
|
||||
// an empty chunk of a streamed bank, filled with the data of the bank
|
||||
gfx::geometry_handle
|
||||
geometry_bank::create_streamed( unsigned int const Type ) {
|
||||
|
||||
gfx::index_array indices;
|
||||
gfx::vertex_array vertices;
|
||||
gfx::userdata_array userdata;
|
||||
m_chunks.emplace_back( indices, vertices, userdata, Type );
|
||||
gfx::geometry_handle chunkhandle { 0, static_cast<std::uint32_t>( m_chunks.size() ) };
|
||||
create_( chunkhandle );
|
||||
return chunkhandle;
|
||||
}
|
||||
|
||||
// a bank about to be drawn
|
||||
bool
|
||||
geometry_bank::ready( float const Priority ) {
|
||||
|
||||
if( false == streamed() ) { return true; }
|
||||
touch( Priority );
|
||||
return ( state() == residency::resident );
|
||||
}
|
||||
|
||||
// a streamed bank noted as used, and asked of the streamer when its data isn't there
|
||||
void
|
||||
geometry_bank::touch( float const Priority ) {
|
||||
|
||||
if( false == streamed() ) { return; }
|
||||
m_lastused.store( geometry_streamer::now(), std::memory_order_relaxed );
|
||||
auto current { state() };
|
||||
// a bank whose load failed is asked for again once in a while: a read error that passes (an antivirus, a lock of the file)
|
||||
// doesn't leave the model undrawn till a restart
|
||||
if( ( current == residency::failed ) && retry_due_() ) {
|
||||
auto expected { residency::failed };
|
||||
if( m_residency.compare_exchange_strong( expected, residency::absent, std::memory_order_acq_rel ) ) {
|
||||
current = residency::absent;
|
||||
}
|
||||
}
|
||||
// a bank being loaded is asked for again only when it's wanted sooner, so the queue of the streamer isn't locked by every draw
|
||||
if( ( current == residency::absent )
|
||||
|| ( ( current == residency::loading ) && ( Priority < requested_priority() ) ) ) {
|
||||
geometry_streamer::instance().request( *this, Priority );
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
geometry_bank::note_failure_() {
|
||||
|
||||
m_failedat.store( geometry_streamer::now(), std::memory_order_relaxed );
|
||||
m_failures.fetch_add( 1, std::memory_order_relaxed );
|
||||
m_epoch.fetch_add( 1, std::memory_order_acq_rel );
|
||||
m_residency.store( residency::failed, std::memory_order_release );
|
||||
}
|
||||
|
||||
bool
|
||||
geometry_bank::retry_due_() const {
|
||||
|
||||
auto const failures { m_failures.load( std::memory_order_relaxed ) };
|
||||
auto const doublings { std::min<std::uint32_t>( failures > 0 ? failures - 1 : 0, 6 ) };
|
||||
auto const wait { std::min<std::uint32_t>( 5'000u << doublings, 300'000u ) };
|
||||
// the clock of the streamer counts milliseconds; the difference holds across its wrap
|
||||
return ( geometry_streamer::now() - m_failedat.load( std::memory_order_relaxed ) ) >= wait;
|
||||
}
|
||||
|
||||
// the streamer: a load begun for an absent bank
|
||||
bool
|
||||
geometry_bank::begin_load( float const Priority ) {
|
||||
|
||||
m_priority.store( Priority, std::memory_order_relaxed );
|
||||
auto expected { residency::absent };
|
||||
return m_residency.compare_exchange_strong( expected, residency::loading, std::memory_order_acq_rel );
|
||||
}
|
||||
|
||||
// the data taken by the chunks, with the locks held
|
||||
void
|
||||
geometry_bank::take_( bank_data &Data ) {
|
||||
|
||||
std::size_t bytes { 0 };
|
||||
for( std::size_t idx = 0; idx < m_chunks.size(); ++idx ) {
|
||||
auto &chunk { m_chunks[ idx ] };
|
||||
auto &data { Data[ idx ] };
|
||||
chunk.indices.swap( data.indices );
|
||||
chunk.positions.swap( data.positions );
|
||||
chunk.attributes.swap( data.attributes );
|
||||
chunk.vertices.swap( data.vertices );
|
||||
chunk.userdata.swap( data.userdata );
|
||||
bytes += memory_of( chunk.indices ) + memory_of( chunk.positions ) + memory_of( chunk.attributes ) + memory_of( chunk.vertices ) + memory_of( chunk.userdata );
|
||||
}
|
||||
m_databytes.store( bytes, std::memory_order_relaxed );
|
||||
m_lastused.store( geometry_streamer::now(), std::memory_order_relaxed );
|
||||
m_failures.store( 0, std::memory_order_relaxed );
|
||||
// a load begun before is of no use now
|
||||
m_epoch.fetch_add( 1, std::memory_order_acq_rel );
|
||||
m_residency.store( residency::resident, std::memory_order_release );
|
||||
adopted_();
|
||||
}
|
||||
|
||||
// the streamer: the data of a load taken, unless the bank was let go of or loaded since
|
||||
bool
|
||||
geometry_bank::adopt( bank_data &Data, std::uint32_t const Epoch ) {
|
||||
|
||||
std::scoped_lock lock { m_buildmutex, m_decodemutex };
|
||||
if( ( epoch() != Epoch )
|
||||
|| ( state() != residency::loading )
|
||||
|| ( Data.size() != m_chunks.size() ) ) {
|
||||
return false;
|
||||
}
|
||||
take_( Data );
|
||||
return true;
|
||||
}
|
||||
|
||||
// the streamer: the load failed
|
||||
bool
|
||||
geometry_bank::fail_load( std::uint32_t const Epoch ) {
|
||||
|
||||
std::scoped_lock lock { m_buildmutex, m_decodemutex };
|
||||
if( ( epoch() != Epoch ) || ( state() != residency::loading ) ) { return false; }
|
||||
note_failure_();
|
||||
return true;
|
||||
}
|
||||
|
||||
// the data of a streamed bank let go of
|
||||
void
|
||||
geometry_bank::evict() {
|
||||
|
||||
std::scoped_lock lock { m_buildmutex, m_decodemutex };
|
||||
if( ( false == streamed() ) || pinned() || ( state() != residency::resident ) ) { return; }
|
||||
for( auto &chunk : m_chunks ) {
|
||||
gfx::index_array().swap( chunk.indices );
|
||||
gfx::position_array().swap( chunk.positions );
|
||||
gfx::compact_array().swap( chunk.attributes );
|
||||
gfx::vertex_array().swap( chunk.vertices );
|
||||
gfx::userdata_array().swap( chunk.userdata );
|
||||
}
|
||||
m_databytes.store( 0, std::memory_order_relaxed );
|
||||
m_epoch.fetch_add( 1, std::memory_order_acq_rel );
|
||||
m_residency.store( residency::absent, std::memory_order_release );
|
||||
release_();
|
||||
}
|
||||
|
||||
// the data of a streamed bank loaded now by the thread which asks
|
||||
void
|
||||
geometry_bank::load_now( bool const Pin ) const {
|
||||
|
||||
if( false == streamed() ) { return; }
|
||||
// the data is a part of the bank as it's read, though not of what the bank is to those who read it: a const bank is filled too
|
||||
auto &bank { const_cast<geometry_bank &>( *this ) };
|
||||
std::scoped_lock loadlock { m_loadmutex };
|
||||
if( Pin ) {
|
||||
bank.m_pinned.store( true, std::memory_order_relaxed );
|
||||
}
|
||||
// a failed bank is read again here as touch() would ask for it again: once in a while
|
||||
if( auto const current { state() }; ( current == residency::resident ) || ( ( current == residency::failed ) && ( false == retry_due_() ) ) ) { return; }
|
||||
bank_data data;
|
||||
std::string error;
|
||||
auto const loaded { m_source->load( data, plain_layout(), error ) };
|
||||
// made while no walk of the passes draws (gfx::walk_sync)
|
||||
gfx::walk_sync::change change;
|
||||
std::scoped_lock lock { m_buildmutex, m_decodemutex };
|
||||
if( state() == residency::resident ) { return; }
|
||||
if( ( false == loaded ) || ( data.size() != m_chunks.size() ) ) {
|
||||
bank.note_failure_();
|
||||
if( failures() == 1 ) {
|
||||
geometry_streamer::instance().report_failure( m_source->name(), loaded ? std::string { "its parts aren't those it had when it was loaded" } : error );
|
||||
}
|
||||
return;
|
||||
}
|
||||
bank.take_( data );
|
||||
geometry_streamer::instance().register_resident( bank );
|
||||
}
|
||||
|
||||
// geometry bank manager, holds collection of geometry banks
|
||||
|
||||
// performs a resource sweep
|
||||
@@ -663,6 +848,8 @@ geometrybank_manager::draw( gfx::geometry_handle const &Geometry, unsigned int c
|
||||
auto &bankrecord = bank( Geometry );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
// a streamed bank without its data draws nothing meanwhile
|
||||
if( false == bankrecord.first->ready() ) { return; }
|
||||
m_primitivecount += bankrecord.first->draw( Geometry, m_units, Streams );
|
||||
}
|
||||
|
||||
@@ -676,6 +863,7 @@ geometrybank_manager::draw_instanced( gfx::geometry_handle const &Geometry, std:
|
||||
auto &bankrecord = bank( Geometry );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
if( false == bankrecord.first->ready() ) { return; }
|
||||
m_primitivecount += bankrecord.first->draw_instanced( Geometry, m_units, InstanceCount, BaseInstance, Streams );
|
||||
}
|
||||
|
||||
@@ -699,7 +887,9 @@ geometrybank_manager::draw_batch( gfx::geometry_handle const *First, gfx::geomet
|
||||
auto &bankrecord = bank( *First );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
m_primitivecount += bankrecord.first->draw_batch( First, last, m_units, Streams );
|
||||
if( true == bankrecord.first->ready() ) {
|
||||
m_primitivecount += bankrecord.first->draw_batch( First, last, m_units, Streams );
|
||||
}
|
||||
|
||||
First = last;
|
||||
}
|
||||
@@ -714,6 +904,7 @@ geometrybank_manager::indirect_source( gfx::geometry_handle const &Geometry, gfx
|
||||
auto &bankrecord = bank( Geometry );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
if( false == bankrecord.first->ready() ) { return false; }
|
||||
return bankrecord.first->indirect_source( Geometry, Source );
|
||||
}
|
||||
|
||||
@@ -726,6 +917,47 @@ geometrybank_manager::mark_used( gfx::geometry_handle const &Geometry ) {
|
||||
bank( Geometry ).second = m_garbagecollector.timestamp();
|
||||
}
|
||||
|
||||
// the streaming of the geometry: the chunks of the bank take their data from Source
|
||||
void
|
||||
geometrybank_manager::stream( gfx::geometrybank_handle const &Bank, std::shared_ptr<geometry_source const> Source ) {
|
||||
|
||||
if( false == valid( Bank ) ) { return; }
|
||||
bank( Bank ).first->stream_from( std::move( Source ) );
|
||||
}
|
||||
|
||||
// an empty chunk of a streamed bank
|
||||
gfx::geometry_handle
|
||||
geometrybank_manager::create_chunk_streamed( gfx::geometrybank_handle const &Bank, unsigned int const Type ) {
|
||||
|
||||
if( false == valid( Bank ) ) { return { 0, 0 }; }
|
||||
auto const newchunkhandle { bank( Bank ).first->create_streamed( Type ) };
|
||||
if( newchunkhandle.chunk != 0 ) { return { Bank.bank, newchunkhandle.chunk }; }
|
||||
else { return { 0, 0 }; }
|
||||
}
|
||||
|
||||
// the data of a streamed bank loaded now and kept for good
|
||||
void
|
||||
geometrybank_manager::pin( gfx::geometrybank_handle const &Bank ) {
|
||||
|
||||
if( false == valid( Bank ) ) { return; }
|
||||
bank( Bank ).first->load_now( true );
|
||||
}
|
||||
|
||||
// a streamed bank noted as used and asked for ahead of its drawing
|
||||
void
|
||||
geometrybank_manager::touch( gfx::geometrybank_handle const &Bank, float const Priority ) {
|
||||
|
||||
if( false == valid( Bank ) ) { return; }
|
||||
bank( Bank ).first->touch( Priority );
|
||||
}
|
||||
|
||||
// whether the bank is streamed
|
||||
bool
|
||||
geometrybank_manager::streamed( gfx::geometrybank_handle const &Bank ) const {
|
||||
|
||||
return valid( Bank ) && bank( Bank ).first->streamed();
|
||||
}
|
||||
|
||||
// draws geometry stored in specified chunk with the command at Offset in the bound draw indirect buffer
|
||||
void
|
||||
geometrybank_manager::draw_indirect( gfx::geometry_handle const &Geometry, std::intptr_t const Offset, unsigned int const Streams ) {
|
||||
@@ -735,6 +967,7 @@ geometrybank_manager::draw_indirect( gfx::geometry_handle const &Geometry, std::
|
||||
auto &bankrecord = bank( Geometry );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
if( false == bankrecord.first->ready() ) { return; }
|
||||
bankrecord.first->draw_indirect( Geometry, Offset, Streams );
|
||||
}
|
||||
|
||||
@@ -747,6 +980,8 @@ geometrybank_manager::draw_indirect_multi( gfx::geometry_handle const &Geometry,
|
||||
auto &bankrecord = bank( Geometry );
|
||||
|
||||
bankrecord.second = m_garbagecollector.timestamp();
|
||||
// nothing drawn, though the commands were taken: they're of chunks which aren't there
|
||||
if( false == bankrecord.first->ready() ) { return true; }
|
||||
return bankrecord.first->draw_indirect_multi( Geometry, Offset, Count, Stride );
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,11 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "utilities/memorystats.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
struct world_vertex;
|
||||
|
||||
@@ -93,6 +97,36 @@ using compact_array = std::vector<compact_attributes>;
|
||||
// the vertices the compact streams stand for (the normal and the tangent from the quaternion)
|
||||
auto decode_compact( position_array const &Positions, compact_array const &Attributes ) -> vertex_array;
|
||||
|
||||
// the data of a chunk of a streamed bank: the compact layout (positions and attributes) or basic_vertex, with indices or without
|
||||
struct chunk_data {
|
||||
index_array indices;
|
||||
position_array positions;
|
||||
compact_array attributes;
|
||||
vertex_array vertices;
|
||||
userdata_array userdata;
|
||||
};
|
||||
// the data of the chunks of a streamed bank, in the order the chunks were made in
|
||||
using bank_data = std::vector<chunk_data>;
|
||||
|
||||
// where a streamed bank takes the data of its chunks from (modelstreaming): read by a thread of the streamer before the bank is
|
||||
// drawn, or at once by the thread which reads its vertices
|
||||
class geometry_source {
|
||||
public:
|
||||
virtual ~geometry_source() = default;
|
||||
// the data of the chunks, in the compact layout or as basic_vertex (Plain). false with the reason when it can't be had. any thread
|
||||
virtual auto load( bank_data &Data, bool const Plain, std::string &Error ) const -> bool = 0;
|
||||
// what the data is of, for the log
|
||||
virtual auto name() const -> std::string const & = 0;
|
||||
};
|
||||
|
||||
// whether the data of a streamed bank is there
|
||||
enum class residency : std::uint8_t {
|
||||
resident, // in place, drawn and read; a bank which isn't streamed always is
|
||||
absent, // not loaded yet, or let go of
|
||||
loading, // asked of the streamer
|
||||
failed // it couldn't be had: the bank draws nothing
|
||||
};
|
||||
|
||||
void calculate_tangents( vertex_array &vertices, index_array const &indices, int const type );
|
||||
void calculate_indices( index_array &Indices, vertex_array &Vertices, userdata_array &Userdata, float tolerancescale = 1.0f );
|
||||
|
||||
@@ -196,6 +230,51 @@ public:
|
||||
auto primitive( gfx::geometry_handle const &Geometry ) const -> unsigned int;
|
||||
static constexpr unsigned int no_primitive { ~0u };
|
||||
|
||||
// the streaming of the geometry (modelstreaming, geometrystreamer.h)
|
||||
// the chunks of the bank take their data from Source when they're drawn or read, and let go of it when they're unused for a
|
||||
// while. set before the chunks are made (create_streamed())
|
||||
void stream_from( std::shared_ptr<geometry_source const> Source );
|
||||
// an empty chunk of a streamed bank, filled with the data of the bank. returns: handle to the chunk
|
||||
auto create_streamed( unsigned int const Type ) -> gfx::geometry_handle;
|
||||
auto streamed() const -> bool {
|
||||
return m_source != nullptr; }
|
||||
auto state() const -> gfx::residency {
|
||||
return m_residency.load( std::memory_order_acquire ); }
|
||||
// a bank about to be drawn: a streamed one is noted as used, and asked of the streamer when its data isn't there (the lower the
|
||||
// Priority, the sooner). returns: whether it can be drawn. any thread
|
||||
auto ready( float const Priority = 0.f ) -> bool;
|
||||
// a streamed bank noted as used, and asked of the streamer without being drawn (the prefetch). any thread
|
||||
void touch( float const Priority );
|
||||
// the data of a streamed bank loaded now by the thread which asks, unless it's there; Pin keeps it for good
|
||||
void load_now( bool const Pin ) const;
|
||||
// the streamer: a load begun for an absent bank. returns: false when the bank isn't absent
|
||||
auto begin_load( float const Priority ) -> bool;
|
||||
// the streamer: the data of a load begun at Epoch taken, unless the bank was let go of or loaded since. returns: whether it was taken
|
||||
auto adopt( bank_data &Data, std::uint32_t const Epoch ) -> bool;
|
||||
// the streamer: the load begun at Epoch failed, the bank stays without its data
|
||||
auto fail_load( std::uint32_t const Epoch ) -> bool;
|
||||
// the loads failed one after another since the bank last had its data: the first one is logged, those trying again aren't
|
||||
auto failures() const -> std::uint32_t {
|
||||
return m_failures.load( std::memory_order_relaxed ); }
|
||||
// the data of a streamed bank let go of, unless it's kept for good. the bank is asked for again when it's drawn
|
||||
void evict();
|
||||
auto epoch() const -> std::uint32_t {
|
||||
return m_epoch.load( std::memory_order_acquire ); }
|
||||
auto requested_priority() const -> float {
|
||||
return m_priority.load( std::memory_order_relaxed ); }
|
||||
auto last_used() const -> std::uint32_t {
|
||||
return m_lastused.load( std::memory_order_relaxed ); }
|
||||
auto pinned() const -> bool {
|
||||
return m_pinned.load( std::memory_order_relaxed ); }
|
||||
// the bytes of the data of the chunks, as the bank took them
|
||||
auto data_bytes() const -> std::size_t {
|
||||
return m_databytes.load( std::memory_order_relaxed ); }
|
||||
auto source() const -> std::shared_ptr<geometry_source const> const & {
|
||||
return m_source; }
|
||||
// the layout the data of the streamed bank is to come in
|
||||
auto plain_layout() const -> bool {
|
||||
return false == compact_layout_(); }
|
||||
|
||||
protected:
|
||||
// types:
|
||||
struct geometry_chunk {
|
||||
@@ -243,6 +322,34 @@ protected:
|
||||
geometrychunk_sequence m_chunks;
|
||||
// the vertices of the compact chunks made when they're first read, by one of the threads reading them at a time
|
||||
mutable std::mutex m_decodemutex;
|
||||
// the buffers made of the chunks by one of the threads drawing the bank at a time (vulkan), and the data of a streamed bank taken
|
||||
// or let go of meanwhile by none of them
|
||||
mutable std::mutex m_buildmutex;
|
||||
|
||||
private:
|
||||
// methods:
|
||||
// the data taken by the chunks, with the locks held
|
||||
void take_( bank_data &Data );
|
||||
// a streamed bank got its data (adopt(), load_now()): the subclass makes its buffers anew. by default they're let go of
|
||||
virtual void adopted_() { release_(); }
|
||||
// whether the data of a streamed bank is to come in the compact layout, which the subclass keeps on the gpu as it is
|
||||
virtual auto compact_layout_() const -> bool { return false; }
|
||||
// a load of a streamed bank failed, with the locks held: the bank draws nothing and is tried again later (retry_due_())
|
||||
void note_failure_();
|
||||
// whether a failed bank is to be tried again: 5 s after its first failure, twice as long after each one that follows, up to 5 min
|
||||
auto retry_due_() const -> bool;
|
||||
|
||||
// members:
|
||||
std::shared_ptr<geometry_source const> m_source; // of a streamed bank
|
||||
std::atomic<gfx::residency> m_residency { gfx::residency::resident };
|
||||
std::atomic<std::uint32_t> m_failedat { 0 }; // geometry_streamer::now() the last load failed at
|
||||
std::atomic<std::uint32_t> m_failures { 0 }; // the loads failed one after another since the bank last had its data
|
||||
std::atomic<std::uint32_t> m_epoch { 0 }; // changed each time the data is taken or let go of
|
||||
std::atomic<float> m_priority { 0.f }; // the one it was asked for with
|
||||
std::atomic<std::uint32_t> m_lastused { 0 }; // geometry_streamer::now() it was drawn or touched last
|
||||
std::atomic<bool> m_pinned { false };
|
||||
std::atomic<std::size_t> m_databytes { 0 };
|
||||
mutable std::mutex m_loadmutex; // load_now() by one thread at a time
|
||||
|
||||
private:
|
||||
// methods:
|
||||
@@ -319,6 +426,16 @@ public:
|
||||
auto draw_group( gfx::geometry_handle const &Geometry ) const -> std::uint32_t;
|
||||
// marks the bank of the chunk as used, as the draws do (the vulkan renderer marks the banks its walkers drew from, M2)
|
||||
void mark_used( gfx::geometry_handle const &Geometry );
|
||||
// the streaming of the geometry (geometry_bank::stream_from()): the chunks of the bank take their data from Source
|
||||
void stream( gfx::geometrybank_handle const &Bank, std::shared_ptr<geometry_source const> Source );
|
||||
// an empty chunk of a streamed bank. returns: handle to the chunk or NULL
|
||||
auto create_chunk_streamed( gfx::geometrybank_handle const &Bank, unsigned int const Type ) -> gfx::geometry_handle;
|
||||
// the data of a streamed bank loaded now and kept for good
|
||||
void pin( gfx::geometrybank_handle const &Bank );
|
||||
// a streamed bank noted as used and asked for ahead of its drawing (the prefetch); the lower the Priority, the sooner
|
||||
void touch( gfx::geometrybank_handle const &Bank, float const Priority );
|
||||
// whether the bank is streamed
|
||||
auto streamed( gfx::geometrybank_handle const &Bank ) const -> bool;
|
||||
template <typename Iterator_>
|
||||
void draw( Iterator_ First, Iterator_ Last, unsigned int const Streams = basic_streams ) {
|
||||
while( First != Last ) {
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
|
||||
#include "rendering/common/walksync.h"
|
||||
#include "utilities/Globals.h"
|
||||
#include "utilities/Logs.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace gfx {
|
||||
|
||||
namespace {
|
||||
|
||||
// what a frame hands to the banks at most: the bytes of their data (the vulkan renderer sends them to the gpu the next time it draws
|
||||
// them) and the time
|
||||
constexpr std::size_t frame_bytes { std::size_t { 64 } << 20 };
|
||||
constexpr std::chrono::milliseconds frame_time { 3 };
|
||||
// the banks with their data gone through by the sweep of a frame
|
||||
constexpr std::size_t sweep_count { 256 };
|
||||
// over the budget of the memory (modelstreaming.budget), a bank unused for this long is let go of before its time
|
||||
constexpr std::uint32_t over_budget_unused_ms { 2000 };
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
geometry_streamer &
|
||||
geometry_streamer::instance() {
|
||||
|
||||
static geometry_streamer streamer;
|
||||
return streamer;
|
||||
}
|
||||
|
||||
geometry_streamer::~geometry_streamer() {
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
std::uint32_t
|
||||
geometry_streamer::now() {
|
||||
|
||||
return instance().m_now.load( std::memory_order_relaxed );
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::start_threads() {
|
||||
|
||||
if( ( false == m_threads.empty() ) || m_stopped ) { return; }
|
||||
// the loads read the disk and unpack: a few threads, not to take the cores the frame needs
|
||||
auto const count { std::clamp( std::thread::hardware_concurrency() / 4u, 1u, 3u ) };
|
||||
for( unsigned idx = 0; idx < count; ++idx ) {
|
||||
m_threads.emplace_back( [ this ]( std::stop_token const Stop ) { work( Stop ); } );
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::request( geometry_bank &Bank, float const Priority ) {
|
||||
|
||||
std::scoped_lock lock { m_mutex };
|
||||
if( m_stopped ) { return; }
|
||||
if( auto const queued { m_queued.find( &Bank ) }; queued != m_queued.end() ) {
|
||||
// asked for sooner: put ahead
|
||||
if( Priority < queued->second->first.first ) {
|
||||
m_queue.erase( queued->second );
|
||||
queued->second = m_queue.emplace( queue_key { Priority, m_order++ }, &Bank ).first;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if( false == Bank.begin_load( Priority ) ) { return; }
|
||||
m_queued.emplace( &Bank, m_queue.emplace( queue_key { Priority, m_order++ }, &Bank ).first );
|
||||
start_threads();
|
||||
m_wake.notify_one();
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::work( std::stop_token const Stop ) {
|
||||
|
||||
while( false == Stop.stop_requested() ) {
|
||||
geometry_bank *bank { nullptr };
|
||||
{
|
||||
std::unique_lock lock { m_mutex };
|
||||
if( false == m_wake.wait( lock, Stop, [ this ]() { return false == m_queue.empty(); } ) ) {
|
||||
return; // stopped
|
||||
}
|
||||
auto const first { m_queue.begin() };
|
||||
bank = first->second;
|
||||
m_queued.erase( bank );
|
||||
m_queue.erase( first );
|
||||
++m_working;
|
||||
}
|
||||
// the epoch the load is of: a bank loaded or let go of meanwhile doesn't take it (geometry_bank::adopt())
|
||||
result done;
|
||||
done.bank = bank;
|
||||
done.epoch = bank->epoch();
|
||||
done.ok = bank->source()->load( done.data, bank->plain_layout(), done.error );
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_done.emplace_back( std::move( done ) );
|
||||
--m_working;
|
||||
}
|
||||
m_idle.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::hand_over_one( result &Result ) {
|
||||
|
||||
auto &bank { *Result.bank };
|
||||
if( false == Result.ok ) {
|
||||
if( false == bank.fail_load( Result.epoch ) ) {
|
||||
return; // loaded meanwhile by the thread which read it
|
||||
}
|
||||
++m_failed;
|
||||
if( bank.failures() == 1 ) {
|
||||
ErrorLog( std::format( "Bad model: the geometry of \"{}\" can't be loaded: {}", bank.source()->name(), Result.error ), logtype::model );
|
||||
}
|
||||
return;
|
||||
}
|
||||
if( false == bank.adopt( Result.data, Result.epoch ) ) {
|
||||
// loaded meanwhile by the thread which read it, or let go of
|
||||
return;
|
||||
}
|
||||
++m_loaded;
|
||||
m_adoptions.fetch_add( 1, std::memory_order_acq_rel );
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_resident.push_back( &bank );
|
||||
}
|
||||
|
||||
std::size_t
|
||||
geometry_streamer::hand_over( std::size_t const Bytes, std::chrono::steady_clock::duration const Time ) {
|
||||
|
||||
auto const start { std::chrono::steady_clock::now() };
|
||||
std::size_t handed { 0 };
|
||||
while( true ) {
|
||||
result done;
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
if( m_done.empty() ) { break; }
|
||||
done = std::move( m_done.front() );
|
||||
m_done.pop_front();
|
||||
}
|
||||
{
|
||||
// the chunks of the bank change while no walk of the passes draws (gfx::walk_sync)
|
||||
gfx::walk_sync::change change;
|
||||
hand_over_one( done );
|
||||
}
|
||||
handed += done.bank->data_bytes();
|
||||
if( ( Bytes > 0 ) && ( ( handed >= Bytes ) || ( std::chrono::steady_clock::now() - start >= Time ) ) ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return handed;
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::update() {
|
||||
|
||||
m_now.store( static_cast<std::uint32_t>( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - m_start ).count() ), std::memory_order_relaxed );
|
||||
hand_over( frame_bytes, frame_time );
|
||||
report_failures();
|
||||
sweep();
|
||||
}
|
||||
|
||||
std::size_t
|
||||
geometry_streamer::finish( std::chrono::milliseconds const Timeout ) {
|
||||
|
||||
auto const deadline { std::chrono::steady_clock::now() + Timeout };
|
||||
while( true ) {
|
||||
hand_over( 0, {} );
|
||||
report_failures();
|
||||
std::unique_lock lock { m_mutex };
|
||||
auto const left { m_queue.size() + m_working + m_done.size() };
|
||||
if( ( left == 0 ) || ( std::chrono::steady_clock::now() >= deadline ) ) {
|
||||
return left;
|
||||
}
|
||||
m_idle.wait_for( lock, std::chrono::milliseconds { 50 } );
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t
|
||||
geometry_streamer::pending() const {
|
||||
|
||||
std::scoped_lock lock { m_mutex };
|
||||
return m_queue.size() + m_working + m_done.size();
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::register_resident( geometry_bank &Bank ) {
|
||||
|
||||
m_adoptions.fetch_add( 1, std::memory_order_acq_rel );
|
||||
std::scoped_lock lock { m_mutex };
|
||||
++m_loaded;
|
||||
m_resident.push_back( &Bank );
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::report_failure( std::string_view const Name, std::string_view const Error ) {
|
||||
|
||||
std::scoped_lock lock { m_mutex };
|
||||
++m_failed;
|
||||
m_failures.emplace_back( std::format( "Bad model: the geometry of \"{}\" can't be loaded: {}", Name, Error ) );
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::report_failures() {
|
||||
|
||||
std::vector<std::string> failures;
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
failures.swap( m_failures );
|
||||
}
|
||||
for( auto const &failure : failures ) {
|
||||
ErrorLog( failure, logtype::model );
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::sweep() {
|
||||
|
||||
std::vector<geometry_bank *> unused;
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
if( m_resident.empty() ) { return; }
|
||||
auto const clock { now() };
|
||||
auto const lifetime { static_cast<std::uint32_t>( std::max( 0.f, Global.modelstreaming_evictafter ) * 1000.f ) };
|
||||
std::size_t bytes { 0 };
|
||||
if( Global.modelstreaming_budget > 0 ) {
|
||||
for( auto const *bank : m_resident ) {
|
||||
bytes += bank->data_bytes();
|
||||
}
|
||||
}
|
||||
auto const overbudget { ( Global.modelstreaming_budget > 0 ) && ( bytes > ( static_cast<std::size_t>( Global.modelstreaming_budget ) << 20 ) ) };
|
||||
auto const limit { overbudget ? std::min( lifetime, over_budget_unused_ms ) : lifetime };
|
||||
for( std::size_t step = 0; ( step < sweep_count ) && ( false == m_resident.empty() ); ++step ) {
|
||||
if( m_sweepcursor >= m_resident.size() ) {
|
||||
m_sweepcursor = 0;
|
||||
}
|
||||
auto *bank { m_resident[ m_sweepcursor ] };
|
||||
auto const gone { bank->state() != residency::resident };
|
||||
auto const stale { ( false == gone ) && ( false == bank->pinned() ) && ( clock - bank->last_used() > limit ) };
|
||||
if( false == ( gone || stale ) ) {
|
||||
++m_sweepcursor;
|
||||
continue;
|
||||
}
|
||||
if( stale ) {
|
||||
unused.push_back( bank );
|
||||
}
|
||||
m_resident[ m_sweepcursor ] = m_resident.back();
|
||||
m_resident.pop_back();
|
||||
}
|
||||
}
|
||||
if( unused.empty() ) { return; }
|
||||
// the chunks of the banks change while no walk of the passes draws (gfx::walk_sync)
|
||||
gfx::walk_sync::change change;
|
||||
for( auto *bank : unused ) {
|
||||
bank->evict();
|
||||
}
|
||||
m_evicted += unused.size();
|
||||
}
|
||||
|
||||
std::size_t
|
||||
geometry_streamer::evict_all() {
|
||||
|
||||
std::vector<geometry_bank *> banks;
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
banks.swap( m_resident );
|
||||
m_sweepcursor = 0;
|
||||
}
|
||||
std::size_t evicted { 0 };
|
||||
gfx::walk_sync::change change;
|
||||
for( auto *bank : banks ) {
|
||||
if( bank->pinned() || ( bank->state() != residency::resident ) ) {
|
||||
if( bank->state() == residency::resident ) {
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_resident.push_back( bank );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
bank->evict();
|
||||
++evicted;
|
||||
}
|
||||
m_evicted += evicted;
|
||||
return evicted;
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::stop() {
|
||||
|
||||
std::vector<std::jthread> threads;
|
||||
{
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_stopped = true;
|
||||
threads.swap( m_threads );
|
||||
}
|
||||
for( auto &thread : threads ) {
|
||||
thread.request_stop();
|
||||
}
|
||||
m_wake.notify_all();
|
||||
threads.clear(); // joined here
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_queue.clear();
|
||||
m_queued.clear();
|
||||
m_done.clear();
|
||||
m_resident.clear();
|
||||
}
|
||||
|
||||
void
|
||||
geometry_streamer::resume() {
|
||||
|
||||
std::scoped_lock lock { m_mutex };
|
||||
m_stopped = false;
|
||||
}
|
||||
|
||||
geometry_streamer::statistics
|
||||
geometry_streamer::stats() const {
|
||||
|
||||
statistics values;
|
||||
std::scoped_lock lock { m_mutex };
|
||||
values.resident = m_resident.size();
|
||||
for( auto const *bank : m_resident ) {
|
||||
values.bytes += bank->data_bytes();
|
||||
}
|
||||
values.pending = m_queue.size() + m_working + m_done.size();
|
||||
values.loaded = m_loaded;
|
||||
values.evicted = m_evicted;
|
||||
values.failed = m_failed;
|
||||
return values;
|
||||
}
|
||||
|
||||
} // namespace gfx
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// the streaming of the geometry of the scenery models (modelstreaming): a streamed geometry bank is made with its chunks empty, and
|
||||
// its data is read and unpacked by the threads of the streamer when the bank is about to be drawn (or ahead of it, the prefetch),
|
||||
// handed to the bank by the main thread a few at a frame, and let go of once the bank isn't drawn for a while. what reads the vertices
|
||||
// of a bank without its data loads them at once (geometry_bank::load_now())
|
||||
|
||||
#include "rendering/geometrybank.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <stop_token>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace gfx {
|
||||
|
||||
class geometry_streamer {
|
||||
|
||||
public:
|
||||
geometry_streamer() = default;
|
||||
~geometry_streamer();
|
||||
geometry_streamer( geometry_streamer const & ) = delete;
|
||||
geometry_streamer &operator=( geometry_streamer const & ) = delete;
|
||||
|
||||
static auto instance() -> geometry_streamer &;
|
||||
// the clock the banks note their use with, in milliseconds; moved on by update()
|
||||
static auto now() -> std::uint32_t;
|
||||
|
||||
// a load of the bank asked for, or asked for sooner (the lower the Priority, the sooner). any thread
|
||||
void request( geometry_bank &Bank, float const Priority );
|
||||
// the main thread, once a frame, while no walk draws: the loads done handed to their banks as far as the budget of the frame goes,
|
||||
// and the banks unused for a while let go of
|
||||
void update();
|
||||
// the loads done handed over at once, the ones under way waited for, till none is left or Timeout passes (the loading screen).
|
||||
// returns: the loads left
|
||||
auto finish( std::chrono::milliseconds const Timeout ) -> std::size_t;
|
||||
// the loads asked for and not handed over yet
|
||||
auto pending() const -> std::size_t;
|
||||
// a bank which got its data by itself (geometry_bank::load_now()), let go of with the others
|
||||
void register_resident( geometry_bank &Bank );
|
||||
// the data of every streamed bank which isn't kept for good let go of (the self-test: modelstream evict). the main thread
|
||||
auto evict_all() -> std::size_t;
|
||||
// a load which failed, told in the log by the main thread. any thread
|
||||
void report_failure( std::string_view const Name, std::string_view const Error );
|
||||
// the threads ended and the loads dropped, before the banks go (the renderer is closed)
|
||||
void stop();
|
||||
// the loads taken again after stop(), by a renderer made after another one closed (vulkan falling back to opengl as it starts,
|
||||
// before any bank is made); the threads start with the first request
|
||||
void resume();
|
||||
// how many times banks were given their data. the walks kept by the gpu culling, made while a bank had none, are made anew when
|
||||
// it changes
|
||||
auto adoptions() const -> std::uint64_t {
|
||||
return m_adoptions.load( std::memory_order_acquire ); }
|
||||
|
||||
struct statistics {
|
||||
std::size_t resident { 0 }; // banks with their data
|
||||
std::size_t bytes { 0 }; // of their data
|
||||
std::size_t pending { 0 };
|
||||
std::uint64_t loaded { 0 }; // since the start
|
||||
std::uint64_t evicted { 0 };
|
||||
std::uint64_t failed { 0 };
|
||||
};
|
||||
auto stats() const -> statistics;
|
||||
|
||||
private:
|
||||
// types
|
||||
// a bank asked for: by the priority, then in the order of the requests
|
||||
using queue_key = std::pair<float, std::uint64_t>;
|
||||
using queue_map = std::map<queue_key, geometry_bank *>;
|
||||
struct result {
|
||||
geometry_bank *bank { nullptr };
|
||||
std::uint32_t epoch { 0 };
|
||||
bank_data data;
|
||||
bool ok { false };
|
||||
std::string error;
|
||||
};
|
||||
|
||||
// methods
|
||||
void start_threads();
|
||||
void work( std::stop_token const Stop );
|
||||
// the results handed to their banks, at most Bytes of them (0: all). returns: the bytes handed over
|
||||
auto hand_over( std::size_t const Bytes, std::chrono::steady_clock::duration const Time ) -> std::size_t;
|
||||
void hand_over_one( result &Result );
|
||||
// a part of the banks with their data gone through, the ones unused for a while let go of
|
||||
void sweep();
|
||||
void report_failures();
|
||||
|
||||
// members
|
||||
mutable std::mutex m_mutex;
|
||||
std::condition_variable_any m_wake; // a request for the threads
|
||||
std::condition_variable m_idle; // a load done
|
||||
queue_map m_queue;
|
||||
std::unordered_map<geometry_bank *, queue_map::iterator> m_queued;
|
||||
std::uint64_t m_order { 0 };
|
||||
std::size_t m_working { 0 }; // loads under way
|
||||
std::deque<result> m_done;
|
||||
std::vector<std::jthread> m_threads;
|
||||
bool m_stopped { false };
|
||||
std::vector<geometry_bank *> m_resident; // the banks with their data, for the sweep
|
||||
std::size_t m_sweepcursor { 0 };
|
||||
std::vector<std::string> m_failures;
|
||||
std::atomic<std::uint64_t> m_adoptions { 0 };
|
||||
std::chrono::steady_clock::time_point const m_start { std::chrono::steady_clock::now() };
|
||||
std::atomic<std::uint32_t> m_now { 0 }; // now(), since m_start
|
||||
std::atomic<std::uint64_t> m_loaded { 0 };
|
||||
std::atomic<std::uint64_t> m_evicted { 0 };
|
||||
std::atomic<std::uint64_t> m_failed { 0 };
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
@@ -8,6 +8,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/common/memoryreport.h"
|
||||
#include "rendering/opengl46/opengl46renderer.h"
|
||||
#include "rendering/common/shadersource.h"
|
||||
#include "utilities/color.h"
|
||||
@@ -507,6 +509,8 @@ bool opengl46_renderer::Init(GLFWwindow *Window)
|
||||
|
||||
void opengl46_renderer::Shutdown()
|
||||
{
|
||||
// the loads of the streamed geometry end before the banks they're for go
|
||||
gfx::geometry_streamer::instance().stop();
|
||||
vr.reset();
|
||||
}
|
||||
|
||||
@@ -3295,6 +3299,38 @@ gfx::geometry_handle opengl46_renderer::Insert(gfx::vertex_array &Vertices, gfx:
|
||||
return m_geometry.create_chunk(Vertices, Userdata, Geometry, Type);
|
||||
}
|
||||
|
||||
// the streaming of the geometry (modelstreaming): the banks of the streamed models get their data as basic_vertex, made by the threads
|
||||
// of the streamer
|
||||
std::vector<std::string> opengl46_renderer::Memory_Report()
|
||||
{
|
||||
return gfx::memory_report( &m_textures, m_geometry );
|
||||
}
|
||||
|
||||
bool opengl46_renderer::Streams_Geometry() const
|
||||
{
|
||||
return Global.modelstreaming;
|
||||
}
|
||||
|
||||
void opengl46_renderer::Stream_Bank( gfx::geometrybank_handle const &Bank, std::shared_ptr<gfx::geometry_source const> Source )
|
||||
{
|
||||
m_geometry.stream( Bank, std::move( Source ) );
|
||||
}
|
||||
|
||||
gfx::geometry_handle opengl46_renderer::Insert_Streamed( gfx::geometrybank_handle const &Bank, int const Type )
|
||||
{
|
||||
return m_geometry.create_chunk_streamed( Bank, Type );
|
||||
}
|
||||
|
||||
void opengl46_renderer::Pin_Bank( gfx::geometrybank_handle const &Bank )
|
||||
{
|
||||
m_geometry.pin( Bank );
|
||||
}
|
||||
|
||||
void opengl46_renderer::Touch_Bank( gfx::geometrybank_handle const &Bank, float const Priority )
|
||||
{
|
||||
m_geometry.touch( Bank, Priority );
|
||||
}
|
||||
|
||||
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
|
||||
bool opengl46_renderer::Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset)
|
||||
{
|
||||
|
||||
@@ -89,6 +89,13 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk {
|
||||
gfx::geometry_handle Insert(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override;
|
||||
// creates a new geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL
|
||||
gfx::geometry_handle Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override;
|
||||
std::vector<std::string> Memory_Report() override;
|
||||
// the streaming of the geometry (modelstreaming)
|
||||
bool Streams_Geometry() const override;
|
||||
void Stream_Bank( gfx::geometrybank_handle const &Bank, std::shared_ptr<gfx::geometry_source const> Source ) override;
|
||||
gfx::geometry_handle Insert_Streamed( gfx::geometrybank_handle const &Bank, int const Type ) override;
|
||||
void Pin_Bank( gfx::geometrybank_handle const &Bank ) override;
|
||||
void Touch_Bank( gfx::geometrybank_handle const &Bank, float const Priority ) override;
|
||||
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
|
||||
bool Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset = 0) override;
|
||||
// replaces the index and the vertex data of specified indexed chunk with the supplied data of the same counts
|
||||
|
||||
@@ -115,6 +115,33 @@ public:
|
||||
gfx::position_array().swap( Positions );
|
||||
gfx::compact_array().swap( Attributes );
|
||||
return Indices.empty() ? Insert( vertices, Userdata, Geometry, Type ) : Insert( Indices, vertices, Userdata, Geometry, Type ); }
|
||||
// what the process and its parts keep in memory, in lines of text (rendering/common/memoryreport.h), for the self-test
|
||||
virtual auto Memory_Report() -> std::vector<std::string> { return {}; }
|
||||
// the streaming of the geometry of the scenery models (modelstreaming, rendering/geometrystreamer.h). whether the renderer streams
|
||||
virtual auto Streams_Geometry() const -> bool { return false; }
|
||||
// the chunks of the bank take their data from Source when they're drawn or read, and let go of it when unused for a while. made
|
||||
// before the chunks of the bank (Insert_Streamed())
|
||||
virtual void Stream_Bank( gfx::geometrybank_handle const & /*Bank*/, std::shared_ptr<gfx::geometry_source const> /*Source*/ ) {}
|
||||
// an empty chunk of a streamed bank, filled with the data of the bank. returns: handle to the chunk or NULL
|
||||
virtual auto Insert_Streamed( gfx::geometrybank_handle const & /*Bank*/, int const /*Type*/ ) -> gfx::geometry_handle { return {}; }
|
||||
// the data of a streamed bank loaded now and kept for good (a model of a vehicle which was streamed for the scenery)
|
||||
virtual void Pin_Bank( gfx::geometrybank_handle const & /*Bank*/ ) {}
|
||||
// a streamed bank asked for ahead of its drawing (the prefetch), and kept meanwhile; the lower the Priority, the sooner
|
||||
virtual void Touch_Bank( gfx::geometrybank_handle const & /*Bank*/, float const /*Priority*/ ) {}
|
||||
// the streaming of the textures (gfx.textures.streaming): whether the renderer reads the textures of the models ahead through
|
||||
// Prefetch_Textures(), which the prefetch of the models calls (rendering/common/modelprefetch.h). the opengl renderer goes through
|
||||
// the cells for them itself
|
||||
virtual auto Prefetches_Textures() const -> bool { return false; }
|
||||
// the data of the textures of the model and of the replaceable skins read ahead of their drawing, by the workers of the textures
|
||||
virtual void Prefetch_Textures( TModel3d * /*Model*/, material_data const * /*Skins*/, glm::dvec3 const & /*Origin*/ ) {}
|
||||
// the data of the textures of the material read ahead of its drawing (the shapes and the tracks of the scenery)
|
||||
virtual void Prefetch_Material( material_handle const /*Material*/, glm::dvec3 const & /*Origin*/ ) {}
|
||||
// the textures whose data the workers are reading now (gfx.textures.streaming), for the loading screen
|
||||
virtual auto Textures_Being_Read() const -> std::size_t { return 0; }
|
||||
// the textures read ahead around the start made on the gpu before the simulation starts (the loading screen): Collect, while the
|
||||
// prefetch goes through the area, gathers them; Make_Start_Textures() has them made and returns how many aren't made yet
|
||||
virtual void Collect_Start_Textures( bool const /*Collect*/ ) {}
|
||||
virtual auto Make_Start_Textures() -> std::size_t { return 0; }
|
||||
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
|
||||
virtual auto Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset = 0) -> bool = 0;
|
||||
// replaces the index and the vertex data of specified indexed chunk with the supplied data of the same counts.
|
||||
|
||||
@@ -28,6 +28,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
#include "model/Model3d.h"
|
||||
#include "model/AnimModel.h"
|
||||
#include "utilities/Globals.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/Timer.h"
|
||||
#include "utilities/utilities.h"
|
||||
@@ -4717,6 +4719,114 @@ void vulkan14_renderer::update_texture_release()
|
||||
textures.release_unneeded();
|
||||
}
|
||||
|
||||
// the streaming of the textures (gfx.textures.streaming): the data of the textures of the models read ahead of their drawing by the
|
||||
// workers of the textures, as the opengl renderer has it read (Update_Texture_Prefetch()), and let go of when it isn't drawn
|
||||
bool vulkan14_renderer::Prefetches_Textures() const
|
||||
{
|
||||
return Global.gfx_texture_streaming && m_context && m_context->textures;
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Prefetch_Textures(TModel3d *Model, material_data const *Skins, glm::dvec3 const &Origin)
|
||||
{
|
||||
if (false == Prefetches_Textures())
|
||||
{
|
||||
return;
|
||||
}
|
||||
auto &textures{*m_context->textures};
|
||||
if (Model != nullptr)
|
||||
{
|
||||
for (auto const texture : Model_Textures(Model))
|
||||
{
|
||||
textures.prefetch(texture, Origin);
|
||||
if (m_collectstart)
|
||||
{
|
||||
m_starttextures.push_back(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Skins == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (auto const skin : Skins->replacable_skins)
|
||||
{
|
||||
Prefetch_Material(skin, Origin);
|
||||
}
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Prefetch_Material(material_handle const Material, glm::dvec3 const &Origin)
|
||||
{
|
||||
if ((Material <= 0) || (false == Prefetches_Textures()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
auto &textures{*m_context->textures};
|
||||
auto const &material{m_materials.material(Material)};
|
||||
auto const prefetch{[this, &textures, &Origin](texture_handle const Texture) {
|
||||
textures.prefetch(Texture, Origin);
|
||||
if (m_collectstart && (Texture > 0))
|
||||
{
|
||||
m_starttextures.push_back(Texture);
|
||||
}
|
||||
}};
|
||||
for (auto const texture : material.textures)
|
||||
{
|
||||
prefetch(texture);
|
||||
}
|
||||
for (auto const &variant : material.texture_variants)
|
||||
{
|
||||
for (auto const texture : variant)
|
||||
{
|
||||
prefetch(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Collect_Start_Textures(bool const Collect)
|
||||
{
|
||||
m_collectstart = Collect && Prefetches_Textures();
|
||||
if (m_collectstart)
|
||||
{
|
||||
m_starttextures.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
// each once
|
||||
std::ranges::sort(m_starttextures);
|
||||
auto const [first, last]{std::ranges::unique(m_starttextures)};
|
||||
m_starttextures.erase(first, last);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t vulkan14_renderer::Make_Start_Textures()
|
||||
{
|
||||
if (m_starttextures.empty() || (false == Prefetches_Textures()))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
std::size_t left{0};
|
||||
for (auto const handle : m_starttextures)
|
||||
{
|
||||
auto &texture{static_cast<vk14::vulkan14_texture &>(m_context->textures->texture(handle))};
|
||||
if (texture.made())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
++left;
|
||||
texture.request_background(false);
|
||||
}
|
||||
if (left == 0)
|
||||
{
|
||||
m_starttextures.clear();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
std::size_t vulkan14_renderer::Textures_Being_Read() const
|
||||
{
|
||||
return Prefetches_Textures() ? static_cast<std::size_t>(m_context->textures->memory().reading) : 0;
|
||||
}
|
||||
|
||||
std::vector<texture_handle> const &vulkan14_renderer::Model_Textures(TModel3d *Model)
|
||||
{
|
||||
auto const lookup{m_modeltextures.find(Model)};
|
||||
|
||||
@@ -319,7 +319,12 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
// a streamed bank without its data draws nothing meanwhile; it's asked of the streamer
|
||||
if (false == ready())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::scoped_lock lock(m_buildmutex);
|
||||
// a bank of the compact layout whose programs can't be had is made anew of basic_vertex
|
||||
if (m_layoutdirty || (m_compact && (false == compact_layout_usable())))
|
||||
{
|
||||
|
||||
@@ -98,6 +98,11 @@ class vulkan14_geometrybank : public gfx::geometry_bank
|
||||
}
|
||||
bool indirect_source_(gfx::geometry_handle const &Geometry, gfx::indirect_source &Source) override;
|
||||
void release_() override;
|
||||
// a streamed bank keeps the compact layout of an EU07M model on the gpu as it is
|
||||
bool compact_layout_() const override
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// the buffers made anew for all the chunks
|
||||
bool build();
|
||||
// the chunks changed in place copied to the buffers
|
||||
@@ -126,8 +131,7 @@ class vulkan14_geometrybank : public gfx::geometry_bank
|
||||
bool m_failed{false};
|
||||
std::chrono::steady_clock::time_point m_failedat{};
|
||||
VkDeviceSize m_bytes{0};
|
||||
// the buffers made or updated by one of the threads drawing from the bank at a time
|
||||
std::mutex m_mutex;
|
||||
// the buffers are made or updated by one of the threads drawing from the bank at a time (gfx::geometry_bank::m_buildmutex)
|
||||
};
|
||||
|
||||
} // namespace vk14
|
||||
|
||||
@@ -8,6 +8,7 @@ http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/geometrystreamer.h"
|
||||
#include "rendering/vulkan14/vulkan14context.h"
|
||||
#include "rendering/nullrenderer.h"
|
||||
#include "application/application.h"
|
||||
@@ -1030,6 +1031,8 @@ void vulkan14_renderer::Shutdown()
|
||||
// a walker has nothing of its own to let go of
|
||||
return;
|
||||
}
|
||||
// the loads of the streamed geometry end before the banks they're for go
|
||||
gfx::geometry_streamer::instance().stop();
|
||||
if (m_context)
|
||||
{
|
||||
join_walks();
|
||||
@@ -1226,6 +1229,12 @@ void vulkan14_renderer::Update(double const Deltatime)
|
||||
{
|
||||
update_texture_release();
|
||||
}
|
||||
if (Prefetches_Textures() && (true == simulation::is_ready) && (m_colorpass.draw_range > 0.f))
|
||||
{
|
||||
// the data read ahead for textures nothing drew since, or ahead of the camera which went far from there, let go of
|
||||
auto const range{static_cast<double>(m_colorpass.draw_range) * Global.fDistanceFactor + 500.0};
|
||||
m_context->textures->drop_read_ahead(std::chrono::minutes(5), m_colorpass.pass_camera.position(), 2.0 * range);
|
||||
}
|
||||
save_pipeline_cache();
|
||||
update_info();
|
||||
}
|
||||
|
||||
@@ -83,6 +83,20 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk
|
||||
gfx::geometry_handle Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override;
|
||||
// the compact streams stay as they are: the bank of an EU07M model keeps them on the gpu, 28 bytes a vertex
|
||||
gfx::geometry_handle Insert_Compact(gfx::index_array &Indices, gfx::position_array &Positions, gfx::compact_array &Attributes, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type) override;
|
||||
std::vector<std::string> Memory_Report() override;
|
||||
// the streaming of the geometry (modelstreaming)
|
||||
bool Streams_Geometry() const override;
|
||||
void Stream_Bank(gfx::geometrybank_handle const &Bank, std::shared_ptr<gfx::geometry_source const> Source) override;
|
||||
gfx::geometry_handle Insert_Streamed(gfx::geometrybank_handle const &Bank, int const Type) override;
|
||||
void Pin_Bank(gfx::geometrybank_handle const &Bank) override;
|
||||
void Touch_Bank(gfx::geometrybank_handle const &Bank, float const Priority) override;
|
||||
// the streaming of the textures (gfx.textures.streaming): read ahead by the prefetch of the models
|
||||
bool Prefetches_Textures() const override;
|
||||
void Prefetch_Textures(TModel3d *Model, material_data const *Skins, glm::dvec3 const &Origin) override;
|
||||
std::size_t Textures_Being_Read() const override;
|
||||
void Collect_Start_Textures(bool const Collect) override;
|
||||
std::size_t Make_Start_Textures() override;
|
||||
void Prefetch_Material(material_handle const Material, glm::dvec3 const &Origin) override;
|
||||
bool Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, std::size_t const Offset = 0) override;
|
||||
bool Replace_Indexed(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry) override;
|
||||
bool Append(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type) override;
|
||||
@@ -567,6 +581,9 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk
|
||||
gfx::geometrybank_manager &m_geometry{m_geometrystore};
|
||||
std::vector<gfx::geometry_bank *> m_bankstore;
|
||||
std::vector<gfx::geometry_bank *> &m_banks{m_bankstore};
|
||||
// the textures read ahead around the start, made before the simulation starts (Collect_Start_Textures())
|
||||
bool m_collectstart{false};
|
||||
std::vector<texture_handle> m_starttextures;
|
||||
material_manager m_materialstore;
|
||||
material_manager &m_materials{m_materialstore};
|
||||
material_handle m_invalid_material{null_handle};
|
||||
|
||||
@@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/.
|
||||
// recorded into the pass under way. the passes are in vulkan14frame.cpp
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "rendering/common/memoryreport.h"
|
||||
#include "rendering/vulkan14/vulkan14context.h"
|
||||
#include "rendering/vulkan14/vulkan14commands.h"
|
||||
#include "rendering/common/walksync.h"
|
||||
@@ -1308,6 +1309,40 @@ gfx::geometry_handle vulkan14_renderer::Insert_Compact(gfx::index_array &Indices
|
||||
return m_geometry.create_chunk_compact(Indices, Positions, Attributes, Userdata, Geometry, Type);
|
||||
}
|
||||
|
||||
std::vector<std::string> vulkan14_renderer::Memory_Report()
|
||||
{
|
||||
return gfx::memory_report(m_context ? m_context->textures.get() : nullptr, m_geometry);
|
||||
}
|
||||
|
||||
bool vulkan14_renderer::Streams_Geometry() const
|
||||
{
|
||||
return Global.modelstreaming && m_context;
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Stream_Bank(gfx::geometrybank_handle const &Bank, std::shared_ptr<gfx::geometry_source const> Source)
|
||||
{
|
||||
// made while no walk of the passes draws (gfx::walk_sync)
|
||||
gfx::walk_sync::change change;
|
||||
m_geometry.stream(Bank, std::move(Source));
|
||||
}
|
||||
|
||||
gfx::geometry_handle vulkan14_renderer::Insert_Streamed(gfx::geometrybank_handle const &Bank, int const Type)
|
||||
{
|
||||
// made while no walk of the passes draws (gfx::walk_sync)
|
||||
gfx::walk_sync::change change;
|
||||
return m_geometry.create_chunk_streamed(Bank, Type);
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Pin_Bank(gfx::geometrybank_handle const &Bank)
|
||||
{
|
||||
m_geometry.pin(Bank);
|
||||
}
|
||||
|
||||
void vulkan14_renderer::Touch_Bank(gfx::geometrybank_handle const &Bank, float const Priority)
|
||||
{
|
||||
m_geometry.touch(Bank, Priority);
|
||||
}
|
||||
|
||||
gfx::geometry_handle vulkan14_renderer::Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type)
|
||||
{
|
||||
// made while no walk of the passes draws (gfx::walk_sync)
|
||||
|
||||
@@ -661,7 +661,7 @@ bool vulkan14_texture::create(bool const Static)
|
||||
return ready;
|
||||
}
|
||||
|
||||
bool vulkan14_texture::request_background()
|
||||
bool vulkan14_texture::request_background(bool const Draw)
|
||||
{
|
||||
if (m_made)
|
||||
{
|
||||
@@ -681,7 +681,7 @@ bool vulkan14_texture::request_background()
|
||||
if (state != job_none)
|
||||
{
|
||||
// being made, or made and waiting for the thread of the renderer
|
||||
if (m_resources.pending != nullptr)
|
||||
if (Draw && (m_resources.pending != nullptr))
|
||||
{
|
||||
++m_resources.pending->late_count;
|
||||
}
|
||||
@@ -694,10 +694,16 @@ bool vulkan14_texture::request_background()
|
||||
// asked for by one of the threads walking the passes at a time
|
||||
if (false == m_job.compare_exchange_strong(state, job_running))
|
||||
{
|
||||
++m_resources.pending->late_count;
|
||||
if (Draw)
|
||||
{
|
||||
++m_resources.pending->late_count;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
++m_resources.pending->late_count;
|
||||
if (Draw)
|
||||
{
|
||||
++m_resources.pending->late_count;
|
||||
}
|
||||
// the texture outlives the job: its destruction waits for it (the background threads are stopped before the bank goes, too). a job
|
||||
// the threads let go of without running it (they were stopped with it in their queue) leaves the texture as it was before it
|
||||
auto const ticket{std::make_shared<job_ticket>(m_job, job_none)};
|
||||
|
||||
@@ -209,8 +209,13 @@ struct vulkan14_texture : public texture_source
|
||||
|
||||
bool create(bool const Static = false) override;
|
||||
// the texture for a draw of the walks: true when it's made, otherwise it's made by the background threads (or made now, without
|
||||
// them) and the draw goes without it
|
||||
bool request_background();
|
||||
// them) and the draw goes without it. Draw false: asked for ahead of the draws (the loading screen), not counted as a draw without it
|
||||
bool request_background(bool const Draw = true);
|
||||
// the image is made and taken over by the thread of the renderer
|
||||
bool made() const
|
||||
{
|
||||
return m_made;
|
||||
}
|
||||
// the thread of the renderer takes over what a background thread made of the texture. unless Force, one with a copy to the gpu
|
||||
// to make is left for a later frame when the copies of the frame reached their budget (pending_textures::upload_budget)
|
||||
void publish(bool Force = false);
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
#include "stdafx.h"
|
||||
|
||||
#include "doctest.h"
|
||||
#include "scratch.h"
|
||||
|
||||
#include "model/eu07m/eu07m_build.h"
|
||||
#include "model/eu07m/eu07m_dump.h"
|
||||
#include "model/eu07m/eu07m_geometry.h"
|
||||
#include "model/eu07m/eu07m_io.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <string_view>
|
||||
|
||||
// the parts of EU07M the streaming of the geometry (modelstreaming) stands on: the structure of a model read without its streams, the
|
||||
// streams read later from the same file, and the chunks the game makes of the primitives
|
||||
|
||||
namespace {
|
||||
|
||||
// a model of two nodes with geometry and one without: a quad with indices and user data, and a strip without indices
|
||||
eu07m::model streamed_model() {
|
||||
eu07m::model model;
|
||||
auto const node{[&model](std::string_view const Name, std::int32_t const Parent) {
|
||||
eu07m::node_record record;
|
||||
record.name = model.intern(Name);
|
||||
record.parent = Parent;
|
||||
model.nodes.push_back(record);
|
||||
return static_cast<std::uint32_t>(model.nodes.size() - 1);
|
||||
}};
|
||||
auto const root{node("root", -1)};
|
||||
auto const quad{node("quad", static_cast<std::int32_t>(root))};
|
||||
auto const strip{node("strip", static_cast<std::int32_t>(root))};
|
||||
model.nodes[root].subtree_end = 3;
|
||||
model.nodes[quad].subtree_end = 2;
|
||||
model.nodes[strip].subtree_end = 3;
|
||||
model.nodes[quad].translation = {10.f, 0.f, 0.f};
|
||||
eu07m::material_record material;
|
||||
material.name = model.intern("wall.mat");
|
||||
model.materials.push_back(material);
|
||||
for (auto const &corner : std::array<std::array<float, 2>, 4>{{{0.f, 0.f}, {1.f, 0.f}, {1.f, 1.f}, {0.f, 1.f}}}) {
|
||||
model.positions.push_back({corner[0], corner[1], 0.f});
|
||||
eu07m::attributes attribute;
|
||||
attribute.qtangent = eu07m::encode_qtangent({{0.f, 0.f, 1.f}, {1.f, 0.f, 0.f}, 1.f});
|
||||
attribute.uv = {corner[0], corner[1]};
|
||||
model.vertex_attributes.push_back(attribute);
|
||||
model.vertex_userdata.push_back({corner[0], corner[1], 0.f, 1.f});
|
||||
}
|
||||
for (int idx = 0; idx < 3; ++idx) {
|
||||
model.positions.push_back({0.f, static_cast<float>(idx), 2.f});
|
||||
model.vertex_attributes.push_back({});
|
||||
model.vertex_userdata.push_back({});
|
||||
}
|
||||
model.indices16 = {0, 1, 2, 0, 2, 3};
|
||||
eu07m::primitive_record first;
|
||||
first.index_count = 6;
|
||||
first.vertex_count = 4;
|
||||
first.node = quad;
|
||||
first.flags = static_cast<std::uint32_t>(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque;
|
||||
model.primitives.push_back(first);
|
||||
eu07m::primitive_record second;
|
||||
second.base_vertex = 4;
|
||||
second.vertex_count = 3;
|
||||
second.index_count = 3;
|
||||
second.node = strip;
|
||||
second.flags = static_cast<std::uint32_t>(eu07m::topology::triangle_strip) | eu07m::primitive_flags::opaque;
|
||||
model.primitives.push_back(second);
|
||||
model.meshes.push_back({0, 1, -1, 0});
|
||||
model.meshes.push_back({1, 1, -1, 0});
|
||||
model.nodes[quad].mesh = 0;
|
||||
model.nodes[strip].mesh = 1;
|
||||
eu07m::build_name_index(model);
|
||||
eu07m::compute_bounds(model);
|
||||
return model;
|
||||
}
|
||||
|
||||
std::string_view as_text(std::vector<std::byte> const &File) {
|
||||
return {reinterpret_cast<char const *>(File.data()), File.size()};
|
||||
}
|
||||
|
||||
eu07m::read_options game_options(bool const Streams) {
|
||||
eu07m::read_options options{false, false};
|
||||
options.streams = Streams;
|
||||
return options;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("eu07m streaming: a file read from the disk is the model read from memory")
|
||||
{
|
||||
test::scratch_folder folder{"eu07m_streaming_read"};
|
||||
auto const original{streamed_model()};
|
||||
REQUIRE(eu07m::validate(original).empty());
|
||||
for (auto const compress : {false, true}) {
|
||||
CAPTURE(compress);
|
||||
auto const file{eu07m::write(original, {compress, 9})};
|
||||
auto const path{folder.write("model.ng3d", as_text(file))};
|
||||
eu07m::model frommemory;
|
||||
auto const memory{eu07m::read(file, frommemory, game_options(true))};
|
||||
REQUIRE_MESSAGE(memory.ok, memory.error);
|
||||
eu07m::model fromdisk;
|
||||
auto const disk{eu07m::read_file(path, fromdisk, game_options(true))};
|
||||
REQUIRE_MESSAGE(disk.ok, disk.error);
|
||||
CHECK(eu07m::dump(fromdisk) == eu07m::dump(frommemory));
|
||||
CHECK(fromdisk.indices16 == frommemory.indices16);
|
||||
CHECK(fromdisk.positions.size() == 7);
|
||||
CHECK(disk.content_hash == memory.content_hash);
|
||||
CHECK(disk.content_hash != 0);
|
||||
CHECK(disk.stream_bytes == memory.stream_bytes);
|
||||
CHECK(disk.stream_bytes > 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("eu07m streaming: without the streams the structure alone is read and checked")
|
||||
{
|
||||
test::scratch_folder folder{"eu07m_streaming_structure"};
|
||||
auto const original{streamed_model()};
|
||||
auto const path{folder.write("model.ng3d", as_text(eu07m::write(original)))};
|
||||
eu07m::model structure;
|
||||
auto const result{eu07m::read_file(path, structure, game_options(false))};
|
||||
REQUIRE_MESSAGE(result.ok, result.error);
|
||||
CHECK(structure.positions.empty());
|
||||
CHECK(structure.vertex_attributes.empty());
|
||||
CHECK(structure.vertex_userdata.empty());
|
||||
CHECK(structure.indices16.empty());
|
||||
CHECK(structure.nodes.size() == original.nodes.size());
|
||||
CHECK(structure.primitives.size() == original.primitives.size());
|
||||
CHECK(structure.bounds.size() == original.bounds.size());
|
||||
CHECK(structure.strings == original.strings);
|
||||
CHECK(eu07m::validate(structure, 16, eu07m::validate_scope::structure).empty());
|
||||
// the whole check misses the streams
|
||||
CHECK_FALSE(eu07m::validate(structure).empty());
|
||||
// the same from memory
|
||||
eu07m::model frommemory;
|
||||
auto const memory{eu07m::read(eu07m::write(original), frommemory, game_options(false))};
|
||||
REQUIRE_MESSAGE(memory.ok, memory.error);
|
||||
CHECK(eu07m::dump(frommemory) == eu07m::dump(structure));
|
||||
}
|
||||
|
||||
TEST_CASE("eu07m streaming: the structure is read without touching the streams")
|
||||
{
|
||||
test::scratch_folder folder{"eu07m_streaming_untouched"};
|
||||
// the positions marked as packed with zstd, which they aren't: whatever reads them fails
|
||||
auto file{eu07m::write(streamed_model(), {false, 9})};
|
||||
auto const header{[&file] {
|
||||
eu07m::file_header value;
|
||||
std::memcpy(&value, file.data(), sizeof(value));
|
||||
return value;
|
||||
}()};
|
||||
for (std::size_t idx = 0; idx < header.section_count; ++idx) {
|
||||
eu07m::section_entry entry;
|
||||
auto const offset{header.toc_offset + idx * sizeof(entry)};
|
||||
std::memcpy(&entry, file.data() + offset, sizeof(entry));
|
||||
if (entry.id != eu07m::section::positions)
|
||||
continue;
|
||||
REQUIRE((entry.flags & eu07m::section_flags::zstd) == 0);
|
||||
entry.flags |= eu07m::section_flags::zstd;
|
||||
std::memcpy(file.data() + offset, &entry, sizeof(entry));
|
||||
}
|
||||
auto const path{folder.write("model.ng3d", as_text(file))};
|
||||
eu07m::model model;
|
||||
auto const structure{eu07m::read_file(path, model, game_options(false))};
|
||||
CHECK_MESSAGE(structure.ok, structure.error);
|
||||
auto const whole{eu07m::read_file(path, model, game_options(true))};
|
||||
CHECK_FALSE(whole.ok);
|
||||
CHECK(model.nodes.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("eu07m streaming: a file cut short or missing is refused with a reason")
|
||||
{
|
||||
test::scratch_folder folder{"eu07m_streaming_broken"};
|
||||
auto const file{eu07m::write(streamed_model())};
|
||||
eu07m::model model;
|
||||
auto const missing{eu07m::read_file(folder.path("none.ng3d"), model, game_options(false))};
|
||||
CHECK_FALSE(missing.ok);
|
||||
CHECK_FALSE(missing.error.empty());
|
||||
auto const shortpath{folder.write("short.ng3d", as_text(file).substr(0, file.size() - 8))};
|
||||
auto const cut{eu07m::read_file(shortpath, model, game_options(false))};
|
||||
CHECK_FALSE(cut.ok);
|
||||
CHECK(cut.error.find("cut short") != std::string::npos);
|
||||
auto const tinypath{folder.write("tiny.ng3d", as_text(file).substr(0, 10))};
|
||||
auto const tiny{eu07m::read_file(tinypath, model, game_options(false))};
|
||||
CHECK_FALSE(tiny.ok);
|
||||
CHECK(tiny.error.find("shorter than the header") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("eu07m streaming: the chunks are the first primitives of the nodes with geometry, in their order")
|
||||
{
|
||||
auto const model{streamed_model()};
|
||||
auto const primitives{eu07m::drawn_primitives(model)};
|
||||
REQUIRE(primitives == std::vector<std::uint32_t>{0, 1});
|
||||
auto const quad{eu07m::geometry_of(model, 0)};
|
||||
CHECK(quad.indices == std::vector<std::uint32_t>{0, 1, 2, 0, 2, 3});
|
||||
REQUIRE(quad.positions.size() == 4);
|
||||
CHECK(quad.positions[2] == eu07m::position{1.f, 1.f, 0.f});
|
||||
REQUIRE(quad.vertex_userdata.size() == 4);
|
||||
CHECK(quad.vertex_userdata[1] == eu07m::userdata{1.f, 0.f, 0.f, 1.f});
|
||||
auto const strip{eu07m::geometry_of(model, 1)};
|
||||
CHECK(strip.indices.empty());
|
||||
REQUIRE(strip.positions.size() == 3);
|
||||
CHECK(strip.positions[0] == eu07m::position{0.f, 0.f, 2.f});
|
||||
CHECK(strip.vertex_attributes.size() == 3);
|
||||
// out of range: nothing
|
||||
CHECK(eu07m::geometry_of(model, 7).positions.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("eu07m streaming: what keeps a model from being streamed")
|
||||
{
|
||||
auto model{streamed_model()};
|
||||
CHECK(eu07m::not_streamable(model).empty());
|
||||
auto withoutbounds{model};
|
||||
withoutbounds.bounds.clear();
|
||||
CHECK_FALSE(eu07m::not_streamable(withoutbounds).empty());
|
||||
auto withskin{model};
|
||||
withskin.skins.push_back({0, 0, -1, 0});
|
||||
CHECK_FALSE(eu07m::not_streamable(withskin).empty());
|
||||
auto withstars{model};
|
||||
withstars.add_component(eu07m::component::legacy_stars, eu07m::target_kind::node, 1, eu07m::payload_writer{}.put(std::uint32_t{0}).data());
|
||||
CHECK_FALSE(eu07m::not_streamable(withstars).empty());
|
||||
}
|
||||
@@ -1008,6 +1008,31 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string&
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token == "modelstreaming")
|
||||
{
|
||||
// yes: the geometry of the larger scenery models of .ng3d files is read when they're about to be drawn
|
||||
ParseOne(Parser, modelstreaming);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token == "modelstreaming.minsize")
|
||||
{
|
||||
ParseOneClamped(Parser, modelstreaming_minsize, 0, 1 << 20);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token == "modelstreaming.evictafter")
|
||||
{
|
||||
ParseOneClamped(Parser, modelstreaming_evictafter, 1.f, 3600.f);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token == "modelstreaming.budget")
|
||||
{
|
||||
ParseOneClamped(Parser, modelstreaming_budget, 0, 1 << 20);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token == "fpslimit")
|
||||
{
|
||||
float fpslimit = 0.f;
|
||||
@@ -1806,6 +1831,7 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token
|
||||
{
|
||||
Parser.getTokens();
|
||||
Parser >> gfx_texture_streaming;
|
||||
gfx_texture_streaming_set = true;
|
||||
}
|
||||
else if (Token == "gfx.textures.releasedistance")
|
||||
{
|
||||
@@ -2701,6 +2727,10 @@ global_settings::export_as_text( std::ostream &Output ) const {
|
||||
export_as_text( Output, "pause", ( iPause & 1 ) != 0 );
|
||||
export_as_text(Output, "priorityLoadText3D", priorityLoadText3D);
|
||||
export_as_text(Output, "modelformat", std::string{modelformat_eu07m ? "ng3d" : "legacy"});
|
||||
export_as_text(Output, "modelstreaming", modelstreaming);
|
||||
export_as_text(Output, "modelstreaming.minsize", modelstreaming_minsize);
|
||||
export_as_text(Output, "modelstreaming.evictafter", modelstreaming_evictafter);
|
||||
export_as_text(Output, "modelstreaming.budget", modelstreaming_budget);
|
||||
export_as_text( Output, "lang", asLang );
|
||||
export_as_text( Output, "python.updatetime", PythonScreenUpdateRate );
|
||||
Output
|
||||
|
||||
@@ -122,6 +122,12 @@ struct global_settings {
|
||||
// logs
|
||||
bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo
|
||||
bool modelformat_eu07m{false}; // modelformat ng3d: models are loaded from their .ng3d files where there are some
|
||||
// modelstreaming yes: the geometry of the larger scenery models loaded from .ng3d files is read when they're about to be drawn and
|
||||
// let go of when they're unused for a while (rendering/geometrystreamer.h); no: it's read with the models, as before
|
||||
bool modelstreaming{true};
|
||||
int modelstreaming_minsize{256}; // KiB of the .ng3d file, below which a model is loaded whole
|
||||
float modelstreaming_evictafter{30.f}; // seconds a streamed model goes undrawn before its geometry is let go of
|
||||
int modelstreaming_budget{0}; // MB of the geometry of the streamed models above which it's let go of sooner; 0 no limit
|
||||
int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów
|
||||
bool MultipleLogs{ false };
|
||||
bool crashdump_full{ false }; // crash dump with the whole memory of the process instead of the small one
|
||||
@@ -267,6 +273,8 @@ struct global_settings {
|
||||
bool ResourceSweep{ true }; // gfx resource garbage collection
|
||||
bool ResourceMove{ false }; // gfx resources are moved between cpu and gpu side instead of sending a copy
|
||||
bool gfx_texture_streaming{ false }; // data of dds textures is read by worker threads, the rest of the loading doesn't wait for it
|
||||
// whether eu07.ini sets gfx.textures.streaming; when it doesn't, the textures are streamed with the vulkan renderer only
|
||||
bool gfx_texture_streaming_set{ false };
|
||||
float gfx_texture_releasedistance{ 0.f }; // gl textures of vehicles farther than this many draw ranges are released. 0 = off
|
||||
bool compress_tex{ true }; // all textures are compressed on gpu side
|
||||
std::string asSky{ "1" };
|
||||
|
||||
@@ -41,3 +41,55 @@ whole_file read_whole_file(std::string const &Path)
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
bool seek_to(std::FILE *const File, std::uint64_t const Offset, int const Origin)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return _fseeki64(File, static_cast<__int64>(Offset), Origin) == 0;
|
||||
#else
|
||||
return fseeko(File, static_cast<off_t>(Offset), Origin) == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
file_parts::file_parts(std::string const &Path)
|
||||
{
|
||||
m_file = std::fopen(Path.c_str(), "rb");
|
||||
if (m_file == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::setvbuf(m_file, nullptr, _IONBF, 0);
|
||||
seek_to(m_file, 0, SEEK_END);
|
||||
#ifdef _WIN32
|
||||
auto const length{_ftelli64(m_file)};
|
||||
#else
|
||||
auto const length{ftello(m_file)};
|
||||
#endif
|
||||
m_size = (length > 0 ? static_cast<std::uint64_t>(length) : 0);
|
||||
}
|
||||
|
||||
file_parts::~file_parts()
|
||||
{
|
||||
if (m_file != nullptr)
|
||||
{
|
||||
std::fclose(m_file);
|
||||
}
|
||||
}
|
||||
|
||||
bool file_parts::read(std::uint64_t const Offset, std::size_t const Size, void *const Output)
|
||||
{
|
||||
if ((m_file == nullptr) || (Offset > m_size) || (Size > m_size - Offset))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (Size == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return seek_to(m_file, Offset, SEEK_SET) && (std::fread(Output, 1, Size, m_file) == Size);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
@@ -24,3 +26,28 @@ struct whole_file
|
||||
// hard disk in small pieces, slower (2026-11, .e3d files of a scenario: about 24 MB/s against 38 MB/s for one read).
|
||||
// a file which can't be opened or is empty gives no data; a read which stops early gives what was read
|
||||
whole_file read_whole_file(std::string const &Path);
|
||||
|
||||
// a file opened for reads of its parts, each with one unbuffered read, as read_whole_file() reads the whole
|
||||
class file_parts
|
||||
{
|
||||
public:
|
||||
explicit file_parts(std::string const &Path);
|
||||
~file_parts();
|
||||
file_parts(file_parts const &) = delete;
|
||||
file_parts &operator=(file_parts const &) = delete;
|
||||
|
||||
bool is_open() const
|
||||
{
|
||||
return m_file != nullptr;
|
||||
}
|
||||
std::uint64_t size() const
|
||||
{
|
||||
return m_size;
|
||||
}
|
||||
// Size bytes from Offset into Output. false when the file hasn't them all
|
||||
bool read(std::uint64_t Offset, std::size_t Size, void *Output);
|
||||
|
||||
private:
|
||||
std::FILE *m_file{nullptr};
|
||||
std::uint64_t m_size{0};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user