From dae5e7863ae93fc368b741d8f049100f38c47fb0 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 12:26:55 +0100 Subject: [PATCH 1/8] perf(CMake): build minizip-ng with zlib-ng for a fast CRC32 minizip-ng was built without zlib (MZ_ZLIB OFF), so every zip read and write computed the CRC32 with its byte-wise software table, most of the unzip time. It now links the zlib-ng of the superbuild (PCLMUL CRC32), without fetching its own libraries. OpenGeode finds zlib-ng before minizip-ng and makes the find_dependency(ZLIB) of minizip-ng use config mode, in the build and in the exported package, so that no system zlib is picked. DEFLATE-compressed archives (e.g. a model re-zipped with a standard tool) are now readable. OpenGeode still writes stored entries. Co-Authored-By: Claude Opus 5.5 --- cmake/ConfigureMinizip.cmake | 7 +- cmake/OpenGeode.cmake | 6 +- cmake/OpenGeodeConfig.cmake.in | 4 + cmake/SuperBuild.cmake | 2 +- tests/basic/CMakeLists.txt | 1 + tests/basic/test-zip-file.cpp | 109 +++++++++++++++++ tests/model/CMakeLists.txt | 8 ++ tests/model/test-model-deflate-archive.cpp | 130 +++++++++++++++++++++ 8 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 tests/model/test-model-deflate-archive.cpp diff --git a/cmake/ConfigureMinizip.cmake b/cmake/ConfigureMinizip.cmake index 482289e74..b8d478fba 100644 --- a/cmake/ConfigureMinizip.cmake +++ b/cmake/ConfigureMinizip.cmake @@ -29,6 +29,7 @@ ExternalProject_Add(minizip GIT_TAG 4.1.0 GIT_SHALLOW ON GIT_PROGRESS ON + DEPENDS zlib CMAKE_GENERATOR ${CMAKE_GENERATOR} CMAKE_GENERATOR_PLATFORM ${CMAKE_GENERATOR_PLATFORM} CMAKE_ARGS @@ -39,7 +40,11 @@ ExternalProject_Add(minizip -DCMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD} CMAKE_CACHE_ARGS -DMZ_COMPAT:BOOL=OFF - -DMZ_ZLIB:BOOL=OFF + -DMZ_ZLIB:BOOL=ON + -DMZ_FETCH_LIBS:BOOL=OFF + -DMZ_FORCE_FETCH_LIBS:BOOL=OFF + -DCMAKE_FIND_PACKAGE_PREFER_CONFIG:BOOL=ON + -DZLIB_ROOT:PATH=${ZLIB_INSTALL_PREFIX} -DMZ_BZIP2:BOOL=OFF -DMZ_LZMA:BOOL=OFF -DMZ_PKCRYPT:BOOL=OFF diff --git a/cmake/OpenGeode.cmake b/cmake/OpenGeode.cmake index 202df4920..6b0abd898 100644 --- a/cmake/OpenGeode.cmake +++ b/cmake/OpenGeode.cmake @@ -32,11 +32,15 @@ find_package(absl REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ABSEIL_INSTALL_PREFIX} find_package(Async++ REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ASYNCPLUSPLUS_INSTALL_PREFIX}) find_package(Bitsery REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${BITSERY_INSTALL_PREFIX}) find_package(earcut_hpp REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${EARCUT_INSTALL_PREFIX}) +find_package(ZLIB REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ZLIB_INSTALL_PREFIX}) +# minizip-ng calls find_dependency(ZLIB): reuse the zlib-ng config found above +set(GEODE_PREFER_CONFIG ${CMAKE_FIND_PACKAGE_PREFER_CONFIG}) +set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) find_package(minizip-ng REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${MINIZIP_INSTALL_PREFIX}) +set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ${GEODE_PREFER_CONFIG}) find_package(nanoflann REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${NANOFLANN_INSTALL_PREFIX}) find_package(spdlog REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${SPDLOG_INSTALL_PREFIX}) find_package(nlohmann_json REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${JSON_INSTALL_PREFIX}) -find_package(zlib REQUIRED CONFIG NO_DEFAULT_PATH PATHS ${ZLIB_INSTALL_PREFIX}) find_package(Threads REQUIRED) # Install OpenGeode third-parties diff --git a/cmake/OpenGeodeConfig.cmake.in b/cmake/OpenGeodeConfig.cmake.in index 5222dd224..23743e9e4 100644 --- a/cmake/OpenGeodeConfig.cmake.in +++ b/cmake/OpenGeodeConfig.cmake.in @@ -44,7 +44,11 @@ find_dependency(Async++) get_target_property(library_type OpenGeode::basic TYPE) if(library_type STREQUAL "STATIC_LIBRARY") find_dependency(earcut_hpp) + # minizip-ng calls find_dependency(ZLIB): use the installed zlib-ng config + set(GEODE_PREFER_CONFIG ${CMAKE_FIND_PACKAGE_PREFER_CONFIG}) + set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) find_dependency(minizip-ng) + set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ${GEODE_PREFER_CONFIG}) find_dependency(nanoflann) find_dependency(spdlog) find_dependency(nlohmann_json) diff --git a/cmake/SuperBuild.cmake b/cmake/SuperBuild.cmake index 05415925e..60b8abf42 100644 --- a/cmake/SuperBuild.cmake +++ b/cmake/SuperBuild.cmake @@ -63,6 +63,7 @@ include(${PROJECT_SOURCE_DIR}/cmake/ConfigureAbseil.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureAsync++.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureBitsery.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureEarcut.cmake) +include(${PROJECT_SOURCE_DIR}/cmake/ConfigureZlib.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureMinizip.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureNanoflann.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureSpdlog.cmake) @@ -70,7 +71,6 @@ include(${PROJECT_SOURCE_DIR}/cmake/ConfigureSQLite.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigurePROJ.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureGDAL.cmake) include(${PROJECT_SOURCE_DIR}/cmake/ConfigureJson.cmake) -include(${PROJECT_SOURCE_DIR}/cmake/ConfigureZlib.cmake) if(OPENGEODE_WITH_PYTHON OR INCLUDE_PYBIND11) include(${PROJECT_SOURCE_DIR}/cmake/ConfigurePybind11.cmake) diff --git a/tests/basic/CMakeLists.txt b/tests/basic/CMakeLists.txt index 36e57b511..bb7c8f87f 100644 --- a/tests/basic/CMakeLists.txt +++ b/tests/basic/CMakeLists.txt @@ -110,4 +110,5 @@ add_geode_test( SOURCE "test-zip-file.cpp" DEPENDENCIES ${PROJECT_NAME}::basic + MINIZIP::minizip-ng ) diff --git a/tests/basic/test-zip-file.cpp b/tests/basic/test-zip-file.cpp index a85d3a78e..ca8fc69b5 100644 --- a/tests/basic/test-zip-file.cpp +++ b/tests/basic/test-zip-file.cpp @@ -21,15 +21,124 @@ * */ +#include +#include +#include +#include +#include +#include +#include +#include + #include +#include +#include +#include +#include + #include +#include +#include #include #include +using ZipEntries = std::vector< std::pair< std::string, std::string > >; + +void write_deflate_zip( const std::string& zip, const ZipEntries& entries ) +{ + void* writer = mz_zip_writer_create(); + mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_DEFLATE ); + auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); + for( const auto& [name, content] : entries ) + { + if( status != MZ_OK ) + { + break; + } + mz_zip_file info{}; + info.filename = name.c_str(); + info.compression_method = MZ_COMPRESS_METHOD_DEFLATE; + info.flag = MZ_ZIP_FLAG_UTF8; + info.modified_date = std::time( nullptr ); + status = mz_zip_writer_add_buffer( writer, content.data(), + static_cast< int32_t >( content.size() ), &info ); + } + const auto close_status = mz_zip_writer_close( writer ); + mz_zip_writer_delete( &writer ); + geode::OpenGeodeBasicException::test( + status == MZ_OK && close_status == MZ_OK, "Cannot write DEFLATE zip (", + status, ", ", close_status, ")" ); +} + +void check_entries_are_deflated( const std::string& zip ) +{ + void* reader = mz_zip_reader_create(); + geode::OpenGeodeBasicException::test( + mz_zip_reader_open_file( reader, zip.c_str() ) == MZ_OK, + "Cannot open DEFLATE zip" ); + auto status = mz_zip_reader_goto_first_entry( reader ); + while( status == MZ_OK ) + { + mz_zip_file* info = nullptr; + geode::OpenGeodeBasicException::test( + mz_zip_reader_entry_get_info( reader, &info ) == MZ_OK, + "Cannot read DEFLATE zip entry" ); + geode::OpenGeodeBasicException::test( + info->compression_method == MZ_COMPRESS_METHOD_DEFLATE + && info->compressed_size < info->uncompressed_size, + "Zip entry ", info->filename, " is not DEFLATE-compressed" ); + status = mz_zip_reader_goto_next_entry( reader ); + } + mz_zip_reader_close( reader ); + mz_zip_reader_delete( &reader ); + geode::OpenGeodeBasicException::test( + status == MZ_END_OF_LIST, "Error while reading DEFLATE zip entries" ); +} + +std::string read_file( const std::filesystem::path& file ) +{ + std::ifstream stream{ file, std::ios::binary }; + geode::OpenGeodeBasicException::test( + stream.is_open(), "Cannot open extracted file ", file.u8string() ); + return { std::istreambuf_iterator< char >{ stream }, + std::istreambuf_iterator< char >{} }; +} + +void test_unzip_deflate() +{ + std::string text; + for( const auto i : geode::Range{ 10000 } ) + { + absl::StrAppend( &text, "line ", i, " of a compressible file\n" ); + } + std::string binary; + for( const auto i : geode::Range{ 100000 } ) + { + binary.push_back( static_cast< char >( ( i * i ) % 7 ) ); + } + const ZipEntries entries{ { "text.txt", text }, + { "folder/binary.bin", binary } }; + const std::string zip{ "deflate.zip" }; + write_deflate_zip( zip, entries ); + check_entries_are_deflated( zip ); + + const geode::UnzipFile unzip{ zip, geode::uuid{}.string() }; + unzip.extract_all(); + const std::filesystem::path directory{ unzip.directory() }; + for( const auto& [name, content] : entries ) + { + geode::OpenGeodeBasicException::test( + read_file( directory / name ) == content, "Extracted entry ", name, + " differs from the DEFLATE-compressed content" ); + } + std::filesystem::remove( zip ); +} + void test() { + test_unzip_deflate(); const auto is_not_a_zip = geode::is_zip_file( absl::StrCat( geode::DATA_PATH, "triange.og_tsf3d" ) ); geode::OpenGeodeBasicException::test( diff --git a/tests/model/CMakeLists.txt b/tests/model/CMakeLists.txt index 38d6ea10e..a6e44756c 100644 --- a/tests/model/CMakeLists.txt +++ b/tests/model/CMakeLists.txt @@ -96,6 +96,14 @@ add_geode_test( ${PROJECT_NAME}::mesh ${PROJECT_NAME}::model ) +add_geode_test( + SOURCE "test-model-deflate-archive.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh + ${PROJECT_NAME}::model + MINIZIP::minizip-ng +) add_geode_test( SOURCE "test-model-component-filter.cpp" DEPENDENCIES diff --git a/tests/model/test-model-deflate-archive.cpp b/tests/model/test-model-deflate-archive.cpp new file mode 100644 index 000000000..4badb7487 --- /dev/null +++ b/tests/model/test-model-deflate-archive.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include + +void rezip_with_deflate( const std::string& input, const std::string& output ) +{ + void* reader = mz_zip_reader_create(); + geode::OpenGeodeModelException::test( + mz_zip_reader_open_file( reader, input.c_str() ) == MZ_OK, + "Cannot open ", input ); + void* writer = mz_zip_writer_create(); + mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_DEFLATE ); + auto write_status = mz_zip_writer_open_file( writer, output.c_str(), 0, 0 ); + auto status = mz_zip_reader_goto_first_entry( reader ); + geode::index_t nb_entries{ 0 }; + while( status == MZ_OK && write_status == MZ_OK ) + { + mz_zip_file* info = nullptr; + geode::OpenGeodeModelException::test( + mz_zip_reader_entry_get_info( reader, &info ) == MZ_OK, + "Cannot read entry of ", input ); + std::vector< uint8_t > buffer( + static_cast< size_t >( info->uncompressed_size ) ); + const auto length = static_cast< int32_t >( buffer.size() ); + geode::OpenGeodeModelException::test( + mz_zip_reader_entry_save_buffer( reader, buffer.data(), length ) + == MZ_OK, + "Cannot read entry ", info->filename, " of ", input ); + mz_zip_file deflated = *info; + deflated.compression_method = MZ_COMPRESS_METHOD_DEFLATE; + write_status = mz_zip_writer_add_buffer( + writer, buffer.data(), length, &deflated ); + nb_entries++; + status = mz_zip_reader_goto_next_entry( reader ); + } + const auto close_status = mz_zip_writer_close( writer ); + mz_zip_writer_delete( &writer ); + mz_zip_reader_close( reader ); + mz_zip_reader_delete( &reader ); + geode::OpenGeodeModelException::test( + status == MZ_END_OF_LIST && write_status == MZ_OK + && close_status == MZ_OK && nb_entries > 0, + "Cannot re-zip ", input, " with DEFLATE (", status, ", ", write_status, + ", ", close_status, ")" ); +} + +void check_same_brep( const geode::BRep& brep, const geode::BRep& reference ) +{ + geode::OpenGeodeModelException::test( + brep.nb_corners() == reference.nb_corners() + && brep.nb_lines() == reference.nb_lines() + && brep.nb_surfaces() == reference.nb_surfaces() + && brep.nb_blocks() == reference.nb_blocks() + && brep.nb_unique_vertices() == reference.nb_unique_vertices(), + "BRep loaded from the DEFLATE archive differs from the reference" ); + for( const auto& surface : reference.surfaces() ) + { + const auto& mesh = brep.surface( surface.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == surface.mesh().nb_vertices() + && mesh.nb_polygons() == surface.mesh().nb_polygons(), + "Surface mesh loaded from the DEFLATE archive differs" ); + } + for( const auto& block : reference.blocks() ) + { + const auto& mesh = brep.block( block.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == block.mesh().nb_vertices() + && mesh.nb_polyhedra() == block.mesh().nb_polyhedra(), + "Block mesh loaded from the DEFLATE archive differs" ); + } +} + +void test() +{ + geode::OpenGeodeModelLibrary::initialize(); + const auto filename = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + const std::string deflated{ "layers_deflate.og_brep" }; + rezip_with_deflate( filename, deflated ); + const auto reference = + geode::load_one( geode::load_brep( filename ), filename ); + const auto brep = geode::load_one( geode::load_brep( deflated ), deflated ); + check_same_brep( brep, reference ); + std::filesystem::remove( deflated ); +} + +OPENGEODE_TEST( "model-deflate-archive" ) From ce0f196d1a99edea1ec00228c1235879147847c0 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 15:24:03 +0100 Subject: [PATCH 2/8] perf(Serialization): no random uuid for objects about to be deserialized Bitsery default-constructs every element it deserializes: each ComponentMeshVertex, uuid map key, mesh and attribute identifier generated a random UUIDv7 immediately overwritten by the file content (1.77 M generations when loading a 900 k unique vertices model). Add non-generating uuid(BITSERY), ComponentID(BITSERY), Identifier(BITSERY) and VertexSet/PointSet(BITSERY) constructors, specialize bitsery::Access::create for uuid and ComponentID, and use them where the object is built only to be deserialized. Old file versions that do not store an identifier still get a generated one. Co-Authored-By: Claude Opus 5.5 --- include/geode/basic/bitsery_archive.hpp | 6 +- include/geode/basic/growable.hpp | 9 +++ include/geode/basic/identifier.hpp | 7 +++ include/geode/basic/uuid.hpp | 19 ++++++ .../mesh/core/geode/geode_vertex_set.hpp | 2 +- include/geode/mesh/core/point_set.hpp | 1 + include/geode/mesh/core/vertex_set.hpp | 5 ++ .../geode/model/mixin/core/component_type.hpp | 18 ++++++ src/geode/basic/identifier.cpp | 6 ++ src/geode/mesh/core/geode/geode_point_set.cpp | 3 +- src/geode/mesh/core/graph.cpp | 2 +- src/geode/mesh/core/solid_mesh.cpp | 2 +- src/geode/mesh/core/surface_mesh.cpp | 3 +- src/geode/mesh/core/vertex_set.cpp | 4 ++ src/geode/model/mixin/core/component.cpp | 3 +- .../model/mixin/core/physical_properties.cpp | 3 +- .../model/mixin/core/vertex_identifier.cpp | 13 +++- tests/basic/test-uuid.cpp | 63 +++++++++++++++++++ tests/mesh/test-graph.cpp | 4 ++ tests/mesh/test-polygonal-surface.cpp | 5 ++ tests/mesh/test-polyhedral-solid.cpp | 5 ++ tests/mesh/test-tetrahedral-solid.cpp | 28 +++++++++ tests/mesh/test-triangulated-surface.cpp | 29 +++++++++ tests/model/test-brep.cpp | 53 ++++++++++++++++ tests/model/test-section.cpp | 49 +++++++++++++++ tests/model/test-vertex-identifier.cpp | 55 ++++++++++++++++ 26 files changed, 383 insertions(+), 14 deletions(-) diff --git a/include/geode/basic/bitsery_archive.hpp b/include/geode/basic/bitsery_archive.hpp index 40ffc3486..b73d8854a 100644 --- a/include/geode/basic/bitsery_archive.hpp +++ b/include/geode/basic/bitsery_archive.hpp @@ -34,6 +34,7 @@ #include #include #include +#include #include namespace geode @@ -48,11 +49,6 @@ namespace geode using Deserializer = bitsery::Deserializer< bitsery::InputStreamAdapter, TContext >; - enum struct BITSERY - { - constructor - }; - /*! * Register all the information needed by Bitsery to serialize the objects * in the basic library. diff --git a/include/geode/basic/growable.hpp b/include/geode/basic/growable.hpp index c2b55fd31..2f809d273 100644 --- a/include/geode/basic/growable.hpp +++ b/include/geode/basic/growable.hpp @@ -32,6 +32,15 @@ namespace geode { + /*! + * Tag of the constructors building an object only to deserialize it + * (no expensive initialization of values about to be overwritten). + */ + enum struct BITSERY + { + constructor + }; + /*! * Maximum size of a serialized name. Prevents corrupted files from * requesting huge allocations. diff --git a/include/geode/basic/identifier.hpp b/include/geode/basic/identifier.hpp index 7346175cf..ba9b83241 100644 --- a/include/geode/basic/identifier.hpp +++ b/include/geode/basic/identifier.hpp @@ -38,6 +38,7 @@ namespace geode { class IdentifierBuilder; struct uuid; + enum struct BITSERY; } // namespace geode namespace geode @@ -71,6 +72,12 @@ namespace geode protected: Identifier(); + /*! + * Nil identifier (no uuid generated), for an object about to be + * deserialized. + */ + explicit Identifier( BITSERY bitsery ); + Identifier& operator=( Identifier&& other ) noexcept; void set_id( const uuid& unique_id ); diff --git a/include/geode/basic/uuid.hpp b/include/geode/basic/uuid.hpp index 4b0962455..abeedeb81 100644 --- a/include/geode/basic/uuid.hpp +++ b/include/geode/basic/uuid.hpp @@ -37,8 +37,16 @@ namespace geode struct opengeode_basic_api uuid { public: + /*! + * Generate a new unique identifier (UUIDv7). + */ uuid(); explicit uuid( std::string_view string ); + /*! + * Nil uuid (all bytes zero), without generating a new identifier: for + * a uuid about to be overwritten by deserialization. + */ + explicit uuid( BITSERY /*unused*/ ) : bytes_{} {} uuid( const uuid & ) = default; uuid( uuid && ) = default; uuid &operator=( uuid &&other ) = default; @@ -96,6 +104,17 @@ namespace geode }; } // namespace geode +namespace bitsery +{ + // Bitsery builds the uuids it deserializes (map keys, optionals...) with + // Access::create: do not generate an identifier about to be overwritten. + template <> + inline geode::uuid Access::create< geode::uuid >() + { + return geode::uuid{ geode::BITSERY::constructor }; + } +} // namespace bitsery + namespace std { template <> diff --git a/include/geode/mesh/core/geode/geode_vertex_set.hpp b/include/geode/mesh/core/geode/geode_vertex_set.hpp index f1eeb19c1..239777ca5 100644 --- a/include/geode/mesh/core/geode/geode_vertex_set.hpp +++ b/include/geode/mesh/core/geode/geode_vertex_set.hpp @@ -44,7 +44,7 @@ namespace geode using Builder = OpenGeodeVertexSetBuilder; OpenGeodeVertexSet() = default; - OpenGeodeVertexSet( BITSERY ) {}; + OpenGeodeVertexSet( BITSERY bitsery ) : VertexSet{ bitsery } {}; [[nodiscard]] static MeshImpl impl_name_static() { diff --git a/include/geode/mesh/core/point_set.hpp b/include/geode/mesh/core/point_set.hpp index 0d0335cf4..fa1a68324 100644 --- a/include/geode/mesh/core/point_set.hpp +++ b/include/geode/mesh/core/point_set.hpp @@ -73,6 +73,7 @@ namespace geode protected: PointSet() = default; + explicit PointSet( BITSERY bitsery ) : VertexSet{ bitsery } {} PointSet( PointSet&& other ) noexcept = default; PointSet& operator=( PointSet&& other ) noexcept = default; diff --git a/include/geode/mesh/core/vertex_set.hpp b/include/geode/mesh/core/vertex_set.hpp index accce45f7..9fd891db2 100644 --- a/include/geode/mesh/core/vertex_set.hpp +++ b/include/geode/mesh/core/vertex_set.hpp @@ -82,6 +82,11 @@ namespace geode protected: VertexSet(); + /*! + * Nil identifier (no uuid generated), for a mesh about to be + * deserialized. + */ + explicit VertexSet( BITSERY bitsery ); VertexSet( VertexSet&& other ) noexcept; VertexSet& operator=( VertexSet&& other ) noexcept; diff --git a/include/geode/model/mixin/core/component_type.hpp b/include/geode/model/mixin/core/component_type.hpp index 7805b57f7..c51e4a068 100644 --- a/include/geode/model/mixin/core/component_type.hpp +++ b/include/geode/model/mixin/core/component_type.hpp @@ -48,6 +48,15 @@ namespace geode { ComponentID() : ComponentID( ComponentType{ "undefined" }, uuid{} ) {} + /*! + * Undefined type and nil uuid, without generating a new identifier: + * for a ComponentID about to be overwritten by deserialization. + */ + explicit ComponentID( BITSERY bitsery ) + : ComponentID( ComponentType{ "undefined" }, uuid{ bitsery } ) + { + } + ComponentID( ComponentType component_type, uuid input_id ) : type{ std::move( component_type ) }, id{ std::move( input_id ) } {}; @@ -101,6 +110,15 @@ namespace geode } // namespace geode +namespace bitsery +{ + template <> + inline geode::ComponentID Access::create< geode::ComponentID >() + { + return geode::ComponentID{ geode::BITSERY::constructor }; + } +} // namespace bitsery + namespace std { template <> diff --git a/src/geode/basic/identifier.cpp b/src/geode/basic/identifier.cpp index 496cd02b9..3bf424d4d 100644 --- a/src/geode/basic/identifier.cpp +++ b/src/geode/basic/identifier.cpp @@ -37,6 +37,10 @@ namespace geode class Identifier::Impl { public: + Impl() = default; + + explicit Impl( BITSERY bitsery ) : id_{ bitsery } {} + const uuid& id() const { return id_; @@ -138,6 +142,8 @@ namespace geode Identifier::Identifier() = default; + Identifier::Identifier( BITSERY bitsery ) : impl_{ bitsery } {} + Identifier::~Identifier() = default; Identifier::Identifier( Identifier&& ) noexcept = default; diff --git a/src/geode/mesh/core/geode/geode_point_set.cpp b/src/geode/mesh/core/geode/geode_point_set.cpp index 1d19c576c..21d2a0f90 100644 --- a/src/geode/mesh/core/geode/geode_point_set.cpp +++ b/src/geode/mesh/core/geode/geode_point_set.cpp @@ -69,7 +69,8 @@ namespace geode } template < index_t dimension > - OpenGeodePointSet< dimension >::OpenGeodePointSet( BITSERY ) + OpenGeodePointSet< dimension >::OpenGeodePointSet( BITSERY bitsery ) + : PointSet< dimension >{ bitsery } { } diff --git a/src/geode/mesh/core/graph.cpp b/src/geode/mesh/core/graph.cpp index 2eb0a396c..0a2d2af32 100644 --- a/src/geode/mesh/core/graph.cpp +++ b/src/geode/mesh/core/graph.cpp @@ -201,7 +201,7 @@ namespace geode Graph::Graph() = default; - Graph::Graph( BITSERY ) {} + Graph::Graph( BITSERY bitsery ) : VertexSet{ bitsery } {} Graph::Graph( Graph&& ) noexcept = default; diff --git a/src/geode/mesh/core/solid_mesh.cpp b/src/geode/mesh/core/solid_mesh.cpp index 411be21c9..78acb95f3 100644 --- a/src/geode/mesh/core/solid_mesh.cpp +++ b/src/geode/mesh/core/solid_mesh.cpp @@ -1045,7 +1045,7 @@ namespace geode SolidMesh< dimension >::SolidMesh() = default; template < index_t dimension > - SolidMesh< dimension >::SolidMesh( BITSERY ) + SolidMesh< dimension >::SolidMesh( BITSERY bitsery ) : VertexSet{ bitsery } { } diff --git a/src/geode/mesh/core/surface_mesh.cpp b/src/geode/mesh/core/surface_mesh.cpp index e548ab084..adfd24933 100644 --- a/src/geode/mesh/core/surface_mesh.cpp +++ b/src/geode/mesh/core/surface_mesh.cpp @@ -589,7 +589,8 @@ namespace geode SurfaceMesh< dimension >::SurfaceMesh() = default; template < index_t dimension > - SurfaceMesh< dimension >::SurfaceMesh( BITSERY ) + SurfaceMesh< dimension >::SurfaceMesh( BITSERY bitsery ) + : VertexSet{ bitsery } { } diff --git a/src/geode/mesh/core/vertex_set.cpp b/src/geode/mesh/core/vertex_set.cpp index 8fb717eef..4333c2807 100644 --- a/src/geode/mesh/core/vertex_set.cpp +++ b/src/geode/mesh/core/vertex_set.cpp @@ -58,6 +58,8 @@ namespace geode VertexSet::VertexSet() = default; + VertexSet::VertexSet( BITSERY bitsery ) : Identifier{ bitsery } {} + VertexSet::VertexSet( VertexSet&& ) noexcept = default; VertexSet& VertexSet::operator=( VertexSet&& ) noexcept = default; @@ -97,6 +99,8 @@ namespace geode *this, Growable< Archive, VertexSet >{ { []( Archive& archive, VertexSet& vertex_set ) { archive.object( vertex_set.impl_ ); + // Identifier not stored in this version + vertex_set.set_id( uuid{} ); }, []( Archive& archive, VertexSet& vertex_set ) { archive.object( vertex_set.impl_ ); diff --git a/src/geode/model/mixin/core/component.cpp b/src/geode/model/mixin/core/component.cpp index 886b95f49..98b76e7f4 100644 --- a/src/geode/model/mixin/core/component.cpp +++ b/src/geode/model/mixin/core/component.cpp @@ -77,7 +77,8 @@ namespace geode private: std::string backward_compatible_name_ = std::string{ "unknown" }; - uuid backward_compatible_id_; + // Only read (and used) by the first version of Component + uuid backward_compatible_id_{ BITSERY::constructor }; bool is_active_{ true }; }; diff --git a/src/geode/model/mixin/core/physical_properties.cpp b/src/geode/model/mixin/core/physical_properties.cpp index 688d07aef..ee245f598 100644 --- a/src/geode/model/mixin/core/physical_properties.cpp +++ b/src/geode/model/mixin/core/physical_properties.cpp @@ -145,7 +145,8 @@ namespace namespace geode { PhysicalProperties::Info::Info() - : component_type( bitsery::Access::create< ComponentType >() ) + : component_type( bitsery::Access::create< ComponentType >() ), + attribute_id( BITSERY::constructor ) { } diff --git a/src/geode/model/mixin/core/vertex_identifier.cpp b/src/geode/model/mixin/core/vertex_identifier.cpp index a24634140..1ebf13fb3 100644 --- a/src/geode/model/mixin/core/vertex_identifier.cpp +++ b/src/geode/model/mixin/core/vertex_identifier.cpp @@ -66,7 +66,7 @@ namespace geode } ComponentMeshVertex::ComponentMeshVertex() - : component_id( bitsery::Access::create< ComponentID >() ) + : component_id( BITSERY::constructor ) { } @@ -157,7 +157,10 @@ namespace geode unique_vertices_attribute_id ); } - Impl( BITSERY ) {} + Impl( BITSERY bitsery ) + : unique_vertices_{ bitsery }, unique_vertex_id_{ bitsery } + { + } index_t nb_unique_vertices() const { @@ -554,6 +557,8 @@ namespace geode serializer.ext( *this, Growable< Archive, Impl >{ { []( Archive& archive, Impl& impl ) { + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; archive.object( impl.unique_vertices_ ); archive.ext( impl.component_vertices_, bitsery::ext::StdSmartPtr{} ); @@ -577,6 +582,8 @@ namespace geode false } ); }, []( Archive& archive, Impl& impl ) { + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; archive.object( impl.unique_vertices_ ); archive.ext( impl.component_vertices_, bitsery::ext::StdSmartPtr{} ); @@ -595,6 +602,8 @@ namespace geode } ); }, []( Archive& archive, Impl& impl ) { + // Not stored in this version + impl.unique_vertex_id_ = uuid{}; archive.object( impl.unique_vertices_ ); archive.ext( impl.component_vertices_, bitsery::ext::StdSmartPtr{} ); diff --git a/tests/basic/test-uuid.cpp b/tests/basic/test-uuid.cpp index 24f86f8b8..aa6e26fc6 100644 --- a/tests/basic/test-uuid.cpp +++ b/tests/basic/test-uuid.cpp @@ -21,6 +21,13 @@ * */ +#include + +#include + +#include + +#include #include #include #include @@ -70,10 +77,66 @@ void test_invalid_string() } } +void test_deserialization() +{ + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto byte : nil.bytes_ ) + { + geode::OpenGeodeBasicException::test( + byte == 0, "UUID built for deserialization should be nil" ); + } + geode::OpenGeodeBasicException::test( + bitsery::Access::create< geode::uuid >() == nil, + "UUID created by bitsery should be nil (not generated)" ); + + using Map = absl::flat_hash_map< geode::uuid, geode::index_t >; + const geode::uuid id; + Map map; + for( const auto i : geode::Range{ 10 } ) + { + map.emplace( geode::uuid{}, i ); + } + std::stringstream stream; + { + geode::TContext context{}; + geode::Serializer archive{ context, stream }; + archive.object( id ); + archive.ext( map, bitsery::ext::StdMap{ map.size() }, + []( geode::Serializer& local_archive, geode::uuid& key, + geode::index_t& value ) { + local_archive.object( key ); + local_archive.value4b( value ); + } ); + archive.adapter().flush(); + } + geode::uuid loaded_id{ geode::BITSERY::constructor }; + Map loaded_map; + { + geode::TContext context{}; + geode::Deserializer archive{ context, stream }; + archive.object( loaded_id ); + archive.ext( loaded_map, bitsery::ext::StdMap{ map.size() }, + []( geode::Deserializer& local_archive, geode::uuid& key, + geode::index_t& value ) { + local_archive.object( key ); + local_archive.value4b( value ); + } ); + geode::OpenGeodeBasicException::test( + archive.adapter().error() == bitsery::ReaderError::NoError + && archive.adapter().isCompletedSuccessfully(), + "UUID deserialization should succeed" ); + } + geode::OpenGeodeBasicException::test( + loaded_id == id, "Deserialized UUID should be the saved one" ); + geode::OpenGeodeBasicException::test( + loaded_map == map, "Deserialized UUID keys should be the saved ones" ); +} + void test() { test_generation(); test_invalid_string(); + test_deserialization(); } OPENGEODE_TEST( "uuid" ) \ No newline at end of file diff --git a/tests/mesh/test-graph.cpp b/tests/mesh/test-graph.cpp index 1fc8b795c..a41a79042 100644 --- a/tests/mesh/test-graph.cpp +++ b/tests/mesh/test-graph.cpp @@ -22,6 +22,7 @@ */ #include #include +#include #include #include @@ -137,6 +138,9 @@ void test_io( const geode::Graph& graph, const std::string& filename ) void test_backward_io( const std::string& filename ) { auto graph = geode::load_one( geode::load_graph( filename ), filename ); + geode::OpenGeodeMeshException::test( + graph->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward Graph should have a valid id" ); geode::OpenGeodeMeshException::test( graph->edges_around_vertex( 2 ).size() == 3, diff --git a/tests/mesh/test-polygonal-surface.cpp b/tests/mesh/test-polygonal-surface.cpp index b73db1ce9..c25007d69 100644 --- a/tests/mesh/test-polygonal-surface.cpp +++ b/tests/mesh/test-polygonal-surface.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -566,6 +567,10 @@ void test_backward_io( const std::string& filename ) geode::load_polygonal_surface< 3 >( geode::OpenGeodePolygonalSurface3D::impl_name_static(), filename ), filename ); + geode::OpenGeodeMeshException::test( + new_polygonal_surface->id() + != geode::uuid{ geode::BITSERY::constructor }, + "Backward PolygonalSurface should have a valid id" ); geode::OpenGeodeMeshException::test( new_polygonal_surface->nb_vertices() == 7, diff --git a/tests/mesh/test-polyhedral-solid.cpp b/tests/mesh/test-polyhedral-solid.cpp index ac00a4caf..da1699450 100644 --- a/tests/mesh/test-polyhedral-solid.cpp +++ b/tests/mesh/test-polyhedral-solid.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -473,6 +474,10 @@ void test_backward_io( const std::string& filename ) { const auto new_polyhedral_solid = geode::load_one( geode::load_polyhedral_solid< 3 >( filename ), filename ); + geode::OpenGeodeMeshException::test( + new_polyhedral_solid->id() + != geode::uuid{ geode::BITSERY::constructor }, + "Backward PolyhedralSolid should have a valid id" ); geode::OpenGeodeMeshException::test( new_polyhedral_solid->nb_vertices() == 8, diff --git a/tests/mesh/test-tetrahedral-solid.cpp b/tests/mesh/test-tetrahedral-solid.cpp index e8a830dad..5868dccc8 100644 --- a/tests/mesh/test-tetrahedral-solid.cpp +++ b/tests/mesh/test-tetrahedral-solid.cpp @@ -21,6 +21,7 @@ * */ +#include #include #include @@ -343,6 +344,24 @@ void test_delete_polyhedron( const geode::TetrahedralSolid3D& solid, "TetrahedralSolid facet vertex index is not correct" ); } +void check_same_attribute_ids( const geode::AttributeManager& manager, + const geode::AttributeManager& manager2 ) +{ + auto ids = manager.attribute_ids(); + auto ids2 = manager2.attribute_ids(); + std::sort( ids.begin(), ids.end() ); + std::sort( ids2.begin(), ids2.end() ); + geode::OpenGeodeMeshException::test( + std::equal( ids.begin(), ids.end(), ids2.begin(), ids2.end() ), + "Reloaded attribute ids should be the saved ones" ); + for( const auto& id : ids2 ) + { + geode::OpenGeodeMeshException::test( + manager2.find_generic_attribute( id )->id() == id, + "Reloaded attribute should keep its id" ); + } +} + void test_io( const geode::TetrahedralSolid3D& solid, const std::string& filename ) { @@ -369,6 +388,12 @@ void test_io( "Reloaded TetrahedralSolid should have 12 edges" ); geode::OpenGeodeMeshException::test( new_solid->nb_polyhedra() == 3, "Reloaded TetrahedralSolid should have 3 polyhedra" ); + geode::OpenGeodeMeshException::test( new_solid->id() == solid.id(), + "Reloaded TetrahedralSolid should keep its id" ); + check_same_attribute_ids( solid.vertex_attribute_manager(), + new_solid->vertex_attribute_manager() ); + check_same_attribute_ids( solid.polyhedron_attribute_manager(), + new_solid->polyhedron_attribute_manager() ); } void test_backward_io( const std::string& filename ) @@ -377,6 +402,9 @@ void test_backward_io( const std::string& filename ) geode::load_tetrahedral_solid< 3 >( filename ), filename ); geode::OpenGeodeMeshException::test( solid->nb_vertices() == 6, "Backward TetrahedralSolid should have 6 vertices" ); + geode::OpenGeodeMeshException::test( + solid->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward TetrahedralSolid should have a valid id" ); geode::OpenGeodeMeshException::test( solid->nb_polyhedra() == 3, "Backward TetrahedralSolid should have 3 polyhedra" ); geode::OpenGeodeMeshException::test( solid->edges().nb_edges() == 12, diff --git a/tests/mesh/test-triangulated-surface.cpp b/tests/mesh/test-triangulated-surface.cpp index eda20b41f..e2c06bddf 100644 --- a/tests/mesh/test-triangulated-surface.cpp +++ b/tests/mesh/test-triangulated-surface.cpp @@ -21,6 +21,8 @@ * */ +#include + #include #include #include @@ -238,6 +240,24 @@ void test_delete_polygon( const geode::TriangulatedSurface3D& surface, "TriangulatedSurface should have 5 edges" ); } +void check_same_attribute_ids( const geode::AttributeManager& manager, + const geode::AttributeManager& manager2 ) +{ + auto ids = manager.attribute_ids(); + auto ids2 = manager2.attribute_ids(); + std::sort( ids.begin(), ids.end() ); + std::sort( ids2.begin(), ids2.end() ); + geode::OpenGeodeMeshException::test( + std::equal( ids.begin(), ids.end(), ids2.begin(), ids2.end() ), + "Reloaded attribute ids should be the saved ones" ); + for( const auto& id : ids2 ) + { + geode::OpenGeodeMeshException::test( + manager2.find_generic_attribute( id )->id() == id, + "Reloaded attribute should keep its id" ); + } +} + void test_io( const geode::TriangulatedSurface3D& surface, std::string_view filename ) { @@ -262,6 +282,12 @@ void test_io( .inexact_equal( surface2->point( vertex_id ) ), "Wrong reloaded mesh point coordinates." ); } + geode::OpenGeodeMeshException::test( surface2->id() == surface.id(), + "Reloaded TriangulatedSurface should keep its id" ); + check_same_attribute_ids( surface.vertex_attribute_manager(), + surface2->vertex_attribute_manager() ); + check_same_attribute_ids( surface.polygon_attribute_manager(), + surface2->polygon_attribute_manager() ); } void test_backward_io( const std::string& filename ) @@ -270,6 +296,9 @@ void test_backward_io( const std::string& filename ) geode::load_triangulated_surface< 3 >( filename ), filename ); geode::OpenGeodeMeshException::test( surface->nb_vertices() == 5, "Backward TriangulatedSurface should have 5 vertices" ); + geode::OpenGeodeMeshException::test( + surface->id() != geode::uuid{ geode::BITSERY::constructor }, + "Backward TriangulatedSurface should have a valid id" ); geode::OpenGeodeMeshException::test( surface->nb_polygons() == 3, "Backward TriangulatedSurface should have 3 polygons" ); geode::OpenGeodeMeshException::test( diff --git a/tests/model/test-brep.cpp b/tests/model/test-brep.cpp index 4c3cd6962..b79a52368 100644 --- a/tests/model/test-brep.cpp +++ b/tests/model/test-brep.cpp @@ -1190,6 +1190,48 @@ void test_block_collection_ranges( const geode::BRep& model, "ItemBlockRange should iterates on 1 Block." ); } +void test_compare_component_mesh_vertices( + const geode::BRep& model, const geode::BRep& model2 ) +{ + geode::OpenGeodeModelException::test( model.nb_unique_vertices() > 0, + "[Test] Model should have unique vertices" ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == model2.nb_unique_vertices(), + "[Test] Reloaded model should have ", model.nb_unique_vertices(), + " unique vertices" ); + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + const auto& vertices2 = model2.component_mesh_vertices( unique_vertex ); + geode::OpenGeodeModelException::test( vertices == vertices2, + "[Test] Reloaded component mesh vertices of unique vertex ", + unique_vertex, " should be equal to the saved ones" ); + for( const auto& vertex : vertices2 ) + { + geode::OpenGeodeModelException::test( vertex.component_id.id != nil, + "[Test] Reloaded component id should not be nil" ); + geode::OpenGeodeModelException::test( + model2.unique_vertex( vertex ) == unique_vertex, + "[Test] Reloaded component mesh vertex should map to unique " + "vertex ", + unique_vertex ); + } + } +} + +void test_component_mesh_vertices_round_trip() +{ + const auto filename = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + const auto model = + geode::load_one( geode::load_brep( filename ), filename ); + const auto file_io = absl::StrCat( + "test_component_mesh_vertices.", model.native_extension() ); + geode::save_brep( model, file_io ); + const auto model2 = geode::load_one( geode::load_brep( file_io ), file_io ); + test_compare_component_mesh_vertices( model, model2 ); +} + void test_compare_brep( const geode::BRep& model, const geode::BRep& model2 ) { geode::OpenGeodeModelException::test( @@ -1824,6 +1866,11 @@ void test_backward_io() absl::StrCat( geode::DATA_PATH, "backward_io/v17/v17.og_brep" ); auto brep_v17 = geode::load_one( geode::load_brep( brep_v17_filename ), brep_v17_filename ); + geode::OpenGeodeModelException::test( + brep_v17.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v17 BRep should have a valid unique vertex attribute " + "id" ); geode::BRepBuilder brep_builder_v17{ brep_v17 }; for( const auto& block : brep_v17.blocks() ) { @@ -1862,6 +1909,11 @@ void test_backward_io() absl::StrCat( geode::DATA_PATH, "backward_io/v18_0/v18_0.og_brep" ); auto brep_v18_0 = geode::load_one( geode::load_brep( brep_v18_0_filename ), brep_v18_0_filename ); + geode::OpenGeodeModelException::test( + brep_v18_0.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v18_0 BRep should have a valid unique vertex attribute " + "id" ); geode::BRepBuilder brep_builder_v18{ brep_v18_0 }; for( const auto& block : brep_v18_0.blocks() ) { @@ -2353,6 +2405,7 @@ void test() geode::BRep model3{ std::move( model2 ) }; test_compare_brep( model, model3 ); + test_component_mesh_vertices_round_trip(); test_backward_io(); test_physical_properties_backward_io(); test_components_filter(); diff --git a/tests/model/test-section.cpp b/tests/model/test-section.cpp index 8711170f2..8c2b77306 100644 --- a/tests/model/test-section.cpp +++ b/tests/model/test-section.cpp @@ -880,6 +880,49 @@ void test_clone( const geode::Section& section ) } } +void test_compare_component_mesh_vertices( + const geode::Section& model, const geode::Section& model2 ) +{ + geode::OpenGeodeModelException::test( model.nb_unique_vertices() > 0, + "[Test] Model should have unique vertices" ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == model2.nb_unique_vertices(), + "[Test] Reloaded model should have ", model.nb_unique_vertices(), + " unique vertices" ); + const geode::uuid nil{ geode::BITSERY::constructor }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + const auto& vertices2 = model2.component_mesh_vertices( unique_vertex ); + geode::OpenGeodeModelException::test( vertices == vertices2, + "[Test] Reloaded component mesh vertices of unique vertex ", + unique_vertex, " should be equal to the saved ones" ); + for( const auto& vertex : vertices2 ) + { + geode::OpenGeodeModelException::test( vertex.component_id.id != nil, + "[Test] Reloaded component id should not be nil" ); + geode::OpenGeodeModelException::test( + model2.unique_vertex( vertex ) == unique_vertex, + "[Test] Reloaded component mesh vertex should map to unique " + "vertex ", + unique_vertex ); + } + } +} + +void test_component_mesh_vertices_round_trip() +{ + const auto filename = absl::StrCat( geode::DATA_PATH, "fractures.og_sctn" ); + const auto model = + geode::load_one( geode::load_section( filename ), filename ); + const auto file_io = absl::StrCat( + "test_component_mesh_vertices.", model.native_extension() ); + geode::save_section( model, file_io ); + const auto model2 = + geode::load_one( geode::load_section( file_io ), file_io ); + test_compare_component_mesh_vertices( model, model2 ); +} + void test_compare_section( const geode::Section& model, const geode::Section& model2 ) { @@ -1101,11 +1144,17 @@ void test() auto backward_model = geode::load_one( geode::load_section( backward_model_filename ), backward_model_filename ); + geode::OpenGeodeModelException::test( + backward_model.unique_vertex_attribute_id() + != geode::uuid{ geode::BITSERY::constructor }, + "[Backward_IO] v17 Section should have a valid unique vertex " + "attribute id" ); auto model2 = geode::load_one( geode::load_section( file_io ), file_io ); test_compare_section( model, model2 ); geode::Section model3{ std::move( model2 ) }; test_compare_section( model, model3 ); + test_component_mesh_vertices_round_trip(); } OPENGEODE_TEST( "section" ) \ No newline at end of file diff --git a/tests/model/test-vertex-identifier.cpp b/tests/model/test-vertex-identifier.cpp index 22aa35fb7..e340f900f 100644 --- a/tests/model/test-vertex-identifier.cpp +++ b/tests/model/test-vertex-identifier.cpp @@ -21,7 +21,12 @@ * */ +#include + +#include + #include +#include #include #include @@ -425,9 +430,59 @@ void test_unregister_after_load() } } +void test_component_mesh_vertex_deserialization() +{ + const geode::uuid nil{ geode::BITSERY::constructor }; + const auto created_id = bitsery::Access::create< geode::ComponentID >(); + geode::OpenGeodeModelException::test( + created_id.type.get() == "undefined" && created_id.id == nil, + "ComponentID created by bitsery should be undefined and nil" ); + const auto created_vertex = + bitsery::Access::create< geode::ComponentMeshVertex >(); + geode::OpenGeodeModelException::test( + created_vertex.component_id.type.get() == "undefined" + && created_vertex.component_id.id == nil, + "ComponentMeshVertex created by bitsery should have an undefined and " + "nil ComponentID" ); + const geode::ComponentID default_id; + geode::OpenGeodeModelException::test( + default_id.id != nil, "Default ComponentID should generate its uuid" ); + + const geode::ComponentID component_id{ + geode::Corner2D::component_type_static(), geode::uuid{} + }; + std::vector< geode::ComponentMeshVertex > vertices{ { component_id, 3 }, + { { geode::Surface2D::component_type_static(), geode::uuid{} }, 7 } }; + std::stringstream stream; + { + geode::TContext context{}; + geode::Serializer archive{ context, stream }; + archive.object( component_id ); + archive.container( vertices, vertices.size() ); + archive.adapter().flush(); + } + geode::ComponentID loaded_id{ geode::BITSERY::constructor }; + std::vector< geode::ComponentMeshVertex > loaded_vertices; + { + geode::TContext context{}; + geode::Deserializer archive{ context, stream }; + archive.object( loaded_id ); + archive.container( loaded_vertices, vertices.size() ); + geode::OpenGeodeModelException::test( + archive.adapter().error() == bitsery::ReaderError::NoError + && archive.adapter().isCompletedSuccessfully(), + "ComponentMeshVertex deserialization should succeed" ); + } + geode::OpenGeodeModelException::test( loaded_id == component_id, + "Deserialized ComponentID should be the saved one" ); + geode::OpenGeodeModelException::test( loaded_vertices == vertices, + "Deserialized ComponentMeshVertex should be the saved ones" ); +} + void test() { geode::OpenGeodeModelLibrary::initialize(); + test_component_mesh_vertex_deserialization(); geode::VertexIdentifier vertex_identifier; geode::OpenGeodeModelException::test( vertex_identifier.nb_unique_vertices() == 0, From f4d9a6fb2f106e86c7848485259750cf485f6da9 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 15:53:56 +0100 Subject: [PATCH 3/8] perf(Serialization): deserialize bitsery from memory buffers geode::Deserializer read through bitsery::InputStreamAdapter: every value was a virtual std::streambuf call. It now reads a geode::ByteSpan (read-only bytes, owned elsewhere) with bitsery::InputBufferAdapter, so that both a file read in memory and a slice of an archive in memory can be deserialized. Add detail::read_file_content (whole file in one read, UTF-8 path) and detail::deserialize_bytes (contexts of every registered library and the usual completion check), and use them at every native read site: identifier, relationships, unique vertices, physical properties, components, meshes, light regular grids, raster images and external time series. Native mesh, light regular grid and raster image files are now read and written with UTF-8 paths. Co-Authored-By: Claude Opus 5.5 --- include/geode/basic/bitsery_archive.hpp | 111 +++++++++++++++++- .../io/geode/geode_bitsery_raster_input.hpp | 22 +--- .../io/geode/geode_bitsery_raster_output.hpp | 4 +- .../io/geode/geode_bitsery_mesh_input.hpp | 27 ++--- .../io/geode/geode_bitsery_mesh_output.hpp | 4 +- .../geode/geode_light_regular_grid_input.hpp | 24 ++-- .../mixin/core/detail/components_storage.hpp | 19 ++- src/geode/basic/bitsery_archive.cpp | 34 ++++++ src/geode/basic/identifier.cpp | 17 +-- .../mesh/io/light_regular_grid_output.cpp | 4 +- .../model/mixin/core/physical_properties.cpp | 19 ++- src/geode/model/mixin/core/relationships.cpp | 18 +-- .../model/mixin/core/vertex_identifier.cpp | 22 ++-- .../io/external_time_series_input.cpp | 18 +-- tests/basic/test-attribute.cpp | 17 ++- tests/basic/test-growable.cpp | 8 +- tests/basic/test-uuid.cpp | 3 +- tests/geometry/test-octree.cpp | 8 +- tests/image/test-raster-image.cpp | 5 + tests/mesh/test-light-regular-grid.cpp | 3 + tests/mesh/test-mesh-truncated-files.cpp | 37 ++++++ tests/mesh/test-polygonal-surface.cpp | 7 +- tests/mesh/test-texture-manager.cpp | 7 +- tests/mesh/test-triangulated-surface.cpp | 3 + tests/model/test-model-corrupted-files.cpp | 93 +++++++++++++++ tests/model/test-vertex-identifier.cpp | 3 +- 26 files changed, 390 insertions(+), 147 deletions(-) diff --git a/include/geode/basic/bitsery_archive.hpp b/include/geode/basic/bitsery_archive.hpp index b73d8854a..ba47fc716 100644 --- a/include/geode/basic/bitsery_archive.hpp +++ b/include/geode/basic/bitsery_archive.hpp @@ -23,9 +23,16 @@ #pragma once +#include +#include +#include +#include + #include #include +#include +#include #include #include #include @@ -37,6 +44,41 @@ #include #include +namespace geode +{ + /*! + * Read-only bytes to deserialize, owned elsewhere (file content, slice of + * an archive in memory...). + */ + using ByteSpan = absl::Span< const char >; +} // namespace geode + +namespace bitsery +{ + namespace traits + { + template <> + struct ContainerTraits< geode::ByteSpan > + { + using TValue = char; + static constexpr bool isResizable = false; + static constexpr bool isContiguous = true; + static size_t size( const geode::ByteSpan &container ) + { + return container.size(); + } + }; + + template <> + struct BufferAdapterTraits< geode::ByteSpan > + { + using TIterator = const char *; + using TConstIterator = const char *; + using TValue = char; + }; + } // namespace traits +} // namespace bitsery + namespace geode { using PContext = @@ -46,8 +88,13 @@ namespace geode bitsery::ext::InheritanceContext >; using Serializer = bitsery::Serializer< bitsery::OutputBufferedStreamAdapter, TContext >; + /*! + * Deserializer reading a ByteSpan: + * Deserializer archive{ context, bytes.data(), bytes.size() }. + */ using Deserializer = - bitsery::Deserializer< bitsery::InputStreamAdapter, TContext >; + bitsery::Deserializer< bitsery::InputBufferAdapter< ByteSpan >, + TContext >; /*! * Register all the information needed by Bitsery to serialize the objects @@ -79,6 +126,68 @@ namespace geode static void register_deserialize_pcontext( PContext &context ); }; + + namespace detail + { + /*! + * Owned bytes, uninitialized at construction. + */ + class ByteBuffer + { + public: + explicit ByteBuffer( size_t size ) + : data_{ new char[size] }, size_{ size } + { + } + + [[nodiscard]] char *data() + { + return data_.get(); + } + + [[nodiscard]] size_t size() const + { + return size_; + } + + [[nodiscard]] ByteSpan span() const + { + return { data_.get(), size_ }; + } + + private: + std::unique_ptr< char[] > data_; + size_t size_; + }; + + /*! + * Read the whole content of a file (UTF-8 path) in one call. + * @return std::nullopt if the file cannot be opened. + * @exception OpenGeodeException (data) if the file cannot be read. + */ + [[nodiscard]] std::optional< ByteBuffer > + opengeode_basic_api read_file_content( std::string_view filename ); + + /*! + * Deserialize an object from bytes, with the deserialize contexts of + * every registered library. + * @return true if the bytes were read without error, entirely, and + * every pointer was linked. + */ + template < typename Object > + [[nodiscard]] bool deserialize_bytes( ByteSpan bytes, Object &object ) + { + TContext context{}; + BitseryExtensions::register_deserialize_pcontext( + std::get< 0 >( context ) ); + Deserializer archive{ context, bytes.data(), bytes.size() }; + archive.object( object ); + const auto &adapter = archive.adapter(); + return adapter.error() == bitsery::ReaderError::NoError + && adapter.isCompletedSuccessfully() + && std::get< 1 >( context ).isValid(); + } + } // namespace detail } // namespace geode namespace bitsery diff --git a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp index d8328cb3c..a5adaf1f5 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp @@ -41,24 +41,14 @@ namespace geode [[nodiscard]] std::vector< RasterImage< dimension > > read() final { - std::ifstream file{ to_string( this->filename() ), - std::ifstream::binary }; - OpenGeodeImageException::check_exception( !file.fail(), nullptr, - OpenGeodeException::TYPE::data, - "[RasterImageInput] Failed to open file: ", - to_string( this->filename() ) ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; + const auto content = detail::read_file_content( this->filename() ); + OpenGeodeImageException::check_exception( content.has_value(), + nullptr, OpenGeodeException::TYPE::data, + "[RasterImageInput] Failed to open file: ", this->filename() ); RasterImage< dimension > image; - archive.object( image ); - const auto& adapter = archive.adapter(); OpenGeodeImageException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::data, + detail::deserialize_bytes( content->span(), image ), nullptr, + OpenGeodeException::TYPE::data, "[Bitsery::read] Error while reading file: ", this->filename() ); std::vector< RasterImage< dimension > > images; diff --git a/include/geode/image/io/geode/geode_bitsery_raster_output.hpp b/include/geode/image/io/geode/geode_bitsery_raster_output.hpp index 4f699dac0..195f1825f 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_output.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_output.hpp @@ -23,6 +23,7 @@ #pragma once +#include #include #include #include @@ -44,7 +45,8 @@ namespace geode std::vector< std::string > write( const RasterImage< dimension >& mesh ) const final { - std::ofstream file{ to_string( this->filename() ), + std::ofstream file{ std::filesystem::u8path( + to_string( this->filename() ) ), std::ofstream::binary }; OpenGeodeImageException::check_exception( !file.fail(), nullptr, OpenGeodeException::TYPE::data, diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp index 67329ba25..4fa23d473 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp @@ -35,21 +35,18 @@ [[nodiscard]] std::vector< std::unique_ptr< Mesh > > read( \ const MeshImpl& /*impl*/ ) final \ { \ - std::ifstream file{ to_string( this->filename() ), \ - std::ifstream::binary }; \ - geode::OpenGeodeMeshException::check_exception( !file.fail(), nullptr, \ - geode::OpenGeodeException::TYPE::data, \ - "[Bitsery::read] Failed to open file: ", \ - to_string( this->filename() ) ); \ - TContext context{}; \ - BitseryExtensions::register_deserialize_pcontext( \ - std::get< 0 >( context ) ); \ - Deserializer archive{ context, file }; \ + const auto content = \ + geode::detail::read_file_content( this->filename() ); \ + geode::OpenGeodeMeshException::check_exception( content.has_value(), \ + nullptr, geode::OpenGeodeException::TYPE::data, \ + "[Bitsery::read] Failed to open file: ", this->filename() ); \ std::unique_ptr< Mesh > mesh{ new OpenGeode##Mesh{ \ BITSERY::constructor } }; \ + bool success{ false }; \ try \ { \ - archive.object( dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ + success = geode::detail::deserialize_bytes( \ + content->span(), dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ } \ catch( const geode::OpenGeodeException& ) \ { \ @@ -62,12 +59,8 @@ "[Bitsery::read] Error while reading file: ", \ this->filename(), " (", exception.what(), ")" }; \ } \ - const auto& adapter = archive.adapter(); \ - geode::OpenGeodeMeshException::check_exception( \ - adapter.error() == bitsery::ReaderError::NoError \ - && adapter.isCompletedSuccessfully() \ - && std::get< 1 >( context ).isValid(), \ - nullptr, geode::OpenGeodeException::TYPE::internal, \ + geode::OpenGeodeMeshException::check_exception( success, nullptr, \ + geode::OpenGeodeException::TYPE::internal, \ "[Bitsery::read] Error while reading file: ", this->filename() ); \ std::vector< std::unique_ptr< Mesh > > meshes; \ meshes.emplace_back( std::move( mesh ) ); \ diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp index c7edbb812..77b7cbb58 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_output.hpp @@ -23,6 +23,7 @@ #pragma once +#include #include #include @@ -44,7 +45,8 @@ geode::OpenGeodeException::TYPE::data, "[Bitsery] Cannot save ", \ mesh.type_name().get(), " in native format because it is not ", \ OpenGeode##Mesh::impl_name_static().get() ); \ - std::ofstream file{ to_string( this->filename() ), \ + std::ofstream file{ std::filesystem::u8path( \ + to_string( this->filename() ) ), \ std::ofstream::binary }; \ geode::OpenGeodeMeshException::check_exception( !file.fail(), nullptr, \ geode::OpenGeodeException::TYPE::data, \ diff --git a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp index 2cdc1a258..a59a79d25 100644 --- a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp +++ b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp @@ -55,16 +55,11 @@ namespace geode [[nodiscard]] std::vector< LightRegularGrid< dimension > > read() override { - std::ifstream file{ to_string( this->filename() ), - std::ifstream::binary }; - OpenGeodeMeshException::check_exception( !file.fail(), nullptr, - OpenGeodeException::TYPE::data, + const auto content = detail::read_file_content( this->filename() ); + OpenGeodeMeshException::check_exception( content.has_value(), + nullptr, OpenGeodeException::TYPE::data, "[LightRegularGridInput] Failed to open file: ", - to_string( this->filename() ) ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; + this->filename() ); Point< dimension > origin; std::array< index_t, dimension > cells_number; cells_number.fill( 1 ); @@ -72,9 +67,10 @@ namespace geode cells_length.fill( 1 ); LightRegularGrid< dimension > grid{ origin, cells_number, cells_length }; + bool success{ false }; try { - archive.object( grid ); + success = detail::deserialize_bytes( content->span(), grid ); } catch( const OpenGeodeException& ) { @@ -87,12 +83,8 @@ namespace geode "[Bitsery::read] Error while reading file: ", this->filename(), " (", exception.what(), ")" }; } - const auto& adapter = archive.adapter(); - OpenGeodeMeshException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + OpenGeodeMeshException::check_exception( success, nullptr, + OpenGeodeException::TYPE::internal, "[Bitsery::read] Error while reading file: ", this->filename() ); std::vector< LightRegularGrid< dimension > > grids; diff --git a/include/geode/model/mixin/core/detail/components_storage.hpp b/include/geode/model/mixin/core/detail/components_storage.hpp index 78ac4af53..bee722642 100644 --- a/include/geode/model/mixin/core/detail/components_storage.hpp +++ b/include/geode/model/mixin/core/detail/components_storage.hpp @@ -186,21 +186,18 @@ namespace geode::detail } return; } - std::ifstream file{ path, std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + const auto content = detail::read_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::internal, "[ComponentsStorage::load_components] Error while reading " "file: ", filename ); + OpenGeodeModelException::check_exception( + detail::deserialize_bytes( content->span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, + "[ComponentsStorage::load_components] Error while reading " + "file: ", + filename ); repair_loaded_components( filename ); } diff --git a/src/geode/basic/bitsery_archive.cpp b/src/geode/basic/bitsery_archive.cpp index 4fb32eea3..0c4beb16c 100644 --- a/src/geode/basic/bitsery_archive.cpp +++ b/src/geode/basic/bitsery_archive.cpp @@ -23,8 +23,13 @@ #include +#include +#include + #include +#include + namespace { class BitseryExtensionsStorage @@ -85,4 +90,33 @@ namespace geode function( context ); } } + + namespace detail + { + std::optional< ByteBuffer > read_file_content( + std::string_view filename ) + { + std::ifstream file{ std::filesystem::u8path( + to_string( filename ) ), + std::ifstream::binary | std::ifstream::ate }; + if( !file ) + { + return std::nullopt; + } + const auto end = file.tellg(); + OpenGeodeBasicException::check_exception( end >= 0, nullptr, + OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + ByteBuffer buffer{ static_cast< size_t >( end ) }; + file.seekg( 0 ); + file.read( buffer.data(), + static_cast< std::streamsize >( buffer.size() ) ); + OpenGeodeBasicException::check_exception( + file.gcount() + == static_cast< std::streamsize >( buffer.size() ), + nullptr, OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + return buffer; + } + } // namespace detail } // namespace geode diff --git a/src/geode/basic/identifier.cpp b/src/geode/basic/identifier.cpp index 3bf424d4d..5f15b1557 100644 --- a/src/geode/basic/identifier.cpp +++ b/src/geode/basic/identifier.cpp @@ -84,23 +84,14 @@ namespace geode void load( std::string_view directory ) { const auto filename = absl::StrCat( directory, "/identifier" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - if( !file ) + const auto content = detail::read_file_content( filename ); + if( !content ) { return; } - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); OpenGeodeBasicException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + detail::deserialize_bytes( content->span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, "[Identifier::load] Error while reading file: ", filename ); } diff --git a/src/geode/mesh/io/light_regular_grid_output.cpp b/src/geode/mesh/io/light_regular_grid_output.cpp index 45af78c42..5d712792a 100644 --- a/src/geode/mesh/io/light_regular_grid_output.cpp +++ b/src/geode/mesh/io/light_regular_grid_output.cpp @@ -23,6 +23,7 @@ #include +#include #include #include #include @@ -40,7 +41,8 @@ namespace geode std::vector< std::string > LightRegularGridOutput< dimension >::write( const LightRegularGrid< dimension >& grid ) const { - std::ofstream file{ to_string( this->filename() ), + std::ofstream file{ std::filesystem::u8path( + to_string( this->filename() ) ), std::ofstream::binary }; OpenGeodeMeshException::check_exception( !file.fail(), nullptr, OpenGeodeException::TYPE::data, diff --git a/src/geode/model/mixin/core/physical_properties.cpp b/src/geode/model/mixin/core/physical_properties.cpp index ee245f598..4a81b3fcd 100644 --- a/src/geode/model/mixin/core/physical_properties.cpp +++ b/src/geode/model/mixin/core/physical_properties.cpp @@ -230,21 +230,16 @@ namespace geode { return; } - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + const auto content = detail::read_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::internal, "[PhysicalProperties::load] Error while reading file: ", filename ); + OpenGeodeModelException::check_exception( + detail::deserialize_bytes( content->span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, + "[PhysicalProperties::load] Error while reading file: ", + filename ); } private: diff --git a/src/geode/model/mixin/core/relationships.cpp b/src/geode/model/mixin/core/relationships.cpp index 912d2d05e..12c0a2c44 100644 --- a/src/geode/model/mixin/core/relationships.cpp +++ b/src/geode/model/mixin/core/relationships.cpp @@ -201,20 +201,14 @@ namespace geode void load( std::string_view directory ) { const auto filename = absl::StrCat( directory, "/relationships" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + const auto content = detail::read_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::internal, "[Relationships::load] Error while reading file: ", filename ); + OpenGeodeModelException::check_exception( + detail::deserialize_bytes( content->span(), *this ), nullptr, + OpenGeodeException::TYPE::internal, + "[Relationships::load] Error while reading file: ", filename ); } private: diff --git a/src/geode/model/mixin/core/vertex_identifier.cpp b/src/geode/model/mixin/core/vertex_identifier.cpp index 1ebf13fb3..4e0bb612e 100644 --- a/src/geode/model/mixin/core/vertex_identifier.cpp +++ b/src/geode/model/mixin/core/vertex_identifier.cpp @@ -531,22 +531,18 @@ namespace geode void load( std::string_view directory ) { const auto filename = absl::StrCat( directory, "/vertices" ); - std::ifstream file{ std::filesystem::u8path( filename ), - std::ifstream::binary }; - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; - archive.object( *this ); - nb_component_mesh_vertices_up_to_date_ = false; - const auto& adapter = archive.adapter(); - OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), + const auto content = detail::read_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::internal, "[VertexIdentifier::load] Error while reading file: ", filename ); + const auto success = + detail::deserialize_bytes( content->span(), *this ); + nb_component_mesh_vertices_up_to_date_ = false; + OpenGeodeModelException::check_exception( success, nullptr, + OpenGeodeException::TYPE::internal, + "[VertexIdentifier::load] Error while reading file: ", + filename ); } private: diff --git a/src/geode/model/representation/io/external_time_series_input.cpp b/src/geode/model/representation/io/external_time_series_input.cpp index 80cc38cf3..4d5d9f83e 100644 --- a/src/geode/model/representation/io/external_time_series_input.cpp +++ b/src/geode/model/representation/io/external_time_series_input.cpp @@ -23,8 +23,6 @@ #include -#include - #include #include #include @@ -44,22 +42,14 @@ namespace geode "[load_external_time_series] Wrong extension for file ", filename, ", only ", ExternalTimeSeries::native_extension_static(), " is supported" ); - std::ifstream file{ to_string( filename ), std::ifstream::binary }; - OpenGeodeModelException::check_exception( !file.fail(), nullptr, + const auto content = detail::read_file_content( filename ); + OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, "[load_external_time_series] Failed to open file: ", filename ); - TContext context{}; - BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - Deserializer archive{ context, file }; ExternalTimeSeries time_series; - archive.object( time_series ); - const auto& adapter = archive.adapter(); OpenGeodeModelException::check_exception( - adapter.error() == bitsery::ReaderError::NoError - && adapter.isCompletedSuccessfully() - && std::get< 1 >( context ).isValid(), - nullptr, OpenGeodeException::TYPE::internal, + detail::deserialize_bytes( content->span(), time_series ), nullptr, + OpenGeodeException::TYPE::internal, "[load_external_time_series] Error while reading file: ", filename ); Logger::info( "ExternalTimeSeries loaded from ", filename, " in ", diff --git a/tests/basic/test-attribute.cpp b/tests/basic/test-attribute.cpp index 1ca08cbc1..84ddd66a8 100644 --- a/tests/basic/test-attribute.cpp +++ b/tests/basic/test-attribute.cpp @@ -524,7 +524,9 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - std::ifstream infile{ filename, std::ifstream::binary }; + const auto content = geode::detail::read_file_content( filename ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; geode::TContext reload_context{}; geode::register_attribute_type< std::array< double, 30 >, @@ -536,7 +538,8 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::register_attribute_type< std::array< double, 2 >, geode::Deserializer >( std::get< 0 >( reload_context ), "array_double_2" ); - geode::Deserializer unarchive{ reload_context, infile }; + geode::Deserializer unarchive{ reload_context, content->span().data(), + content->size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( @@ -925,12 +928,15 @@ void test_no_value() geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - std::ifstream infile{ filename, std::ifstream::binary }; + const auto content = geode::detail::read_file_content( filename ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; geode::TContext reload_context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( reload_context ) ); - geode::Deserializer unarchive{ reload_context, infile }; + geode::Deserializer unarchive{ reload_context, content->span().data(), + content->size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( @@ -1124,7 +1130,8 @@ void test_time_series_serialization( const geode::AttributeManager& manager ) geode::TContext reload_context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( reload_context ) ); - geode::Deserializer unarchive{ reload_context, stream }; + const auto bytes = stream.str(); + geode::Deserializer unarchive{ reload_context, bytes.data(), bytes.size() }; unarchive.object( reloaded ); geode::OpenGeodeBasicException::test( unarchive.adapter().error() == bitsery::ReaderError::NoError, diff --git a/tests/basic/test-growable.cpp b/tests/basic/test-growable.cpp index 02faf7fc3..5b6f49557 100644 --- a/tests/basic/test-growable.cpp +++ b/tests/basic/test-growable.cpp @@ -110,9 +110,13 @@ Out test_growable( const T &foo ) serializer.object( foo ); serializer.adapter().flush(); - std::ifstream input{ "name", std::ifstream::binary }; + output.close(); + const auto content = geode::detail::read_file_content( "name" ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot open file" ); geode::TContext context_input{}; - geode::Deserializer deserializer{ context_input, input }; + geode::Deserializer deserializer{ context_input, content->span().data(), + content->size() }; Out new_foo; deserializer.object( new_foo ); const auto &adapter = deserializer.adapter(); diff --git a/tests/basic/test-uuid.cpp b/tests/basic/test-uuid.cpp index aa6e26fc6..11c78b38b 100644 --- a/tests/basic/test-uuid.cpp +++ b/tests/basic/test-uuid.cpp @@ -113,7 +113,8 @@ void test_deserialization() Map loaded_map; { geode::TContext context{}; - geode::Deserializer archive{ context, stream }; + const auto bytes = stream.str(); + geode::Deserializer archive{ context, bytes.data(), bytes.size() }; archive.object( loaded_id ); archive.ext( loaded_map, bitsery::ext::StdMap{ map.size() }, []( geode::Deserializer& local_archive, geode::uuid& key, diff --git a/tests/geometry/test-octree.cpp b/tests/geometry/test-octree.cpp index 33fb0cc77..a5757f4c2 100644 --- a/tests/geometry/test-octree.cpp +++ b/tests/geometry/test-octree.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include @@ -690,13 +691,16 @@ namespace } geode::Octree< dimension > reloaded; { - std::ifstream file{ filename, std::ifstream::binary }; + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeGeometryException::test( + content.has_value(), "[Test] Cannot open file" ); geode::TContext context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_geometry_deserialize_pcontext( std::get< 0 >( context ) ); - geode::Deserializer archive{ context, file }; + geode::Deserializer archive{ context, content->span().data(), + content->span().size() }; archive.object( reloaded ); const auto& adapter = archive.adapter(); geode::OpenGeodeGeometryException::test( diff --git a/tests/image/test-raster-image.cpp b/tests/image/test-raster-image.cpp index 435bcdfa2..39baf93c0 100644 --- a/tests/image/test-raster-image.cpp +++ b/tests/image/test-raster-image.cpp @@ -235,6 +235,11 @@ void test() geode::load_one( geode::load_raster_image< 2 >( filename_with_spaces ), filename_with_spaces ); test_raster( reload ); + // UTF-8 file name + const std::string utf8_filename{ "image_\xc3\xa9t\xc3\xa9.og_img2d" }; + geode::save_raster_image( raster, utf8_filename ); + test_raster( geode::load_one( + geode::load_raster_image< 2 >( utf8_filename ), utf8_filename ) ); test_save_failure( raster ); test_unknown_extension( raster ); test_io< 1 >( { 7 } ); diff --git a/tests/mesh/test-light-regular-grid.cpp b/tests/mesh/test-light-regular-grid.cpp index 0ed80438c..da68f6043 100644 --- a/tests/mesh/test-light-regular-grid.cpp +++ b/tests/mesh/test-light-regular-grid.cpp @@ -719,6 +719,9 @@ void test() test_nan_query( grid ); test_clone_exact_geometry(); test_io( grid, absl::StrCat( "test.", grid.native_extension() ) ); + // UTF-8 file name + test_io( grid, + absl::StrCat( "grille_\xc3\xa9t\xc3\xa9.", grid.native_extension() ) ); test_save_unwritable( grid ); test_coordinate_reference_systems(); test_backward_io(); diff --git a/tests/mesh/test-mesh-truncated-files.cpp b/tests/mesh/test-mesh-truncated-files.cpp index 8c3d37f93..8525823ac 100644 --- a/tests/mesh/test-mesh-truncated-files.cpp +++ b/tests/mesh/test-mesh-truncated-files.cpp @@ -128,6 +128,38 @@ namespace nb_throws > 0, "Truncated files of ", filename, " should throw" ); } + /* + * Load a copy of the given file truncated at half its size: data error. + */ + void test_half_file( const std::string& filename, const Loader& loader ) + { + const auto content = read_file( filename ); + const auto extension = + std::filesystem::path{ filename }.extension().string(); + const auto truncated_filename = absl::StrCat( "half", extension ); + { + std::ofstream file{ truncated_filename, std::ofstream::binary }; + file.write( content.data(), + static_cast< std::streamsize >( content.size() / 2 ) ); + } + try + { + loader( truncated_filename ); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::Logger::info( "Half ", filename, ": ", exception.what() ); + geode::OpenGeodeMeshException::test( + exception.type() == geode::OpenGeodeException::TYPE::data, + "[Test] Half ", filename, + " should raise a data error: ", exception.string() ); + return; + } + throw geode::OpenGeodeMeshException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "[Test] Half ", filename, + " should not be loaded" }; + } + std::string data_file( std::string_view name ) { return absl::StrCat( geode::DATA_PATH, "backward_io/", name ); @@ -233,6 +265,11 @@ void test() data_file( "v18_5/v18_5.og_tso3d" ), tetrahedral_solid ); test_truncated_file( save_textured_surface(), triangulated_surface2d ); test_truncated_file( save_light_grid(), light_grid ); + test_half_file( + data_file( "v18_5/v18_5.og_tsf3d" ), triangulated_surface3d ); + test_half_file( data_file( "v17/v17.og_pso3d" ), polyhedral_solid ); + test_half_file( save_textured_surface(), triangulated_surface2d ); + test_half_file( save_light_grid(), light_grid ); } OPENGEODE_TEST( "mesh-truncated-files" ) diff --git a/tests/mesh/test-polygonal-surface.cpp b/tests/mesh/test-polygonal-surface.cpp index c25007d69..a0acef5b3 100644 --- a/tests/mesh/test-polygonal-surface.cpp +++ b/tests/mesh/test-polygonal-surface.cpp @@ -785,12 +785,7 @@ std::string serialize_edges( const FacetEdges& edges ) void deserialize_edges( const std::string& buffer, FacetEdges& edges ) { - std::istringstream input{ buffer, std::ios::binary }; - geode::TContext context{}; - geode::BitseryExtensions::register_deserialize_pcontext( - std::get< 0 >( context ) ); - geode::Deserializer archive{ context, input }; - archive.object( edges ); + geode_unused( geode::detail::deserialize_bytes( buffer, edges ) ); } constexpr std::array< geode::index_t, 2 > EDGE_A{ 1000001, 1000002 }; diff --git a/tests/mesh/test-texture-manager.cpp b/tests/mesh/test-texture-manager.cpp index f8cb0b641..ea05c5a7d 100644 --- a/tests/mesh/test-texture-manager.cpp +++ b/tests/mesh/test-texture-manager.cpp @@ -101,13 +101,16 @@ void save( const geode::TextureStorage2D& storage, std::string_view filename ) geode::TextureStorage2D load( std::string_view filename ) { - std::ifstream file{ geode::to_string( filename ), std::ifstream::binary }; + const auto content = geode::detail::read_file_content( filename ); + geode::OpenGeodeMeshException::test( + content.has_value(), "[Bitsery::read] Cannot open file: ", filename ); geode::TContext context{}; geode::register_basic_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_geometry_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_image_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_mesh_deserialize_pcontext( std::get< 0 >( context ) ); - geode::Deserializer archive{ context, file }; + geode::Deserializer archive{ context, content->span().data(), + content->size() }; geode::TextureStorage2D storage; archive.object( storage ); const auto& adapter = archive.adapter(); diff --git a/tests/mesh/test-triangulated-surface.cpp b/tests/mesh/test-triangulated-surface.cpp index e2c06bddf..f13f2bee6 100644 --- a/tests/mesh/test-triangulated-surface.cpp +++ b/tests/mesh/test-triangulated-surface.cpp @@ -805,6 +805,9 @@ void test() test_create_polygons( *surface, *builder ); test_polygon_adjacencies( *surface, *builder ); test_io( *surface, absl::StrCat( "test.", surface->native_extension() ) ); + // UTF-8 file name + test_io( *surface, absl::StrCat( "surface_\xc3\xa9t\xc3\xa9.", + surface->native_extension() ) ); test_backward_io( absl::StrCat( geode::DATA_PATH, "backward_io/v17/v17.", surface->native_extension() ) ); test_permutation( *surface, *builder ); diff --git a/tests/model/test-model-corrupted-files.cpp b/tests/model/test-model-corrupted-files.cpp index af475bfe0..10f79c787 100644 --- a/tests/model/test-model-corrupted-files.cpp +++ b/tests/model/test-model-corrupted-files.cpp @@ -776,6 +776,97 @@ namespace "[Test] Truncated relationships should not be loaded" }; } + /* Messages of the exception thrown by loading the BRep, parents included */ + std::string brep_load_error( + std::string_view filename, geode::OpenGeodeException::TYPE type ) + { + try + { + geode_unused( geode::load_brep( filename ) ); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::OpenGeodeModelException::test( exception.type() == type, + "[Test] Wrong exception type loading ", filename, ": ", + exception.string() ); + std::string messages; + const geode::OpenGeodeException* current = &exception; + while( true ) + { + absl::StrAppend( &messages, current->what(), "\n" ); + if( !current->has_parent() ) + { + break; + } + current = ¤t->parent(); + } + return messages; + } + throw geode::OpenGeodeModelException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "[Test] Loading ", + filename, " should throw" }; + } + + /* + * Truncated model files are not loaded: data error raised by the loading + * of the file. + */ + void test_truncated_model_files() + { + saved_brep( "truncated_files.og_brep" ); + const auto files = extract_archive( "truncated_files.og_brep" ); + for( const std::string name : { "identifier", "physical_properties", + "corners", "relationships", "vertices" } ) + { + auto truncated = files; + auto& content = truncated.at( name ); + content.resize( content.size() / 2 ); + const auto filename = + absl::StrCat( "truncated_", name, ".og_brep" ); + write_archive( truncated, filename ); + const auto messages = brep_load_error( + filename, geode::OpenGeodeException::TYPE::data ); + geode::Logger::info( "Truncated ", name, ": ", messages ); + geode::OpenGeodeModelException::test( + absl::StrContains( messages, filename ), + "[Test] Wrong error for truncated ", name, ": ", messages ); + } + } + + /* + * Optional model files: missing ones are ignored, empty ones are not + * valid files. + */ + void test_empty_optional_files() + { + saved_brep( "optional_files.og_brep" ); + const auto files = extract_archive( "optional_files.og_brep" ); + for( const std::string name : { "identifier", "physical_properties" } ) + { + auto missing = files; + missing.erase( name ); + const auto missing_filename = + absl::StrCat( "missing_", name, ".og_brep" ); + write_archive( missing, missing_filename ); + const auto loaded = geode::load_one( + geode::load_brep( missing_filename ), missing_filename ); + geode::OpenGeodeModelException::test( loaded.nb_corners() != 0, + "[Test] Model without ", name, " should be loaded" ); + + auto empty = files; + empty.at( name ).clear(); + const auto empty_filename = + absl::StrCat( "empty_", name, ".og_brep" ); + write_archive( empty, empty_filename ); + const auto messages = brep_load_error( + empty_filename, geode::OpenGeodeException::TYPE::data ); + geode::Logger::info( "Empty ", name, ": ", messages ); + geode::OpenGeodeModelException::test( + absl::StrContains( messages, empty_filename ), + "[Test] Wrong error for empty ", name, ": ", messages ); + } + } + template < typename Base > class ThrowingInput final : public Base { @@ -902,6 +993,8 @@ void test() test_too_long_component_name(); test_logger_level_restored(); test_std_exceptions(); + test_truncated_model_files(); + test_empty_optional_files(); } OPENGEODE_TEST( "model-corrupted-files" ) diff --git a/tests/model/test-vertex-identifier.cpp b/tests/model/test-vertex-identifier.cpp index e340f900f..31cf1eb12 100644 --- a/tests/model/test-vertex-identifier.cpp +++ b/tests/model/test-vertex-identifier.cpp @@ -465,7 +465,8 @@ void test_component_mesh_vertex_deserialization() std::vector< geode::ComponentMeshVertex > loaded_vertices; { geode::TContext context{}; - geode::Deserializer archive{ context, stream }; + const auto bytes = stream.str(); + geode::Deserializer archive{ context, bytes.data(), bytes.size() }; archive.object( loaded_id ); archive.container( loaded_vertices, vertices.size() ); geode::OpenGeodeModelException::test( From 960b09371e7e9ee02ff43da6659bcfcdf3e07240 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 16:38:43 +0100 Subject: [PATCH 4/8] perf(VertexIdentifier): rebuild the component vertices on load instead of saving them The vertices file duplicated the "unique vertices" attribute of each component mesh: version 5 only stores the number of unique vertices and the attribute id. repair_component_vertices rebuilds the component vertices from the mesh attributes (components in registration order, i.e. the model order when loading, then increasing vertex indices) and removes links to unknown unique vertices with a warning. Versions 1 to 4 read the same bytes into a temporary vertex set and keep the previous repair. VertexIdentifier no longer owns a vertex set and attribute manager. Compatibility: files saved by this version cannot be loaded by earlier releases (they do not know the version 5 of the vertices file); files saved by earlier releases still load. Tests: component vertices are compared as sets after a reload, since the order after load is the rebuild order (checked separately, and identical for two loads); the standalone save/load test loads the components and repairs; legacy v20_2 BRep/Section files cover the old format, and the missing attribute restoration uses the legacy BRep file. Co-Authored-By: Claude Opus 5.5 --- .../model/mixin/core/vertex_identifier.cpp | 7 +- .../builder/vertex_identifier_builder.hpp | 13 +- .../model/mixin/core/vertex_identifier.hpp | 23 +- .../model/mixin/core/vertex_identifier.cpp | 399 +++++++++++------- tests/data/backward_io/v20_2/v20_2.og_brep | Bin 0 -> 27224 bytes tests/data/backward_io/v20_2/v20_2.og_sctn | Bin 0 -> 6826 bytes tests/model/test-brep.cpp | 178 +++++++- tests/model/test-model-corrupted-files.cpp | 65 ++- tests/model/test-section.cpp | 159 ++++++- tests/model/test-vertex-identifier.cpp | 66 ++- 10 files changed, 730 insertions(+), 180 deletions(-) create mode 100644 tests/data/backward_io/v20_2/v20_2.og_brep create mode 100644 tests/data/backward_io/v20_2/v20_2.og_sctn diff --git a/bindings/python/src/model/mixin/core/vertex_identifier.cpp b/bindings/python/src/model/mixin/core/vertex_identifier.cpp index 24edb2013..198c5f126 100644 --- a/bindings/python/src/model/mixin/core/vertex_identifier.cpp +++ b/bindings/python/src/model/mixin/core/vertex_identifier.cpp @@ -90,8 +90,11 @@ namespace geode }, pybind11::arg( "unique_vertex_id" ), "Return the list of ComponentMeshVertex identified with the " - "unique vertex; raise an IndexError if unique_vertex_id is not " - "in [0, nb_unique_vertices)" ) + "unique vertex, in insertion order (after loading a native " + "file of the current format: Corners, Lines, Surfaces then " + "Blocks in the model order, then increasing vertex " + "indices); raise an IndexError if " + "unique_vertex_id is not in [0, nb_unique_vertices)" ) .def( "is_unique_vertex_isolated", []( const VertexIdentifier& identifier, diff --git a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp index d88540af8..6c08c30a3 100644 --- a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp +++ b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp @@ -107,6 +107,9 @@ namespace geode /*! * Load the VertexIdentifier from a file. + * Files saved by the current version do not store the component + * vertices: they are rebuilt by repair_component_vertices once the + * mesh components are loaded. * @param[in] directory Folder containing the file that stores * VertexIdentifier information. */ @@ -118,9 +121,13 @@ namespace geode std::vector< index_t > delete_isolated_vertices(); /*! - * Remove component vertices referencing an unregistered component or - * an invalid vertex, and restore missing links from component vertices - * to their unique vertex. Used after loading a model. + * Used after loading a model, once its mesh components are loaded. + * Rebuild the component vertices from the component mesh attributes + * if the file does not store them (components in their registration + * order, then vertices in increasing order), otherwise remove + * component vertices referencing an unregistered component or an + * invalid vertex, and restore missing links from component vertices + * to their unique vertex. */ void repair_component_vertices(); diff --git a/include/geode/model/mixin/core/vertex_identifier.hpp b/include/geode/model/mixin/core/vertex_identifier.hpp index 226b9d5f5..0c38c6a2e 100644 --- a/include/geode/model/mixin/core/vertex_identifier.hpp +++ b/include/geode/model/mixin/core/vertex_identifier.hpp @@ -103,6 +103,10 @@ namespace geode /*! * Return the component vertices identified with an unique vertex. + * The order is the insertion order; after loading a file, it is the + * order of the rebuild done by repair_component_vertices (components + * in their registration order, then vertices in increasing order), + * which can differ from the order before saving. * @param[in] unique_vertex_id Indice of the unique vertex. */ [[nodiscard]] const std::vector< ComponentMeshVertex >& @@ -130,6 +134,10 @@ namespace geode /*! * Save the VertexIdentifier into a file. + * The file stores the number of unique vertices and the identifier of + * the "unique vertices" attribute of the component meshes, not the + * component vertices: these are rebuilt from the component mesh + * attributes when loading (see repair_component_vertices). * @param[in] directory Folder in which create the file. */ void save_unique_vertices( std::string_view directory ) const; @@ -203,6 +211,10 @@ namespace geode /*! * Load the VertexIdentifier from a file. + * Files saved by the current version do not store the component + * vertices: unique vertices are isolated until the mesh components + * are loaded (load_mesh_component) and repair_component_vertices + * rebuilds the component vertices. Older files store them. * @param[in] directory Folder containing the file that stores * VertexIdentifier information. */ @@ -215,9 +227,14 @@ namespace geode std::vector< index_t > delete_isolated_vertices( BuilderKey /*key*/ ); /*! - * Remove component vertices referencing an unregistered component or - * an invalid vertex, and restore missing links from component vertices - * to their unique vertex. Used after loading a model. + * Used after loading a model, once its mesh components are loaded. + * If the loaded file does not store the component vertices, rebuild + * them from the component mesh attributes: components in their + * registration order, then their vertices in increasing order. + * Attribute values out of the unique vertex range are removed. + * Otherwise, remove component vertices referencing an unregistered + * component or an invalid vertex, and restore missing links from + * component vertices to their unique vertex. */ void repair_component_vertices( BuilderKey /*key*/ ); diff --git a/src/geode/model/mixin/core/vertex_identifier.cpp b/src/geode/model/mixin/core/vertex_identifier.cpp index 4e0bb612e..22b668a48 100644 --- a/src/geode/model/mixin/core/vertex_identifier.cpp +++ b/src/geode/model/mixin/core/vertex_identifier.cpp @@ -42,7 +42,6 @@ #include -#include #include #include #include @@ -111,21 +110,32 @@ namespace geode struct RegisteredComponent { - explicit RegisteredComponent( - std::shared_ptr< VariableAttribute< index_t > > attribute_in ) - : attribute( std::move( attribute_in ) ) + RegisteredComponent( ComponentID component_id_in, + std::shared_ptr< VariableAttribute< index_t > > attribute_in, + index_t registration_in ) + : component_id( std::move( component_id_in ) ), + attribute( std::move( attribute_in ) ), + registration( registration_in ) { } RegisteredComponent( RegisteredComponent&& other ) noexcept - : attribute( std::move( other.attribute ) ), + : component_id( std::move( other.component_id ) ), + attribute( std::move( other.attribute ) ), + registration( other.registration ), nb_component_mesh_vertices( other.nb_component_mesh_vertices.load( std::memory_order_relaxed ) ) { } + ComponentID component_id; std::shared_ptr< VariableAttribute< index_t > > attribute; + /*! + * Registration rank, giving a deterministic component order to + * the rebuild of component_vertices_ + */ + index_t registration; /*! * Number of ComponentMeshVertex of this component stored in * component_vertices_. Used to detect inconsistencies between @@ -135,36 +145,13 @@ namespace geode }; public: - Impl() - { - AttributeProperties attribute_properties; - attribute_properties.assignable = false; - attribute_properties.interpolable = false; - attribute_properties.transferable = false; - AttributeValues< std::vector< ComponentMeshVertex > > - component_vertices_attribute_values; - component_vertices_attribute_values.default_value = {}; - const auto unique_vertices_attribute_id = - unique_vertices_.vertex_attribute_manager() - .create_attribute< VariableAttribute, - std::vector< ComponentMeshVertex > >( - "component vertices", - component_vertices_attribute_values, - attribute_properties ); - component_vertices_ = unique_vertices_.vertex_attribute_manager() - .find_attribute< VariableAttribute, - std::vector< ComponentMeshVertex > >( - unique_vertices_attribute_id ); - } + Impl() = default; - Impl( BITSERY bitsery ) - : unique_vertices_{ bitsery }, unique_vertex_id_{ bitsery } - { - } + Impl( BITSERY bitsery ) : unique_vertex_id_{ bitsery } {} index_t nb_unique_vertices() const { - return unique_vertices_.nb_vertices(); + return static_cast< index_t >( component_vertices_.size() ); } bool is_unique_vertex_isolated( index_t unique_vertex_id ) const @@ -180,7 +167,7 @@ namespace geode "[VertexIdentifier::component_mesh_vertices] Given " "unique_vertex_id is bigger than the number of unique " "vertices." ); - return component_vertices_->value( unique_vertex_id ); + return component_vertices_[unique_vertex_id]; } index_t unique_vertex( @@ -239,11 +226,13 @@ namespace geode .template create_attribute< VariableAttribute, index_t >( UNIQUE_VERTICES_NAME, unique_vertex_id_, unique_vertex_attribute_values, attribute_properties ); - const auto [_, inserted] = - vertex2unique_vertex_.try_emplace( component.id(), - mesh.vertex_attribute_manager() - .template find_attribute< VariableAttribute, index_t >( - unique_vertex_id_ ) ); + const auto [_, inserted] = vertex2unique_vertex_.try_emplace( + component.id(), component.component_id(), + mesh.vertex_attribute_manager() + .template find_attribute< VariableAttribute, index_t >( + unique_vertex_id_ ), + nb_registrations_ ); + nb_registrations_++; OpenGeodeModelException::check_exception( inserted, component.component_id(), OpenGeodeException::TYPE::data, "[VertexIdentifier::register_component] Component ", @@ -260,11 +249,13 @@ namespace geode import_old_attribute_based_on_name( mesh.vertex_attribute_manager(), mesh.nb_vertices() ); } - const auto [_, inserted] = - vertex2unique_vertex_.try_emplace( component.id(), - mesh.vertex_attribute_manager() - .template find_attribute< VariableAttribute, index_t >( - unique_vertex_id_ ) ); + const auto [_, inserted] = vertex2unique_vertex_.try_emplace( + component.id(), component.component_id(), + mesh.vertex_attribute_manager() + .template find_attribute< VariableAttribute, index_t >( + unique_vertex_id_ ), + nb_registrations_ ); + nb_registrations_++; OpenGeodeModelException::check_exception( inserted, component.component_id(), OpenGeodeException::TYPE::data, "[VertexIdentifier::load_component] Component ", @@ -290,14 +281,14 @@ namespace geode index_t create_unique_vertex() { - return VertexSetBuilder::create( unique_vertices_ ) - ->create_vertex(); + return create_unique_vertices( 1 ); } index_t create_unique_vertices( const index_t nb ) { - return VertexSetBuilder::create( unique_vertices_ ) - ->create_vertices( nb ); + const auto first = nb_unique_vertices(); + component_vertices_.resize( component_vertices_.size() + nb ); + return first; } void set_unique_vertex( ComponentMeshVertex component_vertex_id, @@ -319,17 +310,14 @@ namespace geode } component.attribute->set_value( component_vertex_id.vertex, unique_vertex_id ); - component_vertices_->modify_value( unique_vertex_id, - [&component_vertex_id, &component]( - std::vector< ComponentMeshVertex >& value ) { - if( absl::c_find( value, component_vertex_id ) - == value.end() ) - { - value.emplace_back( std::move( component_vertex_id ) ); - component.nb_component_mesh_vertices.fetch_add( - 1, std::memory_order_relaxed ); - } - } ); + auto& vertices = component_vertices_[unique_vertex_id]; + if( absl::c_find( vertices, component_vertex_id ) + == vertices.end() ) + { + vertices.emplace_back( std::move( component_vertex_id ) ); + component.nb_component_mesh_vertices.fetch_add( + 1, std::memory_order_relaxed ); + } } void unset_unique_vertex( @@ -346,8 +334,7 @@ namespace geode const index_t unique_vertex_id ) { component.attribute->set_value( component_vertex_id.vertex, NO_ID ); - const auto& vertices = - component_vertices_->value( unique_vertex_id ); + auto& vertices = component_vertices_[unique_vertex_id]; const auto it = absl::c_find( vertices, component_vertex_id ); if( it == vertices.end() ) { @@ -355,12 +342,7 @@ namespace geode } component.nb_component_mesh_vertices.fetch_sub( 1, std::memory_order_relaxed ); - component_vertices_->modify_value( unique_vertex_id, - [&it]( std::vector< ComponentMeshVertex >& value ) { - value.erase( - // workaround for gcc < 4.9 - value.begin() + ( it - value.cbegin() ) ); - } ); + vertices.erase( it ); } void update_unique_vertices( const ComponentID& component_id, @@ -374,12 +356,12 @@ namespace geode { return; } - const auto& all_vertices = component_vertices_->value( uv ); + auto& all_vertices = component_vertices_[uv]; std::vector< bool > to_delete( all_vertices.size(), false ); bool need_to_delete{ false }; for( const auto v : Indices{ all_vertices } ) { - const auto& cmv = all_vertices[v]; + auto& cmv = all_vertices[v]; if( cmv.component_id.id != component_id.id ) { continue; @@ -392,11 +374,7 @@ namespace geode } else { - component_vertices_->modify_value( uv, - [v, new_id]( std::vector< ComponentMeshVertex >& - vertices ) { - vertices[v].vertex = new_id; - } ); + cmv.vertex = new_id; } } if( need_to_delete ) @@ -405,11 +383,7 @@ namespace geode static_cast< index_t >( absl::c_count( to_delete, true ) ), std::memory_order_relaxed ); - component_vertices_->modify_value( uv, - [&to_delete]( - std::vector< ComponentMeshVertex >& vertices ) { - delete_vector_elements( to_delete, vertices ); - } ); + delete_vector_elements( to_delete, all_vertices ); } } ); const auto component_it = @@ -441,14 +415,30 @@ namespace geode absl::c_iota( old2new, index_t{ 0 } ); return old2new; } - const auto old2new = VertexSetBuilder::create( unique_vertices_ ) - ->delete_vertices( to_delete ); + std::vector< index_t > old2new( nb_vertices ); + index_t nb_kept{ 0 }; + for( const auto v : Range{ nb_vertices } ) + { + if( to_delete[v] ) + { + old2new[v] = NO_ID; + continue; + } + old2new[v] = nb_kept; + if( nb_kept != v ) + { + component_vertices_[nb_kept] = + std::move( component_vertices_[v] ); + } + nb_kept++; + } + component_vertices_.resize( nb_kept ); // Unique vertices before the first deleted one keep their index const uuid* last_component{ nullptr }; VariableAttribute< index_t >* attribute{ nullptr }; for( const auto uv : Range{ first_deleted, nb_unique_vertices() } ) { - for( const auto& cmv : component_vertices_->value( uv ) ) + for( const auto& cmv : component_vertices_[uv] ) { if( !last_component || *last_component != cmv.component_id.id ) @@ -477,13 +467,18 @@ namespace geode void repair_component_vertices() { + if( rebuild_component_vertices_ ) + { + rebuild_component_vertices(); + return; + } // Read-only parallel scan, nothing to repair in a valid model std::vector< uint8_t > to_repair( nb_unique_vertices(), 0 ); async::parallel_for( async::irange( index_t{ 0 }, nb_unique_vertices() ), [this, &to_repair]( index_t unique_vertex ) { for( const auto& vertex : - component_vertices_->value( unique_vertex ) ) + component_vertices_[unique_vertex] ) { if( !is_linked_to_unique_vertex( vertex, unique_vertex ) ) @@ -507,6 +502,80 @@ namespace geode repair.log(); } + /*! + * Rebuild component_vertices_ from the component mesh attributes. + * Components are visited in their registration order (the model + * component order when loading), then their vertices in increasing + * order: the result does not depend on hash order. + */ + void rebuild_component_vertices() + { + rebuild_component_vertices_ = false; + std::vector< RegisteredComponent* > components; + components.reserve( vertex2unique_vertex_.size() ); + for( auto& [_, component] : vertex2unique_vertex_ ) + { + components.push_back( &component ); + } + absl::c_sort( components, []( const RegisteredComponent* lhs, + const RegisteredComponent* rhs ) { + return lhs->registration < rhs->registration; + } ); + const auto nb_vertices = nb_unique_vertices(); + std::vector< index_t > nb_component_vertices( nb_vertices, 0 ); + index_t nb_invalid_links{ 0 }; + for( auto* component : components ) + { + auto& attribute = *component->attribute; + for( const auto v : Range{ attribute.size() } ) + { + const auto unique_vertex = attribute.value( v ); + if( unique_vertex == NO_ID ) + { + continue; + } + if( unique_vertex >= nb_vertices ) + { + attribute.set_value( v, NO_ID ); + nb_invalid_links++; + continue; + } + nb_component_vertices[unique_vertex]++; + } + } + for( const auto unique_vertex : Range{ nb_vertices } ) + { + auto& vertices = component_vertices_[unique_vertex]; + vertices.clear(); + vertices.reserve( nb_component_vertices[unique_vertex] ); + } + for( auto* component : components ) + { + const auto& attribute = *component->attribute; + index_t nb_vertices_in_component{ 0 }; + for( const auto v : Range{ attribute.size() } ) + { + const auto unique_vertex = attribute.value( v ); + if( unique_vertex == NO_ID ) + { + continue; + } + component_vertices_[unique_vertex].emplace_back( + component->component_id, v ); + nb_vertices_in_component++; + } + component->nb_component_mesh_vertices.store( + nb_vertices_in_component, std::memory_order_relaxed ); + } + nb_component_mesh_vertices_up_to_date_ = true; + if( nb_invalid_links > 0 ) + { + Logger::warning( "[VertexIdentifier::load] Removed ", + nb_invalid_links, + " component vertex links to unknown unique vertices" ); + } + } + void save( std::string_view directory ) const { const auto filename = absl::StrCat( directory, "/vertices" ); @@ -536,6 +605,10 @@ namespace geode nullptr, OpenGeodeException::TYPE::internal, "[VertexIdentifier::load] Error while reading file: ", filename ); + // Versions before 5 store the component vertices and reset this + // flag + component_vertices_.clear(); + rebuild_component_vertices_ = true; const auto success = detail::deserialize_bytes( content->span(), *this ); nb_component_mesh_vertices_up_to_date_ = false; @@ -547,6 +620,61 @@ namespace geode private: friend class bitsery::Access; + using LegacyComponentVertices = + VariableAttribute< std::vector< ComponentMeshVertex > >; + + /*! + * Versions 1 to 4 stored the unique vertices as a vertex set holding + * the component vertices in an attribute. + */ + template < typename Archive > + void serialize_legacy_unique_vertices( Archive& archive ) + { + OpenGeodeVertexSet unique_vertices{ BITSERY::constructor }; + std::shared_ptr< LegacyComponentVertices > component_vertices; + archive.object( unique_vertices ); + archive.ext( component_vertices, bitsery::ext::StdSmartPtr{} ); + set_legacy_component_vertices( + component_vertices, unique_vertices.nb_vertices() ); + } + + template < typename Archive > + static void serialize_legacy_map( Archive& archive ) + { + absl::flat_hash_map< uuid, + std::shared_ptr< VariableAttribute< index_t > > > + old_map; + archive.ext( old_map, bitsery::ext::StdMap{ old_map.max_size() }, + []( Archive& archive2, uuid& id, + std::shared_ptr< VariableAttribute< index_t > >& + attribute ) { + archive2.object( id ); + archive2.ext( attribute, bitsery::ext::StdSmartPtr{} ); + } ); + } + + void set_legacy_component_vertices( + const std::shared_ptr< LegacyComponentVertices >& + component_vertices, + index_t nb_unique_vertices ) + { + component_vertices_.resize( nb_unique_vertices ); + rebuild_component_vertices_ = false; + if( !component_vertices ) + { + return; + } + const auto nb_values = + std::min( nb_unique_vertices, component_vertices->size() ); + for( const auto uv : Range{ nb_values } ) + { + component_vertices->modify_value( uv, + [this, uv]( std::vector< ComponentMeshVertex >& value ) { + component_vertices_[uv] = std::move( value ); + } ); + } + } + template < typename Archive > void serialize( Archive& serializer ) { @@ -555,60 +683,39 @@ namespace geode { []( Archive& archive, Impl& impl ) { // Not stored in this version impl.unique_vertex_id_ = uuid{}; - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); - absl::flat_hash_map< uuid, - std::shared_ptr< VariableAttribute< index_t > > > - old_map; - archive.ext( old_map, - bitsery::ext::StdMap{ old_map.max_size() }, - []( Archive& archive2, uuid& id, - std::shared_ptr< VariableAttribute< - index_t > >& attribute ) { - archive2.object( id ); - archive2.ext( - attribute, bitsery::ext::StdSmartPtr{} ); - } ); - const auto& old_component_vertices_properties = - impl.component_vertices_->properties(); - impl.component_vertices_->set_properties( - { old_component_vertices_properties.assignable, - old_component_vertices_properties.interpolable, - false } ); + impl.serialize_legacy_unique_vertices( archive ); + serialize_legacy_map( archive ); }, []( Archive& archive, Impl& impl ) { // Not stored in this version impl.unique_vertex_id_ = uuid{}; - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); - absl::flat_hash_map< uuid, - std::shared_ptr< - VariableAttribute< index_t > > > - old_map; - archive.ext( old_map, - bitsery::ext::StdMap{ old_map.max_size() }, - []( Archive& archive2, uuid& id, - std::shared_ptr< VariableAttribute< - index_t > >& attribute ) { - archive2.object( id ); - archive2.ext( attribute, - bitsery::ext::StdSmartPtr{} ); - } ); + impl.serialize_legacy_unique_vertices( archive ); + serialize_legacy_map( archive ); }, []( Archive& archive, Impl& impl ) { // Not stored in this version impl.unique_vertex_id_ = uuid{}; - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); + impl.serialize_legacy_unique_vertices( archive ); + }, + []( Archive& archive, Impl& impl ) { + impl.serialize_legacy_unique_vertices( archive ); + archive.object( impl.unique_vertex_id_ ); }, []( Archive& archive, Impl& impl ) { - archive.object( impl.unique_vertices_ ); - archive.ext( impl.component_vertices_, - bitsery::ext::StdSmartPtr{} ); + // Component vertices are not stored, they are + // rebuilt from the component mesh attributes + // (see rebuild_component_vertices). Loading + // starts from an empty Impl, so the size only + // changes on reading. + auto nb_unique_vertices = impl.nb_unique_vertices(); + archive.value4b( nb_unique_vertices ); archive.object( impl.unique_vertex_id_ ); + if( nb_unique_vertices + != impl.nb_unique_vertices() ) + { + impl.component_vertices_.resize( + nb_unique_vertices ); + } } } } ); } @@ -666,28 +773,20 @@ namespace geode index_t filter_unique_vertex( index_t unique_vertex_id, const uuid& component_id ) { - const auto& component_mesh_vertices = - component_vertices_->value( unique_vertex_id ); + auto& vertices = component_vertices_[unique_vertex_id]; const auto is_component = [&component_id]( const ComponentMeshVertex& cmv ) { return cmv.component_id.id == component_id; }; - if( absl::c_none_of( component_mesh_vertices, is_component ) ) + if( absl::c_none_of( vertices, is_component ) ) { return 0; } - index_t nb_removed{ 0 }; - component_vertices_->modify_value( unique_vertex_id, - [&is_component, &nb_removed]( - std::vector< ComponentMeshVertex >& vertices ) { - const auto old_size = vertices.size(); - vertices.erase( std::remove_if( vertices.begin(), - vertices.end(), is_component ), - vertices.end() ); - nb_removed = - static_cast< index_t >( old_size - vertices.size() ); - } ); - return nb_removed; + const auto old_size = vertices.size(); + vertices.erase( std::remove_if( vertices.begin(), vertices.end(), + is_component ), + vertices.end() ); + return static_cast< index_t >( old_size - vertices.size() ); } void filter_component_vertices( const uuid& component_id ) @@ -712,7 +811,7 @@ namespace geode } for( const auto uv : Range{ nb_unique_vertices() } ) { - for( const auto& cmv : component_vertices_->value( uv ) ) + for( const auto& cmv : component_vertices_[uv] ) { const auto it = vertex2unique_vertex_.find( cmv.component_id.id ); @@ -837,7 +936,7 @@ namespace geode void repair_unique_vertex( index_t unique_vertex, ComponentVerticesRepair& repair ) { - const auto& vertices = component_vertices_->value( unique_vertex ); + auto& vertices = component_vertices_[unique_vertex]; std::vector< bool > to_keep( vertices.size(), true ); bool update{ false }; for( const auto v : Indices{ vertices } ) @@ -875,18 +974,24 @@ namespace geode } if( update ) { - component_vertices_->set_value( unique_vertex, - extract_vector_elements( to_keep, vertices ) ); + vertices = extract_vector_elements( to_keep, vertices ); } } - OpenGeodeVertexSet unique_vertices_; - std::shared_ptr< - VariableAttribute< std::vector< ComponentMeshVertex > > > - component_vertices_; + /*! + * Component mesh vertices of each unique vertex, its size is the + * number of unique vertices + */ + std::vector< std::vector< ComponentMeshVertex > > component_vertices_; absl::flat_hash_map< uuid, RegisteredComponent > vertex2unique_vertex_; geode::uuid unique_vertex_id_; + index_t nb_registrations_{ 0 }; bool nb_component_mesh_vertices_up_to_date_{ true }; + /*! + * True after loading a file not storing the component vertices: + * repair_component_vertices rebuilds them + */ + bool rebuild_component_vertices_{ false }; }; VertexIdentifier::VertexIdentifier() = default; diff --git a/tests/data/backward_io/v20_2/v20_2.og_brep b/tests/data/backward_io/v20_2/v20_2.og_brep new file mode 100644 index 0000000000000000000000000000000000000000..2bb0d1ed06f8f2fca8b08076d6c4e32d48b32ced GIT binary patch literal 27224 zcmdsA32eWB_`t>n!*WEK zRqwT?`~81kU;q7g|Nm>PTIOpwL~Cl&v>jJocClt%{~Ipb{=x zV3BwesNAyH{=T<|p80;q^Ditst1-XWxvq?{xuf4KwxDABtzt7WF@955ZsR6n=A}k& ze=cqG>0i+$@X&o!ngHEG1Y}!j*FAaG>LH3aC3p5-O*Hv*(QFo-T9cybO&L)0j-q?C z*;ZrBU@T>Cw$QjaPQ$i$clT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ZfnRf#rYZCE=b1@Fy@Yh`$>aIWu6MeBw3{mFnZgu1|tDFKz~zY-c4E zt;^3UXg%>V;9KKr^Zkq%sJ&Bx?ZnHT?=q^R{*SBjM|~x`?cN;t-XYdM=7rW4=U9_% zUR!fXp=w{-h^EuC$LP(GZy>2nwv(upCaYwJ(aWB%#nmR;w>H1YD%q3r=D=4rY7XNr c$j_mY75=Jajk4{J(T>q(k_tLo{uinL0|r`{^8f$< literal 0 HcmV?d00001 diff --git a/tests/data/backward_io/v20_2/v20_2.og_sctn b/tests/data/backward_io/v20_2/v20_2.og_sctn new file mode 100644 index 0000000000000000000000000000000000000000..63bfd4d951e5e6c4331e4a6408b83700495079c7 GIT binary patch literal 6826 zcmd5=eQXnD7{B-0ZS6kT2Vf+KkVqm%587Vat!8l{9Za$z4MQXlT&{Q5(a^P}?WSXB z1V2DQLr66K;Rg`;QX%0ZF&ZEUqQ)3aRN^N_;|D4x5($aK=zN~L-g_Ut-RR;LZh5=* z?tahvywCG{KHfLh>2gnDJRXKQz3G9~Oz}EI7{(9ZyOL?y=NAILh|kCQd_IY57K1Vu zm*Rdd4EI|6&7veo(%ejMk1UA+$>ky}Auw2$1w6}=-Cl;N+Ymd_721Bs_Tx3K8S5NKzK%Z1Yu;x2`e$}GN>XF)OZMN012yrV)cwP{dIt?=$| zE?o6=oan14RV$g6}V~Eea#`{psYoetFh_oGTjT^o?&k&D`C0WcOvq+XHJ0QVaSLz;+7u@`=@OsuoYbM6>di|)n|vn9iMcoKy7 zyZdtqK`h||FL04SbBGiCJ|7Sz?DzYF$cJn`fqc;DfWD=6Xg&VzneR8ZUcOQu9Vkq* ziH)mqWu{AAu<=&$6`c+i%%!#o;D^d}Pz!x;n`gbw2o@<-}cRk=XFKVZ7qUh6_ zYb8Q05TS+=p-z!Ase&c-s@YsB>r|pDpDfJN04!-FChc6vXYEp6RGg{MXXopi{y>7@ zu%{0K8esHgBstX+&-AAy$N+MlDEO1NoL+%%;IPNHg5)}Qnv+vPA(=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;;;VzLYEN; literal 0 HcmV?d00001 diff --git a/tests/model/test-brep.cpp b/tests/model/test-brep.cpp index b79a52368..3b01ff199 100644 --- a/tests/model/test-brep.cpp +++ b/tests/model/test-brep.cpp @@ -23,6 +23,7 @@ #include +#include #include #include #include @@ -1190,6 +1191,57 @@ void test_block_collection_ranges( const geode::BRep& model, "ItemBlockRange should iterates on 1 Block." ); } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::BRep& model, geode::index_t unique_vertex ) +{ + auto vertices = model.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +/* + * Loaded component mesh vertices are rebuilt from the component meshes: + * components in the model order (Corners, Lines, Surfaces, Blocks), then + * their vertices in increasing order. + */ +void check_loaded_component_mesh_vertices_order( const geode::BRep& model ) +{ + absl::flat_hash_map< geode::uuid, geode::index_t > ranks; + geode::index_t rank{ 0 }; + for( const auto& component : model.corners() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.lines() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.surfaces() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.blocks() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto v : geode::Range{ 1, vertices.size() } ) + { + const auto& previous = vertices[v - 1]; + const auto& current = vertices[v]; + geode::OpenGeodeModelException::test( + std::make_pair( + ranks.at( previous.component_id.id ), previous.vertex ) + < std::make_pair( + ranks.at( current.component_id.id ), current.vertex ), + "[Test] Loaded component mesh vertices of unique vertex ", + unique_vertex, " are not in the model order" ); + } + } +} + void test_compare_component_mesh_vertices( const geode::BRep& model, const geode::BRep& model2 ) { @@ -1202,12 +1254,13 @@ void test_compare_component_mesh_vertices( const geode::uuid nil{ geode::BITSERY::constructor }; for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) { - const auto& vertices = model.component_mesh_vertices( unique_vertex ); - const auto& vertices2 = model2.component_mesh_vertices( unique_vertex ); - geode::OpenGeodeModelException::test( vertices == vertices2, + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( model, unique_vertex ) + == sorted_component_mesh_vertices( model2, unique_vertex ), "[Test] Reloaded component mesh vertices of unique vertex ", unique_vertex, " should be equal to the saved ones" ); - for( const auto& vertex : vertices2 ) + for( const auto& vertex : + model2.component_mesh_vertices( unique_vertex ) ) { geode::OpenGeodeModelException::test( vertex.component_id.id != nil, "[Test] Reloaded component id should not be nil" ); @@ -1218,6 +1271,24 @@ void test_compare_component_mesh_vertices( unique_vertex ); } } + check_loaded_component_mesh_vertices_order( model2 ); +} + +/* + * Loading the same model twice gives the same component mesh vertices, in + * the same order. + */ +void test_compare_component_mesh_vertices_order( + const geode::BRep& model, const geode::BRep& model2 ) +{ + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + model.component_mesh_vertices( unique_vertex ) + == model2.component_mesh_vertices( unique_vertex ), + "[Test] Component mesh vertices of unique vertex ", unique_vertex, + " should be in the same order in both loaded models" ); + } } void test_component_mesh_vertices_round_trip() @@ -1230,6 +1301,13 @@ void test_component_mesh_vertices_round_trip() geode::save_brep( model, file_io ); const auto model2 = geode::load_one( geode::load_brep( file_io ), file_io ); test_compare_component_mesh_vertices( model, model2 ); + const auto file_io2 = absl::StrCat( + "test_component_mesh_vertices2.", model.native_extension() ); + geode::save_brep( model2, file_io2 ); + const auto model3 = + geode::load_one( geode::load_brep( file_io2 ), file_io2 ); + test_compare_component_mesh_vertices( model, model3 ); + test_compare_component_mesh_vertices_order( model2, model3 ); } void test_compare_brep( const geode::BRep& model, const geode::BRep& model2 ) @@ -1950,6 +2028,97 @@ void test_backward_io() test_registry( brep_v18_0, 4, 6, 9, 5, 1, 5, 2, 2, 2, 1, 3 ); } +geode::index_t count_multi_type_unique_vertices( const geode::BRep& model ) +{ + geode::index_t count{ 0 }; + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto& vertex : vertices ) + { + if( vertex.component_id.type != vertices.front().component_id.type ) + { + count++; + break; + } + } + } + return count; +} + +/* + * v20_2.og_brep was saved from box_brep.og_brep with 3 more isolated unique + * vertices, when the component mesh vertices were stored in the file. + */ +void test_backward_io_component_mesh_vertices() +{ + const auto box_filename = + absl::StrCat( geode::DATA_PATH, "box_brep.og_brep" ); + const auto box = + geode::load_one( geode::load_brep( box_filename ), box_filename ); + const auto filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_brep" ); + const auto brep = geode::load_one( geode::load_brep( filename ), filename ); + const auto nb_box_vertices = box.nb_unique_vertices(); + geode::OpenGeodeModelException::test( + brep.nb_unique_vertices() == nb_box_vertices + 3, + "[Backward_IO] Wrong number of unique vertices" ); + geode::OpenGeodeModelException::test( + brep.nb_blocks() > 0, "[Backward_IO] v20_2 model should have blocks" ); + geode::OpenGeodeModelException::test( + count_multi_type_unique_vertices( brep ) > 0, + "[Backward_IO] Some unique vertices should have several component " + "types" ); + for( const auto unique_vertex : geode::Range{ brep.nb_unique_vertices() } ) + { + if( unique_vertex >= nb_box_vertices ) + { + geode::OpenGeodeModelException::test( + brep.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Unique vertex ", unique_vertex, + " should be isolated" ); + continue; + } + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( box, unique_vertex ) + == sorted_component_mesh_vertices( brep, unique_vertex ), + "[Backward_IO] Wrong component mesh vertices of unique vertex ", + unique_vertex ); + for( const auto& vertex : + brep.component_mesh_vertices( unique_vertex ) ) + { + geode::OpenGeodeModelException::test( + brep.unique_vertex( vertex ) == unique_vertex, + "[Backward_IO] Wrong unique vertex of ", vertex.string() ); + } + } + + const auto file_io = + absl::StrCat( "v20_2_resaved.", brep.native_extension() ); + geode::save_brep( brep, file_io ); + auto reloaded = geode::load_one( geode::load_brep( file_io ), file_io ); + test_compare_component_mesh_vertices( brep, reloaded ); + for( const auto unique_vertex : + geode::Range{ nb_box_vertices, reloaded.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + reloaded.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Reloaded unique vertex ", unique_vertex, + " should be isolated" ); + } + + geode::BRepBuilder builder{ reloaded }; + const auto old2new = builder.delete_isolated_vertices(); + std::vector< geode::index_t > expected( nb_box_vertices + 3, geode::NO_ID ); + for( const auto unique_vertex : geode::Range{ nb_box_vertices } ) + { + expected[unique_vertex] = unique_vertex; + } + geode::OpenGeodeModelException::test( old2new == expected, + "[Backward_IO] Wrong mapping after deleting isolated unique vertices" ); + test_compare_component_mesh_vertices( box, reloaded ); +} + void test_registry_remove_unknown_type() { geode::BRep brep; @@ -2407,6 +2576,7 @@ void test() test_component_mesh_vertices_round_trip(); test_backward_io(); + test_backward_io_component_mesh_vertices(); test_physical_properties_backward_io(); test_components_filter(); test_registry_remove_unknown_type(); diff --git a/tests/model/test-model-corrupted-files.cpp b/tests/model/test-model-corrupted-files.cpp index 10f79c787..7a21b35f9 100644 --- a/tests/model/test-model-corrupted-files.cpp +++ b/tests/model/test-model-corrupted-files.cpp @@ -338,12 +338,16 @@ namespace /* * Mesh components have a "unique vertices" attribute linking their * vertices to the model unique vertices. When this attribute is missing, - * it is restored from the unique vertices. + * it is restored from the unique vertices of the files storing their + * component mesh vertices (before version 5 of the vertices file). */ void test_missing_unique_vertices_attribute() { - const auto brep = saved_brep( "unique_vertices.og_brep" ); - auto files = extract_archive( "unique_vertices.og_brep" ); + const auto legacy_filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_brep" ); + const auto brep = geode::load_one( + geode::load_brep( legacy_filename ), legacy_filename ); + auto files = extract_archive( legacy_filename ); replace_unique( files.at( "vertices" ), serialized_uuid( brep.unique_vertex_attribute_id() ), serialized_uuid( geode::uuid{} ), "Unique vertex attribute id" ); @@ -361,6 +365,60 @@ namespace check_same_unique_vertices( brep, loaded ); } + /* + * The vertices file stores the number of unique vertices, the component + * mesh vertices are rebuilt from the "unique vertices" attribute of the + * component meshes. Attribute values out of the unique vertex range are + * removed. + */ + void test_invalid_unique_vertex_links() + { + const auto brep = saved_brep( "invalid_links.og_brep" ); + auto files = extract_archive( "invalid_links.og_brep" ); + const auto nb_unique_vertices = brep.nb_unique_vertices(); + const auto last = nb_unique_vertices - 1; + geode::OpenGeodeModelException::test( + !brep.is_unique_vertex_isolated( last ), + "[Test] Last unique vertex should not be isolated" ); + const auto id = serialized_uuid( brep.unique_vertex_attribute_id() ); + replace_unique( files.at( "vertices" ), + absl::StrCat( serialized_u32( nb_unique_vertices ), id ), + absl::StrCat( serialized_u32( last ), id ), + "Number of unique vertices" ); + write_archive( files, "corrupted_invalid_links.og_brep" ); + + WarningRecorder::start(); + const auto loaded = geode::load_one( + geode::load_brep( "corrupted_invalid_links.og_brep" ), + "corrupted_invalid_links.og_brep" ); + check_warning( "component vertex links to unknown unique vertices" ); + geode::OpenGeodeModelException::test( + loaded.nb_unique_vertices() == last, + "[Test] Wrong number of unique vertices" ); + for( const auto& vertex : brep.component_mesh_vertices( last ) ) + { + geode::OpenGeodeModelException::test( + loaded.unique_vertex( vertex ) == geode::NO_ID, + "[Test] Link to a removed unique vertex should be removed" ); + } + for( const auto unique_vertex : geode::Range{ last } ) + { + const auto& vertices = + brep.component_mesh_vertices( unique_vertex ); + geode::OpenGeodeModelException::test( + loaded.component_mesh_vertices( unique_vertex ).size() + == vertices.size(), + "[Test] Wrong number of component vertices for unique vertex ", + unique_vertex ); + for( const auto& vertex : vertices ) + { + geode::OpenGeodeModelException::test( + loaded.unique_vertex( vertex ) == unique_vertex, + "[Test] Wrong unique vertex for component vertex" ); + } + } + } + /* * Unique vertices referencing a component that does not exist in the * model are removed. @@ -981,6 +1039,7 @@ void test() geode::OpenGeodeModelLibrary::initialize(); test_inconsistent_relationships_map(); test_missing_unique_vertices_attribute(); + test_invalid_unique_vertex_links(); test_unknown_component_vertices(); test_missing_components_file(); test_wrong_component_key(); diff --git a/tests/model/test-section.cpp b/tests/model/test-section.cpp index 8c2b77306..db458128f 100644 --- a/tests/model/test-section.cpp +++ b/tests/model/test-section.cpp @@ -21,6 +21,9 @@ * */ +#include +#include + #include #include #include @@ -880,6 +883,53 @@ void test_clone( const geode::Section& section ) } } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::Section& model, geode::index_t unique_vertex ) +{ + auto vertices = model.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +/* + * Loaded component mesh vertices are rebuilt from the component meshes: + * components in the model order (Corners, Lines, Surfaces), then + * their vertices in increasing order. + */ +void check_loaded_component_mesh_vertices_order( const geode::Section& model ) +{ + absl::flat_hash_map< geode::uuid, geode::index_t > ranks; + geode::index_t rank{ 0 }; + for( const auto& component : model.corners() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.lines() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto& component : model.surfaces() ) + { + ranks.emplace( component.id(), rank++ ); + } + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + const auto& vertices = model.component_mesh_vertices( unique_vertex ); + for( const auto v : geode::Range{ 1, vertices.size() } ) + { + const auto& previous = vertices[v - 1]; + const auto& current = vertices[v]; + geode::OpenGeodeModelException::test( + std::make_pair( + ranks.at( previous.component_id.id ), previous.vertex ) + < std::make_pair( + ranks.at( current.component_id.id ), current.vertex ), + "[Test] Loaded component mesh vertices of unique vertex ", + unique_vertex, " are not in the model order" ); + } + } +} + void test_compare_component_mesh_vertices( const geode::Section& model, const geode::Section& model2 ) { @@ -892,12 +942,13 @@ void test_compare_component_mesh_vertices( const geode::uuid nil{ geode::BITSERY::constructor }; for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) { - const auto& vertices = model.component_mesh_vertices( unique_vertex ); - const auto& vertices2 = model2.component_mesh_vertices( unique_vertex ); - geode::OpenGeodeModelException::test( vertices == vertices2, + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( model, unique_vertex ) + == sorted_component_mesh_vertices( model2, unique_vertex ), "[Test] Reloaded component mesh vertices of unique vertex ", unique_vertex, " should be equal to the saved ones" ); - for( const auto& vertex : vertices2 ) + for( const auto& vertex : + model2.component_mesh_vertices( unique_vertex ) ) { geode::OpenGeodeModelException::test( vertex.component_id.id != nil, "[Test] Reloaded component id should not be nil" ); @@ -908,6 +959,24 @@ void test_compare_component_mesh_vertices( unique_vertex ); } } + check_loaded_component_mesh_vertices_order( model2 ); +} + +/* + * Loading the same model twice gives the same component mesh vertices, in + * the same order. + */ +void test_compare_component_mesh_vertices_order( + const geode::Section& model, const geode::Section& model2 ) +{ + for( const auto unique_vertex : geode::Range{ model.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + model.component_mesh_vertices( unique_vertex ) + == model2.component_mesh_vertices( unique_vertex ), + "[Test] Component mesh vertices of unique vertex ", unique_vertex, + " should be in the same order in both loaded models" ); + } } void test_component_mesh_vertices_round_trip() @@ -921,6 +990,87 @@ void test_component_mesh_vertices_round_trip() const auto model2 = geode::load_one( geode::load_section( file_io ), file_io ); test_compare_component_mesh_vertices( model, model2 ); + const auto file_io2 = absl::StrCat( + "test_component_mesh_vertices2.", model.native_extension() ); + geode::save_section( model2, file_io2 ); + const auto model3 = + geode::load_one( geode::load_section( file_io2 ), file_io2 ); + test_compare_component_mesh_vertices( model, model3 ); + test_compare_component_mesh_vertices_order( model2, model3 ); +} + +/* + * v20_2.og_sctn was saved when the component mesh vertices were stored in the + * file: a triangle Surface, its 3 Lines and 3 Corners on unique vertices 0 to + * 2, and 2 isolated unique vertices. + */ +void test_backward_io_component_mesh_vertices() +{ + const auto filename = + absl::StrCat( geode::DATA_PATH, "backward_io/v20_2/v20_2.og_sctn" ); + const auto section = + geode::load_one( geode::load_section( filename ), filename ); + geode::OpenGeodeModelException::test( section.nb_unique_vertices() == 5, + "[Backward_IO] Wrong number of unique vertices" ); + for( const auto unique_vertex : geode::Range{ 3 } ) + { + const auto& vertices = section.component_mesh_vertices( unique_vertex ); + geode::index_t nb_corners{ 0 }; + geode::index_t nb_lines{ 0 }; + geode::index_t nb_surfaces{ 0 }; + for( const auto& vertex : vertices ) + { + geode::OpenGeodeModelException::test( + section.unique_vertex( vertex ) == unique_vertex, + "[Backward_IO] Wrong unique vertex of ", vertex.string() ); + if( vertex.component_id.type + == geode::Corner2D::component_type_static() ) + { + nb_corners++; + } + else if( vertex.component_id.type + == geode::Line2D::component_type_static() ) + { + nb_lines++; + } + else if( vertex.component_id.type + == geode::Surface2D::component_type_static() ) + { + geode::OpenGeodeModelException::test( + vertex.vertex == unique_vertex, + "[Backward_IO] Wrong surface vertex" ); + nb_surfaces++; + } + } + geode::OpenGeodeModelException::test( + vertices.size() == 4 && nb_corners == 1 && nb_lines == 2 + && nb_surfaces == 1, + "[Backward_IO] Wrong component mesh vertices of unique vertex ", + unique_vertex ); + } + for( const auto unique_vertex : geode::Range{ 3, 5 } ) + { + geode::OpenGeodeModelException::test( + section.is_unique_vertex_isolated( unique_vertex ), + "[Backward_IO] Unique vertex ", unique_vertex, + " should be isolated" ); + } + + const auto file_io = + absl::StrCat( "v20_2_resaved.", section.native_extension() ); + geode::save_section( section, file_io ); + auto reloaded = geode::load_one( geode::load_section( file_io ), file_io ); + test_compare_component_mesh_vertices( section, reloaded ); + + geode::SectionBuilder builder{ reloaded }; + const auto old2new = builder.delete_isolated_vertices(); + geode::OpenGeodeModelException::test( + old2new + == std::vector< geode::index_t >{ 0, 1, 2, geode::NO_ID, + geode::NO_ID }, + "[Backward_IO] Wrong mapping after deleting isolated unique vertices" ); + geode::OpenGeodeModelException::test( reloaded.nb_unique_vertices() == 3, + "[Backward_IO] Wrong number of unique vertices after deletion" ); } void test_compare_section( @@ -1155,6 +1305,7 @@ void test() geode::Section model3{ std::move( model2 ) }; test_compare_section( model, model3 ); test_component_mesh_vertices_round_trip(); + test_backward_io_component_mesh_vertices(); } OPENGEODE_TEST( "section" ) \ No newline at end of file diff --git a/tests/model/test-vertex-identifier.cpp b/tests/model/test-vertex-identifier.cpp index 31cf1eb12..64faa1cb3 100644 --- a/tests/model/test-vertex-identifier.cpp +++ b/tests/model/test-vertex-identifier.cpp @@ -21,10 +21,13 @@ * */ +#include #include #include +#include + #include #include #include @@ -170,10 +173,31 @@ void test_modify_unique_vertices( geode::VertexIdentifier& vertex_identifier ) "Reset of a unique vertex is not correct - values" ); } +std::vector< geode::ComponentMeshVertex > sorted_component_mesh_vertices( + const geode::VertexIdentifier& vertex_identifier, + geode::index_t unique_vertex ) +{ + auto vertices = vertex_identifier.component_mesh_vertices( unique_vertex ); + absl::c_sort( vertices ); + return vertices; +} + +std::uintmax_t vertices_file_size() +{ + return std::filesystem::file_size( std::filesystem::u8path( "vertices" ) ); +} + +/* + * The vertices file stores the number of unique vertices, not their component + * mesh vertices: these are rebuilt from the component mesh attributes when + * the components are loaded, by repair_component_vertices. The rebuilt order + * follows the component registration order, so lists are compared as sets. + */ void test_save_and_load_unique_vertices( - geode::VertexIdentifier& vertex_identifier ) + geode::VertexIdentifier& vertex_identifier, const CornerProvider& provider ) { vertex_identifier.save_unique_vertices( "." ); + const auto file_size = vertices_file_size(); geode::VertexIdentifier vertex_identifier2; geode::VertexIdentifierBuilder loader{ vertex_identifier2 }; loader.load_unique_vertices( "." ); @@ -186,20 +210,34 @@ void test_save_and_load_unique_vertices( geode::Range{ vertex_identifier2.nb_unique_vertices() } ) { geode::OpenGeodeModelException::test( - vertex_identifier.component_mesh_vertices( v_id ).size() - == vertex_identifier2.component_mesh_vertices( v_id ).size(), + vertex_identifier2.is_unique_vertex_isolated( v_id ), + "Loaded unique vertices should be isolated before loading their " + "components" ); + } + for( const auto& corner : provider.corners() ) + { + loader.load_mesh_component( corner ); + } + loader.repair_component_vertices(); + for( const auto v_id : + geode::Range{ vertex_identifier2.nb_unique_vertices() } ) + { + geode::OpenGeodeModelException::test( + sorted_component_mesh_vertices( vertex_identifier, v_id ) + == sorted_component_mesh_vertices( vertex_identifier2, v_id ), "Save/Load of unique vertices are not correct (different " - "number of component mesh vertices)" ); - for( const auto cmv : geode::Range{ - vertex_identifier.component_mesh_vertices( v_id ).size() } ) - { - geode::OpenGeodeModelException::test( - vertex_identifier.component_mesh_vertices( v_id )[cmv] - == vertex_identifier2.component_mesh_vertices( v_id )[cmv], - "Save/Load of unique vertices are not correct " - "(different component mesh vertices)" ); - } + "component mesh vertices)" ); } + + // The file size does not depend on the number of component mesh vertices + geode::VertexIdentifier empty_identifier; + geode::VertexIdentifierBuilder{ empty_identifier }.create_unique_vertices( + vertex_identifier.nb_unique_vertices() ); + empty_identifier.save_unique_vertices( "." ); + geode::OpenGeodeModelException::test( vertices_file_size() == file_size, + "Saved unique vertices should not store the component mesh vertices " + "(file size ", + file_size, " instead of ", vertices_file_size(), ")" ); } void test_update_unique_vertices() @@ -514,7 +552,7 @@ void test() test_create_unique_vertices( vertex_identifier ); test_set_unique_vertices( vertex_identifier, provider ); test_modify_unique_vertices( vertex_identifier ); - test_save_and_load_unique_vertices( vertex_identifier ); + test_save_and_load_unique_vertices( vertex_identifier, provider ); test_update_unique_vertices(); test_unregister_mesh_component(); From 605699f24db67cfb48da941c28f5018d9e3b04e5 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 17:53:55 +0100 Subject: [PATCH 5/8] perf(Model): read native model archives in place without extracting them Loading a BRep or a Section extracted every entry of the archive to the temporary directory, then read the files back. The archive is now read in place through geode::detail::InputFiles: the archive is memory-mapped (positional reads if it cannot be mapped), stored entries are zero-copy slices of the mapping, deflated entries are inflated with zlib-ng, and the CRC-32 of each entry is checked when it is read (a mismatch is a data error naming the entry). The pages of an entry leave the process memory once it is deserialized. Native mesh, light regular grid and raster inputs read from bytes (Input::read_bytes); other inputs of an archive entry get a temporary file. Plain files (meshes loaded by path, model directories) are memory-mapped instead of copied into a buffer. The load_* builder methods taking a directory are kept as wrappers of the directory input files. Co-Authored-By: Claude Opus 5.5 --- cmake/OpenGeodeConfig.cmake.in | 1 + include/geode/basic/bitsery_archive.hpp | 49 +- include/geode/basic/byte_span.hpp | 35 ++ include/geode/basic/detail/file_content.hpp | 151 +++++ .../geode/basic/detail/geode_input_impl.hpp | 48 ++ include/geode/basic/detail/input_files.hpp | 175 ++++++ include/geode/basic/identifier.hpp | 7 +- include/geode/basic/identifier_builder.hpp | 7 + include/geode/basic/input.hpp | 15 + .../io/geode/geode_bitsery_raster_input.hpp | 36 +- .../io/geode/geode_bitsery_mesh_input.hpp | 21 +- .../geode/geode_light_regular_grid_input.hpp | 50 +- .../builder/block_collections_builder.hpp | 7 + .../model/mixin/builder/blocks_builder.hpp | 7 + .../builder/corner_collections_builder.hpp | 7 + .../model/mixin/builder/corners_builder.hpp | 7 + .../builder/line_collections_builder.hpp | 7 + .../model/mixin/builder/lines_builder.hpp | 7 + .../builder/model_boundaries_builder.hpp | 7 + .../builder/physical_properties_builder.hpp | 7 + .../mixin/builder/relationships_builder.hpp | 7 + .../builder/surface_collections_builder.hpp | 7 + .../model/mixin/builder/surfaces_builder.hpp | 7 + .../builder/vertex_identifier_builder.hpp | 7 + .../model/mixin/core/block_collections.hpp | 7 +- include/geode/model/mixin/core/blocks.hpp | 8 +- .../model/mixin/core/corner_collections.hpp | 7 +- include/geode/model/mixin/core/corners.hpp | 8 +- .../mixin/core/detail/components_storage.hpp | 72 ++- .../model/mixin/core/line_collections.hpp | 7 +- include/geode/model/mixin/core/lines.hpp | 7 +- .../model/mixin/core/model_boundaries.hpp | 7 +- .../model/mixin/core/physical_properties.hpp | 7 +- .../geode/model/mixin/core/relationships.hpp | 7 +- .../model/mixin/core/surface_collections.hpp | 7 +- include/geode/model/mixin/core/surfaces.hpp | 7 +- .../model/mixin/core/vertex_identifier.hpp | 7 +- .../io/geode/geode_brep_input.hpp | 60 +- .../io/geode/geode_section_input.hpp | 49 +- src/geode/basic/CMakeLists.txt | 17 + src/geode/basic/bitsery_archive.cpp | 34 -- src/geode/basic/file_content.cpp | 300 ++++++++++ src/geode/basic/identifier.cpp | 18 +- src/geode/basic/identifier_builder.cpp | 8 +- src/geode/basic/input_files.cpp | 141 +++++ src/geode/basic/singleton.cpp | 3 + src/geode/basic/zip_file.cpp | 391 +++++++++++++ .../builder/block_collections_builder.cpp | 15 +- .../model/mixin/builder/blocks_builder.cpp | 13 +- .../builder/corner_collections_builder.cpp | 15 +- .../model/mixin/builder/corners_builder.cpp | 13 +- .../builder/line_collections_builder.cpp | 15 +- .../model/mixin/builder/lines_builder.cpp | 13 +- .../builder/model_boundaries_builder.cpp | 15 +- .../builder/physical_properties_builder.cpp | 10 +- .../mixin/builder/relationships_builder.cpp | 10 +- .../builder/surface_collections_builder.cpp | 15 +- .../model/mixin/builder/surfaces_builder.cpp | 13 +- .../builder/vertex_identifier_builder.cpp | 10 +- .../model/mixin/core/block_collections.cpp | 5 +- src/geode/model/mixin/core/blocks.cpp | 37 +- .../model/mixin/core/corner_collections.cpp | 5 +- src/geode/model/mixin/core/corners.cpp | 18 +- .../model/mixin/core/line_collections.cpp | 5 +- src/geode/model/mixin/core/lines.cpp | 19 +- .../model/mixin/core/model_boundaries.cpp | 5 +- .../model/mixin/core/physical_properties.cpp | 22 +- src/geode/model/mixin/core/relationships.cpp | 16 +- .../model/mixin/core/surface_collections.cpp | 5 +- src/geode/model/mixin/core/surfaces.cpp | 34 +- .../model/mixin/core/vertex_identifier.cpp | 16 +- .../io/external_time_series_input.cpp | 2 +- .../io/geode/geode_brep_input.cpp | 8 +- .../io/geode/geode_section_input.cpp | 8 +- tests/basic/CMakeLists.txt | 16 + tests/basic/check-hidden-symbols.cmake | 38 ++ tests/basic/test-attribute.cpp | 9 +- tests/basic/test-growable.cpp | 5 +- tests/basic/test-input-files.cpp | 539 ++++++++++++++++++ tests/mesh/CMakeLists.txt | 8 + tests/mesh/test-mesh-input-bytes.cpp | 458 +++++++++++++++ tests/mesh/test-texture-manager.cpp | 5 +- tests/model/CMakeLists.txt | 7 + tests/model/test-model-archive-input.cpp | 368 ++++++++++++ 84 files changed, 3330 insertions(+), 343 deletions(-) create mode 100644 include/geode/basic/byte_span.hpp create mode 100644 include/geode/basic/detail/file_content.hpp create mode 100644 include/geode/basic/detail/input_files.hpp create mode 100644 src/geode/basic/file_content.cpp create mode 100644 src/geode/basic/input_files.cpp create mode 100644 tests/basic/check-hidden-symbols.cmake create mode 100644 tests/basic/test-input-files.cpp create mode 100644 tests/mesh/test-mesh-input-bytes.cpp create mode 100644 tests/model/test-model-archive-input.cpp diff --git a/cmake/OpenGeodeConfig.cmake.in b/cmake/OpenGeodeConfig.cmake.in index 23743e9e4..e8d304a28 100644 --- a/cmake/OpenGeodeConfig.cmake.in +++ b/cmake/OpenGeodeConfig.cmake.in @@ -44,6 +44,7 @@ find_dependency(Async++) get_target_property(library_type OpenGeode::basic TYPE) if(library_type STREQUAL "STATIC_LIBRARY") find_dependency(earcut_hpp) + find_dependency(ZLIB CONFIG) # minizip-ng calls find_dependency(ZLIB): use the installed zlib-ng config set(GEODE_PREFER_CONFIG ${CMAKE_FIND_PACKAGE_PREFER_CONFIG}) set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) diff --git a/include/geode/basic/bitsery_archive.hpp b/include/geode/basic/bitsery_archive.hpp index ba47fc716..dc529677d 100644 --- a/include/geode/basic/bitsery_archive.hpp +++ b/include/geode/basic/bitsery_archive.hpp @@ -40,19 +40,11 @@ #include #include +#include #include #include #include -namespace geode -{ - /*! - * Read-only bytes to deserialize, owned elsewhere (file content, slice of - * an archive in memory...). - */ - using ByteSpan = absl::Span< const char >; -} // namespace geode - namespace bitsery { namespace traits @@ -129,45 +121,6 @@ namespace geode namespace detail { - /*! - * Owned bytes, uninitialized at construction. - */ - class ByteBuffer - { - public: - explicit ByteBuffer( size_t size ) - : data_{ new char[size] }, size_{ size } - { - } - - [[nodiscard]] char *data() - { - return data_.get(); - } - - [[nodiscard]] size_t size() const - { - return size_; - } - - [[nodiscard]] ByteSpan span() const - { - return { data_.get(), size_ }; - } - - private: - std::unique_ptr< char[] > data_; - size_t size_; - }; - - /*! - * Read the whole content of a file (UTF-8 path) in one call. - * @return std::nullopt if the file cannot be opened. - * @exception OpenGeodeException (data) if the file cannot be read. - */ - [[nodiscard]] std::optional< ByteBuffer > - opengeode_basic_api read_file_content( std::string_view filename ); - /*! * Deserialize an object from bytes, with the deserialize contexts of * every registered library. diff --git a/include/geode/basic/byte_span.hpp b/include/geode/basic/byte_span.hpp new file mode 100644 index 000000000..dc220c59e --- /dev/null +++ b/include/geode/basic/byte_span.hpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include + +namespace geode +{ + /*! + * Read-only bytes to deserialize, owned elsewhere (file content, slice of + * an archive in memory...). + */ + using ByteSpan = absl::Span< const char >; +} // namespace geode diff --git a/include/geode/basic/detail/file_content.hpp b/include/geode/basic/detail/file_content.hpp new file mode 100644 index 000000000..52b642b17 --- /dev/null +++ b/include/geode/basic/detail/file_content.hpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace geode::detail +{ + /*! + * Owned bytes, uninitialized at construction. + */ + class ByteBuffer + { + public: + explicit ByteBuffer( size_t size ) + : data_{ new char[size] }, size_{ size } + { + } + + [[nodiscard]] char* data() + { + return data_.get(); + } + + [[nodiscard]] size_t size() const + { + return size_; + } + + [[nodiscard]] ByteSpan span() const + { + return { data_.get(), size_ }; + } + + private: + std::unique_ptr< char[] > data_; + size_t size_; + }; + + /*! + * A whole file mapped read-only in memory: its pages are read from the + * file when first accessed, and belong to the system file cache. + * The file must not be truncated while it is mapped. + */ + class opengeode_basic_api MappedFile + { + public: + /*! + * Map a whole file (UTF-8 path) read-only. + * @return nullptr if the file cannot be mapped (missing, not a regular + * file, or mapping not supported). + */ + [[nodiscard]] static std::shared_ptr< const MappedFile > map( + std::string_view filename ); + + MappedFile( const MappedFile& ) = delete; + MappedFile& operator=( const MappedFile& ) = delete; + MappedFile( MappedFile&& ) = delete; + MappedFile& operator=( MappedFile&& ) = delete; + ~MappedFile(); + + /*! + * Bytes of the file (empty for an empty file). + */ + [[nodiscard]] ByteSpan span() const; + + /*! + * Remove the pages lying entirely within the given bytes of span() + * from the memory of the process (they stay in the file cache). + * The bytes stay readable: their pages are mapped again if accessed. + */ + void release( ByteSpan bytes ) const; + + private: + MappedFile( const char* data, size_t size ); + + private: + const char* data_; + size_t size_; + }; + + /*! + * Bytes of a file: either a slice of a mapped file (kept mapped while + * this object lives, and released from memory when it is destroyed), or + * an owned buffer. + */ + class opengeode_basic_api FileContent + { + public: + explicit FileContent( ByteBuffer buffer ); + + /*! + * @param[in] bytes Bytes inside mapping->span(). + */ + FileContent( + std::shared_ptr< const MappedFile > mapping, ByteSpan bytes ); + + FileContent( const FileContent& ) = delete; + FileContent& operator=( const FileContent& ) = delete; + FileContent( FileContent&& other ) noexcept; + FileContent& operator=( FileContent&& ) = delete; + ~FileContent(); + + [[nodiscard]] ByteSpan span() const + { + return bytes_; + } + + private: + std::shared_ptr< const MappedFile > mapping_; + std::optional< ByteBuffer > buffer_; + ByteSpan bytes_; + }; + + /*! + * Content of a whole file (UTF-8 path): mapped when possible, otherwise + * read into memory. + * @return std::nullopt if the file cannot be opened or is not a regular + * file. + * @exception OpenGeodeException (data) if the file cannot be read. + */ + [[nodiscard]] std::optional< FileContent > + opengeode_basic_api map_file_content( std::string_view filename ); +} // namespace geode::detail diff --git a/include/geode/basic/detail/geode_input_impl.hpp b/include/geode/basic/detail/geode_input_impl.hpp index ce987ddfc..af5bfd45e 100644 --- a/include/geode/basic/detail/geode_input_impl.hpp +++ b/include/geode/basic/detail/geode_input_impl.hpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -80,6 +81,53 @@ namespace geode::detail return objects; } + /*! + * Load the objects of one of the given files with the input registered + * for its extension: from its content in memory when the input supports + * it, otherwise from the file on disk (written to a temporary directory + * if the files are not in a directory). + */ + template < typename Factory, typename... Args > + [[nodiscard]] std::vector< typename Factory::BaseClass::InputData > + geode_object_input_from_files( std::string_view type, + const InputFiles& files, + std::string_view name, + const Args&... args ) + { + const Timer timer; + const auto location = files.location( name ); + const auto extension = lowercase_extension( name ); + OpenGeodeBasicException::check_exception( + Factory::has_creator( extension ), nullptr, + OpenGeodeException::TYPE::data, "Unknown extension \"", extension, + "\" for file \"", location, "\". Available extensions: ", + absl::StrJoin( Factory::list_creators(), ", " ), + ". Other formats may be provided by IO libraries, which must be " + "initialized (or imported in Python) first" ); + auto objects = [&] { + const auto content = files.content( name ); + auto input = Factory::create( extension, location ); + if( auto from_bytes = input->read_bytes( content.span(), args... ) ) + { + return std::move( from_bytes.value() ); + } + if( const auto path = files.path( name ) ) + { + return Factory::create( extension, path.value() ) + ->read( args... ); + } + const TemporaryFile file{ name, content.span() }; + return Factory::create( extension, file.path() )->read( args... ); + }(); + OpenGeodeBasicException::check_exception( !objects.empty(), nullptr, + OpenGeodeException::TYPE::data, "[", type, + "] No object found in file \"", location, "\"" ); + Logger::info( type, " loaded from ", location, " in ", timer.duration(), + " (", objects.size(), + objects.size() == 1 ? " object)" : " objects)" ); + return objects; + } + template < typename Exception, typename Factory, typename... ParentFactories, diff --git a/include/geode/basic/detail/input_files.hpp b/include/geode/basic/detail/input_files.hpp new file mode 100644 index 000000000..cc38a4557 --- /dev/null +++ b/include/geode/basic/detail/input_files.hpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace geode::detail +{ + /*! + * Read-only set of named files making up a saved object (e.g. a model): + * either the files of a directory or the entries of an archive. + * All the const functions can be called concurrently. + */ + class opengeode_basic_api InputFiles + { + public: + InputFiles( const InputFiles& ) = delete; + InputFiles& operator=( const InputFiles& ) = delete; + InputFiles( InputFiles&& ) = delete; + InputFiles& operator=( InputFiles&& ) = delete; + virtual ~InputFiles(); + + /*! + * Return true if there is a file of this name. + */ + [[nodiscard]] virtual bool has( std::string_view name ) const = 0; + + /*! + * Names of every file (directories excluded), in a deterministic + * order. + */ + [[nodiscard]] virtual std::vector< std::string > names() const = 0; + + /*! + * Bytes of a file, without copy when possible. + * @exception OpenGeodeException (data) if the file is missing, cannot + * be read, or is corrupted. + */ + [[nodiscard]] virtual FileContent content( + std::string_view name ) const = 0; + + /*! + * Path of a file on disk, if the files are in a directory. + * @return std::nullopt for an entry of an archive. + */ + [[nodiscard]] virtual std::optional< std::string > path( + std::string_view name ) const = 0; + + /*! + * Description of a file for messages: its path, or the archive path + * followed by the entry name. + */ + [[nodiscard]] virtual std::string location( + std::string_view name ) const = 0; + + protected: + InputFiles() = default; + }; + + /*! + * Files of a directory (not recursive): files are mapped in memory when + * read. + */ + class opengeode_basic_api DirectoryInputFiles final : public InputFiles + { + public: + explicit DirectoryInputFiles( std::string_view directory ); + ~DirectoryInputFiles() final; + + [[nodiscard]] bool has( std::string_view name ) const final; + + [[nodiscard]] std::vector< std::string > names() const final; + + [[nodiscard]] FileContent content( std::string_view name ) const final; + + [[nodiscard]] std::optional< std::string > path( + std::string_view name ) const final; + + [[nodiscard]] std::string location( std::string_view name ) const final; + + private: + std::string directory_; + }; + + /*! + * Entries of a zip archive, read in place: the archive is mapped in + * memory (or read entry by entry if it cannot be mapped), stored entries + * are returned without copy and deflated entries are decompressed. + * The CRC-32 of an entry is checked each time it is read. + */ + class opengeode_basic_api ArchiveInputFiles final : public InputFiles + { + public: + /*! + * Read the list of entries of a zip archive (UTF-8 path). + * @exception OpenGeodeException (data) if the file is not a readable + * zip archive or holds an entry with an unsafe path (absolute or + * with ".."), encrypted or compressed by another method than DEFLATE. + */ + explicit ArchiveInputFiles( std::string_view filename ); + ~ArchiveInputFiles() final; + + [[nodiscard]] bool has( std::string_view name ) const final; + + [[nodiscard]] std::vector< std::string > names() const final; + + /*! + * @exception OpenGeodeException (data) if the entry is missing, + * cannot be read or decompressed, or does not match its CRC-32. + */ + [[nodiscard]] FileContent content( std::string_view name ) const final; + + [[nodiscard]] std::optional< std::string > path( + std::string_view name ) const final; + + [[nodiscard]] std::string location( std::string_view name ) const final; + + private: + IMPLEMENTATION_MEMBER( impl_ ); + }; + + /*! + * A file holding the given bytes, in a new directory of the temporary + * directory of the system. Both are removed on destruction. + */ + class opengeode_basic_api TemporaryFile + { + public: + /*! + * @param[in] name Name of the file (without directory). + * @exception OpenGeodeException (internal) if there is no temporary + * directory, or if the directory or the file cannot be created. + */ + TemporaryFile( std::string_view name, ByteSpan content ); + TemporaryFile( const TemporaryFile& ) = delete; + TemporaryFile& operator=( const TemporaryFile& ) = delete; + TemporaryFile( TemporaryFile&& ) = delete; + TemporaryFile& operator=( TemporaryFile&& ) = delete; + ~TemporaryFile(); + + [[nodiscard]] const std::string& path() const; + + private: + std::string directory_; + std::string path_; + }; +} // namespace geode::detail diff --git a/include/geode/basic/identifier.hpp b/include/geode/basic/identifier.hpp index ba9b83241..cc7bceb4a 100644 --- a/include/geode/basic/identifier.hpp +++ b/include/geode/basic/identifier.hpp @@ -34,6 +34,11 @@ namespace bitsery class Access; } // namespace bitsery +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class IdentifierBuilder; @@ -65,7 +70,7 @@ namespace geode void set_name( std::string_view name, IdentifierKey /*key*/ ); void load_identifier( - std::string_view directory, IdentifierKey /*key*/ ); + const detail::InputFiles& files, IdentifierKey /*key*/ ); void copy_identifier( const Identifier& other, IdentifierKey /*key*/ ); diff --git a/include/geode/basic/identifier_builder.hpp b/include/geode/basic/identifier_builder.hpp index b8fcb4bbb..a456b1f9c 100644 --- a/include/geode/basic/identifier_builder.hpp +++ b/include/geode/basic/identifier_builder.hpp @@ -25,6 +25,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class Identifier; @@ -46,6 +51,8 @@ namespace geode void load_identifier( std::string_view directory ); + void load_identifier( const detail::InputFiles& files ); + private: Identifier& identifier_; }; diff --git a/include/geode/basic/input.hpp b/include/geode/basic/input.hpp index 638acac27..c5204ee50 100644 --- a/include/geode/basic/input.hpp +++ b/include/geode/basic/input.hpp @@ -23,11 +23,13 @@ #pragma once +#include #include #include #include +#include #include #include #include @@ -78,6 +80,19 @@ namespace geode [[nodiscard]] virtual std::vector< Object > read( const Args&... args ) = 0; + /*! + * Read the objects from the content of the file, already in memory + * (e.g. an entry of an archive), instead of opening the file: the + * filename only names the content in messages. + * @return std::nullopt if this input can only read files: the caller + * then calls read() on a file holding the content. + */ + [[nodiscard]] virtual std::optional< std::vector< Object > > read_bytes( + ByteSpan /*content*/, const Args&... /*args*/ ) + { + return std::nullopt; + } + ~Input() { if( inspect_required_ ) diff --git a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp index a5adaf1f5..d9fa9ded3 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp @@ -24,6 +24,9 @@ #pragma once #include +#include + +#include #include #include @@ -41,19 +44,17 @@ namespace geode [[nodiscard]] std::vector< RasterImage< dimension > > read() final { - const auto content = detail::read_file_content( this->filename() ); + const auto content = detail::map_file_content( this->filename() ); OpenGeodeImageException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, "[RasterImageInput] Failed to open file: ", this->filename() ); - RasterImage< dimension > image; - OpenGeodeImageException::check_exception( - detail::deserialize_bytes( content->span(), image ), nullptr, - OpenGeodeException::TYPE::data, - "[Bitsery::read] Error while reading file: ", - this->filename() ); - std::vector< RasterImage< dimension > > images; - images.emplace_back( std::move( image ) ); - return images; + return read_image( content->span() ); + } + + [[nodiscard]] std::optional< std::vector< RasterImage< dimension > > > + read_bytes( ByteSpan content ) final + { + return read_image( content ); } AdditionalFiles additional_files() const final @@ -70,6 +71,21 @@ namespace geode { return Percentage{ 1 }; } + + private: + [[nodiscard]] std::vector< RasterImage< dimension > > read_image( + ByteSpan content ) const + { + RasterImage< dimension > image; + OpenGeodeImageException::check_exception( + detail::deserialize_bytes( content, image ), nullptr, + OpenGeodeException::TYPE::data, + "[Bitsery::read] Error while reading file: ", + this->filename() ); + std::vector< RasterImage< dimension > > images; + images.emplace_back( std::move( image ) ); + return images; + } }; ALIAS_1D_AND_2D_AND_3D( OpenGeodeRasterImageInput ); } // namespace geode diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp index 4fa23d473..39125cdca 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp @@ -24,6 +24,9 @@ #pragma once #include +#include + +#include #include @@ -36,17 +39,30 @@ const MeshImpl& /*impl*/ ) final \ { \ const auto content = \ - geode::detail::read_file_content( this->filename() ); \ + geode::detail::map_file_content( this->filename() ); \ geode::OpenGeodeMeshException::check_exception( content.has_value(), \ nullptr, geode::OpenGeodeException::TYPE::data, \ "[Bitsery::read] Failed to open file: ", this->filename() ); \ + return read_mesh( content->span() ); \ + } \ + \ + [[nodiscard]] std::optional< std::vector< std::unique_ptr< Mesh > > > \ + read_bytes( geode::ByteSpan content, const MeshImpl& /*impl*/ ) final \ + { \ + return read_mesh( content ); \ + } \ + \ +private: \ + [[nodiscard]] std::vector< std::unique_ptr< Mesh > > read_mesh( \ + geode::ByteSpan content ) const \ + { \ std::unique_ptr< Mesh > mesh{ new OpenGeode##Mesh{ \ BITSERY::constructor } }; \ bool success{ false }; \ try \ { \ success = geode::detail::deserialize_bytes( \ - content->span(), dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ + content, dynamic_cast< OpenGeode##Mesh& >( *mesh ) ); \ } \ catch( const geode::OpenGeodeException& ) \ { \ @@ -67,6 +83,7 @@ return meshes; \ } \ \ +public: \ index_t object_priority() const final \ { \ return 0; \ diff --git a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp index a59a79d25..f37d6930b 100644 --- a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp +++ b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp @@ -23,8 +23,10 @@ #pragma once +#include #include +#include #include #include @@ -55,11 +57,40 @@ namespace geode [[nodiscard]] std::vector< LightRegularGrid< dimension > > read() override { - const auto content = detail::read_file_content( this->filename() ); + const auto content = detail::map_file_content( this->filename() ); OpenGeodeMeshException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, "[LightRegularGridInput] Failed to open file: ", this->filename() ); + return read_grid( content->span() ); + } + + [[nodiscard]] std::optional< + std::vector< LightRegularGrid< dimension > > > + read_bytes( ByteSpan content ) override + { + return read_grid( content ); + } + + AdditionalFiles additional_files() const override + { + return {}; + } + + index_t object_priority() const override + { + return 0; + } + + Percentage is_loadable() const final + { + return Percentage{ 1 }; + } + + private: + [[nodiscard]] std::vector< LightRegularGrid< dimension > > read_grid( + ByteSpan content ) const + { Point< dimension > origin; std::array< index_t, dimension > cells_number; cells_number.fill( 1 ); @@ -70,7 +101,7 @@ namespace geode bool success{ false }; try { - success = detail::deserialize_bytes( content->span(), grid ); + success = detail::deserialize_bytes( content, grid ); } catch( const OpenGeodeException& ) { @@ -91,21 +122,6 @@ namespace geode grids.emplace_back( std::move( grid ) ); return grids; } - - AdditionalFiles additional_files() const override - { - return {}; - } - - index_t object_priority() const override - { - return 0; - } - - Percentage is_loadable() const final - { - return Percentage{ 1 }; - } }; ALIAS_2D_AND_3D( OpenGeodeLightRegularGridInput ); } // namespace geode diff --git a/include/geode/model/mixin/builder/block_collections_builder.hpp b/include/geode/model/mixin/builder/block_collections_builder.hpp index e91badfb5..cf9b0259e 100644 --- a/include/geode/model/mixin/builder/block_collections_builder.hpp +++ b/include/geode/model/mixin/builder/block_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( BlockCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_block_collections( std::string_view directory ); + void load_block_collections( const detail::InputFiles& files ); + void set_block_collection_name( const BlockCollection< dimension >& block_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/blocks_builder.hpp b/include/geode/model/mixin/builder/blocks_builder.hpp index de5e7bf10..5adc9744b 100644 --- a/include/geode/model/mixin/builder/blocks_builder.hpp +++ b/include/geode/model/mixin/builder/blocks_builder.hpp @@ -33,6 +33,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Block ); @@ -51,6 +56,8 @@ namespace geode public: void load_blocks( std::string_view directory ); + void load_blocks( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Block mesh * @param[in] Block Block component to get the builder of diff --git a/include/geode/model/mixin/builder/corner_collections_builder.hpp b/include/geode/model/mixin/builder/corner_collections_builder.hpp index d6970d356..257461b8a 100644 --- a/include/geode/model/mixin/builder/corner_collections_builder.hpp +++ b/include/geode/model/mixin/builder/corner_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( CornerCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_corner_collections( std::string_view directory ); + void load_corner_collections( const detail::InputFiles& files ); + void set_corner_collection_name( const CornerCollection< dimension >& corner_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/corners_builder.hpp b/include/geode/model/mixin/builder/corners_builder.hpp index 68e9a2986..7a29701d3 100644 --- a/include/geode/model/mixin/builder/corners_builder.hpp +++ b/include/geode/model/mixin/builder/corners_builder.hpp @@ -32,6 +32,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Corner ); @@ -50,6 +55,8 @@ namespace geode public: void load_corners( std::string_view directory ); + void load_corners( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Corner mesh * @param[in] corner Corner in the model diff --git a/include/geode/model/mixin/builder/line_collections_builder.hpp b/include/geode/model/mixin/builder/line_collections_builder.hpp index 96faa9173..c90cf0da0 100644 --- a/include/geode/model/mixin/builder/line_collections_builder.hpp +++ b/include/geode/model/mixin/builder/line_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( LineCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_line_collections( std::string_view directory ); + void load_line_collections( const detail::InputFiles& files ); + void set_line_collection_name( const LineCollection< dimension >& line_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/lines_builder.hpp b/include/geode/model/mixin/builder/lines_builder.hpp index 214e79ac1..6a3d273c4 100644 --- a/include/geode/model/mixin/builder/lines_builder.hpp +++ b/include/geode/model/mixin/builder/lines_builder.hpp @@ -32,6 +32,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Line ); @@ -50,6 +55,8 @@ namespace geode public: void load_lines( std::string_view directory ); + void load_lines( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Line mesh * @param[in] line Line component to get the builder of diff --git a/include/geode/model/mixin/builder/model_boundaries_builder.hpp b/include/geode/model/mixin/builder/model_boundaries_builder.hpp index 00ef7d9d1..0a4b468c6 100644 --- a/include/geode/model/mixin/builder/model_boundaries_builder.hpp +++ b/include/geode/model/mixin/builder/model_boundaries_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( ModelBoundary ); @@ -43,6 +48,8 @@ namespace geode public: void load_model_boundaries( std::string_view directory ); + void load_model_boundaries( const detail::InputFiles& files ); + void set_model_boundary_name( const ModelBoundary< dimension >& id, std::string_view name ); diff --git a/include/geode/model/mixin/builder/physical_properties_builder.hpp b/include/geode/model/mixin/builder/physical_properties_builder.hpp index dfa201fbd..d77dd6659 100644 --- a/include/geode/model/mixin/builder/physical_properties_builder.hpp +++ b/include/geode/model/mixin/builder/physical_properties_builder.hpp @@ -28,6 +28,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { struct uuid; @@ -60,6 +65,8 @@ namespace geode void load_physical_properties( std::string_view directory ); + void load_physical_properties( const detail::InputFiles& files ); + private: PhysicalProperties& physical_properties_; }; diff --git a/include/geode/model/mixin/builder/relationships_builder.hpp b/include/geode/model/mixin/builder/relationships_builder.hpp index 5d8c447ef..2c3b9d4f7 100644 --- a/include/geode/model/mixin/builder/relationships_builder.hpp +++ b/include/geode/model/mixin/builder/relationships_builder.hpp @@ -26,6 +26,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { /*! @@ -81,6 +86,8 @@ namespace geode void load_relationships( std::string_view directory ); + void load_relationships( const detail::InputFiles& files ); + private: Relationships& relationships_; }; diff --git a/include/geode/model/mixin/builder/surface_collections_builder.hpp b/include/geode/model/mixin/builder/surface_collections_builder.hpp index 681fc6c6c..38c98a227 100644 --- a/include/geode/model/mixin/builder/surface_collections_builder.hpp +++ b/include/geode/model/mixin/builder/surface_collections_builder.hpp @@ -27,6 +27,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceCollection ); @@ -43,6 +48,8 @@ namespace geode public: void load_surface_collections( std::string_view directory ); + void load_surface_collections( const detail::InputFiles& files ); + void set_surface_collection_name( const SurfaceCollection< dimension >& surface_collection, std::string_view name ); diff --git a/include/geode/model/mixin/builder/surfaces_builder.hpp b/include/geode/model/mixin/builder/surfaces_builder.hpp index 63d131b3b..8b2f3e02d 100644 --- a/include/geode/model/mixin/builder/surfaces_builder.hpp +++ b/include/geode/model/mixin/builder/surfaces_builder.hpp @@ -33,6 +33,11 @@ #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Surface ); @@ -51,6 +56,8 @@ namespace geode public: void load_surfaces( std::string_view directory ); + void load_surfaces( const detail::InputFiles& files ); + /*! * Get a pointer to the builder of a Surface mesh * @param[in] surface Surface component to get the builder of diff --git a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp index 6c08c30a3..fdda4544d 100644 --- a/include/geode/model/mixin/builder/vertex_identifier_builder.hpp +++ b/include/geode/model/mixin/builder/vertex_identifier_builder.hpp @@ -28,6 +28,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { /*! @@ -115,6 +120,8 @@ namespace geode */ void load_unique_vertices( std::string_view directory ); + void load_unique_vertices( const detail::InputFiles& files ); + /*! * Delete all unique vertices not associated with any component */ diff --git a/include/geode/model/mixin/core/block_collections.hpp b/include/geode/model/mixin/core/block_collections.hpp index 49cd9addc..65fefe449 100644 --- a/include/geode/model/mixin/core/block_collections.hpp +++ b/include/geode/model/mixin/core/block_collections.hpp @@ -29,6 +29,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( BlockCollection ); @@ -156,7 +161,7 @@ namespace geode BlockCollectionsBuilderKey key ); void load_block_collections( - std::string_view directory, BlockCollectionsBuilderKey key ); + const detail::InputFiles& files, BlockCollectionsBuilderKey key ); [[nodiscard]] ModifiableBlockCollectionRange modifiable_block_collections( BlockCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/blocks.hpp b/include/geode/model/mixin/core/blocks.hpp index ded38a484..43ab93b47 100644 --- a/include/geode/model/mixin/core/blocks.hpp +++ b/include/geode/model/mixin/core/blocks.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Block ); @@ -170,7 +175,8 @@ namespace geode void delete_block( const Block< dimension >& block, BlocksBuilderKey key ); - void load_blocks( std::string_view directory, BlocksBuilderKey key ); + void load_blocks( + const detail::InputFiles& files, BlocksBuilderKey key ); [[nodiscard]] ModifiableBlockRange modifiable_blocks( BlocksBuilderKey key ); diff --git a/include/geode/model/mixin/core/corner_collections.hpp b/include/geode/model/mixin/core/corner_collections.hpp index 49b35be5f..143203b35 100644 --- a/include/geode/model/mixin/core/corner_collections.hpp +++ b/include/geode/model/mixin/core/corner_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( CornerCollection ); @@ -159,7 +164,7 @@ namespace geode CornerCollectionsBuilderKey key ); void load_corner_collections( - std::string_view directory, CornerCollectionsBuilderKey key ); + const detail::InputFiles& files, CornerCollectionsBuilderKey key ); [[nodiscard]] ModifiableCornerCollectionRange modifiable_corner_collections( CornerCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/corners.hpp b/include/geode/model/mixin/core/corners.hpp index a2aa8ce52..e3ad3c87b 100644 --- a/include/geode/model/mixin/core/corners.hpp +++ b/include/geode/model/mixin/core/corners.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Corner ); @@ -169,7 +174,8 @@ namespace geode void delete_corner( const Corner< dimension >& corner, CornersBuilderKey key ); - void load_corners( std::string_view directory, CornersBuilderKey key ); + void load_corners( + const detail::InputFiles& files, CornersBuilderKey key ); [[nodiscard]] ModifiableCornerRange modifiable_corners( CornersBuilderKey key ); diff --git a/include/geode/model/mixin/core/detail/components_storage.hpp b/include/geode/model/mixin/core/detail/components_storage.hpp index bee722642..1a3184219 100644 --- a/include/geode/model/mixin/core/detail/components_storage.hpp +++ b/include/geode/model/mixin/core/detail/components_storage.hpp @@ -34,7 +34,10 @@ #include #include +#include +#include #include +#include #include #include @@ -87,6 +90,31 @@ namespace geode::detail MeshFactory::default_impl( fallback_type ) ); } + /*! + * Load the single mesh of a component file of the input files, with the + * input of the given factory registered for its extension. + */ + template < typename Factory > + [[nodiscard]] typename Factory::BaseClass::InputData load_component_mesh( + const InputFiles& files, std::string_view name, const MeshImpl& impl ) + { + const auto& type = MeshFactory::type( impl ).get(); + try + { + return load_one( geode_object_input_from_files< Factory >( + type, files, name, impl ), + files.location( name ) ); + } + catch( const std::exception& exception ) + { + Logger::error( exception.what() ); + throw OpenGeodeModelException{ nullptr, + OpenGeodeException::TYPE::data, "Cannot load ", type, + " from file: ", files.location( name ), ": ", + exception.what() }; + } + } + template < typename Component > class ComponentsStorage { @@ -168,53 +196,53 @@ namespace geode::detail } /*! - * Load the components stored in the given file. + * Load the components stored in the given file of the input files. * @param[in] required If false, a missing file is expected (e.g. for * files written before this component type existed) and silently * ignored. Otherwise a warning is emitted. */ - void load_components( std::string_view filename, bool required = true ) + void load_components( + const InputFiles& files, std::string_view name, bool required ) { - const auto path = std::filesystem::u8path( to_string( filename ) ); - if( !std::filesystem::exists( path ) ) + if( !files.has( name ) ) { if( required ) { Logger::warning( "[ComponentsStorage::load_components] " "Missing file: ", - filename, ", no component loaded from it" ); + files.location( name ), + ", no component loaded from it" ); } return; } - const auto content = detail::read_file_content( filename ); - OpenGeodeModelException::check_exception( content.has_value(), - nullptr, OpenGeodeException::TYPE::internal, - "[ComponentsStorage::load_components] Error while reading " - "file: ", - filename ); + const auto location = files.location( name ); + const auto content = files.content( name ); OpenGeodeModelException::check_exception( - detail::deserialize_bytes( content->span(), *this ), nullptr, + detail::deserialize_bytes( content.span(), *this ), nullptr, OpenGeodeException::TYPE::internal, "[ComponentsStorage::load_components] Error while reading " "file: ", - filename ); - repair_loaded_components( filename ); + location ); + repair_loaded_components( location ); } + /*! + * Map the uuid ending the name of each file (before its extension) + * to the file name. + */ [[nodiscard]] absl::flat_hash_map< std::string, std::string > - file_mapping( std::string_view directory ) const + file_mapping( const InputFiles& files ) const { absl::flat_hash_map< std::string, std::string > mapping; - for( const auto& file : std::filesystem::directory_iterator( - std::filesystem::u8path( to_string( directory ) ) ) ) + for( auto& name : files.names() ) { - auto path = file.path(); - auto filename = path.replace_extension( "" ).u8string(); - if( filename.size() > 36 ) + const auto stem = std::filesystem::u8path( name ) + .replace_extension( "" ) + .u8string(); + if( stem.size() > 36 ) { - auto uuid = filename.substr( filename.size() - 36 ); mapping.emplace( - std::move( uuid ), file.path().u8string() ); + stem.substr( stem.size() - 36 ), std::move( name ) ); } } return mapping; diff --git a/include/geode/model/mixin/core/line_collections.hpp b/include/geode/model/mixin/core/line_collections.hpp index c66d8b5c6..a6ac349e4 100644 --- a/include/geode/model/mixin/core/line_collections.hpp +++ b/include/geode/model/mixin/core/line_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( LineCollection ); @@ -155,7 +160,7 @@ namespace geode LineCollectionsBuilderKey key ); void load_line_collections( - std::string_view directory, LineCollectionsBuilderKey key ); + const detail::InputFiles& files, LineCollectionsBuilderKey key ); [[nodiscard]] ModifiableLineCollectionRange modifiable_line_collections( LineCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/lines.hpp b/include/geode/model/mixin/core/lines.hpp index 81344e7bc..67c6efaef 100644 --- a/include/geode/model/mixin/core/lines.hpp +++ b/include/geode/model/mixin/core/lines.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Line ); @@ -152,7 +157,7 @@ namespace geode void delete_line( const Line< dimension >& line, LinesBuilderKey key ); - void load_lines( std::string_view directory, LinesBuilderKey key ); + void load_lines( const detail::InputFiles& files, LinesBuilderKey key ); [[nodiscard]] ModifiableLineRange modifiable_lines( LinesBuilderKey key ); diff --git a/include/geode/model/mixin/core/model_boundaries.hpp b/include/geode/model/mixin/core/model_boundaries.hpp index 7ea024013..1236660bc 100644 --- a/include/geode/model/mixin/core/model_boundaries.hpp +++ b/include/geode/model/mixin/core/model_boundaries.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( ModelBoundary ); @@ -154,7 +159,7 @@ namespace geode ModelBoundariesBuilderKey key ); void load_model_boundaries( - std::string_view directory, ModelBoundariesBuilderKey key ); + const detail::InputFiles& files, ModelBoundariesBuilderKey key ); [[nodiscard]] ModifiableModelBoundaryRange modifiable_model_boundaries( ModelBoundariesBuilderKey key ); diff --git a/include/geode/model/mixin/core/physical_properties.hpp b/include/geode/model/mixin/core/physical_properties.hpp index b82aa7e72..ebd2ef2c8 100644 --- a/include/geode/model/mixin/core/physical_properties.hpp +++ b/include/geode/model/mixin/core/physical_properties.hpp @@ -34,6 +34,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class PhysicalPropertiesBuilder; @@ -119,7 +124,7 @@ namespace geode const PhysicalProperties& other, BuilderKey /*key*/ ); void load_physical_properties( - std::string_view directory, BuilderKey /*key*/ ); + const detail::InputFiles& files, BuilderKey /*key*/ ); protected: PhysicalProperties( PhysicalProperties&& other ) noexcept; diff --git a/include/geode/model/mixin/core/relationships.hpp b/include/geode/model/mixin/core/relationships.hpp index 094ffcea5..88b834b39 100644 --- a/include/geode/model/mixin/core/relationships.hpp +++ b/include/geode/model/mixin/core/relationships.hpp @@ -35,6 +35,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { class AttributeManager; @@ -489,7 +494,7 @@ namespace geode RelationshipsBuilderKey /*key*/ ); void load_relationships( - std::string_view directory, RelationshipsBuilderKey /*key*/ ); + const detail::InputFiles& files, RelationshipsBuilderKey /*key*/ ); protected: Relationships( Relationships&& other ) noexcept; diff --git a/include/geode/model/mixin/core/surface_collections.hpp b/include/geode/model/mixin/core/surface_collections.hpp index 77950340b..b5ac9fd0f 100644 --- a/include/geode/model/mixin/core/surface_collections.hpp +++ b/include/geode/model/mixin/core/surface_collections.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( SurfaceCollection ); @@ -161,7 +166,7 @@ namespace geode SurfaceCollectionsBuilderKey key ); void load_surface_collections( - std::string_view directory, SurfaceCollectionsBuilderKey key ); + const detail::InputFiles& files, SurfaceCollectionsBuilderKey key ); [[nodiscard]] ModifiableSurfaceCollectionRange modifiable_surface_collections( SurfaceCollectionsBuilderKey key ); diff --git a/include/geode/model/mixin/core/surfaces.hpp b/include/geode/model/mixin/core/surfaces.hpp index dbaca2c4d..92e459f92 100644 --- a/include/geode/model/mixin/core/surfaces.hpp +++ b/include/geode/model/mixin/core/surfaces.hpp @@ -31,6 +31,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { FORWARD_DECLARATION_DIMENSION_CLASS( Surface ); @@ -156,7 +161,7 @@ namespace geode const Surface< dimension >& surface, SurfacesBuilderKey key ); void load_surfaces( - std::string_view directory, SurfacesBuilderKey key ); + const detail::InputFiles& files, SurfacesBuilderKey key ); [[nodiscard]] ModifiableSurfaceRange modifiable_surfaces( SurfacesBuilderKey key ); diff --git a/include/geode/model/mixin/core/vertex_identifier.hpp b/include/geode/model/mixin/core/vertex_identifier.hpp index 0c38c6a2e..884c1b105 100644 --- a/include/geode/model/mixin/core/vertex_identifier.hpp +++ b/include/geode/model/mixin/core/vertex_identifier.hpp @@ -35,6 +35,11 @@ #include #include +namespace geode::detail +{ + class InputFiles; +} // namespace geode::detail + namespace geode { struct MeshVertex; @@ -219,7 +224,7 @@ namespace geode * VertexIdentifier information. */ void load_unique_vertices( - std::string_view directory, BuilderKey /*key*/ ); + const detail::InputFiles& files, BuilderKey /*key*/ ); /*! * Delete all unique vertices not associated with any component diff --git a/include/geode/model/representation/io/geode/geode_brep_input.hpp b/include/geode/model/representation/io/geode/geode_brep_input.hpp index 5b5e8668e..1bfdd1b5c 100644 --- a/include/geode/model/representation/io/geode/geode_brep_input.hpp +++ b/include/geode/model/representation/io/geode/geode_brep_input.hpp @@ -25,6 +25,8 @@ #include +#include + #include #include #include @@ -66,52 +68,56 @@ namespace geode namespace detail { + /*! + * Load the files of a BRep (identifier, components, meshes, + * relationships, unique vertices) into an empty model. + */ template < typename Model > - void load_brep_files( Model& brep, std::string_view directory ) + void load_brep_files( Model& brep, const detail::InputFiles& files ) { BRepBuilder builder{ brep }; const detail::ScopedLoggerLevel scoped_level{ Logger::LEVEL::warning }; async::parallel_invoke( - [&builder, &directory] { - builder.load_identifier( directory ); + [&builder, &files] { + builder.load_identifier( files ); }, - [&builder, &directory] { - builder.load_physical_properties( directory ); + [&builder, &files] { + builder.load_physical_properties( files ); }, - [&builder, &directory] { - builder.load_corners( directory ); + [&builder, &files] { + builder.load_corners( files ); }, - [&builder, &directory] { - builder.load_lines( directory ); + [&builder, &files] { + builder.load_lines( files ); }, - [&builder, &directory] { - builder.load_surfaces( directory ); + [&builder, &files] { + builder.load_surfaces( files ); }, - [&builder, &directory] { - builder.load_blocks( directory ); + [&builder, &files] { + builder.load_blocks( files ); }, - [&builder, &directory] { - builder.load_model_boundaries( directory ); + [&builder, &files] { + builder.load_model_boundaries( files ); }, - [&builder, &directory] { - builder.load_corner_collections( directory ); + [&builder, &files] { + builder.load_corner_collections( files ); }, - [&builder, &directory] { - builder.load_line_collections( directory ); + [&builder, &files] { + builder.load_line_collections( files ); }, - [&builder, &directory] { - builder.load_surface_collections( directory ); + [&builder, &files] { + builder.load_surface_collections( files ); }, - [&builder, &directory] { - builder.load_block_collections( directory ); + [&builder, &files] { + builder.load_block_collections( files ); }, - [&builder, &directory] { - builder.load_relationships( directory ); + [&builder, &files] { + builder.load_relationships( files ); }, - [&builder, &directory] { - builder.load_unique_vertices( directory ); + [&builder, &files] { + builder.load_unique_vertices( files ); } ); detail::register_all_components( brep ); detail::filter_unsupported_components( brep ); diff --git a/include/geode/model/representation/io/geode/geode_section_input.hpp b/include/geode/model/representation/io/geode/geode_section_input.hpp index 00b8572d5..699e76388 100644 --- a/include/geode/model/representation/io/geode/geode_section_input.hpp +++ b/include/geode/model/representation/io/geode/geode_section_input.hpp @@ -25,6 +25,8 @@ #include +#include + #include #include #include @@ -66,43 +68,48 @@ namespace geode namespace detail { + /*! + * Load the files of a Section (identifier, components, meshes, + * relationships, unique vertices) into an empty model. + */ template < typename Model > - void load_section_files( Model& section, std::string_view directory ) + void load_section_files( + Model& section, const detail::InputFiles& files ) { SectionBuilder builder{ section }; const detail::ScopedLoggerLevel scoped_level{ Logger::LEVEL::warning }; async::parallel_invoke( - [&builder, &directory] { - builder.load_identifier( directory ); + [&builder, &files] { + builder.load_identifier( files ); }, - [&builder, &directory] { - builder.load_corners( directory ); + [&builder, &files] { + builder.load_corners( files ); }, - [&builder, &directory] { - builder.load_lines( directory ); + [&builder, &files] { + builder.load_lines( files ); }, - [&builder, &directory] { - builder.load_surfaces( directory ); + [&builder, &files] { + builder.load_surfaces( files ); }, - [&builder, &directory] { - builder.load_model_boundaries( directory ); + [&builder, &files] { + builder.load_model_boundaries( files ); }, - [&builder, &directory] { - builder.load_corner_collections( directory ); + [&builder, &files] { + builder.load_corner_collections( files ); }, - [&builder, &directory] { - builder.load_line_collections( directory ); + [&builder, &files] { + builder.load_line_collections( files ); }, - [&builder, &directory] { - builder.load_surface_collections( directory ); + [&builder, &files] { + builder.load_surface_collections( files ); }, - [&builder, &directory] { - builder.load_relationships( directory ); + [&builder, &files] { + builder.load_relationships( files ); }, - [&builder, &directory] { - builder.load_unique_vertices( directory ); + [&builder, &files] { + builder.load_unique_vertices( files ); } ); detail::register_all_components( section ); detail::filter_unsupported_components( section ); diff --git a/src/geode/basic/CMakeLists.txt b/src/geode/basic/CMakeLists.txt index 021ddaaaf..0e75ff62e 100644 --- a/src/geode/basic/CMakeLists.txt +++ b/src/geode/basic/CMakeLists.txt @@ -33,10 +33,12 @@ add_geode_library( "console_logger_client.cpp" "console_progress_logger_client.cpp" "file.cpp" + "file_content.cpp" "file_logger_client.cpp" "filename.cpp" "identifier.cpp" "identifier_builder.cpp" + "input_files.cpp" "library.cpp" "logger.cpp" "logger_manager.cpp" @@ -58,6 +60,7 @@ add_geode_library( "attribute.hpp" "bitsery_archive.hpp" "bitsery_attribute.hpp" + "byte_span.hpp" "cell_array.hpp" "chronometer.hpp" "common.hpp" @@ -103,8 +106,10 @@ add_geode_library( "detail/count_range_elements.hpp" "detail/disable_debug_logger.hpp" "detail/enable_debug_logger.hpp" + "detail/file_content.hpp" "detail/geode_input_impl.hpp" "detail/geode_output_impl.hpp" + "detail/input_files.hpp" INTERNAL_HEADERS "internal/array_impl.hpp" PUBLIC_DEPENDENCIES @@ -120,7 +125,19 @@ add_geode_library( absl::time spdlog::spdlog_header_only MINIZIP::minizip-ng + ZLIB::ZLIB ) if(WIN32 AND BUILD_SHARED_LIBS) target_link_libraries(basic PUBLIC absl::abseil_dll) +endif() +if(UNIX AND NOT APPLE AND BUILD_SHARED_LIBS) + # Keep the static zlib-ng and minizip-ng private: exported, they would + # interpose the zlib of the process (or be interposed by it) + include(CheckLinkerFlag) + check_linker_flag(CXX "-Wl,--exclude-libs,ALL" GEODE_LINKER_EXCLUDE_LIBS) + if(GEODE_LINKER_EXCLUDE_LIBS) + target_link_options(basic PRIVATE + "-Wl,--exclude-libs,$:$" + ) + endif() endif() \ No newline at end of file diff --git a/src/geode/basic/bitsery_archive.cpp b/src/geode/basic/bitsery_archive.cpp index 0c4beb16c..4fb32eea3 100644 --- a/src/geode/basic/bitsery_archive.cpp +++ b/src/geode/basic/bitsery_archive.cpp @@ -23,13 +23,8 @@ #include -#include -#include - #include -#include - namespace { class BitseryExtensionsStorage @@ -90,33 +85,4 @@ namespace geode function( context ); } } - - namespace detail - { - std::optional< ByteBuffer > read_file_content( - std::string_view filename ) - { - std::ifstream file{ std::filesystem::u8path( - to_string( filename ) ), - std::ifstream::binary | std::ifstream::ate }; - if( !file ) - { - return std::nullopt; - } - const auto end = file.tellg(); - OpenGeodeBasicException::check_exception( end >= 0, nullptr, - OpenGeodeException::TYPE::data, - "[read_file_content] Cannot read file: ", filename ); - ByteBuffer buffer{ static_cast< size_t >( end ) }; - file.seekg( 0 ); - file.read( buffer.data(), - static_cast< std::streamsize >( buffer.size() ) ); - OpenGeodeBasicException::check_exception( - file.gcount() - == static_cast< std::streamsize >( buffer.size() ), - nullptr, OpenGeodeException::TYPE::data, - "[read_file_content] Cannot read file: ", filename ); - return buffer; - } - } // namespace detail } // namespace geode diff --git a/src/geode/basic/file_content.cpp b/src/geode/basic/file_content.cpp new file mode 100644 index 000000000..159f793e3 --- /dev/null +++ b/src/geode/basic/file_content.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include +#include + +#ifdef _WIN32 +# ifndef NOMINMAX +# define NOMINMAX +# endif +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#else +# include +# include +# include +# include +#endif + +#include + +namespace +{ + std::filesystem::path to_path( std::string_view utf8_path ) + { + return std::filesystem::u8path( utf8_path.begin(), utf8_path.end() ); + } + + size_t page_size() + { +#ifdef _WIN32 + SYSTEM_INFO info; + GetSystemInfo( &info ); + return static_cast< size_t >( info.dwPageSize ); +#else + return static_cast< size_t >( sysconf( _SC_PAGESIZE ) ); +#endif + } + + struct MappedBytes + { + const char* data{ nullptr }; + size_t size{ 0 }; + bool mapped{ false }; + }; + +#ifdef _WIN32 + MappedBytes map_bytes( const std::filesystem::path& path ) + { + const auto file = + CreateFileW( path.wstring().c_str(), GENERIC_READ, FILE_SHARE_READ, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ); + if( file == INVALID_HANDLE_VALUE ) + { + return {}; + } + MappedBytes result; + LARGE_INTEGER size; + if( GetFileType( file ) == FILE_TYPE_DISK + && GetFileSizeEx( file, &size ) && size.QuadPart >= 0 ) + { + if( size.QuadPart == 0 ) + { + result.mapped = true; + } + else if( const auto mapping = CreateFileMappingW( + file, nullptr, PAGE_READONLY, 0, 0, nullptr ) ) + { + if( const auto* view = + MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 ) ) + { + result.data = static_cast< const char* >( view ); + result.size = static_cast< size_t >( size.QuadPart ); + result.mapped = true; + } + CloseHandle( mapping ); + } + } + CloseHandle( file ); + return result; + } + + void unmap_bytes( const char* data, size_t /*size*/ ) + { + UnmapViewOfFile( data ); + } + + void release_pages( const char* data, size_t size ) + { + // Unlocking pages that are not locked removes them from the working + // set + VirtualUnlock( const_cast< char* >( data ), size ); + } +#else + MappedBytes map_bytes( const std::filesystem::path& path ) + { + const auto file = open( path.c_str(), O_RDONLY | O_CLOEXEC ); + if( file < 0 ) + { + return {}; + } + MappedBytes result; + struct stat status; + if( fstat( file, &status ) == 0 && S_ISREG( status.st_mode ) + && status.st_size >= 0 ) + { + if( status.st_size == 0 ) + { + result.mapped = true; + } + else + { + const auto size = static_cast< size_t >( status.st_size ); + auto* data = + mmap( nullptr, size, PROT_READ, MAP_PRIVATE, file, 0 ); + if( data != MAP_FAILED ) + { + result.data = static_cast< const char* >( data ); + result.size = size; + result.mapped = true; + } + } + } + close( file ); + return result; + } + + void unmap_bytes( const char* data, size_t size ) + { + munmap( const_cast< char* >( data ), size ); + } + + void release_pages( const char* data, size_t size ) + { + // Read-only file mapping: the pages are read again from the file if + // accessed + madvise( const_cast< char* >( data ), size, MADV_DONTNEED ); + } +#endif + + /*! + * Read the whole content of a regular file (UTF-8 path) into memory. + * @return std::nullopt if the file cannot be opened or is not a regular + * file. + * @exception OpenGeodeException (data) if the file cannot be read. + */ + std::optional< geode::detail::ByteBuffer > read_file_content( + std::string_view filename ) + { + const auto path = to_path( filename ); + std::error_code error; + if( !std::filesystem::is_regular_file( path, error ) ) + { + return std::nullopt; + } + std::ifstream file{ path, std::ifstream::binary | std::ifstream::ate }; + if( !file ) + { + return std::nullopt; + } + const auto end = file.tellg(); + geode::OpenGeodeBasicException::check_exception( end >= 0, nullptr, + geode::OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + geode::detail::ByteBuffer buffer{ static_cast< size_t >( end ) }; + file.seekg( 0 ); + file.read( + buffer.data(), static_cast< std::streamsize >( buffer.size() ) ); + geode::OpenGeodeBasicException::check_exception( + file.gcount() == static_cast< std::streamsize >( buffer.size() ), + nullptr, geode::OpenGeodeException::TYPE::data, + "[read_file_content] Cannot read file: ", filename ); + return buffer; + } +} // namespace + +namespace geode +{ + namespace detail + { + std::shared_ptr< const MappedFile > MappedFile::map( + std::string_view filename ) + { + const auto bytes = map_bytes( to_path( filename ) ); + if( !bytes.mapped ) + { + return nullptr; + } + return std::shared_ptr< const MappedFile >{ new MappedFile{ + bytes.data, bytes.size } }; + } + + MappedFile::MappedFile( const char* data, size_t size ) + : data_{ data }, size_{ size } + { + } + + MappedFile::~MappedFile() + { + if( data_ != nullptr ) + { + unmap_bytes( data_, size_ ); + } + } + + ByteSpan MappedFile::span() const + { + return { data_, size_ }; + } + + void MappedFile::release( ByteSpan bytes ) const + { + if( bytes.empty() || data_ == nullptr ) + { + return; + } + static const auto page = page_size(); + const auto begin_offset = + static_cast< size_t >( bytes.data() - data_ ); + const auto end_offset = begin_offset + bytes.size(); + const auto first_page = ( begin_offset + page - 1 ) / page * page; + const auto last_page = end_offset / page * page; + if( first_page >= last_page ) + { + return; + } + release_pages( data_ + first_page, last_page - first_page ); + } + + FileContent::FileContent( ByteBuffer buffer ) + : buffer_{ std::move( buffer ) }, bytes_{ buffer_->span() } + { + } + + FileContent::FileContent( + std::shared_ptr< const MappedFile > mapping, ByteSpan bytes ) + : mapping_{ std::move( mapping ) }, bytes_{ bytes } + { + } + + FileContent::FileContent( FileContent&& other ) noexcept + : mapping_{ std::move( other.mapping_ ) }, + buffer_{ std::move( other.buffer_ ) }, + bytes_{ other.bytes_ } + { + other.mapping_.reset(); + other.buffer_.reset(); + other.bytes_ = {}; + } + + FileContent::~FileContent() + { + if( mapping_ ) + { + mapping_->release( bytes_ ); + } + } + + std::optional< FileContent > map_file_content( + std::string_view filename ) + { + if( auto mapping = MappedFile::map( filename ) ) + { + const auto bytes = mapping->span(); + return FileContent{ std::move( mapping ), bytes }; + } + Logger::debug( "[map_file_content] Cannot map file ", filename, + ", reading it" ); + if( auto buffer = read_file_content( filename ) ) + { + return FileContent{ std::move( *buffer ) }; + } + return std::nullopt; + } + } // namespace detail +} // namespace geode diff --git a/src/geode/basic/identifier.cpp b/src/geode/basic/identifier.cpp index 5f15b1557..48365f5c7 100644 --- a/src/geode/basic/identifier.cpp +++ b/src/geode/basic/identifier.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -81,18 +82,19 @@ namespace geode "[Identifier::save] Error while writing file: ", filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/identifier" ); - const auto content = detail::read_file_content( filename ); - if( !content ) + static constexpr auto FILENAME = "identifier"; + if( !files.has( FILENAME ) ) { return; } + const auto content = files.content( FILENAME ); OpenGeodeBasicException::check_exception( - detail::deserialize_bytes( content->span(), *this ), nullptr, + detail::deserialize_bytes( content.span(), *this ), nullptr, OpenGeodeException::TYPE::internal, - "[Identifier::load] Error while reading file: ", filename ); + "[Identifier::load] Error while reading file: ", + files.location( FILENAME ) ); } private: @@ -157,9 +159,9 @@ namespace geode } void Identifier::load_identifier( - std::string_view directory, IdentifierKey /*unused*/ ) + const detail::InputFiles& files, IdentifierKey /*unused*/ ) { - impl_->load( directory ); + impl_->load( files ); } void Identifier::set_id( const uuid& unique_id, IdentifierKey /*unused*/ ) diff --git a/src/geode/basic/identifier_builder.cpp b/src/geode/basic/identifier_builder.cpp index ced7ee485..d41e31590 100644 --- a/src/geode/basic/identifier_builder.cpp +++ b/src/geode/basic/identifier_builder.cpp @@ -23,6 +23,7 @@ #include +#include #include #include @@ -50,7 +51,12 @@ namespace geode void IdentifierBuilder::load_identifier( std::string_view directory ) { - identifier_.load_identifier( directory, Identifier::IdentifierKey{} ); + load_identifier( detail::DirectoryInputFiles{ directory } ); + } + + void IdentifierBuilder::load_identifier( const detail::InputFiles& files ) + { + identifier_.load_identifier( files, Identifier::IdentifierKey{} ); } } // namespace geode diff --git a/src/geode/basic/input_files.cpp b/src/geode/basic/input_files.cpp new file mode 100644 index 000000000..2c58744d8 --- /dev/null +++ b/src/geode/basic/input_files.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include + +#include +#include + +#include +#include + +#include +#include + +namespace +{ + std::filesystem::path to_path( std::string_view utf8_path ) + { + return std::filesystem::u8path( utf8_path.begin(), utf8_path.end() ); + } +} // namespace + +namespace geode +{ + namespace detail + { + InputFiles::~InputFiles() = default; + + DirectoryInputFiles::DirectoryInputFiles( std::string_view directory ) + : directory_{ to_string( directory ) } + { + } + + DirectoryInputFiles::~DirectoryInputFiles() = default; + + bool DirectoryInputFiles::has( std::string_view name ) const + { + std::error_code error; + return std::filesystem::is_regular_file( + to_path( location( name ) ), error ); + } + + std::vector< std::string > DirectoryInputFiles::names() const + { + std::vector< std::string > names; + std::error_code error; + for( const auto& file : std::filesystem::directory_iterator( + to_path( directory_ ), error ) ) + { + if( file.is_regular_file( error ) ) + { + names.emplace_back( file.path().filename().u8string() ); + } + } + absl::c_sort( names ); + return names; + } + + FileContent DirectoryInputFiles::content( std::string_view name ) const + { + const auto file = location( name ); + auto content = map_file_content( file ); + OpenGeodeBasicException::check_exception( content.has_value(), + nullptr, OpenGeodeException::TYPE::data, + "[DirectoryInputFiles] Cannot open file: ", file ); + return std::move( content.value() ); + } + + std::optional< std::string > DirectoryInputFiles::path( + std::string_view name ) const + { + return location( name ); + } + + std::string DirectoryInputFiles::location( std::string_view name ) const + { + return absl::StrCat( directory_, "/", name ); + } + + TemporaryFile::TemporaryFile( std::string_view name, ByteSpan content ) + { + std::error_code error; + const auto temp_directory = + std::filesystem::temp_directory_path( error ); + OpenGeodeBasicException::check_exception( !error, nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] No temporary directory: ", error.message() ); + const auto directory = temp_directory / uuid{}.string(); + std::filesystem::create_directories( directory, error ); + OpenGeodeBasicException::check_exception( !error, nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] Cannot create directory: ", + directory.u8string(), " (", error.message(), ")" ); + directory_ = directory.u8string(); + const auto file = directory / to_path( name ).filename(); + path_ = file.u8string(); + std::ofstream stream{ file, std::ofstream::binary }; + stream.write( content.data(), + static_cast< std::streamsize >( content.size() ) ); + stream.close(); + if( !stream ) + { + std::filesystem::remove_all( directory, error ); + throw OpenGeodeBasicException{ nullptr, + OpenGeodeException::TYPE::internal, + "[TemporaryFile] Cannot write file: ", path_ }; + } + } + + TemporaryFile::~TemporaryFile() + { + std::error_code error; + std::filesystem::remove_all( to_path( directory_ ), error ); + } + + const std::string& TemporaryFile::path() const + { + return path_; + } + } // namespace detail +} // namespace geode diff --git a/src/geode/basic/singleton.cpp b/src/geode/basic/singleton.cpp index 87ae9c241..e8bf734ee 100644 --- a/src/geode/basic/singleton.cpp +++ b/src/geode/basic/singleton.cpp @@ -21,6 +21,9 @@ * */ +// common.hpp includes library.hpp, which needs singleton.hpp +#include + #include #include diff --git a/src/geode/basic/zip_file.cpp b/src/geode/basic/zip_file.cpp index 6042bd272..51ccd6812 100644 --- a/src/geode/basic/zip_file.cpp +++ b/src/geode/basic/zip_file.cpp @@ -23,17 +23,26 @@ #include +#include +#include +#include #include #include #include #include +#include +#include + #include #include #include #include #include +#include + +#include #include #include @@ -74,6 +83,100 @@ namespace } return true; } + + constexpr size_t LOCAL_HEADER_SIZE{ 30 }; + constexpr uint32_t LOCAL_HEADER_SIGNATURE{ 0x04034b50 }; + + uint32_t read_little_endian( const char* bytes, size_t nb_bytes ) + { + uint32_t value{ 0 }; + for( size_t byte = nb_bytes; byte > 0; byte-- ) + { + value = ( value << 8U ) + | static_cast< unsigned char >( bytes[byte - 1] ); + } + return value; + } + + class ZipReader + { + public: + explicit ZipReader( const std::filesystem::path& file ) + : reader_{ mz_zip_reader_create() } + { + status_ = reader_ == nullptr ? MZ_MEM_ERROR + : mz_zip_reader_open_file( reader_, + file.u8string().c_str() ); + } + + ~ZipReader() + { + if( reader_ ) + { + mz_zip_reader_close( reader_ ); + mz_zip_reader_delete( &reader_ ); + } + } + + ZipReader( const ZipReader& ) = delete; + ZipReader& operator=( const ZipReader& ) = delete; + + [[nodiscard]] bool is_open() const + { + return status_ == MZ_OK; + } + + [[nodiscard]] void* get() const + { + return reader_; + } + + private: + void* reader_; + int32_t status_; + }; + + geode::detail::ByteBuffer inflate_entry( + geode::ByteSpan compressed, size_t uncompressed_size, bool& success ) + { + geode::detail::ByteBuffer buffer{ uncompressed_size }; + z_stream stream{}; + success = false; + if( inflateInit2_( &stream, -MAX_WBITS, ZLIB_VERSION, + static_cast< int >( sizeof( z_stream ) ) ) + != Z_OK ) + { + return buffer; + } + using Chunk = decltype( stream.avail_in ); + constexpr auto MAX_CHUNK = + static_cast< size_t >( std::numeric_limits< Chunk >::max() ); + const auto* input = + reinterpret_cast< const unsigned char* >( compressed.data() ); + auto input_left = compressed.size(); + auto* output = reinterpret_cast< unsigned char* >( buffer.data() ); + auto output_left = buffer.size(); + auto status = Z_OK; + while( status == Z_OK ) + { + const auto input_chunk = std::min( input_left, MAX_CHUNK ); + const auto output_chunk = std::min( output_left, MAX_CHUNK ); + stream.next_in = const_cast< unsigned char* >( input ); + stream.avail_in = static_cast< Chunk >( input_chunk ); + stream.next_out = output; + stream.avail_out = static_cast< Chunk >( output_chunk ); + status = inflate( &stream, Z_NO_FLUSH ); + const auto nb_read = input_chunk - stream.avail_in; + const auto nb_written = output_chunk - stream.avail_out; + input += nb_read; + input_left -= nb_read; + output += nb_written; + output_left -= nb_written; + } + inflateEnd( &stream ); + success = status == Z_STREAM_END && output_left == 0; + return buffer; + } } // namespace namespace geode @@ -458,6 +561,294 @@ namespace geode return impl_->directory(); } + namespace detail + { + class ArchiveInputFiles::Impl + { + struct ArchiveEntry + { + uint64_t header_offset; + uint64_t compressed_size; + uint64_t uncompressed_size; + uint32_t crc; + uint16_t method; + }; + + public: + explicit Impl( std::string_view filename ) + : filename_{ to_string( filename ) } + { + OpenGeodeBasicException::check_exception( + std::filesystem::exists( to_path( filename ) ), nullptr, + OpenGeodeException::TYPE::data, "[ArchiveInputFiles] File ", + filename, " doesn't exist" ); + read_entries(); + mapping_ = MappedFile::map( filename_ ); + if( !mapping_ ) + { + Logger::debug( "[ArchiveInputFiles] Cannot map ", filename_, + ", reading its entries from disk" ); + } + } + + bool has( std::string_view name ) const + { + return entries_.contains( name ); + } + + std::vector< std::string > names() const + { + return names_; + } + + FileContent content( std::string_view name ) const + { + const auto entry = entries_.find( name ); + OpenGeodeBasicException::check_exception( + entry != entries_.end(), nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Missing entry ", location( name ) ); + auto content = entry->second.method == MZ_COMPRESS_METHOD_STORE + ? stored_content( name, entry->second ) + : inflated_content( name, entry->second ); + const auto bytes = content.span(); + const auto crc = crc32_z( 0, + reinterpret_cast< const unsigned char* >( bytes.data() ), + bytes.size() ); + OpenGeodeBasicException::check_exception( + static_cast< uint32_t >( crc ) == entry->second.crc, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Corrupted entry ", location( name ), + " (CRC-32 mismatch)" ); + return content; + } + + std::string location( std::string_view name ) const + { + return absl::StrCat( filename_, "/", name ); + } + + private: + void read_entries() + { + const ZipReader reader{ to_path( filename_ ) }; + OpenGeodeBasicException::check_exception( reader.is_open(), + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Error opening zip for reading: ", + filename_ ); + auto status = mz_zip_reader_goto_first_entry( reader.get() ); + while( status == MZ_OK ) + { + read_entry( reader.get() ); + status = mz_zip_reader_goto_next_entry( reader.get() ); + } + OpenGeodeBasicException::check_exception( + status == MZ_END_OF_LIST, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Error while reading zip entries of ", + filename_, " (", status, ")" ); + } + + void read_entry( void* reader ) + { + mz_zip_file* info = nullptr; + const auto info_status = + mz_zip_reader_entry_get_info( reader, &info ); + OpenGeodeBasicException::check_exception( + info_status == MZ_OK && info != nullptr, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot read zip entry information " + "of ", + filename_, " (", info_status, ")" ); + std::string name{ info->filename }; + OpenGeodeBasicException::check_exception( + is_safe_entry_path( to_path( name ) ), nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Unsafe zip entry path: ", name ); + if( mz_zip_reader_entry_is_dir( reader ) == MZ_OK ) + { + return; + } + OpenGeodeBasicException::check_exception( + ( info->flag & MZ_ZIP_FLAG_ENCRYPTED ) == 0, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Encrypted zip entry: ", + location( name ) ); + OpenGeodeBasicException::check_exception( + info->compression_method == MZ_COMPRESS_METHOD_STORE + || info->compression_method + == MZ_COMPRESS_METHOD_DEFLATE, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Unsupported compression method ", + info->compression_method, " of zip entry ", + location( name ) ); + OpenGeodeBasicException::check_exception( + info->disk_offset >= 0 && info->compressed_size >= 0 + && info->uncompressed_size >= 0, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid zip entry ", + location( name ) ); + ArchiveEntry entry{ static_cast< uint64_t >( + info->disk_offset ), + static_cast< uint64_t >( info->compressed_size ), + static_cast< uint64_t >( info->uncompressed_size ), + info->crc, info->compression_method }; + const auto [_, inserted] = + entries_.insert_or_assign( name, entry ); + if( inserted ) + { + names_.emplace_back( std::move( name ) ); + } + } + + /*! + * Return the offset of the data of an entry, after its local + * header. + */ + uint64_t data_offset( + std::string_view name, const ArchiveEntry& entry ) const + { + std::array< char, LOCAL_HEADER_SIZE > header_buffer; + const char* header = header_buffer.data(); + if( mapping_ ) + { + const auto archive = mapping_->span(); + check_inside_archive( + name, entry.header_offset, LOCAL_HEADER_SIZE ); + header = archive.data() + entry.header_offset; + } + else + { + read_at( name, entry.header_offset, header_buffer.data(), + LOCAL_HEADER_SIZE ); + } + OpenGeodeBasicException::check_exception( + read_little_endian( header, 4 ) == LOCAL_HEADER_SIGNATURE, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid local header of zip entry ", + location( name ) ); + const auto name_length = read_little_endian( header + 26, 2 ); + const auto extra_length = read_little_endian( header + 28, 2 ); + return entry.header_offset + LOCAL_HEADER_SIZE + name_length + + extra_length; + } + + /*! + * Return the raw (compressed) bytes of an entry: a slice of the + * mapped archive, or a buffer read from the file. + */ + FileContent raw_content( + std::string_view name, const ArchiveEntry& entry ) const + { + const auto offset = data_offset( name, entry ); + if( mapping_ ) + { + check_inside_archive( name, offset, entry.compressed_size ); + return { mapping_, mapping_->span().subspan( + offset, entry.compressed_size ) }; + } + ByteBuffer buffer{ entry.compressed_size }; + read_at( name, offset, buffer.data(), buffer.size() ); + return FileContent{ std::move( buffer ) }; + } + + FileContent stored_content( + std::string_view name, const ArchiveEntry& entry ) const + { + OpenGeodeBasicException::check_exception( + entry.compressed_size == entry.uncompressed_size, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Invalid size of stored zip entry ", + location( name ) ); + return raw_content( name, entry ); + } + + FileContent inflated_content( + std::string_view name, const ArchiveEntry& entry ) const + { + const auto compressed = raw_content( name, entry ); + bool success{ false }; + auto buffer = inflate_entry( + compressed.span(), entry.uncompressed_size, success ); + OpenGeodeBasicException::check_exception( success, nullptr, + OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot decompress zip entry ", + location( name ) ); + return FileContent{ std::move( buffer ) }; + } + + void check_inside_archive( + std::string_view name, uint64_t offset, uint64_t size ) const + { + const auto archive_size = mapping_->span().size(); + OpenGeodeBasicException::check_exception( + offset <= archive_size && size <= archive_size - offset, + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Truncated zip entry ", + location( name ) ); + } + + /*! + * Positional read, used when the archive cannot be mapped. + */ + void read_at( std::string_view name, + uint64_t offset, + char* data, + size_t size ) const + { + std::ifstream file{ to_path( filename_ ), std::ios::binary }; + file.seekg( static_cast< std::streamoff >( offset ) ); + file.read( data, static_cast< std::streamsize >( size ) ); + OpenGeodeBasicException::check_exception( + file.good() + && file.gcount() + == static_cast< std::streamsize >( size ), + nullptr, OpenGeodeException::TYPE::data, + "[ArchiveInputFiles] Cannot read zip entry ", + location( name ) ); + } + + private: + std::string filename_; + absl::flat_hash_map< std::string, ArchiveEntry > entries_; + std::vector< std::string > names_; + std::shared_ptr< const MappedFile > mapping_; + }; + + ArchiveInputFiles::ArchiveInputFiles( std::string_view filename ) + : impl_{ filename } + { + } + + ArchiveInputFiles::~ArchiveInputFiles() = default; + + bool ArchiveInputFiles::has( std::string_view name ) const + { + return impl_->has( name ); + } + + std::vector< std::string > ArchiveInputFiles::names() const + { + return impl_->names(); + } + + FileContent ArchiveInputFiles::content( std::string_view name ) const + { + return impl_->content( name ); + } + + std::optional< std::string > ArchiveInputFiles::path( + std::string_view /*name*/ ) const + { + return std::nullopt; + } + + std::string ArchiveInputFiles::location( std::string_view name ) const + { + return impl_->location( name ); + } + } // namespace detail + bool is_zip_file( std::string_view file ) { void* reader = mz_zip_reader_create(); diff --git a/src/geode/model/mixin/builder/block_collections_builder.cpp b/src/geode/model/mixin/builder/block_collections_builder.cpp index 7a75bc9ef..884285b00 100644 --- a/src/geode/model/mixin/builder/block_collections_builder.cpp +++ b/src/geode/model/mixin/builder/block_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -59,9 +61,16 @@ namespace geode void BlockCollectionsBuilder< dimension >::load_block_collections( std::string_view directory ) { - return block_collections_.load_block_collections( - directory, typename BlockCollections< - dimension >::BlockCollectionsBuilderKey{} ); + load_block_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void BlockCollectionsBuilder< dimension >::load_block_collections( + const detail::InputFiles& files ) + { + block_collections_.load_block_collections( + files, typename BlockCollections< + dimension >::BlockCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/blocks_builder.cpp b/src/geode/model/mixin/builder/blocks_builder.cpp index 0352ec56b..9235533b4 100644 --- a/src/geode/model/mixin/builder/blocks_builder.cpp +++ b/src/geode/model/mixin/builder/blocks_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -71,8 +73,15 @@ namespace geode template < index_t dimension > void BlocksBuilder< dimension >::load_blocks( std::string_view directory ) { - return blocks_.load_blocks( - directory, typename Blocks< dimension >::BlocksBuilderKey{} ); + load_blocks( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void BlocksBuilder< dimension >::load_blocks( + const detail::InputFiles& files ) + { + blocks_.load_blocks( + files, typename Blocks< dimension >::BlocksBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/corner_collections_builder.cpp b/src/geode/model/mixin/builder/corner_collections_builder.cpp index b84a5a1bc..082499e71 100644 --- a/src/geode/model/mixin/builder/corner_collections_builder.cpp +++ b/src/geode/model/mixin/builder/corner_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -60,9 +62,16 @@ namespace geode void CornerCollectionsBuilder< dimension >::load_corner_collections( std::string_view directory ) { - return corner_collections_.load_corner_collections( - directory, typename CornerCollections< - dimension >::CornerCollectionsBuilderKey{} ); + load_corner_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void CornerCollectionsBuilder< dimension >::load_corner_collections( + const detail::InputFiles& files ) + { + corner_collections_.load_corner_collections( + files, typename CornerCollections< + dimension >::CornerCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/corners_builder.cpp b/src/geode/model/mixin/builder/corners_builder.cpp index d86124264..0b5aa8629 100644 --- a/src/geode/model/mixin/builder/corners_builder.cpp +++ b/src/geode/model/mixin/builder/corners_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -72,8 +74,15 @@ namespace geode template < index_t dimension > void CornersBuilder< dimension >::load_corners( std::string_view directory ) { - return corners_.load_corners( - directory, typename Corners< dimension >::CornersBuilderKey{} ); + load_corners( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void CornersBuilder< dimension >::load_corners( + const detail::InputFiles& files ) + { + corners_.load_corners( + files, typename Corners< dimension >::CornersBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/line_collections_builder.cpp b/src/geode/model/mixin/builder/line_collections_builder.cpp index 21d33106c..f32e081d3 100644 --- a/src/geode/model/mixin/builder/line_collections_builder.cpp +++ b/src/geode/model/mixin/builder/line_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -59,9 +61,16 @@ namespace geode void LineCollectionsBuilder< dimension >::load_line_collections( std::string_view directory ) { - return line_collections_.load_line_collections( - directory, typename LineCollections< - dimension >::LineCollectionsBuilderKey{} ); + load_line_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void LineCollectionsBuilder< dimension >::load_line_collections( + const detail::InputFiles& files ) + { + line_collections_.load_line_collections( + files, typename LineCollections< + dimension >::LineCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/lines_builder.cpp b/src/geode/model/mixin/builder/lines_builder.cpp index 6fac0ff4a..20cfc4e37 100644 --- a/src/geode/model/mixin/builder/lines_builder.cpp +++ b/src/geode/model/mixin/builder/lines_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -70,8 +72,15 @@ namespace geode template < index_t dimension > void LinesBuilder< dimension >::load_lines( std::string_view directory ) { - return lines_.load_lines( - directory, typename Lines< dimension >::LinesBuilderKey{} ); + load_lines( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void LinesBuilder< dimension >::load_lines( + const detail::InputFiles& files ) + { + lines_.load_lines( + files, typename Lines< dimension >::LinesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/model_boundaries_builder.cpp b/src/geode/model/mixin/builder/model_boundaries_builder.cpp index fe74b903f..603c52ba4 100644 --- a/src/geode/model/mixin/builder/model_boundaries_builder.cpp +++ b/src/geode/model/mixin/builder/model_boundaries_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -58,9 +60,16 @@ namespace geode void ModelBoundariesBuilder< dimension >::load_model_boundaries( std::string_view directory ) { - return model_boundaries_.load_model_boundaries( - directory, typename ModelBoundaries< - dimension >::ModelBoundariesBuilderKey{} ); + load_model_boundaries( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void ModelBoundariesBuilder< dimension >::load_model_boundaries( + const detail::InputFiles& files ) + { + model_boundaries_.load_model_boundaries( + files, typename ModelBoundaries< + dimension >::ModelBoundariesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/physical_properties_builder.cpp b/src/geode/model/mixin/builder/physical_properties_builder.cpp index 6187dd88a..6ff033b71 100644 --- a/src/geode/model/mixin/builder/physical_properties_builder.cpp +++ b/src/geode/model/mixin/builder/physical_properties_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include namespace geode @@ -52,8 +54,14 @@ namespace geode void PhysicalPropertiesBuilder::load_physical_properties( std::string_view directory ) + { + load_physical_properties( detail::DirectoryInputFiles{ directory } ); + } + + void PhysicalPropertiesBuilder::load_physical_properties( + const detail::InputFiles& files ) { physical_properties_.load_physical_properties( - directory, PhysicalProperties::BuilderKey{} ); + files, PhysicalProperties::BuilderKey{} ); } } // namespace geode diff --git a/src/geode/model/mixin/builder/relationships_builder.cpp b/src/geode/model/mixin/builder/relationships_builder.cpp index 7e4e1e4dd..55557250c 100644 --- a/src/geode/model/mixin/builder/relationships_builder.cpp +++ b/src/geode/model/mixin/builder/relationships_builder.cpp @@ -23,6 +23,8 @@ #include +#include + namespace geode { RelationshipsBuilder::RelationshipsBuilder( Relationships& relationships ) @@ -79,9 +81,15 @@ namespace geode } void RelationshipsBuilder::load_relationships( std::string_view directory ) + { + load_relationships( detail::DirectoryInputFiles{ directory } ); + } + + void RelationshipsBuilder::load_relationships( + const detail::InputFiles& files ) { relationships_.load_relationships( - directory, Relationships::RelationshipsBuilderKey{} ); + files, Relationships::RelationshipsBuilderKey{} ); } } // namespace geode diff --git a/src/geode/model/mixin/builder/surface_collections_builder.cpp b/src/geode/model/mixin/builder/surface_collections_builder.cpp index 40d1c13bf..92daaf8e5 100644 --- a/src/geode/model/mixin/builder/surface_collections_builder.cpp +++ b/src/geode/model/mixin/builder/surface_collections_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -60,9 +62,16 @@ namespace geode void SurfaceCollectionsBuilder< dimension >::load_surface_collections( std::string_view directory ) { - return surface_collections_.load_surface_collections( - directory, typename SurfaceCollections< - dimension >::SurfaceCollectionsBuilderKey{} ); + load_surface_collections( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void SurfaceCollectionsBuilder< dimension >::load_surface_collections( + const detail::InputFiles& files ) + { + surface_collections_.load_surface_collections( + files, typename SurfaceCollections< + dimension >::SurfaceCollectionsBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/surfaces_builder.cpp b/src/geode/model/mixin/builder/surfaces_builder.cpp index 889570330..729b12754 100644 --- a/src/geode/model/mixin/builder/surfaces_builder.cpp +++ b/src/geode/model/mixin/builder/surfaces_builder.cpp @@ -23,6 +23,8 @@ #include +#include + #include #include @@ -73,8 +75,15 @@ namespace geode void SurfacesBuilder< dimension >::load_surfaces( std::string_view directory ) { - return surfaces_.load_surfaces( - directory, typename Surface< dimension >::SurfacesBuilderKey{} ); + load_surfaces( detail::DirectoryInputFiles{ directory } ); + } + + template < index_t dimension > + void SurfacesBuilder< dimension >::load_surfaces( + const detail::InputFiles& files ) + { + surfaces_.load_surfaces( + files, typename Surface< dimension >::SurfacesBuilderKey{} ); } template < index_t dimension > diff --git a/src/geode/model/mixin/builder/vertex_identifier_builder.cpp b/src/geode/model/mixin/builder/vertex_identifier_builder.cpp index 5d53799f7..baf038a95 100644 --- a/src/geode/model/mixin/builder/vertex_identifier_builder.cpp +++ b/src/geode/model/mixin/builder/vertex_identifier_builder.cpp @@ -23,6 +23,8 @@ #include +#include + namespace geode { VertexIdentifierBuilder::VertexIdentifierBuilder( @@ -67,9 +69,15 @@ namespace geode void VertexIdentifierBuilder::load_unique_vertices( std::string_view directory ) + { + load_unique_vertices( detail::DirectoryInputFiles{ directory } ); + } + + void VertexIdentifierBuilder::load_unique_vertices( + const detail::InputFiles& files ) { vertex_identifier_.load_unique_vertices( - directory, VertexIdentifier::BuilderKey{} ); + files, VertexIdentifier::BuilderKey{} ); } std::vector< index_t > VertexIdentifierBuilder::delete_isolated_vertices() diff --git a/src/geode/model/mixin/core/block_collections.cpp b/src/geode/model/mixin/core/block_collections.cpp index 635054ca6..eed661809 100644 --- a/src/geode/model/mixin/core/block_collections.cpp +++ b/src/geode/model/mixin/core/block_collections.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void BlockCollections< dimension >::load_block_collections( - std::string_view directory, BlockCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, BlockCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/block_collections" ), false ); + impl_->load_components( files, "block_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/blocks.cpp b/src/geode/model/mixin/core/blocks.cpp index a620fa7b4..aea548d93 100644 --- a/src/geode/model/mixin/core/blocks.cpp +++ b/src/geode/model/mixin/core/blocks.cpp @@ -181,15 +181,15 @@ namespace geode template < index_t dimension > void Blocks< dimension >::load_blocks( - std::string_view directory, BlocksBuilderKey builder_key ) + const detail::InputFiles& files, BlocksBuilderKey builder_key ) { - impl_->load_components( absl::StrCat( directory, "/blocks" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "blocks", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_blocks() ); index_t count{ 0 }; for( auto& block : modifiable_blocks( builder_key ) ) { - tasks[count++] = async::spawn( [&block, &mapping] { + tasks[count++] = async::spawn( [&block, &mapping, &files] { const auto file = mapping.find( block.id().string() ); if( file == mapping.end() ) { @@ -199,38 +199,39 @@ namespace geode typename Block< dimension >::BlocksKey{} ); return; } + const auto& name = file->second; const auto impl = detail::loadable_mesh_impl( block.mesh_type(), - solid_type_from_file< dimension >( file->second ), - file->second ); + solid_type_from_file< dimension >( name ), + files.location( name ) ); const auto& type = MeshFactory::type( impl ); if( type == TetrahedralSolid< dimension >::type_name_static() ) { block.set_mesh( - load_one( load_tetrahedral_solid< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + TetrahedralSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else if( type == HybridSolid< dimension >::type_name_static() ) { - block.set_mesh( load_one( load_hybrid_solid< dimension >( - impl, file->second ), - file->second ), + block.set_mesh( detail::load_component_mesh< + HybridSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else if( type == RegularGrid< dimension >::type_name_static() ) { - block.set_mesh( load_one( load_regular_grid< dimension >( - impl, file->second ), - file->second ), + block.set_mesh( detail::load_component_mesh< + RegularGridInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } else { block.set_mesh( - load_one( load_polyhedral_solid< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + PolyhedralSolidInputFactory< dimension > >( + files, name, impl ), typename Block< dimension >::BlocksKey{} ); } } ); diff --git a/src/geode/model/mixin/core/corner_collections.cpp b/src/geode/model/mixin/core/corner_collections.cpp index 77e8b3b04..9f6e04a12 100644 --- a/src/geode/model/mixin/core/corner_collections.cpp +++ b/src/geode/model/mixin/core/corner_collections.cpp @@ -98,10 +98,9 @@ namespace geode template < index_t dimension > void CornerCollections< dimension >::load_corner_collections( - std::string_view directory, CornerCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, CornerCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/corner_collections" ), false ); + impl_->load_components( files, "corner_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/corners.cpp b/src/geode/model/mixin/core/corners.cpp index 63e3f69e1..7ca7c555d 100644 --- a/src/geode/model/mixin/core/corners.cpp +++ b/src/geode/model/mixin/core/corners.cpp @@ -115,15 +115,15 @@ namespace geode template < index_t dimension > void Corners< dimension >::load_corners( - std::string_view directory, CornersBuilderKey key ) + const detail::InputFiles& files, CornersBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/corners" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "corners", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_corners() ); index_t count{ 0 }; for( auto& corner : modifiable_corners( key ) ) { - tasks[count++] = async::spawn( [&corner, &mapping] { + tasks[count++] = async::spawn( [&corner, &mapping, &files] { const auto& type = PointSet< dimension >::type_name_static(); const auto file = mapping.find( corner.id().string() ); if( file == mapping.end() ) @@ -134,11 +134,11 @@ namespace geode return; } corner.set_mesh( - load_one( load_point_set< dimension >( - detail::loadable_mesh_impl( - corner.mesh_type(), type, file->second ), - file->second ), - file->second ), + detail::load_component_mesh< + PointSetInputFactory< dimension > >( files, + file->second, + detail::loadable_mesh_impl( corner.mesh_type(), type, + files.location( file->second ) ) ), typename Corner< dimension >::CornersKey{} ); } ); } diff --git a/src/geode/model/mixin/core/line_collections.cpp b/src/geode/model/mixin/core/line_collections.cpp index 9bcd9b5d6..3635c597f 100644 --- a/src/geode/model/mixin/core/line_collections.cpp +++ b/src/geode/model/mixin/core/line_collections.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void LineCollections< dimension >::load_line_collections( - std::string_view directory, LineCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, LineCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/line_collections" ), false ); + impl_->load_components( files, "line_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/lines.cpp b/src/geode/model/mixin/core/lines.cpp index f061743b4..cae622555 100644 --- a/src/geode/model/mixin/core/lines.cpp +++ b/src/geode/model/mixin/core/lines.cpp @@ -113,15 +113,15 @@ namespace geode template < index_t dimension > void Lines< dimension >::load_lines( - std::string_view directory, LinesBuilderKey key ) + const detail::InputFiles& files, LinesBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/lines" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "lines", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_lines() ); index_t count{ 0 }; for( auto& line : modifiable_lines( key ) ) { - tasks[count++] = async::spawn( [&line, &mapping] { + tasks[count++] = async::spawn( [&line, &mapping, &files] { const auto& type = EdgedCurve< dimension >::type_name_static(); const auto file = mapping.find( line.id().string() ); if( file == mapping.end() ) @@ -131,12 +131,11 @@ namespace geode typename Line< dimension >::LinesKey{} ); return; } - line.set_mesh( - load_one( load_edged_curve< dimension >( - detail::loadable_mesh_impl( - line.mesh_type(), type, file->second ), - file->second ), - file->second ), + line.set_mesh( detail::load_component_mesh< + EdgedCurveInputFactory< dimension > >( files, + file->second, + detail::loadable_mesh_impl( line.mesh_type(), + type, files.location( file->second ) ) ), typename Line< dimension >::LinesKey{} ); } ); } diff --git a/src/geode/model/mixin/core/model_boundaries.cpp b/src/geode/model/mixin/core/model_boundaries.cpp index 218241a1f..4c7498509 100644 --- a/src/geode/model/mixin/core/model_boundaries.cpp +++ b/src/geode/model/mixin/core/model_boundaries.cpp @@ -97,10 +97,9 @@ namespace geode template < index_t dimension > void ModelBoundaries< dimension >::load_model_boundaries( - std::string_view directory, ModelBoundariesBuilderKey /*key*/ ) + const detail::InputFiles& files, ModelBoundariesBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/model_boundaries" ) ); + impl_->load_components( files, "model_boundaries", true ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/physical_properties.cpp b/src/geode/model/mixin/core/physical_properties.cpp index 4a81b3fcd..8a611ba11 100644 --- a/src/geode/model/mixin/core/physical_properties.cpp +++ b/src/geode/model/mixin/core/physical_properties.cpp @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -221,22 +222,17 @@ namespace geode filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = - absl::StrCat( directory, "/physical_properties" ); - if( !std::filesystem::exists( - std::filesystem::u8path( filename ) ) ) + static constexpr auto FILENAME = "physical_properties"; + if( !files.has( FILENAME ) ) { return; } - const auto content = detail::read_file_content( filename ); - OpenGeodeModelException::check_exception( content.has_value(), - nullptr, OpenGeodeException::TYPE::internal, - "[PhysicalProperties::load] Error while reading file: ", - filename ); + const auto filename = files.location( FILENAME ); + const auto content = files.content( FILENAME ); OpenGeodeModelException::check_exception( - detail::deserialize_bytes( content->span(), *this ), nullptr, + detail::deserialize_bytes( content.span(), *this ), nullptr, OpenGeodeException::TYPE::internal, "[PhysicalProperties::load] Error while reading file: ", filename ); @@ -317,9 +313,9 @@ namespace geode } void PhysicalProperties::load_physical_properties( - std::string_view directory, BuilderKey /*key*/ ) + const detail::InputFiles& files, BuilderKey /*key*/ ) { - impl_->load( directory ); + impl_->load( files ); } void PhysicalProperties::set_physical_property( PHYSICAL_PROPERTY_NAME name, diff --git a/src/geode/model/mixin/core/relationships.cpp b/src/geode/model/mixin/core/relationships.cpp index 12c0a2c44..73e029038 100644 --- a/src/geode/model/mixin/core/relationships.cpp +++ b/src/geode/model/mixin/core/relationships.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -198,15 +199,16 @@ namespace geode "[Relationships::save] Error while writing file: ", filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/relationships" ); - const auto content = detail::read_file_content( filename ); - OpenGeodeModelException::check_exception( content.has_value(), + static constexpr auto FILENAME = "relationships"; + const auto filename = files.location( FILENAME ); + OpenGeodeModelException::check_exception( files.has( FILENAME ), nullptr, OpenGeodeException::TYPE::internal, "[Relationships::load] Error while reading file: ", filename ); + const auto content = files.content( FILENAME ); OpenGeodeModelException::check_exception( - detail::deserialize_bytes( content->span(), *this ), nullptr, + detail::deserialize_bytes( content.span(), *this ), nullptr, OpenGeodeException::TYPE::internal, "[Relationships::load] Error while reading file: ", filename ); } @@ -477,9 +479,9 @@ namespace geode } void Relationships::load_relationships( - std::string_view directory, RelationshipsBuilderKey /*key*/ ) + const detail::InputFiles& files, RelationshipsBuilderKey /*key*/ ) { - return impl_->load( directory ); + return impl_->load( files ); } AttributeManager& Relationships::relation_attribute_manager() const diff --git a/src/geode/model/mixin/core/surface_collections.cpp b/src/geode/model/mixin/core/surface_collections.cpp index 8009639b9..f7824eb26 100644 --- a/src/geode/model/mixin/core/surface_collections.cpp +++ b/src/geode/model/mixin/core/surface_collections.cpp @@ -99,10 +99,9 @@ namespace geode template < index_t dimension > void SurfaceCollections< dimension >::load_surface_collections( - std::string_view directory, SurfaceCollectionsBuilderKey /*key*/ ) + const detail::InputFiles& files, SurfaceCollectionsBuilderKey /*key*/ ) { - impl_->load_components( - absl::StrCat( directory, "/surface_collections" ), false ); + impl_->load_components( files, "surface_collections", false ); } template < index_t dimension > diff --git a/src/geode/model/mixin/core/surfaces.cpp b/src/geode/model/mixin/core/surfaces.cpp index dfbfc07ce..bbfa66adc 100644 --- a/src/geode/model/mixin/core/surfaces.cpp +++ b/src/geode/model/mixin/core/surfaces.cpp @@ -87,14 +87,15 @@ namespace std::unique_ptr< geode::SurfaceMesh< dimension > > load_grid_surface( const geode::MeshType& type, const geode::MeshImpl& impl, - std::string_view file ) + const geode::detail::InputFiles& files, + std::string_view name ) { if constexpr( dimension == 2 ) { if( type == geode::RegularGrid< 2 >::type_name_static() ) { - return geode::load_one( - geode::load_regular_grid< 2 >( impl, file ), file ); + return geode::detail::load_component_mesh< + geode::RegularGridInputFactory< 2 > >( files, name, impl ); } } return nullptr; @@ -197,15 +198,15 @@ namespace geode template < index_t dimension > void Surfaces< dimension >::load_surfaces( - std::string_view directory, SurfacesBuilderKey key ) + const detail::InputFiles& files, SurfacesBuilderKey key ) { - impl_->load_components( absl::StrCat( directory, "/surfaces" ) ); - const auto mapping = impl_->file_mapping( directory ); + impl_->load_components( files, "surfaces", true ); + const auto mapping = impl_->file_mapping( files ); absl::FixedArray< async::task< void > > tasks( nb_surfaces() ); index_t count{ 0 }; for( auto& surface : modifiable_surfaces( key ) ) { - tasks[count++] = async::spawn( [&surface, &mapping] { + tasks[count++] = async::spawn( [&surface, &mapping, &files] { const auto file = mapping.find( surface.id().string() ); if( file == mapping.end() ) { @@ -215,22 +216,23 @@ namespace geode typename Surface< dimension >::SurfacesKey{} ); return; } + const auto& name = file->second; const auto impl = detail::loadable_mesh_impl( surface.mesh_type(), - surface_type_from_file< dimension >( file->second ), - file->second ); + surface_type_from_file< dimension >( name ), + files.location( name ) ); const auto& type = MeshFactory::type( impl ); if( type == TriangulatedSurface< dimension >::type_name_static() ) { surface.set_mesh( - load_one( load_triangulated_surface< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + TriangulatedSurfaceInputFactory< dimension > >( + files, name, impl ), typename Surface< dimension >::SurfacesKey{} ); } else if( auto grid = load_grid_surface< dimension >( - type, impl, file->second ) ) + type, impl, files, name ) ) { surface.set_mesh( std::move( grid ), typename Surface< dimension >::SurfacesKey{} ); @@ -238,9 +240,9 @@ namespace geode else { surface.set_mesh( - load_one( load_polygonal_surface< dimension >( - impl, file->second ), - file->second ), + detail::load_component_mesh< + PolygonalSurfaceInputFactory< dimension > >( + files, name, impl ), typename Surface< dimension >::SurfacesKey{} ); } } ); diff --git a/src/geode/model/mixin/core/vertex_identifier.cpp b/src/geode/model/mixin/core/vertex_identifier.cpp index 22b668a48..86342159d 100644 --- a/src/geode/model/mixin/core/vertex_identifier.cpp +++ b/src/geode/model/mixin/core/vertex_identifier.cpp @@ -36,6 +36,7 @@ #include #include +#include #include #include #include @@ -597,20 +598,21 @@ namespace geode filename ); } - void load( std::string_view directory ) + void load( const detail::InputFiles& files ) { - const auto filename = absl::StrCat( directory, "/vertices" ); - const auto content = detail::read_file_content( filename ); - OpenGeodeModelException::check_exception( content.has_value(), + static constexpr auto FILENAME = "vertices"; + const auto filename = files.location( FILENAME ); + OpenGeodeModelException::check_exception( files.has( FILENAME ), nullptr, OpenGeodeException::TYPE::internal, "[VertexIdentifier::load] Error while reading file: ", filename ); + const auto content = files.content( FILENAME ); // Versions before 5 store the component vertices and reset this // flag component_vertices_.clear(); rebuild_component_vertices_ = true; const auto success = - detail::deserialize_bytes( content->span(), *this ); + detail::deserialize_bytes( content.span(), *this ); nb_component_mesh_vertices_up_to_date_ = false; OpenGeodeModelException::check_exception( success, nullptr, OpenGeodeException::TYPE::internal, @@ -1110,9 +1112,9 @@ namespace geode } void VertexIdentifier::load_unique_vertices( - std::string_view directory, BuilderKey /*key*/ ) + const detail::InputFiles& files, BuilderKey /*key*/ ) { - return impl_->load( directory ); + return impl_->load( files ); } std::vector< index_t > VertexIdentifier::delete_isolated_vertices( diff --git a/src/geode/model/representation/io/external_time_series_input.cpp b/src/geode/model/representation/io/external_time_series_input.cpp index 4d5d9f83e..c2c287aae 100644 --- a/src/geode/model/representation/io/external_time_series_input.cpp +++ b/src/geode/model/representation/io/external_time_series_input.cpp @@ -42,7 +42,7 @@ namespace geode "[load_external_time_series] Wrong extension for file ", filename, ", only ", ExternalTimeSeries::native_extension_static(), " is supported" ); - const auto content = detail::read_file_content( filename ); + const auto content = detail::map_file_content( filename ); OpenGeodeModelException::check_exception( content.has_value(), nullptr, OpenGeodeException::TYPE::data, "[load_external_time_series] Failed to open file: ", filename ); diff --git a/src/geode/model/representation/io/geode/geode_brep_input.cpp b/src/geode/model/representation/io/geode/geode_brep_input.cpp index 37c0047c6..cbf9c5fd2 100644 --- a/src/geode/model/representation/io/geode/geode_brep_input.cpp +++ b/src/geode/model/representation/io/geode/geode_brep_input.cpp @@ -24,8 +24,7 @@ #include #include -#include -#include +#include #include #include @@ -42,10 +41,9 @@ namespace geode { std::vector< BRep > OpenGeodeBRepInput::read() { - const UnzipFile zip_reader{ filename(), uuid{}.string() }; - zip_reader.extract_all(); + const detail::ArchiveInputFiles files{ filename() }; BRep brep{ BITSERY::constructor }; - detail::load_brep_files( brep, zip_reader.directory() ); + detail::load_brep_files( brep, files ); std::vector< BRep > breps; breps.emplace_back( std::move( brep ) ); return breps; diff --git a/src/geode/model/representation/io/geode/geode_section_input.cpp b/src/geode/model/representation/io/geode/geode_section_input.cpp index 52a57cd5a..ad1c3f47c 100644 --- a/src/geode/model/representation/io/geode/geode_section_input.cpp +++ b/src/geode/model/representation/io/geode/geode_section_input.cpp @@ -26,8 +26,7 @@ #include #include -#include -#include +#include #include #include @@ -42,10 +41,9 @@ namespace geode { std::vector< Section > OpenGeodeSectionInput::read() { - const UnzipFile zip_reader{ filename(), uuid{}.string() }; - zip_reader.extract_all(); + const detail::ArchiveInputFiles files{ filename() }; Section section{ BITSERY::constructor }; - detail::load_section_files( section, zip_reader.directory() ); + detail::load_section_files( section, files ); std::vector< Section > sections; sections.emplace_back( std::move( section ) ); return sections; diff --git a/tests/basic/CMakeLists.txt b/tests/basic/CMakeLists.txt index bb7c8f87f..38cbe1d96 100644 --- a/tests/basic/CMakeLists.txt +++ b/tests/basic/CMakeLists.txt @@ -70,6 +70,13 @@ add_geode_test( DEPENDENCIES ${PROJECT_NAME}::basic ) +add_geode_test( + SOURCE "test-input-files.cpp" + DEPENDENCIES + Async++ + ${PROJECT_NAME}::basic + MINIZIP::minizip-ng +) add_geode_test( SOURCE "test-logger.cpp" DEPENDENCIES @@ -112,3 +119,12 @@ add_geode_test( ${PROJECT_NAME}::basic MINIZIP::minizip-ng ) +if(UNIX AND NOT APPLE AND BUILD_SHARED_LIBS AND CMAKE_NM) + add_test( + NAME test-hidden-zlib-symbols + COMMAND ${CMAKE_COMMAND} + -DNM=${CMAKE_NM} + -DLIBRARY=$ + -P ${CMAKE_CURRENT_SOURCE_DIR}/check-hidden-symbols.cmake + ) +endif() diff --git a/tests/basic/check-hidden-symbols.cmake b/tests/basic/check-hidden-symbols.cmake new file mode 100644 index 000000000..65e5dcb1e --- /dev/null +++ b/tests/basic/check-hidden-symbols.cmake @@ -0,0 +1,38 @@ +# Copyright (c) 2019 - 2026 Geode-solutions +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# Fails if LIBRARY exports a zlib or minizip-ng symbol (they must stay private) +execute_process( + COMMAND "${NM}" -D --defined-only "${LIBRARY}" + OUTPUT_VARIABLE symbols + RESULT_VARIABLE result +) +if(NOT result EQUAL 0) + message(FATAL_ERROR "[Test] nm failed on ${LIBRARY}") +endif() +string(REGEX MATCHALL + "[ \t](crc32|crc32_z|inflate|inflateInit2_|deflate|deflateInit2_|mz_[A-Za-z0-9_]+)\n" + exported "${symbols}\n" +) +if(exported) + string(REGEX REPLACE "[ \t\n]" "" exported "${exported}") + message(FATAL_ERROR "[Test] ${LIBRARY} exports zlib/minizip-ng symbols: ${exported}") +endif() +message(STATUS "[Test] no zlib/minizip-ng symbol exported by ${LIBRARY}") diff --git a/tests/basic/test-attribute.cpp b/tests/basic/test-attribute.cpp index 84ddd66a8..f8e123bf5 100644 --- a/tests/basic/test-attribute.cpp +++ b/tests/basic/test-attribute.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -524,7 +525,7 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - const auto content = geode::detail::read_file_content( filename ); + const auto content = geode::detail::map_file_content( filename ); geode::OpenGeodeBasicException::test( content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; @@ -539,7 +540,7 @@ void test_serialize_manager( geode::AttributeManager& manager, geode::Deserializer >( std::get< 0 >( reload_context ), "array_double_2" ); geode::Deserializer unarchive{ reload_context, content->span().data(), - content->size() }; + content->span().size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( @@ -928,7 +929,7 @@ void test_no_value() geode::OpenGeodeBasicException::test( std::get< 1 >( context ).isValid(), "Error while writing file: ", filename ); - const auto content = geode::detail::read_file_content( filename ); + const auto content = geode::detail::map_file_content( filename ); geode::OpenGeodeBasicException::test( content.has_value(), "Cannot open file: ", filename ); geode::AttributeManager reloaded_manager; @@ -936,7 +937,7 @@ void test_no_value() geode::register_basic_deserialize_pcontext( std::get< 0 >( reload_context ) ); geode::Deserializer unarchive{ reload_context, content->span().data(), - content->size() }; + content->span().size() }; unarchive.object( reloaded_manager ); const auto& adapter = unarchive.adapter(); geode::OpenGeodeBasicException::test( diff --git a/tests/basic/test-growable.cpp b/tests/basic/test-growable.cpp index 5b6f49557..e00356d73 100644 --- a/tests/basic/test-growable.cpp +++ b/tests/basic/test-growable.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -111,12 +112,12 @@ Out test_growable( const T &foo ) serializer.adapter().flush(); output.close(); - const auto content = geode::detail::read_file_content( "name" ); + const auto content = geode::detail::map_file_content( "name" ); geode::OpenGeodeBasicException::test( content.has_value(), "Cannot open file" ); geode::TContext context_input{}; geode::Deserializer deserializer{ context_input, content->span().data(), - content->size() }; + content->span().size() }; Out new_foo; deserializer.object( new_foo ); const auto &adapter = deserializer.adapter(); diff --git a/tests/basic/test-input-files.cpp b/tests/basic/test-input-files.cpp new file mode 100644 index 000000000..e9e9f3a05 --- /dev/null +++ b/tests/basic/test-input-files.cpp @@ -0,0 +1,539 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +using Entries = std::vector< std::pair< std::string, std::string > >; + +std::string as_string( geode::ByteSpan bytes ) +{ + return { bytes.data(), bytes.size() }; +} + +void write_file( const std::filesystem::path& file, std::string_view content ) +{ + std::ofstream stream{ file, std::ios::binary }; + stream.write( + content.data(), static_cast< std::streamsize >( content.size() ) ); + geode::OpenGeodeBasicException::test( + stream.good(), "Cannot write file ", file.u8string() ); +} + +void write_zip( + const std::string& zip, const Entries& entries, uint16_t method ) +{ + void* writer = mz_zip_writer_create(); + mz_zip_writer_set_compress_method( writer, method ); + auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); + for( const auto& [name, content] : entries ) + { + if( status != MZ_OK ) + { + break; + } + mz_zip_file info{}; + info.filename = name.c_str(); + info.compression_method = method; + info.flag = MZ_ZIP_FLAG_UTF8; + info.modified_date = std::time( nullptr ); + status = mz_zip_writer_add_buffer( writer, content.data(), + static_cast< int32_t >( content.size() ), &info ); + } + const auto close_status = mz_zip_writer_close( writer ); + mz_zip_writer_delete( &writer ); + geode::OpenGeodeBasicException::test( + status == MZ_OK && close_status == MZ_OK, "Cannot write zip (", status, + ", ", close_status, ")" ); +} + +Entries test_entries() +{ + std::string text; + for( const auto i : geode::Range{ 10000 } ) + { + absl::StrAppend( &text, "line ", i, " of a compressible file\n" ); + } + std::string binary; + for( const auto i : geode::Range{ 100000 } ) + { + binary.push_back( static_cast< char >( ( i * i ) % 7 ) ); + } + return { { "text.txt", text }, { "folder/binary.bin", binary }, + { "empty", "" }, { "small", "abc" } }; +} + +template < typename Function > +void check_data_error( Function&& function, + std::string_view expected_message, + std::string_view test_name ) +{ + try + { + function(); + } + catch( const geode::OpenGeodeException& exception ) + { + geode::OpenGeodeBasicException::test( + exception.type() == geode::OpenGeodeException::TYPE::data, + test_name, ": expected a data error, got ", exception.what() ); + geode::OpenGeodeBasicException::test( + absl::StrContains( exception.what(), expected_message ), test_name, + ": message \"", exception.what(), "\" does not contain ", + expected_message ); + return; + } + throw geode::OpenGeodeBasicException{ nullptr, + geode::OpenGeodeException::TYPE::internal, test_name, + ": no exception thrown" }; +} + +void check_files_content( const geode::detail::InputFiles& files, + const Entries& entries, + std::string_view test_name ) +{ + for( const auto& [name, content] : entries ) + { + geode::OpenGeodeBasicException::test( + files.has( name ), test_name, ": missing entry ", name ); + const auto file = files.content( name ); + geode::OpenGeodeBasicException::test( + as_string( file.span() ) == content, test_name, + ": wrong content of ", name ); + } + geode::OpenGeodeBasicException::test( + !files.has( "missing" ), test_name, ": unexpected entry" ); + check_data_error( + [&files] { + geode_unused( files.content( "missing" ) ); + }, + "missing", test_name ); +} + +void test_mapped_file() +{ + const std::string filename{ "mapped_file.bin" }; + const auto entries = test_entries(); + const auto& content = entries[1].second; + write_file( filename, content ); + { + const auto mapping = geode::detail::MappedFile::map( filename ); + geode::OpenGeodeBasicException::test( + mapping != nullptr, "[MappedFile] Cannot map a regular file" ); + geode::OpenGeodeBasicException::test( + as_string( mapping->span() ) == content, + "[MappedFile] Wrong mapped content" ); + // Released pages are mapped again when read + mapping->release( mapping->span().subspan( 10, 50000 ) ); + geode::OpenGeodeBasicException::test( + as_string( mapping->span() ) == content, + "[MappedFile] Wrong content after release" ); + geode::detail::FileContent slice{ mapping, + mapping->span().subspan( 100, 30000 ) }; + geode::OpenGeodeBasicException::test( + as_string( slice.span() ) == content.substr( 100, 30000 ), + "[MappedFile] Wrong slice" ); + const auto moved = std::move( slice ); + geode::OpenGeodeBasicException::test( + slice.span().empty() && moved.span().size() == 30000, + "[MappedFile] Wrong moved slice" ); + } + const auto mapped = geode::detail::map_file_content( filename ); + geode::OpenGeodeBasicException::test( + mapped.has_value() && as_string( mapped->span() ) == content, + "[map_file_content] Wrong content" ); + geode::OpenGeodeBasicException::test( + geode::detail::MappedFile::map( "missing_file.bin" ) == nullptr + && !geode::detail::map_file_content( "missing_file.bin" ), + "[MappedFile] Missing file should not be mapped" ); + const std::string empty{ "empty_file.bin" }; + write_file( empty, "" ); + const auto empty_content = geode::detail::map_file_content( empty ); + geode::OpenGeodeBasicException::test( + empty_content.has_value() && empty_content->span().empty(), + "[map_file_content] Wrong empty file content" ); + std::filesystem::remove( filename ); + std::filesystem::remove( empty ); +} + +void test_directory_input_files() +{ + const std::filesystem::path directory{ "input_files_directory" }; + std::filesystem::remove_all( directory ); + std::filesystem::create_directories( directory / "folder" ); + const auto entries = test_entries(); + for( const auto& [name, content] : entries ) + { + write_file( directory / name, content ); + } + const geode::detail::DirectoryInputFiles files{ directory.u8string() }; + check_files_content( files, entries, "[DirectoryInputFiles]" ); + const std::vector< std::string > expected_names{ "empty", "small", + "text.txt" }; + geode::OpenGeodeBasicException::test( files.names() == expected_names, + "[DirectoryInputFiles] Wrong names (not recursive, sorted)" ); + geode::OpenGeodeBasicException::test( + files.path( "small" ) == ( directory.u8string() + "/small" ) + && files.location( "small" ) == files.path( "small" ), + "[DirectoryInputFiles] Wrong path" ); + geode::OpenGeodeBasicException::test( !files.has( "folder" ), + "[DirectoryInputFiles] A directory is not a file" ); + geode::OpenGeodeBasicException::test( + !geode::detail::map_file_content( ( directory / "folder" ).u8string() ), + "[map_file_content] A directory has no content" ); + check_data_error( + [&files] { + geode_unused( files.content( "folder" ) ); + }, + "folder", "[DirectoryInputFiles] directory content" ); + std::filesystem::remove_all( directory ); +} + +void test_archive_input_files( uint16_t method, std::string_view test_name ) +{ + const auto zip = absl::StrCat( "input_files_", method, ".zip" ); + const auto entries = test_entries(); + write_zip( zip, entries, method ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_files_content( files, entries, test_name ); + std::vector< std::string > expected_names; + for( const auto& entry : entries ) + { + expected_names.push_back( entry.first ); + } + geode::OpenGeodeBasicException::test( + files.names() == expected_names, test_name, ": wrong names" ); + geode::OpenGeodeBasicException::test( + !files.path( "small" ).has_value() + && files.location( "small" ) == zip + "/small", + test_name, ": wrong path" ); + // Several threads can read the entries + std::vector< async::task< bool > > tasks; + for( const auto& entry : entries ) + { + tasks.push_back( async::spawn( [&files, &entry] { + const auto& [name, content] = entry; + return as_string( files.content( name ).span() ) == content; + } ) ); + } + for( auto& task : tasks ) + { + geode::OpenGeodeBasicException::test( + task.get(), test_name, ": wrong concurrent content" ); + } + std::filesystem::remove( zip ); +} + +std::string read_file( const std::string& file ) +{ + const auto content = geode::detail::map_file_content( file ); + geode::OpenGeodeBasicException::test( + content.has_value(), "Cannot read ", file ); + return as_string( content->span() ); +} + +void test_corrupted_entry() +{ + const std::string zip{ "corrupted_entry.zip" }; + const auto entries = test_entries(); + write_zip( zip, entries, MZ_COMPRESS_METHOD_STORE ); + auto archive = read_file( zip ); + // Flip one byte in the middle of the stored text entry + const auto position = archive.find( "line 5000 " ); + geode::OpenGeodeBasicException::test( + position != std::string::npos, "Entry not found in the archive" ); + archive[position] = 'X'; + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "text.txt", "[ArchiveInputFiles] corrupted entry" ); + // The other entries are still readable + geode::OpenGeodeBasicException::test( + as_string( files.content( "small" ).span() ) == "abc", + "[ArchiveInputFiles] Wrong entry next to a corrupted one" ); + std::filesystem::remove( zip ); +} + +uint32_t read_uint( const std::string& data, size_t offset, size_t size ) +{ + uint32_t value{ 0 }; + for( const auto i : geode::Range{ size } ) + { + value |= static_cast< uint32_t >( + static_cast< unsigned char >( data[offset + i] ) ) + << ( 8 * i ); + } + return value; +} + +void write_uint( std::string& data, size_t offset, size_t size, uint32_t value ) +{ + for( const auto i : geode::Range{ size } ) + { + data[offset + i] = static_cast< char >( ( value >> ( 8 * i ) ) & 0xFF ); + } +} + +/*! + * Return the offset of the central directory header of the given entry. + */ +size_t central_header( const std::string& archive, std::string_view name ) +{ + const std::string signature{ "PK\x01\x02" }; + for( auto position = archive.find( signature ); + position != std::string::npos; + position = archive.find( signature, position + 1 ) ) + { + const auto name_length = read_uint( archive, position + 28, 2 ); + if( archive.compare( position + 46, name_length, name ) == 0 + && name_length == name.size() ) + { + return position; + } + } + throw geode::OpenGeodeBasicException{ nullptr, + geode::OpenGeodeException::TYPE::internal, "Entry ", name, + " not found in the central directory" }; +} + +void test_corrupted_deflate_stream() +{ + const std::string zip{ "corrupted_deflate.zip" }; + const auto entries = test_entries(); + write_zip( zip, entries, MZ_COMPRESS_METHOD_DEFLATE ); + auto archive = read_file( zip ); + // First entry: its local header is at the start of the archive + geode::OpenGeodeBasicException::test( + archive.compare( 30, 8, "text.txt" ) == 0, + "[ArchiveInputFiles] text.txt should be the first entry" ); + const auto data = + 30 + read_uint( archive, 26, 2 ) + read_uint( archive, 28, 2 ); + // Final block of the reserved (invalid) block type 3 + archive[data] = static_cast< char >( 0x07 ); + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "Cannot decompress zip entry corrupted_deflate.zip/text.txt", + "[ArchiveInputFiles] corrupted deflate stream" ); + geode::OpenGeodeBasicException::test( + as_string( files.content( "small" ).span() ) == "abc", + "[ArchiveInputFiles] Wrong entry next to a corrupted deflate stream" ); + std::filesystem::remove( zip ); +} + +void test_truncated_entry() +{ + const std::string zip{ "truncated_entry.zip" }; + const auto entries = test_entries(); + write_zip( zip, entries, MZ_COMPRESS_METHOD_DEFLATE ); + auto archive = read_file( zip ); + const auto archive_size = static_cast< uint32_t >( archive.size() ); + // Local header of "small" beyond the end of the archive + write_uint( archive, central_header( archive, "small" ) + 42, 4, + archive_size + 1000 ); + // Local header of "empty" not on a local header signature + write_uint( archive, central_header( archive, "empty" ) + 42, 4, 1 ); + // Data of "text.txt" larger than the archive + write_uint( + archive, central_header( archive, "text.txt" ) + 20, 4, archive_size ); + write_file( zip, archive ); + const geode::detail::ArchiveInputFiles files{ zip }; + check_data_error( + [&files] { + geode_unused( files.content( "small" ) ); + }, + "Truncated zip entry truncated_entry.zip/small", + "[ArchiveInputFiles] local header out of range" ); + check_data_error( + [&files] { + geode_unused( files.content( "empty" ) ); + }, + "Invalid local header of zip entry truncated_entry.zip/empty", + "[ArchiveInputFiles] invalid local header" ); + check_data_error( + [&files] { + geode_unused( files.content( "text.txt" ) ); + }, + "Truncated zip entry truncated_entry.zip/text.txt", + "[ArchiveInputFiles] data out of range" ); + geode::OpenGeodeBasicException::test( + files.content( "folder/binary.bin" ).span().size() == 100000, + "[ArchiveInputFiles] Wrong entry next to truncated ones" ); + std::filesystem::remove( zip ); +} + +void test_unsafe_entry() +{ + const std::string zip{ "unsafe_entry.zip" }; + write_zip( zip, { { "../outside", "abc" } }, MZ_COMPRESS_METHOD_STORE ); + check_data_error( + [&zip] { + const geode::detail::ArchiveInputFiles files{ zip }; + }, + "../outside", "[ArchiveInputFiles] unsafe entry" ); + std::filesystem::remove( zip ); +} + +void test_not_an_archive() +{ + check_data_error( + [] { + const geode::detail::ArchiveInputFiles files{ absl::StrCat( + geode::DATA_PATH, "triangle.og_tsf3d" ) }; + }, + "triangle.og_tsf3d", "[ArchiveInputFiles] not an archive" ); + check_data_error( + [] { + const geode::detail::ArchiveInputFiles files{ "missing.zip" }; + }, + "missing.zip", "[ArchiveInputFiles] missing archive" ); +} + +void test_temporary_file() +{ + std::string directory; + { + const geode::detail::TemporaryFile file{ "entry.txt", { "abc", 3 } }; + const std::filesystem::path path{ file.path() }; + geode::OpenGeodeBasicException::test( + path.filename() == "entry.txt" && read_file( file.path() ) == "abc", + "[TemporaryFile] Wrong file" ); + directory = path.parent_path().u8string(); + } + geode::OpenGeodeBasicException::test( !std::filesystem::exists( directory ), + "[TemporaryFile] Directory not removed" ); +} + +void set_environment( + const char* name, const std::optional< std::string >& value ) +{ +#ifdef _WIN32 + _putenv_s( name, value ? value->c_str() : "" ); +#else + if( value ) + { + setenv( name, value->c_str(), 1 ); + } + else + { + unsetenv( name ); + } +#endif +} + +std::optional< std::string > get_environment( const char* name ) +{ + const auto* value = std::getenv( name ); + if( value == nullptr ) + { + return std::nullopt; + } + return std::string{ value }; +} + +void test_temporary_file_without_temporary_directory() +{ + // Not a directory: the temporary directory cannot be used + const std::string not_a_directory{ "temporary_file_not_a_directory" }; + write_file( not_a_directory, "abc" ); + const auto absolute = + std::filesystem::absolute( not_a_directory ).u8string(); + std::vector< std::pair< const char*, std::optional< std::string > > > saved; + for( const auto* name : { "TMPDIR", "TMP", "TEMP", "TEMPDIR" } ) + { + saved.emplace_back( name, get_environment( name ) ); + set_environment( name, absolute ); + } + bool internal_error{ false }; + try + { + const geode::detail::TemporaryFile file{ "entry.txt", { "abc", 3 } }; + } + catch( const geode::OpenGeodeException& exception ) + { + internal_error = + exception.type() == geode::OpenGeodeException::TYPE::internal; + } + catch( ... ) + { + } + for( const auto& [name, value] : saved ) + { + set_environment( name, value ); + } + std::filesystem::remove( not_a_directory ); + geode::OpenGeodeBasicException::test( internal_error, + "[TemporaryFile] Unusable temporary directory should raise an " + "internal OpenGeodeException" ); +} + +void test() +{ + test_mapped_file(); + test_directory_input_files(); + test_archive_input_files( + MZ_COMPRESS_METHOD_STORE, "[ArchiveInputFiles] stored" ); + test_archive_input_files( + MZ_COMPRESS_METHOD_DEFLATE, "[ArchiveInputFiles] deflated" ); + test_corrupted_entry(); + test_corrupted_deflate_stream(); + test_truncated_entry(); + test_unsafe_entry(); + test_not_an_archive(); + test_temporary_file(); + test_temporary_file_without_temporary_directory(); +} + +OPENGEODE_TEST( "input-files" ) diff --git a/tests/mesh/CMakeLists.txt b/tests/mesh/CMakeLists.txt index 01cb77eb6..dfb8c6b9d 100644 --- a/tests/mesh/CMakeLists.txt +++ b/tests/mesh/CMakeLists.txt @@ -141,6 +141,14 @@ add_geode_test( ${PROJECT_NAME}::basic ${PROJECT_NAME}::mesh ) +add_geode_test( + SOURCE "test-mesh-input-bytes.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::image + ${PROJECT_NAME}::mesh + MINIZIP::minizip-ng +) add_geode_test( SOURCE "test-mesh-corrupted-files.cpp" DEPENDENCIES diff --git a/tests/mesh/test-mesh-input-bytes.cpp b/tests/mesh/test-mesh-input-bytes.cpp new file mode 100644 index 000000000..6f897dceb --- /dev/null +++ b/tests/mesh/test-mesh-input-bytes.cpp @@ -0,0 +1,458 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ + template < typename Mesh, typename = void > + struct HasPoints : std::false_type + { + }; + + template < typename Mesh > + struct HasPoints< Mesh, + std::void_t< decltype( std::declval< const Mesh& >().point( 0 ) ) > > + : std::true_type + { + }; + + std::string describe_attributes( const geode::AttributeManager& manager ) + { + std::vector< std::string > ids; + for( const auto& id : manager.attribute_ids() ) + { + // Attributes of old files get a new uuid at each load + ids.push_back( absl::StrCat( manager.attribute_type( id ), ":", + manager.find_generic_attribute( id )->name().value_or( "" ) ) ); + } + absl::c_sort( ids ); + return absl::StrCat( + manager.nb_elements(), "[", absl::StrJoin( ids, "," ), "]" ); + } + + /*! + * Text describing a mesh: its vertices, elements and attributes (not + * its identifier: meshes of old files get a new one at each load). + */ + template < typename Mesh > + std::string describe( const Mesh& mesh ) + { + auto text = absl::StrCat( mesh.nb_vertices(), " vertices ", + describe_attributes( mesh.vertex_attribute_manager() ) ); + if constexpr( HasPoints< Mesh >::value ) + { + for( const auto vertex : geode::Range{ mesh.nb_vertices() } ) + { + absl::StrAppend( &text, " ", mesh.point( vertex ).string() ); + } + } + if constexpr( std::is_base_of_v< geode::Graph, Mesh > ) + { + absl::StrAppend( &text, " edges ", + describe_attributes( mesh.edge_attribute_manager() ) ); + for( const auto edge : geode::Range{ mesh.nb_edges() } ) + { + absl::StrAppend( &text, " ", mesh.edge_vertex( { edge, 0 } ), + "-", mesh.edge_vertex( { edge, 1 } ) ); + } + } + if constexpr( std::is_base_of_v< geode::SurfaceMesh< 2 >, Mesh > + || std::is_base_of_v< geode::SurfaceMesh< 3 >, Mesh > ) + { + absl::StrAppend( &text, " polygons ", + describe_attributes( mesh.polygon_attribute_manager() ) ); + for( const auto polygon : geode::Range{ mesh.nb_polygons() } ) + { + absl::StrAppend( &text, " (" ); + for( const auto v : + geode::LRange{ mesh.nb_polygon_vertices( polygon ) } ) + { + absl::StrAppend( + &text, mesh.polygon_vertex( { polygon, v } ), "," ); + } + absl::StrAppend( &text, ")" ); + } + } + if constexpr( std::is_base_of_v< geode::SolidMesh< 3 >, Mesh > ) + { + absl::StrAppend( &text, " polyhedra ", + describe_attributes( mesh.polyhedron_attribute_manager() ) ); + for( const auto polyhedron : geode::Range{ mesh.nb_polyhedra() } ) + { + absl::StrAppend( &text, " (" ); + for( const auto v : + geode::LRange{ mesh.nb_polyhedron_vertices( polyhedron ) } ) + { + absl::StrAppend( &text, + mesh.polyhedron_vertex( { polyhedron, v } ), "," ); + } + absl::StrAppend( &text, ")" ); + } + } + return text; + } + + template < geode::index_t dimension > + std::string describe_grid( + const geode::LightRegularGrid< dimension >& grid ) + { + auto text = absl::StrCat( grid.nb_cells(), " cells ", + grid.grid_point( {} ).string(), " ", + describe_attributes( grid.cell_attribute_manager() ), + describe_attributes( grid.grid_vertex_attribute_manager() ) ); + for( const auto direction : geode::LRange{ dimension } ) + { + absl::StrAppend( &text, " ", + grid.nb_cells_in_direction( direction ), "x", + grid.cell_length_in_direction( direction ) ); + } + return text; + } + + std::string describe_image( const geode::RasterImage2D& image ) + { + auto text = absl::StrCat( image.nb_cells(), " cells" ); + for( const auto cell : geode::Range{ image.nb_cells() } ) + { + absl::StrAppend( &text, " ", image.color( cell ).string() ); + } + return text; + } + + std::string data_file( std::string_view name ) + { + return absl::StrCat( geode::DATA_PATH, name ); + } + + geode::detail::FileContent read_whole_file( std::string_view filename ) + { + auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeMeshException::test( + content.has_value(), "Cannot read ", filename ); + return std::move( content.value() ); + } + + /*! + * Read a native mesh file by path, from its bytes, and through the + * input files of its directory: the three meshes must be identical. + */ + template < typename OpenGeodeMesh, typename Factory > + void check_mesh( std::string_view filename ) + { + const auto impl = OpenGeodeMesh::impl_name_static(); + const auto extension = geode::detail::lowercase_extension( filename ); + const auto by_path = geode::load_one( + Factory::create( extension, filename )->read( impl ), filename ); + const auto reference = describe( *by_path ); + + const auto bytes = read_whole_file( filename ); + auto from_bytes = Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span(), impl ); + geode::OpenGeodeMeshException::test( from_bytes.has_value(), + "Native input of ", filename, " cannot read bytes" ); + geode::OpenGeodeMeshException::test( + describe( + *geode::load_one( std::move( from_bytes.value() ), filename ) ) + == reference, + "Mesh read from bytes differs from the file ", filename ); + + const std::filesystem::path path{ filename }; + const geode::detail::DirectoryInputFiles files{ + path.parent_path().u8string() + }; + const auto from_files = geode::load_one( + geode::detail::geode_object_input_from_files< Factory >( + "Mesh", files, path.filename().u8string(), impl ), + filename ); + geode::OpenGeodeMeshException::test( + describe( *from_files ) == reference, + "Mesh read from input files differs from the file ", filename ); + } + + template < typename Object, typename Factory, typename Describe > + void check_object( std::string_view filename, const Describe& describe ) + { + const auto extension = geode::detail::lowercase_extension( filename ); + const auto by_path = geode::load_one( + Factory::create( extension, filename )->read(), filename ); + const auto bytes = read_whole_file( filename ); + auto from_bytes = Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span() ); + geode::OpenGeodeMeshException::test( from_bytes.has_value(), + "Native input of ", filename, " cannot read bytes" ); + geode::OpenGeodeMeshException::test( + describe( + geode::load_one( std::move( from_bytes.value() ), filename ) ) + == describe( by_path ), + "Object read from bytes differs from the file ", filename ); + } + + void test_native_meshes() + { + check_mesh< geode::OpenGeodeTriangulatedSurface3D, + geode::TriangulatedSurfaceInputFactory3D >( + data_file( "triangle.og_tsf3d" ) ); + check_mesh< geode::OpenGeodeTriangulatedSurface2D, + geode::TriangulatedSurfaceInputFactory2D >( + data_file( "3patches.og_tsf2d" ) ); + check_mesh< geode::OpenGeodeTetrahedralSolid3D, + geode::TetrahedralSolidInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_tso3d" ) ); + check_mesh< geode::OpenGeodePolygonalSurface3D, + geode::PolygonalSurfaceInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_psf3d" ) ); + check_mesh< geode::OpenGeodePolyhedralSolid3D, + geode::PolyhedralSolidInputFactory3D >( + data_file( "backward_io/v17/v17.og_pso3d" ) ); + check_mesh< geode::OpenGeodeHybridSolid3D, + geode::HybridSolidInputFactory3D >( + data_file( "backward_io/v17/v17.og_hso3d" ) ); + check_mesh< geode::OpenGeodeEdgedCurve3D, + geode::EdgedCurveInputFactory3D >( + data_file( "backward_io/v18_5/v18_5.og_edc3d" ) ); + check_mesh< geode::OpenGeodePointSet3D, geode::PointSetInputFactory3D >( + data_file( "backward_io/v17/v17.og_pts3d" ) ); + check_mesh< geode::OpenGeodeRegularGrid3D, + geode::RegularGridInputFactory3D >( + data_file( "backward_io/v17/v17.og_rgd3d" ) ); + check_mesh< geode::OpenGeodeGraph, geode::GraphInputFactory >( + data_file( "backward_io/v18_5/v18_5.og_grp" ) ); + check_object< geode::LightRegularGrid3D, + geode::LightRegularGridInputFactory3D >( + data_file( "backward_io/v19_8/v19_8.og_lrgd3d" ), + describe_grid< 3 > ); + check_object< geode::LightRegularGrid2D, + geode::LightRegularGridInputFactory2D >( + data_file( "backward_io/v19_8/v19_8.og_lrgd2d" ), + describe_grid< 2 > ); + } + + void test_raster_image() + { + geode::RasterImage2D image{ { 3, 2 } }; + for( const auto cell : geode::Range{ image.nb_cells() } ) + { + image.set_color( + cell, geode::RGBColor{ + static_cast< geode::local_index_t >( cell ), 2, 3 } ); + } + const std::string filename{ "bytes_raster.og_img2d" }; + geode::save_raster_image( image, filename ); + check_object< geode::RasterImage2D, geode::RasterImageInputFactory2D >( + filename, describe_image ); + std::filesystem::remove( filename ); + } + + /*! + * Input reading only files, to check the fallback of the input files. + */ + class PathOnlyInput : public geode::TriangulatedSurfaceInput< 3 > + { + public: + explicit PathOnlyInput( std::string_view filename ) + : geode::TriangulatedSurfaceInput< 3 >( filename ) + { + } + + std::vector< std::unique_ptr< geode::TriangulatedSurface3D > > read( + const geode::MeshImpl& impl ) final + { + read_paths().emplace_back( filename() ); + geode::OpenGeodeMeshException::test( + std::filesystem::exists( + std::filesystem::u8path( geode::to_string( filename() ) ) ), + "[PathOnlyInput] File ", filename(), " does not exist" ); + const auto bytes = read_whole_file( filename() ); + auto meshes = geode::TriangulatedSurfaceInputFactory3D::create( + "og_tsf3d", filename() ) + ->read_bytes( bytes.span(), impl ); + return std::move( meshes.value() ); + } + + geode::AdditionalFiles additional_files() const final + { + return {}; + } + + geode::index_t object_priority() const final + { + return 0; + } + + geode::Percentage is_loadable() const final + { + return geode::Percentage{ 1 }; + } + + static std::vector< std::string >& read_paths() + { + static std::vector< std::string > paths; + return paths; + } + }; + + void write_stored_zip( const std::string& zip, + const std::string& name, + geode::ByteSpan content ) + { + void* writer = mz_zip_writer_create(); + mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_STORE ); + auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); + if( status == MZ_OK ) + { + mz_zip_file info{}; + info.filename = name.c_str(); + info.compression_method = MZ_COMPRESS_METHOD_STORE; + info.flag = MZ_ZIP_FLAG_UTF8; + info.modified_date = std::time( nullptr ); + status = mz_zip_writer_add_buffer( writer, content.data(), + static_cast< int32_t >( content.size() ), &info ); + } + const auto close_status = mz_zip_writer_close( writer ); + mz_zip_writer_delete( &writer ); + geode::OpenGeodeMeshException::test( + status == MZ_OK && close_status == MZ_OK, "Cannot write zip" ); + } + + void test_fallback_to_file() + { + geode::TriangulatedSurfaceInputFactory3D::register_creator< + PathOnlyInput >( "path_only" ); + const auto bytes = read_whole_file( data_file( "triangle.og_tsf3d" ) ); + const auto impl = + geode::OpenGeodeTriangulatedSurface3D::impl_name_static(); + const auto reference = + describe( *geode::load_one( geode::load_triangulated_surface< 3 >( + data_file( "triangle.og_tsf3d" ) ), + "triangle" ) ); + + // Entry of an archive: written to a temporary file + const std::string zip{ "path_only.zip" }; + write_stored_zip( zip, "mesh.path_only", bytes.span() ); + { + const geode::detail::ArchiveInputFiles files{ zip }; + const auto mesh = + geode::load_one( geode::detail::geode_object_input_from_files< + geode::TriangulatedSurfaceInputFactory3D >( + "Mesh", files, "mesh.path_only", impl ), + "mesh" ); + geode::OpenGeodeMeshException::test( describe( *mesh ) == reference, + "Wrong mesh read from a temporary file" ); + } + auto& paths = PathOnlyInput::read_paths(); + geode::OpenGeodeMeshException::test( + paths.size() == 1, "The path only input should be called once" ); + const std::filesystem::path temporary{ paths.front() }; + geode::OpenGeodeMeshException::test( + temporary.filename() == "mesh.path_only" + && !std::filesystem::exists( temporary.parent_path() ), + "The temporary file should be removed: ", paths.front() ); + std::filesystem::remove( zip ); + + // File of a directory: read in place + const std::filesystem::path directory{ "path_only_directory" }; + std::filesystem::create_directories( directory ); + { + std::ofstream file{ directory / "mesh.path_only", + std::ios::binary }; + file.write( bytes.span().data(), + static_cast< std::streamsize >( bytes.span().size() ) ); + } + const geode::detail::DirectoryInputFiles files{ directory.u8string() }; + geode_unused( geode::detail::geode_object_input_from_files< + geode::TriangulatedSurfaceInputFactory3D >( + "Mesh", files, "mesh.path_only", impl ) ); + geode::OpenGeodeMeshException::test( + paths.size() == 2 + && paths.back() == files.location( "mesh.path_only" ), + "A file of a directory should be read in place" ); + std::filesystem::remove_all( directory ); + } +} // namespace + +void test() +{ + geode::OpenGeodeMeshLibrary::initialize(); + test_native_meshes(); + test_raster_image(); + test_fallback_to_file(); +} + +OPENGEODE_TEST( "mesh-input-bytes" ) diff --git a/tests/mesh/test-texture-manager.cpp b/tests/mesh/test-texture-manager.cpp index ea05c5a7d..593fe8c64 100644 --- a/tests/mesh/test-texture-manager.cpp +++ b/tests/mesh/test-texture-manager.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -101,7 +102,7 @@ void save( const geode::TextureStorage2D& storage, std::string_view filename ) geode::TextureStorage2D load( std::string_view filename ) { - const auto content = geode::detail::read_file_content( filename ); + const auto content = geode::detail::map_file_content( filename ); geode::OpenGeodeMeshException::test( content.has_value(), "[Bitsery::read] Cannot open file: ", filename ); geode::TContext context{}; @@ -110,7 +111,7 @@ geode::TextureStorage2D load( std::string_view filename ) geode::register_image_deserialize_pcontext( std::get< 0 >( context ) ); geode::register_mesh_deserialize_pcontext( std::get< 0 >( context ) ); geode::Deserializer archive{ context, content->span().data(), - content->size() }; + content->span().size() }; geode::TextureStorage2D storage; archive.object( storage ); const auto& adapter = archive.adapter(); diff --git a/tests/model/CMakeLists.txt b/tests/model/CMakeLists.txt index a6e44756c..78f2ce21b 100644 --- a/tests/model/CMakeLists.txt +++ b/tests/model/CMakeLists.txt @@ -96,6 +96,13 @@ add_geode_test( ${PROJECT_NAME}::mesh ${PROJECT_NAME}::model ) +add_geode_test( + SOURCE "test-model-archive-input.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh + ${PROJECT_NAME}::model +) add_geode_test( SOURCE "test-model-deflate-archive.cpp" DEPENDENCIES diff --git a/tests/model/test-model-archive-input.cpp b/tests/model/test-model-archive-input.cpp new file mode 100644 index 000000000..0e1408822 --- /dev/null +++ b/tests/model/test-model-archive-input.cpp @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace +{ + template < typename Model > + void check_same_components( + const Model& model, const Model& reference, std::string_view filename ) + { + for( const auto& corner : reference.corners() ) + { + const auto& mesh = model.corner( corner.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == corner.mesh().nb_vertices(), + "Corner mesh differs in ", filename ); + } + for( const auto& line : reference.lines() ) + { + const auto& mesh = model.line( line.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == line.mesh().nb_vertices() + && mesh.nb_edges() == line.mesh().nb_edges(), + "Line mesh differs in ", filename ); + } + for( const auto& surface : reference.surfaces() ) + { + const auto& mesh = model.surface( surface.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == surface.mesh().nb_vertices() + && mesh.nb_polygons() == surface.mesh().nb_polygons() + && mesh.type_name() == surface.mesh().type_name(), + "Surface mesh differs in ", filename ); + } + for( const auto uv : geode::Range{ reference.nb_unique_vertices() } ) + { + auto vertices = model.component_mesh_vertices( uv ); + auto expected = reference.component_mesh_vertices( uv ); + absl::c_sort( vertices ); + absl::c_sort( expected ); + geode::OpenGeodeModelException::test( vertices == expected, + "Unique vertex ", uv, " differs in ", filename ); + } + geode::OpenGeodeModelException::test( + model.nb_corners() == reference.nb_corners() + && model.nb_lines() == reference.nb_lines() + && model.nb_surfaces() == reference.nb_surfaces() + && model.nb_model_boundaries() + == reference.nb_model_boundaries(), + "Components differ in ", filename ); + geode::OpenGeodeModelException::test( + model.nb_unique_vertices() == reference.nb_unique_vertices(), + "Unique vertices differ in ", filename ); + const geode::detail::ArchiveInputFiles files{ filename }; + // Without identifier file, the model gets a new identifier + geode::OpenGeodeModelException::test( + !files.has( "identifier" ) || model.id() == reference.id(), + "Identifier differs in ", filename, ": ", model.id().string(), + " vs ", reference.id().string() ); + geode::OpenGeodeModelException::test( + model.name() == reference.name(), "Name differs in ", filename ); + for( const auto& surface : reference.surfaces() ) + { + geode::OpenGeodeModelException::test( + model.nb_relations( surface.id() ) + == reference.nb_relations( surface.id() ), + "Relations differ in ", filename ); + } + } + + void check_same_brep( const geode::BRep& model, + const geode::BRep& reference, + std::string_view filename ) + { + check_same_components( model, reference, filename ); + geode::OpenGeodeModelException::test( + model.nb_blocks() == reference.nb_blocks(), "Blocks differ in ", + filename ); + for( const auto& block : reference.blocks() ) + { + const auto& mesh = model.block( block.id() ).mesh(); + geode::OpenGeodeModelException::test( + mesh.nb_vertices() == block.mesh().nb_vertices() + && mesh.nb_polyhedra() == block.mesh().nb_polyhedra() + && mesh.type_name() == block.mesh().type_name(), + "Block mesh differs in ", filename ); + } + } + + /*! + * Load every native model file from its archive and from its extracted + * directory (through the directory input files): same models. + */ + void test_data_files() + { + geode::index_t nb_files{ 0 }; + for( const auto& file : std::filesystem::recursive_directory_iterator( + std::filesystem::u8path( geode::DATA_PATH ) ) ) + { + const auto path = file.path().u8string(); + const auto extension = file.path().extension().u8string(); + if( extension != ".og_brep" && extension != ".og_sctn" ) + { + continue; + } + geode::Logger::info( "Checking ", path ); + const geode::UnzipFile unzip{ path, geode::uuid{}.string() }; + unzip.extract_all(); + if( extension == ".og_brep" ) + { + geode::BRep reference{ geode::BITSERY::constructor }; + geode::detail::load_brep_files( reference, + geode::detail::DirectoryInputFiles{ unzip.directory() } ); + const auto brep = + geode::load_one( geode::load_brep( path ), path ); + check_same_brep( brep, reference, path ); + } + else + { + geode::Section reference{ geode::BITSERY::constructor }; + geode::detail::load_section_files( reference, + geode::detail::DirectoryInputFiles{ unzip.directory() } ); + const auto section = + geode::load_one( geode::load_section( path ), path ); + check_same_components( section, reference, path ); + } + nb_files++; + } + geode::OpenGeodeModelException::test( + nb_files >= 10, "Too few model files found: ", nb_files ); + } + + void set_environment( + const char* name, const std::optional< std::string >& value ) + { +#ifdef _WIN32 + _putenv_s( name, value ? value->c_str() : "" ); +#else + if( value ) + { + setenv( name, value->c_str(), 1 ); + } + else + { + unsetenv( name ); + } +#endif + } + + /*! + * Loading a model does not use the temporary directory: pointing it to a + * regular file makes any use of it fail. + */ + void test_no_temporary_directory() + { + const auto brep_file = + absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + const auto section_file = + absl::StrCat( geode::DATA_PATH, "fractures.og_sctn" ); + const auto reference_brep = + geode::load_one( geode::load_brep( brep_file ), brep_file ); + const auto reference_section = geode::load_one( + geode::load_section( section_file ), section_file ); + const std::vector< std::string > variables{ "TMPDIR", "TMP", "TEMP" }; + std::vector< std::optional< std::string > > old_values; + for( const auto& variable : variables ) + { + const auto* value = std::getenv( variable.c_str() ); + old_values.emplace_back( + value ? std::optional< std::string >{ value } : std::nullopt ); + } + const auto not_a_directory = + std::filesystem::absolute( "temporary_directory_file" ); + { + std::ofstream file{ not_a_directory }; + file << "not a directory"; + } + const auto empty_directory = + std::filesystem::absolute( "empty_temporary_directory" ); + std::filesystem::remove_all( empty_directory ); + std::filesystem::create_directories( empty_directory ); + for( const auto& temporary : { not_a_directory, empty_directory } ) + { + for( const auto& variable : variables ) + { + set_environment( variable.c_str(), temporary.u8string() ); + } + const auto brep = + geode::load_one( geode::load_brep( brep_file ), brep_file ); + check_same_brep( brep, reference_brep, brep_file ); + const auto section = geode::load_one( + geode::load_section( section_file ), section_file ); + check_same_components( section, reference_section, section_file ); + } + for( const auto i : geode::Indices{ variables } ) + { + set_environment( variables[i].c_str(), old_values[i] ); + } + geode::OpenGeodeModelException::test( + std::filesystem::is_empty( empty_directory ), + "Loading a model created files in the temporary directory" ); + std::filesystem::remove( not_a_directory ); + std::filesystem::remove_all( empty_directory ); + } + + std::string read_file( const std::string& filename ) + { + const auto content = geode::detail::map_file_content( filename ); + geode::OpenGeodeModelException::test( + content.has_value(), "Cannot read ", filename ); + return { content->span().data(), content->span().size() }; + } + + /*! + * Flip a byte in the middle of the data of an entry of a stored archive. + */ + void corrupt_entry( + const std::string& archive_file, const std::string& name ) + { + const auto size = [&] { + const geode::detail::ArchiveInputFiles files{ archive_file }; + return files.content( name ).span().size(); + }(); + auto archive = read_file( archive_file ); + // Find the local header of the entry + const std::string signature{ "PK\x03\x04" }; + auto header = archive.find( signature ); + const auto read_uint16 = [&archive]( size_t position ) { + return static_cast< size_t >( + static_cast< unsigned char >( archive[position] ) + + 256U + * static_cast< unsigned char >( archive[position + 1] ) ); + }; + while( + header != std::string::npos + && !( read_uint16( header + 26 ) == name.size() + && archive.compare( header + 30, name.size(), name ) == 0 ) ) + { + header = archive.find( signature, header + 1 ); + } + geode::OpenGeodeModelException::test( + header != std::string::npos, "Entry ", name, " not found" ); + const auto name_position = header + 30; + const auto extra_length = read_uint16( header + 28 ); + const auto data = name_position + name.size() + extra_length; + archive[data + size / 2] = + static_cast< char >( ~archive[data + size / 2] ); + std::ofstream file{ std::filesystem::u8path( archive_file ), + std::ios::binary }; + file.write( + archive.data(), static_cast< std::streamsize >( archive.size() ) ); + } + + void test_corrupted_entries() + { + const auto source = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); + std::string mesh_entry; + { + const geode::detail::ArchiveInputFiles files{ source }; + for( const auto& name : files.names() ) + { + if( absl::StartsWith( name, "Surface" ) ) + { + mesh_entry = name; + break; + } + } + } + for( const auto& entry : { mesh_entry, std::string{ "vertices" }, + std::string{ "surfaces" } } ) + { + const std::string corrupted{ "corrupted_entry.og_brep" }; + std::filesystem::copy_file( source, corrupted, + std::filesystem::copy_options::overwrite_existing ); + corrupt_entry( corrupted, entry ); + bool thrown{ false }; + try + { + geode_unused( geode::load_brep( corrupted ) ); + } + catch( const geode::OpenGeodeException& exception ) + { + thrown = true; + geode::OpenGeodeModelException::test( + exception.type() == geode::OpenGeodeException::TYPE::data + && absl::StrContains( exception.what(), + absl::StrCat( corrupted, "/", entry ) ) + && absl::StrContains( exception.what(), "CRC" ), + "Corrupted entry ", entry, + ": wrong error: ", exception.what() ); + } + geode::OpenGeodeModelException::test( + thrown, "Corrupted entry ", entry, " was not detected" ); + std::filesystem::remove( corrupted ); + } + } +} // namespace + +void test() +{ + geode::OpenGeodeModelLibrary::initialize(); + test_data_files(); + test_no_temporary_directory(); + test_corrupted_entries(); +} + +OPENGEODE_TEST( "model-archive-input" ) From 5ba0e5cff5284fd5c72bc325eb41595c4aa0ad14 Mon Sep 17 00:00:00 2001 From: BotellaA <3213882+BotellaA@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:25:22 +0000 Subject: [PATCH 6/8] Apply prepare changes --- tests/basic/test-attribute.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/basic/test-attribute.cpp b/tests/basic/test-attribute.cpp index f8e123bf5..7eeefe613 100644 --- a/tests/basic/test-attribute.cpp +++ b/tests/basic/test-attribute.cpp @@ -30,8 +30,8 @@ #include #include #include -#include #include +#include #include #include From b522a2ea8c3f6f7a1861a8e45284cd5ddd7104e5 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 19:57:13 +0100 Subject: [PATCH 7/8] fix(CMake): tests do not link minizip-ng minizip-ng is only exported by static OpenGeode builds, so the tests configured against a shared install could not find MINIZIP::minizip-ng. DEFLATE archives are now pre-generated data files (Python zipfile, ZIP_DEFLATED); stored archives are written by the tests themselves or by geode::ZipFile. Co-Authored-By: Claude Opus 5.5 --- tests/basic/CMakeLists.txt | 2 - tests/basic/test-input-files.cpp | 141 +++++++++++++++------ tests/basic/test-zip-file.cpp | 111 ++++++++-------- tests/data/input_files_deflate.zip | Bin 0 -> 24196 bytes tests/data/layers_deflate.og_brep | Bin 0 -> 27714 bytes tests/mesh/CMakeLists.txt | 1 - tests/mesh/test-mesh-input-bytes.cpp | 33 ++--- tests/model/CMakeLists.txt | 1 - tests/model/test-model-deflate-archive.cpp | 58 +-------- 9 files changed, 169 insertions(+), 178 deletions(-) create mode 100644 tests/data/input_files_deflate.zip create mode 100644 tests/data/layers_deflate.og_brep diff --git a/tests/basic/CMakeLists.txt b/tests/basic/CMakeLists.txt index 38cbe1d96..b0a312242 100644 --- a/tests/basic/CMakeLists.txt +++ b/tests/basic/CMakeLists.txt @@ -75,7 +75,6 @@ add_geode_test( DEPENDENCIES Async++ ${PROJECT_NAME}::basic - MINIZIP::minizip-ng ) add_geode_test( SOURCE "test-logger.cpp" @@ -117,7 +116,6 @@ add_geode_test( SOURCE "test-zip-file.cpp" DEPENDENCIES ${PROJECT_NAME}::basic - MINIZIP::minizip-ng ) if(UNIX AND NOT APPLE AND BUILD_SHARED_LIBS AND CMAKE_NM) add_test( diff --git a/tests/basic/test-input-files.cpp b/tests/basic/test-input-files.cpp index e9e9f3a05..474ba38b4 100644 --- a/tests/basic/test-input-files.cpp +++ b/tests/basic/test-input-files.cpp @@ -23,7 +23,6 @@ #include #include -#include #include #include #include @@ -37,11 +36,6 @@ #include #include -#include -#include -#include -#include - #include #include #include @@ -66,31 +60,96 @@ void write_file( const std::filesystem::path& file, std::string_view content ) stream.good(), "Cannot write file ", file.u8string() ); } -void write_zip( - const std::string& zip, const Entries& entries, uint16_t method ) +void append_uint( std::string& data, uint32_t value, size_t size ) { - void* writer = mz_zip_writer_create(); - mz_zip_writer_set_compress_method( writer, method ); - auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); - for( const auto& [name, content] : entries ) + for( const auto i : geode::Range{ size } ) + { + data.push_back( static_cast< char >( ( value >> ( 8 * i ) ) & 0xFF ) ); + } +} + +uint32_t crc32( std::string_view content ) +{ + uint32_t crc{ 0xFFFFFFFF }; + for( const auto byte : content ) { - if( status != MZ_OK ) + crc ^= static_cast< unsigned char >( byte ); + for( const auto bit : geode::Range{ 8 } ) { - break; + geode_unused( bit ); + crc = ( crc >> 1 ) ^ ( 0xEDB88320 & ( 0 - ( crc & 1 ) ) ); } - mz_zip_file info{}; - info.filename = name.c_str(); - info.compression_method = method; - info.flag = MZ_ZIP_FLAG_UTF8; - info.modified_date = std::time( nullptr ); - status = mz_zip_writer_add_buffer( writer, content.data(), - static_cast< int32_t >( content.size() ), &info ); } - const auto close_status = mz_zip_writer_close( writer ); - mz_zip_writer_delete( &writer ); - geode::OpenGeodeBasicException::test( - status == MZ_OK && close_status == MZ_OK, "Cannot write zip (", status, - ", ", close_status, ")" ); + return ~crc; +} + +/*! + * Write a zip archive whose entries are stored (not compressed). + */ +void write_stored_zip( const std::string& zip, const Entries& entries ) +{ + std::string archive; + std::string central_directory; + for( const auto& [name, content] : entries ) + { + const auto offset = static_cast< uint32_t >( archive.size() ); + const auto crc = crc32( content ); + const auto size = static_cast< uint32_t >( content.size() ); + const auto name_size = static_cast< uint32_t >( name.size() ); + append_uint( archive, 0x04034b50, 4 ); // local header signature + append_uint( archive, 20, 2 ); // version needed + append_uint( archive, 0, 2 ); // flags + append_uint( archive, 0, 2 ); // method: store + append_uint( archive, 0, 2 ); // time + append_uint( archive, 0x21, 2 ); // date: 1980-01-01 + append_uint( archive, crc, 4 ); + append_uint( archive, size, 4 ); // compressed size + append_uint( archive, size, 4 ); // uncompressed size + append_uint( archive, name_size, 2 ); + append_uint( archive, 0, 2 ); // extra field length + absl::StrAppend( &archive, name, content ); + append_uint( central_directory, 0x02014b50, 4 ); + append_uint( central_directory, 20, 2 ); // version made by + append_uint( central_directory, 20, 2 ); // version needed + append_uint( central_directory, 0, 2 ); // flags + append_uint( central_directory, 0, 2 ); // method: store + append_uint( central_directory, 0, 2 ); // time + append_uint( central_directory, 0x21, 2 ); // date: 1980-01-01 + append_uint( central_directory, crc, 4 ); + append_uint( central_directory, size, 4 ); // compressed size + append_uint( central_directory, size, 4 ); // uncompressed size + append_uint( central_directory, name_size, 2 ); + append_uint( central_directory, 0, 2 ); // extra field length + append_uint( central_directory, 0, 2 ); // comment length + append_uint( central_directory, 0, 2 ); // disk number + append_uint( central_directory, 0, 2 ); // internal attributes + append_uint( central_directory, 0, 4 ); // external attributes + append_uint( central_directory, offset, 4 ); // local header offset + absl::StrAppend( ¢ral_directory, name ); + } + const auto central_directory_offset = + static_cast< uint32_t >( archive.size() ); + const auto nb_entries = static_cast< uint32_t >( entries.size() ); + absl::StrAppend( &archive, central_directory ); + append_uint( archive, 0x06054b50, 4 ); // end of central directory + append_uint( archive, 0, 2 ); // disk number + append_uint( archive, 0, 2 ); // disk of the central directory + append_uint( archive, nb_entries, 2 ); // entries on this disk + append_uint( archive, nb_entries, 2 ); // entries + append_uint( + archive, static_cast< uint32_t >( central_directory.size() ), 4 ); + append_uint( archive, central_directory_offset, 4 ); + append_uint( archive, 0, 2 ); // comment length + write_file( zip, archive ); +} + +/*! + * Archive written by Python zipfile with ZIP_DEFLATED, containing the + * test_entries() in the same order. + */ +std::string deflate_zip() +{ + return absl::StrCat( geode::DATA_PATH, "input_files_deflate.zip" ); } Entries test_entries() @@ -235,11 +294,10 @@ void test_directory_input_files() std::filesystem::remove_all( directory ); } -void test_archive_input_files( uint16_t method, std::string_view test_name ) +void test_archive_input_files( + const std::string& zip, std::string_view test_name ) { - const auto zip = absl::StrCat( "input_files_", method, ".zip" ); const auto entries = test_entries(); - write_zip( zip, entries, method ); const geode::detail::ArchiveInputFiles files{ zip }; check_files_content( files, entries, test_name ); std::vector< std::string > expected_names; @@ -267,6 +325,13 @@ void test_archive_input_files( uint16_t method, std::string_view test_name ) geode::OpenGeodeBasicException::test( task.get(), test_name, ": wrong concurrent content" ); } +} + +void test_stored_archive_input_files() +{ + const std::string zip{ "input_files_stored.zip" }; + write_stored_zip( zip, test_entries() ); + test_archive_input_files( zip, "[ArchiveInputFiles] stored" ); std::filesystem::remove( zip ); } @@ -282,7 +347,7 @@ void test_corrupted_entry() { const std::string zip{ "corrupted_entry.zip" }; const auto entries = test_entries(); - write_zip( zip, entries, MZ_COMPRESS_METHOD_STORE ); + write_stored_zip( zip, entries ); auto archive = read_file( zip ); // Flip one byte in the middle of the stored text entry const auto position = archive.find( "line 5000 " ); @@ -348,9 +413,7 @@ size_t central_header( const std::string& archive, std::string_view name ) void test_corrupted_deflate_stream() { const std::string zip{ "corrupted_deflate.zip" }; - const auto entries = test_entries(); - write_zip( zip, entries, MZ_COMPRESS_METHOD_DEFLATE ); - auto archive = read_file( zip ); + auto archive = read_file( deflate_zip() ); // First entry: its local header is at the start of the archive geode::OpenGeodeBasicException::test( archive.compare( 30, 8, "text.txt" ) == 0, @@ -376,9 +439,7 @@ void test_corrupted_deflate_stream() void test_truncated_entry() { const std::string zip{ "truncated_entry.zip" }; - const auto entries = test_entries(); - write_zip( zip, entries, MZ_COMPRESS_METHOD_DEFLATE ); - auto archive = read_file( zip ); + auto archive = read_file( deflate_zip() ); const auto archive_size = static_cast< uint32_t >( archive.size() ); // Local header of "small" beyond the end of the archive write_uint( archive, central_header( archive, "small" ) + 42, 4, @@ -417,7 +478,7 @@ void test_truncated_entry() void test_unsafe_entry() { const std::string zip{ "unsafe_entry.zip" }; - write_zip( zip, { { "../outside", "abc" } }, MZ_COMPRESS_METHOD_STORE ); + write_stored_zip( zip, { { "../outside", "abc" } } ); check_data_error( [&zip] { const geode::detail::ArchiveInputFiles files{ zip }; @@ -523,10 +584,8 @@ void test() { test_mapped_file(); test_directory_input_files(); - test_archive_input_files( - MZ_COMPRESS_METHOD_STORE, "[ArchiveInputFiles] stored" ); - test_archive_input_files( - MZ_COMPRESS_METHOD_DEFLATE, "[ArchiveInputFiles] deflated" ); + test_stored_archive_input_files(); + test_archive_input_files( deflate_zip(), "[ArchiveInputFiles] deflated" ); test_corrupted_entry(); test_corrupted_deflate_stream(); test_truncated_entry(); diff --git a/tests/basic/test-zip-file.cpp b/tests/basic/test-zip-file.cpp index ca8fc69b5..5c6203624 100644 --- a/tests/basic/test-zip-file.cpp +++ b/tests/basic/test-zip-file.cpp @@ -22,7 +22,6 @@ */ #include -#include #include #include #include @@ -32,11 +31,6 @@ #include -#include -#include -#include -#include - #include #include #include @@ -46,64 +40,67 @@ using ZipEntries = std::vector< std::pair< std::string, std::string > >; -void write_deflate_zip( const std::string& zip, const ZipEntries& entries ) +std::string read_file( const std::filesystem::path& file ) { - void* writer = mz_zip_writer_create(); - mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_DEFLATE ); - auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); - for( const auto& [name, content] : entries ) - { - if( status != MZ_OK ) - { - break; - } - mz_zip_file info{}; - info.filename = name.c_str(); - info.compression_method = MZ_COMPRESS_METHOD_DEFLATE; - info.flag = MZ_ZIP_FLAG_UTF8; - info.modified_date = std::time( nullptr ); - status = mz_zip_writer_add_buffer( writer, content.data(), - static_cast< int32_t >( content.size() ), &info ); - } - const auto close_status = mz_zip_writer_close( writer ); - mz_zip_writer_delete( &writer ); + std::ifstream stream{ file, std::ios::binary }; geode::OpenGeodeBasicException::test( - status == MZ_OK && close_status == MZ_OK, "Cannot write DEFLATE zip (", - status, ", ", close_status, ")" ); + stream.is_open(), "Cannot open file ", file.u8string() ); + return { std::istreambuf_iterator< char >{ stream }, + std::istreambuf_iterator< char >{} }; } -void check_entries_are_deflated( const std::string& zip ) +uint32_t read_uint( const std::string& data, size_t offset, size_t size ) { - void* reader = mz_zip_reader_create(); - geode::OpenGeodeBasicException::test( - mz_zip_reader_open_file( reader, zip.c_str() ) == MZ_OK, - "Cannot open DEFLATE zip" ); - auto status = mz_zip_reader_goto_first_entry( reader ); - while( status == MZ_OK ) + uint32_t value{ 0 }; + for( const auto i : geode::Range{ size } ) { - mz_zip_file* info = nullptr; - geode::OpenGeodeBasicException::test( - mz_zip_reader_entry_get_info( reader, &info ) == MZ_OK, - "Cannot read DEFLATE zip entry" ); - geode::OpenGeodeBasicException::test( - info->compression_method == MZ_COMPRESS_METHOD_DEFLATE - && info->compressed_size < info->uncompressed_size, - "Zip entry ", info->filename, " is not DEFLATE-compressed" ); - status = mz_zip_reader_goto_next_entry( reader ); + value |= static_cast< uint32_t >( + static_cast< unsigned char >( data[offset + i] ) ) + << ( 8 * i ); } - mz_zip_reader_close( reader ); - mz_zip_reader_delete( &reader ); - geode::OpenGeodeBasicException::test( - status == MZ_END_OF_LIST, "Error while reading DEFLATE zip entries" ); + return value; } -std::string read_file( const std::filesystem::path& file ) +void check_entries_are_deflated( + const std::string& zip, const ZipEntries& entries ) { - std::ifstream stream{ file, std::ios::binary }; + const auto archive = read_file( zip ); + // End of central directory record (no archive comment) + constexpr size_t END_RECORD_SIZE{ 22 }; + const auto end_record = archive.size() - END_RECORD_SIZE; geode::OpenGeodeBasicException::test( - stream.is_open(), "Cannot open extracted file ", file.u8string() ); - return { std::istreambuf_iterator< char >{ stream }, - std::istreambuf_iterator< char >{} }; + archive.compare( end_record, 4, "PK\x05\x06" ) == 0, + "End of central directory not found in ", zip ); + const auto nb_entries = read_uint( archive, end_record + 10, 2 ); + size_t header = read_uint( archive, end_record + 16, 4 ); + geode::index_t nb_checked{ 0 }; + for( const auto entry : geode::Range{ nb_entries } ) + { + geode_unused( entry ); + geode::OpenGeodeBasicException::test( + archive.compare( header, 4, "PK\x01\x02" ) == 0, + "Invalid central directory header in ", zip ); + const auto name_length = read_uint( archive, header + 28, 2 ); + const auto name = archive.substr( header + 46, name_length ); + geode::OpenGeodeBasicException::test( + read_uint( archive, header + 10, 2 ) == 8, "Zip entry ", name, + " is not DEFLATE-compressed" ); + for( const auto& [entry_name, content] : entries ) + { + if( entry_name == name ) + { + geode::OpenGeodeBasicException::test( + read_uint( archive, header + 20, 4 ) + < read_uint( archive, header + 24, 4 ), + "Zip entry ", name, " is not DEFLATE-compressed" ); + nb_checked++; + } + } + header += 46 + name_length + read_uint( archive, header + 30, 2 ) + + read_uint( archive, header + 32, 2 ); + } + geode::OpenGeodeBasicException::test( nb_checked == entries.size(), + "Missing DEFLATE-compressed entries in ", zip ); } void test_unzip_deflate() @@ -120,9 +117,10 @@ void test_unzip_deflate() } const ZipEntries entries{ { "text.txt", text }, { "folder/binary.bin", binary } }; - const std::string zip{ "deflate.zip" }; - write_deflate_zip( zip, entries ); - check_entries_are_deflated( zip ); + // Written by Python zipfile with ZIP_DEFLATED + const auto zip = + absl::StrCat( geode::DATA_PATH, "input_files_deflate.zip" ); + check_entries_are_deflated( zip, entries ); const geode::UnzipFile unzip{ zip, geode::uuid{}.string() }; unzip.extract_all(); @@ -133,7 +131,6 @@ void test_unzip_deflate() read_file( directory / name ) == content, "Extracted entry ", name, " differs from the DEFLATE-compressed content" ); } - std::filesystem::remove( zip ); } void test() diff --git a/tests/data/input_files_deflate.zip b/tests/data/input_files_deflate.zip new file mode 100644 index 0000000000000000000000000000000000000000..3eaba2684d27c4902db9d48e9f08b662a9c92993 GIT binary patch literal 24196 zcmeHPeN2iXy~R=w)Co44-;u=3P+HP*<*At@7w_hV$Ed z&Ym-S{`$?{zjMZq_3rdAMNta*84yvMAEkLVf}-|z@@exdnDx$rK?~kl@LuVW&pW-e za{YH%pUvqp=#V0L#>zhRRM%ZkC0NbR_4gG%8yq$`dqc>73s|=+!{a(?mRvTS#|Atu z;Bo3aCp|4W9x20f@ua7@N$05ro{REyCdcEMW~-d$tejR=Iqm4toO2t@)f>#~HkeB{ zn7N#jxv%7$TwXT+fFrA-X?m?`d-L$g(z${0Nj-DIzAf9@*X?&HE8IOb$egjJ&GDn7 zsIG}=F=bxN3U^KYT+H~%Q6w}m4OboU8Iy9twC$sLaEYUc|M{qK6t#~*?opyC^U`(0 zofYnx`nfryI47*CZ0k_BN8anI@9CVd|CDV#;wbv5iE)}TTe3>ZXXanETv;XVsdLR4 zyK}TfL^BXSEapA1=1@O&#C-Bp!(8l6w_5{A5i`1^@_zR|K(JFdXpke zmA0H3KyOpzs{B__LG*4#xhic1HJHv;P=Wr5)RVMT;UAcmNU3RF@m!$)htyEISTQ{? z?L+Dr`kZ2Mp#Ms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;W@Z1O*dB;^trBBBc2`~fjhzA-2E@9C6 z=^6L{CJ&yRKqJ3W1Vo;mISOF%;CTcz@)DvT^7Kq60FwuI`qRkEih=t6!HQiDfNw-1;DxMhaMp-p)y2YMQ4z#PCmC^Qbw*8J6x0)7bG??8JfUvzh_=;Z2fgZ>$m;)HO zO5?zcUCMzT94nXu7z;|{AgBr6W;&3eVDey~C5`+lEf9HnV3%O>U>GBfyzttephoaB zV00nvnQOo^V7;IRYY6552JF!|)MH=M!%041||H!HEkxpjTi9U|bZ9 zK`;*V_Vl2nz~sSzBO3V-0}y$7;74HcU?dNXe5BzL@z8_o0W$!DZfFd2j6mzB2Z948 z4~DbQ$Q!I%vVMBNEno&<=n0L%XMn*kUJE@y6fk)(u7gJYtMQWc(}VH=GXUc+Xbg%? zmRd)8&=_D2U}yu4Lz(H4SD**z0A>KjBG4FYGh6x!^dJ+!9KfZ18VB$7;7z8Z@DC;r zE}+xM?=}aKr>C3_CJ(Ml)5!0)SSlZSs?=Z(;DRrW!(q!G5m)n #include #include #include @@ -34,17 +33,14 @@ #include #include -#include -#include -#include -#include - #include #include #include #include #include #include +#include +#include #include @@ -372,23 +368,18 @@ namespace const std::string& name, geode::ByteSpan content ) { - void* writer = mz_zip_writer_create(); - mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_STORE ); - auto status = mz_zip_writer_open_file( writer, zip.c_str(), 0, 0 ); - if( status == MZ_OK ) + const std::filesystem::path directory{ "path_only_zip_content" }; + std::filesystem::create_directories( directory ); + const auto file = directory / name; { - mz_zip_file info{}; - info.filename = name.c_str(); - info.compression_method = MZ_COMPRESS_METHOD_STORE; - info.flag = MZ_ZIP_FLAG_UTF8; - info.modified_date = std::time( nullptr ); - status = mz_zip_writer_add_buffer( writer, content.data(), - static_cast< int32_t >( content.size() ), &info ); + std::ofstream stream{ file, std::ios::binary }; + stream.write( content.data(), + static_cast< std::streamsize >( content.size() ) ); } - const auto close_status = mz_zip_writer_close( writer ); - mz_zip_writer_delete( &writer ); - geode::OpenGeodeMeshException::test( - status == MZ_OK && close_status == MZ_OK, "Cannot write zip" ); + geode::ZipFile archive{ zip, geode::uuid{}.string() }; + archive.archive_file( file.u8string() ); + archive.finalize(); + std::filesystem::remove_all( directory ); } void test_fallback_to_file() diff --git a/tests/model/CMakeLists.txt b/tests/model/CMakeLists.txt index 78f2ce21b..2643169ba 100644 --- a/tests/model/CMakeLists.txt +++ b/tests/model/CMakeLists.txt @@ -109,7 +109,6 @@ add_geode_test( ${PROJECT_NAME}::basic ${PROJECT_NAME}::mesh ${PROJECT_NAME}::model - MINIZIP::minizip-ng ) add_geode_test( SOURCE "test-model-component-filter.cpp" diff --git a/tests/model/test-model-deflate-archive.cpp b/tests/model/test-model-deflate-archive.cpp index 4badb7487..958b878db 100644 --- a/tests/model/test-model-deflate-archive.cpp +++ b/tests/model/test-model-deflate-archive.cpp @@ -21,18 +21,8 @@ * */ -#include -#include -#include -#include - #include -#include -#include -#include -#include - #include #include @@ -45,48 +35,6 @@ #include -void rezip_with_deflate( const std::string& input, const std::string& output ) -{ - void* reader = mz_zip_reader_create(); - geode::OpenGeodeModelException::test( - mz_zip_reader_open_file( reader, input.c_str() ) == MZ_OK, - "Cannot open ", input ); - void* writer = mz_zip_writer_create(); - mz_zip_writer_set_compress_method( writer, MZ_COMPRESS_METHOD_DEFLATE ); - auto write_status = mz_zip_writer_open_file( writer, output.c_str(), 0, 0 ); - auto status = mz_zip_reader_goto_first_entry( reader ); - geode::index_t nb_entries{ 0 }; - while( status == MZ_OK && write_status == MZ_OK ) - { - mz_zip_file* info = nullptr; - geode::OpenGeodeModelException::test( - mz_zip_reader_entry_get_info( reader, &info ) == MZ_OK, - "Cannot read entry of ", input ); - std::vector< uint8_t > buffer( - static_cast< size_t >( info->uncompressed_size ) ); - const auto length = static_cast< int32_t >( buffer.size() ); - geode::OpenGeodeModelException::test( - mz_zip_reader_entry_save_buffer( reader, buffer.data(), length ) - == MZ_OK, - "Cannot read entry ", info->filename, " of ", input ); - mz_zip_file deflated = *info; - deflated.compression_method = MZ_COMPRESS_METHOD_DEFLATE; - write_status = mz_zip_writer_add_buffer( - writer, buffer.data(), length, &deflated ); - nb_entries++; - status = mz_zip_reader_goto_next_entry( reader ); - } - const auto close_status = mz_zip_writer_close( writer ); - mz_zip_writer_delete( &writer ); - mz_zip_reader_close( reader ); - mz_zip_reader_delete( &reader ); - geode::OpenGeodeModelException::test( - status == MZ_END_OF_LIST && write_status == MZ_OK - && close_status == MZ_OK && nb_entries > 0, - "Cannot re-zip ", input, " with DEFLATE (", status, ", ", write_status, - ", ", close_status, ")" ); -} - void check_same_brep( const geode::BRep& brep, const geode::BRep& reference ) { geode::OpenGeodeModelException::test( @@ -118,13 +66,13 @@ void test() { geode::OpenGeodeModelLibrary::initialize(); const auto filename = absl::StrCat( geode::DATA_PATH, "layers.og_brep" ); - const std::string deflated{ "layers_deflate.og_brep" }; - rezip_with_deflate( filename, deflated ); + // layers.og_brep re-zipped by Python zipfile with ZIP_DEFLATED + const auto deflated = + absl::StrCat( geode::DATA_PATH, "layers_deflate.og_brep" ); const auto reference = geode::load_one( geode::load_brep( filename ), filename ); const auto brep = geode::load_one( geode::load_brep( deflated ), deflated ); check_same_brep( brep, reference ); - std::filesystem::remove( deflated ); } OPENGEODE_TEST( "model-deflate-archive" ) From a889d9aed2643ec0ea31403b17672572a750e045 Mon Sep 17 00:00:00 2001 From: Arnaud Botella Date: Mon, 23 Nov 2026 20:29:14 +0100 Subject: [PATCH 8/8] fix(Input): byte reading interface does not need the complete object type Input::read_bytes fills a vector given by reference and returns false when the input can only read files, instead of returning std::optional of the objects: MSVC instantiates the inline virtual body with the class, which needed the complete mesh type in headers that only forward declare it. Co-Authored-By: Claude Opus 5.5 --- .../geode/basic/detail/geode_input_impl.hpp | 5 +- include/geode/basic/input.hpp | 13 ++-- .../io/geode/geode_bitsery_raster_input.hpp | 7 ++- .../io/geode/geode_bitsery_mesh_input.hpp | 8 ++- .../geode/geode_light_regular_grid_input.hpp | 8 +-- tests/mesh/CMakeLists.txt | 6 ++ tests/mesh/test-mesh-input-bytes.cpp | 32 +++++----- .../test-mesh-input-forward-declaration.cpp | 60 +++++++++++++++++++ 8 files changed, 108 insertions(+), 31 deletions(-) create mode 100644 tests/mesh/test-mesh-input-forward-declaration.cpp diff --git a/include/geode/basic/detail/geode_input_impl.hpp b/include/geode/basic/detail/geode_input_impl.hpp index af5bfd45e..4eecea6a4 100644 --- a/include/geode/basic/detail/geode_input_impl.hpp +++ b/include/geode/basic/detail/geode_input_impl.hpp @@ -107,9 +107,10 @@ namespace geode::detail auto objects = [&] { const auto content = files.content( name ); auto input = Factory::create( extension, location ); - if( auto from_bytes = input->read_bytes( content.span(), args... ) ) + std::vector< typename Factory::BaseClass::InputData > from_bytes; + if( input->read_bytes( content.span(), from_bytes, args... ) ) { - return std::move( from_bytes.value() ); + return from_bytes; } if( const auto path = files.path( name ) ) { diff --git a/include/geode/basic/input.hpp b/include/geode/basic/input.hpp index c5204ee50..fd2083008 100644 --- a/include/geode/basic/input.hpp +++ b/include/geode/basic/input.hpp @@ -84,13 +84,16 @@ namespace geode * Read the objects from the content of the file, already in memory * (e.g. an entry of an archive), instead of opening the file: the * filename only names the content in messages. - * @return std::nullopt if this input can only read files: the caller - * then calls read() on a file holding the content. + * @param[out] objects Receives the objects read (only when returning + * true). + * @return false if this input can only read files: the caller then + * calls read() on a file holding the content. */ - [[nodiscard]] virtual std::optional< std::vector< Object > > read_bytes( - ByteSpan /*content*/, const Args&... /*args*/ ) + [[nodiscard]] virtual bool read_bytes( ByteSpan /*content*/, + std::vector< Object >& /*objects*/, + const Args&... /*args*/ ) { - return std::nullopt; + return false; } ~Input() diff --git a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp index d9fa9ded3..3852efe49 100644 --- a/include/geode/image/io/geode/geode_bitsery_raster_input.hpp +++ b/include/geode/image/io/geode/geode_bitsery_raster_input.hpp @@ -51,10 +51,11 @@ namespace geode return read_image( content->span() ); } - [[nodiscard]] std::optional< std::vector< RasterImage< dimension > > > - read_bytes( ByteSpan content ) final + [[nodiscard]] bool read_bytes( ByteSpan content, + std::vector< RasterImage< dimension > >& images ) final { - return read_image( content ); + images = read_image( content ); + return true; } AdditionalFiles additional_files() const final diff --git a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp index 39125cdca..a087bf572 100644 --- a/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp +++ b/include/geode/mesh/io/geode/geode_bitsery_mesh_input.hpp @@ -46,10 +46,12 @@ return read_mesh( content->span() ); \ } \ \ - [[nodiscard]] std::optional< std::vector< std::unique_ptr< Mesh > > > \ - read_bytes( geode::ByteSpan content, const MeshImpl& /*impl*/ ) final \ + [[nodiscard]] bool read_bytes( geode::ByteSpan content, \ + std::vector< std::unique_ptr< Mesh > >& meshes, \ + const MeshImpl& /*impl*/ ) final \ { \ - return read_mesh( content ); \ + meshes = read_mesh( content ); \ + return true; \ } \ \ private: \ diff --git a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp index f37d6930b..f70320df7 100644 --- a/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp +++ b/include/geode/mesh/io/geode/geode_light_regular_grid_input.hpp @@ -65,11 +65,11 @@ namespace geode return read_grid( content->span() ); } - [[nodiscard]] std::optional< - std::vector< LightRegularGrid< dimension > > > - read_bytes( ByteSpan content ) override + [[nodiscard]] bool read_bytes( ByteSpan content, + std::vector< LightRegularGrid< dimension > >& grids ) override { - return read_grid( content ); + grids = read_grid( content ); + return true; } AdditionalFiles additional_files() const override diff --git a/tests/mesh/CMakeLists.txt b/tests/mesh/CMakeLists.txt index 0696142ef..1a00675a5 100644 --- a/tests/mesh/CMakeLists.txt +++ b/tests/mesh/CMakeLists.txt @@ -148,6 +148,12 @@ add_geode_test( ${PROJECT_NAME}::image ${PROJECT_NAME}::mesh ) +add_geode_test( + SOURCE "test-mesh-input-forward-declaration.cpp" + DEPENDENCIES + ${PROJECT_NAME}::basic + ${PROJECT_NAME}::mesh +) add_geode_test( SOURCE "test-mesh-corrupted-files.cpp" DEPENDENCIES diff --git a/tests/mesh/test-mesh-input-bytes.cpp b/tests/mesh/test-mesh-input-bytes.cpp index 35f9f20d3..ecf5741d3 100644 --- a/tests/mesh/test-mesh-input-bytes.cpp +++ b/tests/mesh/test-mesh-input-bytes.cpp @@ -219,13 +219,13 @@ namespace const auto reference = describe( *by_path ); const auto bytes = read_whole_file( filename ); - auto from_bytes = Factory::create( extension, "name_only" ) - ->read_bytes( bytes.span(), impl ); - geode::OpenGeodeMeshException::test( from_bytes.has_value(), + std::vector< typename Factory::BaseClass::InputData > from_bytes; + geode::OpenGeodeMeshException::test( + Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span(), from_bytes, impl ), "Native input of ", filename, " cannot read bytes" ); geode::OpenGeodeMeshException::test( - describe( - *geode::load_one( std::move( from_bytes.value() ), filename ) ) + describe( *geode::load_one( std::move( from_bytes ), filename ) ) == reference, "Mesh read from bytes differs from the file ", filename ); @@ -249,13 +249,13 @@ namespace const auto by_path = geode::load_one( Factory::create( extension, filename )->read(), filename ); const auto bytes = read_whole_file( filename ); - auto from_bytes = Factory::create( extension, "name_only" ) - ->read_bytes( bytes.span() ); - geode::OpenGeodeMeshException::test( from_bytes.has_value(), + std::vector< typename Factory::BaseClass::InputData > from_bytes; + geode::OpenGeodeMeshException::test( + Factory::create( extension, "name_only" ) + ->read_bytes( bytes.span(), from_bytes ), "Native input of ", filename, " cannot read bytes" ); geode::OpenGeodeMeshException::test( - describe( - geode::load_one( std::move( from_bytes.value() ), filename ) ) + describe( geode::load_one( std::move( from_bytes ), filename ) ) == describe( by_path ), "Object read from bytes differs from the file ", filename ); } @@ -336,10 +336,14 @@ namespace std::filesystem::u8path( geode::to_string( filename() ) ) ), "[PathOnlyInput] File ", filename(), " does not exist" ); const auto bytes = read_whole_file( filename() ); - auto meshes = geode::TriangulatedSurfaceInputFactory3D::create( - "og_tsf3d", filename() ) - ->read_bytes( bytes.span(), impl ); - return std::move( meshes.value() ); + std::vector< std::unique_ptr< geode::TriangulatedSurface3D > > + meshes; + geode::OpenGeodeMeshException::test( + geode::TriangulatedSurfaceInputFactory3D::create( + "og_tsf3d", filename() ) + ->read_bytes( bytes.span(), meshes, impl ), + "[PathOnlyInput] Cannot read bytes of ", filename() ); + return meshes; } geode::AdditionalFiles additional_files() const final diff --git a/tests/mesh/test-mesh-input-forward-declaration.cpp b/tests/mesh/test-mesh-input-forward-declaration.cpp new file mode 100644 index 000000000..f209eb1e9 --- /dev/null +++ b/tests/mesh/test-mesh-input-forward-declaration.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2019 - 2026 Geode-solutions + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +/* + * The input headers only forward declare the meshes: instantiating every + * member of their Input base class (as MSVC does for the virtual functions) + * must not need the complete mesh type. + */ +#include +#include +#include +#include +#include +#include +#include + +#include + +template class geode::Input< std::unique_ptr< geode::EdgedCurve< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::HybridSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PointSet< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PolygonalSurface< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::PolyhedralSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::TetrahedralSolid< 3 > >, + geode::MeshImpl >; +template class geode::Input< std::unique_ptr< geode::TriangulatedSurface< 3 > >, + geode::MeshImpl >; + +void test() +{ + geode::Logger::info( + "Input base classes instantiated with forward declared meshes" ); +} + +OPENGEODE_TEST( "mesh-input-forward-declaration" )