forked from URLab-Sim/UnrealRoboticsLab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMjSpecWrapper.cpp
More file actions
397 lines (322 loc) · 13.1 KB
/
Copy pathMjSpecWrapper.cpp
File metadata and controls
397 lines (322 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Copyright (c) 2026 Jonathan Embley-Riches. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// --- LEGAL DISCLAIMER ---
// UnrealRoboticsLab is an independent software plugin. It is NOT affiliated with,
// endorsed by, or sponsored by Epic Games, Inc. "Unreal" and "Unreal Engine" are
// trademarks or registered trademarks of Epic Games, Inc. in the US and elsewhere.
//
// This plugin incorporates third-party software: MuJoCo (Apache 2.0),
// CoACD (MIT), and libzmq (MPL 2.0). See ThirdPartyNotices.txt for details.
#include "MuJoCo/Core/Spec/MjSpecWrapper.h"
#include "Utils/URLabLogging.h"
#include "MuJoCo/Components/Defaults/MjDefault.h"
#include "MuJoCo/Components/Geometry/MjGeom.h"
#include "MuJoCo/Core/MjArticulation.h"
#include "MuJoCo/Utils/MjUtils.h"
#include "PhysicsEngine/BodySetup.h"
#include "Misc/Paths.h"
#include "Utils/IO.h"
#include "Utils/MeshUtils.h"
#include "Chaos/TriangleMeshImplicitObject.h"
#include "MuJoCo/Components/Bodies/MjBody.h"
FMujocoSpecWrapper::FMujocoSpecWrapper(mjSpec* InSpec, mjVFS* InVFS)
: Spec(InSpec), VFS(InVFS)
{
}
mjsBody* FMujocoSpecWrapper::CreateBody(const FString& Name, const FString& ParentName, const FTransform& WorldTransform)
{
mjsBody* ParentBody = mjs_findBody(Spec, TCHAR_TO_UTF8(*ParentName));
if (!ParentBody) {
ParentBody = mjs_findBody(Spec, "world");
}
mjsBody* NewBody = mjs_addBody(ParentBody, nullptr);
mjs_setName(NewBody->element, TCHAR_TO_UTF8(*Name));
MjUtils::UEToMjPosition(WorldTransform.GetLocation(), NewBody->pos);
MjUtils::UEToMjRotation(WorldTransform.GetRotation(), NewBody->quat);
CreatedBodyNames.Add(Name);
return NewBody;
}
mjsBody* FMujocoSpecWrapper::CreateBody(const FString& Name, mjsBody* ParentBody, const FTransform& WorldTransform)
{
if (!ParentBody) {
ParentBody = mjs_findBody(Spec, "world");
}
mjsBody* NewBody = mjs_addBody(ParentBody, nullptr);
mjs_setName(NewBody->element, TCHAR_TO_UTF8(*Name));
MjUtils::UEToMjPosition(WorldTransform.GetLocation(), NewBody->pos);
MjUtils::UEToMjRotation(WorldTransform.GetRotation(), NewBody->quat);
CreatedBodyNames.Add(Name);
return NewBody;
}
mjsFrame* FMujocoSpecWrapper::CreateFrame(const FString& Name, mjsBody* ParentBody, const FTransform& WorldTransform)
{
if (!ParentBody) {
ParentBody = mjs_findBody(Spec, "world");
}
mjsFrame* NewFrame = mjs_addFrame(ParentBody, nullptr);
mjs_setName(NewFrame->element, TCHAR_TO_UTF8(*Name));
MjUtils::UEToMjPosition(WorldTransform.GetLocation(), NewFrame->pos);
MjUtils::UEToMjRotation(WorldTransform.GetRotation(), NewFrame->quat);
return NewFrame;
}
FString FMujocoSpecWrapper::AddMeshAsset(const FString& MeshName, const FString& FilePath, const FVector& Scale)
{
FString UniqueMeshName = GetUniqueName(MeshName, mjOBJ_MESH, nullptr);
mjsMesh* MeshAsset = mjs_addMesh(Spec, nullptr);
mjs_setName(MeshAsset->element, TCHAR_TO_UTF8(*UniqueMeshName));
mjs_setString(MeshAsset->file, TCHAR_TO_UTF8(*FilePath));
MeshAsset->scale[0] = Scale.X;
MeshAsset->scale[1] = Scale.Y;
MeshAsset->scale[2] = Scale.Z;
FString Directory = FPaths::GetPath(FilePath);
FString FileName = FPaths::GetCleanFilename(FilePath);
UE_LOG(LogURLabWrapper, Log, TEXT("MuJoCo VFS: Loading %s from %s with name %s"), *FileName, *Directory, *UniqueMeshName);
int Result = mj_addFileVFS(VFS, TCHAR_TO_UTF8(*Directory), TCHAR_TO_UTF8(*FileName));
if (Result != 0) {
UE_LOG(LogURLabWrapper, Error, TEXT("MuJoCo VFS Error: Failed to load %s (Code %d)"), *FilePath, Result);
}
return UniqueMeshName;
}
mjsGeom* FMujocoSpecWrapper::AddPrimitiveGeom(mjsBody* Body, mjtGeom Type, const FVector& Size, const FVector4& RGBA, double Density)
{
if (!Body) return nullptr;
mjsGeom* Geom = mjs_addGeom(Body, nullptr);
Geom->type = Type;
Geom->size[0] = Size.X;
Geom->size[1] = Size.Y;
Geom->size[2] = Size.Z;
Geom->rgba[0] = RGBA.X;
Geom->rgba[1] = RGBA.Y;
Geom->rgba[2] = RGBA.Z;
Geom->rgba[3] = RGBA.W;
Geom->density = Density;
return Geom;
}
void FMujocoSpecWrapper::AddFreeJoint(mjsBody* Body, const FString& JointName)
{
if (!Body) return;
mjsJoint* Jnt = mjs_addJoint(Body, nullptr);
Jnt->type = mjJNT_FREE;
Jnt->pos[0] = 0.0;
Jnt->pos[1] = 0.0;
Jnt->pos[2] = 0.0;
Jnt->damping[0] = 0.1;
mjs_setName(Jnt->element, TCHAR_TO_UTF8(*JointName));
}
void FMujocoSpecWrapper::AddDefault(UMjDefault* DefaultComp)
{
if (!DefaultComp) return;
// TCHAR_TO_UTF8 returns a pointer into a temporary that dies at the end of
// the full expression. Storing it in a long-lived variable produces a
// dangling pointer; on Linux/clang the stack is reclaimed before the value
// is used and the class registers under a garbage name, breaking
// childclass / inheritance resolution. Use FTCHARToUTF8 with explicit
// function-scope lifetime instead.
FTCHARToUTF8 ClassNameConv(*DefaultComp->ClassName);
const char* ClassName = DefaultComp->ClassName.IsEmpty() ? nullptr : ClassNameConv.Get();
mjsDefault* parentDef = nullptr;
if (!DefaultComp->ParentClassName.IsEmpty())
{
FTCHARToUTF8 ParentNameConv(*DefaultComp->ParentClassName);
parentDef = mjs_findDefault(Spec, ParentNameConv.Get());
if (parentDef)
{
UE_LOG(LogURLabWrapper, Log, TEXT("[AddDefault] Linked Class '%s' to Parent '%s'"), *DefaultComp->ClassName, *DefaultComp->ParentClassName);
}
else
{
UE_LOG(LogURLabWrapper, Warning, TEXT("[AddDefault] Could not find Parent Class '%s' for '%s'"), *DefaultComp->ParentClassName, *DefaultComp->ClassName);
}
}
mjsDefault* def = nullptr;
if (DefaultComp->ClassName.IsEmpty() || DefaultComp->ClassName == TEXT("main"))
{
if (parentDef == nullptr)
{
// This is the root default — use the spec's built-in default
def = mjs_getSpecDefault(Spec);
UE_LOG(LogURLabWrapper, Log, TEXT("[AddDefault] Using root default for class '%s'"), *DefaultComp->ClassName);
}
else
{
def = mjs_addDefault(Spec, ClassName, parentDef);
}
}
else
{
def = mjs_addDefault(Spec, ClassName, parentDef);
}
if (!def) return;
DefaultComp->ExportTo(def);
}
TArray<BodyView> FMujocoSpecWrapper::ReconstructViews(const mjModel* m, mjData* d, const FString& Prefix)
{
TArray<BodyView> Views;
UE_LOG(LogURLabWrapper, Warning, TEXT("ReconstructViews: %i bodies, prefix='%s'"), CreatedBodyNames.Num(), *Prefix);
Views.Reserve(CreatedBodyNames.Num());
for (const FString& Name : CreatedBodyNames)
{
FString PrefixedName = Prefix + Name;
BodyView View = bind<BodyView>(m, d, TCHAR_TO_UTF8(*PrefixedName));
if (View.id >= 0)
{
Views.Add(View);
}
else
{
UE_LOG(LogURLabWrapper, Warning, TEXT("MuJoCo SpecWrapper: Failed to bind view for body '%s'."), *PrefixedName);
}
}
return Views;
}
TArray<FString> FMujocoSpecWrapper::PrepareMeshForMuJoCo(UStaticMeshComponent* SMC, bool bComplexMeshRequired, float CoACDThreshold)
{
TArray<FString> ResultNames;
if (!SMC || !SMC->GetStaticMesh()) return ResultNames;
UStaticMesh* Mesh = SMC->GetStaticMesh();
UBodySetup* BodySetup = Mesh->GetBodySetup();
if (!BodySetup || BodySetup->TriMeshGeometries.Num() == 0) return ResultNames;
FString MeshType = bComplexMeshRequired ? "Complex" : "Simple";
UStaticMesh* StaticMesh = Cast<UStaticMesh>(BodySetup->GetOuter());
FString BaseAssetName = StaticMesh ? StaticMesh->GetName() : SMC->GetName();
FVector Scale = SMC->GetComponentScale();
FString AssetName = BaseAssetName;
if (!Scale.Equals(FVector::OneVector, 0.001f))
{
AssetName = FString::Printf(TEXT("%s_s%.3f_%.3f_%.3f"), *BaseAssetName,
Scale.X, Scale.Y, Scale.Z);
}
FString SubDir = MeshCacheSubDir.IsEmpty() ? TEXT("Shared") : MeshCacheSubDir;
FString FilePath = FString::Printf(
TEXT("%s/URLab/ConvertedMeshes/%s/%s_%s.obj"),
*FPaths::ProjectSavedDir(),
*SubDir,
*MeshType,
*AssetName
);
FString FullFilePath = FPaths::ConvertRelativePathToFull(FilePath);
if (!bComplexMeshRequired)
{
if (mjs_findElement(Spec, mjOBJ_MESH, TCHAR_TO_UTF8(*AssetName)))
{
UE_LOG(LogURLabWrapper, Log, TEXT("Mesh Asset '%s' already exists in Spec. Reusing."), *AssetName);
ResultNames.Add(AssetName);
return ResultNames;
}
}
else
{
FString FirstSubMeshName = FString::Printf(TEXT("%s_0"), *AssetName);
if (mjs_findElement(Spec, mjOBJ_MESH, TCHAR_TO_UTF8(*FirstSubMeshName)))
{
UE_LOG(LogURLabWrapper, Log, TEXT("Complex Mesh Asset '%s' already exists in Spec. Reusing all parts."), *AssetName);
int i = 0;
while (true)
{
FString SubMeshName = FString::Printf(TEXT("%s_%d"), *AssetName, i);
if (mjs_findElement(Spec, mjOBJ_MESH, TCHAR_TO_UTF8(*SubMeshName)))
{
ResultNames.Add(SubMeshName);
i++;
}
else
{
break;
}
}
return ResultNames;
}
}
const int32 GeometryIndex = 0;
auto& TriGeom = BodySetup->TriMeshGeometries[GeometryIndex];
auto& Vertices = TriGeom.GetReference()->Particles().X();
FString CurrentHash;
bool bLargeIndices = TriGeom.GetReference()->Elements().RequiresLargeIndices();
if (bLargeIndices)
{
const auto& Indices = TriGeom.GetReference()->Elements().GetLargeIndexBuffer();
CurrentHash = IO::ComputeMeshHash(Vertices, Indices);
}
else
{
const auto& Indices = TriGeom.GetReference()->Elements().GetSmallIndexBuffer();
CurrentHash = IO::ComputeMeshHash(Vertices, Indices);
}
CurrentHash += bComplexMeshRequired ? TEXT("_complex") : TEXT("_simple");
if (bComplexMeshRequired)
{
CurrentHash += FString::Printf(TEXT("_t%.4f"), CoACDThreshold);
}
int MeshCount = IO::NumFilesExist(FullFilePath, bComplexMeshRequired);
if (MeshCount > 0)
{
FString CachedHash = IO::LoadMeshHash(FullFilePath);
if (CachedHash != CurrentHash)
{
UE_LOG(LogURLabWrapper, Log, TEXT("Mesh '%s' has changed (hash mismatch). Re-exporting."), *AssetName);
IO::DeleteMeshCache(FullFilePath, bComplexMeshRequired);
MeshCount = 0;
}
}
if (MeshCount == 0)
{
UE_LOG(LogURLabWrapper, Log, TEXT("Saving mesh geometry for: %s"), *AssetName);
if (bLargeIndices)
{
const auto& Indices = TriGeom.GetReference()->Elements().GetLargeIndexBuffer();
MeshCount = MeshUtils::SaveMesh(FullFilePath, Vertices, Indices, bComplexMeshRequired, CoACDThreshold);
}
else
{
const auto& Indices = TriGeom.GetReference()->Elements().GetSmallIndexBuffer();
MeshCount = MeshUtils::SaveMesh(FullFilePath, Vertices, Indices, bComplexMeshRequired, CoACDThreshold);
}
if (MeshCount == 0)
{
UE_LOG(LogURLabWrapper, Error, TEXT("MeshUtils::SaveMesh failed to save any meshes for %s."), *AssetName);
return ResultNames;
}
IO::SaveMeshHash(FullFilePath, CurrentHash);
}
FString BaseName = FPaths::GetBaseFilename(FilePath);
FString Directory = FPaths::GetPath(FilePath);
if (!bComplexMeshRequired)
{
FString sub_file_path = FString::Printf(TEXT("%s/%s.obj"), *Directory, *BaseName);
ResultNames.Add(AddMeshAsset(AssetName, sub_file_path, Scale));
}
else
{
for (int i = 0; i < MeshCount; i++)
{
FString sub_file_path = FString::Printf(TEXT("%s/%s_sub_%d.obj"), *Directory, *BaseName, i);
FString SubMeshName = FString::Printf(TEXT("%s_%d"), *AssetName, i);
ResultNames.Add(AddMeshAsset(SubMeshName, sub_file_path, Scale));
}
}
return ResultNames;
}
FString FMujocoSpecWrapper::GetUniqueName(const FString& BaseName, mjtObj Type, const AActor* ContextActor)
{
FString Candidate = BaseName;
FString TestName = Candidate;
int32 Counter = 0;
while (mjs_findElement(Spec, Type, TCHAR_TO_UTF8(*TestName)))
{
++Counter;
TestName = FString::Printf(TEXT("%s_%d"), *Candidate, Counter);
}
return TestName;
}