Change LoadModelFromString to return a smart pointer, add MakeData, and update tests to have C++ RAII clean up model and data.

PiperOrigin-RevId: 935980153
Change-Id: I41d25bfab4935494dc984168820cb7cad123cadf
This commit is contained in:
Kyle Bayes
2026-06-22 04:18:29 -07:00
committed by Copybara-Service
parent 34d142ee50
commit 1490336955
39 changed files with 4616 additions and 5908 deletions
+19 -1
View File
@@ -25,6 +25,7 @@
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -39,6 +40,20 @@ MJAPI mjfLogHandler _mjPRIVATE_setTlsLogHandler(mjfLogHandler handler);
namespace mujoco {
struct MjModelDeleter {
void operator()(mjModel* m) const {
mj_deleteModel(m);
}
};
using MjModelPtr = std::unique_ptr<mjModel, MjModelDeleter>;
struct MjDataDeleter {
void operator()(mjData* d) const {
mj_deleteData(d);
}
};
using MjDataPtr = std::unique_ptr<mjData, MjDataDeleter>;
// Runtime scale factor for test tolerances, controlled by MJTOL_SCALE env var.
// Set MJTOL_SCALE=0 to run tests with zero tolerance and see actual residuals.
inline mjtNum MjTolScale() {
@@ -189,9 +204,12 @@ const std::string GetModelPath(std::string_view path);
// Returns a newly-allocated mjModel, loaded from the contents of xml.
// On failure returns nullptr and populates the error array if present.
mjModel* LoadModelFromString(std::string_view xml, char* error = nullptr,
MjModelPtr LoadModelFromString(std::string_view xml, char* error = nullptr,
int error_size = 0, mjVFS* vfs = nullptr);
// Returns a newly-allocated mjData, initialized using model.
MjDataPtr MakeData(const MjModelPtr& model);
// Returns a newly-allocated mjModel, loaded from the contents in model_path.
// On failure it asserts that model is null.
mjModel* LoadModelFromPath(const char* model_path);