blob: baa32a7fcd460f8c73cd0df07dff5ce2fdbb78c2 [file] [edit]
diff --git a/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.cxx b/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.cxx
index fea83b3..6690f0d 100644
--- a/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.cxx
+++ b/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.cxx
@@ -51,6 +51,14 @@
#include <Standard_WarningsRestore.hxx>
#endif
+#ifdef __linux__
+ #include <sys/syscall.h>
+ #include <unistd.h>
+ #ifndef MFD_CLOEXEC
+ #define MFD_CLOEXEC 0x0001U
+ #endif
+#endif
+
IMPLEMENT_STANDARD_RTTIEXT(RWGltf_CafWriter, Standard_Transient)
namespace
@@ -252,7 +260,10 @@ RWGltf_CafWriter::RWGltf_CafWriter(const TCollection_AsciiString& theFile, bool
myToMergeFaces(false),
myToSplitIndices16(false),
myBinDataLen64(0),
- myToParallel(false)
+ myToParallel(false),
+ myFaceIndex(0),
+ myMeshIndex(0),
+ myBinFileFd(-1)
{
myCSTrsf.SetOutputLengthUnit(1.0); // meters
myCSTrsf.SetOutputCoordinateSystem(RWMesh_CoordinateSystem_glTF);
@@ -262,7 +273,25 @@ RWGltf_CafWriter::RWGltf_CafWriter(const TCollection_AsciiString& theFile, bool
OSD_Path::FileNameAndExtension(aFileName, aShortFileNameBase, aFileExt);
myBinFileNameShort = aShortFileNameBase + ".bin" + (myIsBinary ? ".tmp" : "");
- myBinFileNameFull = !aFolder.IsEmpty() ? aFolder + myBinFileNameShort : myBinFileNameShort;
+
+#ifdef __linux__
+ if (myIsBinary)
+ {
+ // Try memfd for zero filesystem writes
+ myBinFileFd = syscall(SYS_memfd_create, "glb_bin_tmp", MFD_CLOEXEC);
+ if (myBinFileFd >= 0)
+ {
+ myBinFileNameFull = TCollection_AsciiString("/proc/self/fd/")
+ + TCollection_AsciiString(myBinFileFd);
+ }
+ }
+#endif
+
+ if (myBinFileFd < 0)
+ {
+ // Fallback to filesystem temp file
+ myBinFileNameFull = !aFolder.IsEmpty() ? aFolder + myBinFileNameShort : myBinFileNameShort;
+ }
}
//=================================================================================================
@@ -270,6 +299,13 @@ RWGltf_CafWriter::RWGltf_CafWriter(const TCollection_AsciiString& theFile, bool
RWGltf_CafWriter::~RWGltf_CafWriter()
{
myWriter.reset();
+#ifdef __linux__
+ if (myBinFileFd >= 0)
+ {
+ close(myBinFileFd);
+ myBinFileFd = -1;
+ }
+#endif
}
//=================================================================================================
@@ -486,6 +522,13 @@ void RWGltf_CafWriter::saveTriangleIndices(RWGltf_GltfFace& theGltfFac
const RWMesh_FaceIterator& theFaceIter,
const std::shared_ptr<RWGltf_CafWriter::Mesh>& theMesh)
{
+ // Invoke callback with face data before processing (triangle start = current count / 3)
+ if (myFaceDataCallback)
+ {
+ const Standard_Integer aTriStart = theGltfFace.Indices.Count / 3;
+ myFaceDataCallback(myMeshIndex, myFaceIndex++, aTriStart, theFaceIter.NbTriangles(), theFaceIter.Face());
+ }
+
const int aNodeFirst = theGltfFace.NbIndexedNodes - theFaceIter.ElemLower();
theGltfFace.NbIndexedNodes += theFaceIter.NbNodes();
theGltfFace.Indices.Count += theFaceIter.NbTriangles() * 3;
@@ -848,6 +891,7 @@ bool RWGltf_CafWriter::writeBinData(const occ::handle<TDocStd_Document>&
myBinDataMap.Clear();
myBinDataLen64 = 0;
+ myFaceIndex = 0;
Message_ProgressScope aScope(theProgress,
"Write binary data",
@@ -929,9 +973,9 @@ bool RWGltf_CafWriter::writeBinData(const occ::handle<TDocStd_Document>&
aBuffView->ByteOffset = aBinFile->tellp();
aWrittenFaces.Clear(false);
aWrittenPrimData.Clear(false);
-#ifdef HAVE_DRACO
- size_t aMeshIndex = 0;
-#endif
+ size_t aMeshIndex = 0; // Track mesh index for callback (always, not just DRACO)
+ myMeshIndex = -1; // Initialize to -1 so first mesh triggers face index reset
+ myFaceIndex = 0; // Reset face index for this array type pass
bool isFacesOnly = true;
for (ShapeToGltfFaceMap::Iterator aBinDataIter(myBinDataMap);
@@ -952,9 +996,18 @@ bool RWGltf_CafWriter::writeBinData(const occ::handle<TDocStd_Document>&
{
const occ::handle<RWGltf_GltfFace>& aGltfFace = aGltfFaceIter.Value();
+ // Update mesh index for callback (0-based) before incrementing for DRACO (1-based)
+ // Reset face index when moving to a new mesh
+ Standard_Integer aNewMeshIndex = static_cast<Standard_Integer>(aMeshIndex);
+ if (aNewMeshIndex != myMeshIndex)
+ {
+ myFaceIndex = 0;
+ }
+ myMeshIndex = aNewMeshIndex;
+ ++aMeshIndex;
+
std::shared_ptr<RWGltf_CafWriter::Mesh> aMeshPtr;
#ifdef HAVE_DRACO
- ++aMeshIndex;
if (myDracoParameters.DracoCompression)
{
if (aMeshIndex <= aMeshes.Size())
@@ -1305,7 +1358,15 @@ bool RWGltf_CafWriter::writeJson(
}
}
- rapidjson::OStreamWrapper aFileStream(*aGltfContentFile);
+ // Use stringstream for JSON if callback is set in binary mode
+ std::ostringstream aJsonStream;
+ std::ostream* aJsonOutput = aGltfContentFile.get();
+ if (myIsBinary && myJsonPostProcessCallback)
+ {
+ aJsonOutput = &aJsonStream;
+ }
+
+ rapidjson::OStreamWrapper aFileStream(*aJsonOutput);
myWriter.reset(new RWGltf_GltfOStreamWriter(aFileStream));
myWriter->StartObject();
@@ -1337,6 +1398,15 @@ bool RWGltf_CafWriter::writeJson(
writeTextures(aSceneNodeMap);
myWriter->EndObject();
+ myWriter.reset(); // Release writer before post-processing
+
+ // Post-process JSON through callback if set (binary mode only)
+ if (myIsBinary && myJsonPostProcessCallback)
+ {
+ std::string aJsonString = aJsonStream.str();
+ aJsonString = myJsonPostProcessCallback(aJsonString);
+ aGltfContentFile->write(aJsonString.c_str(), aJsonString.size());
+ }
if (!myIsBinary)
{
@@ -1357,12 +1427,15 @@ bool RWGltf_CafWriter::writeJson(
++aContentLen64;
}
- const uint32_t aBinLength = (uint32_t)myBinDataLen64;
+ // Calculate binary length (may include appended data from callback)
+ uint32_t aAppendedBytes = 0;
+ uint32_t aBinLength = (uint32_t)myBinDataLen64;
+
const uint32_t aBinType = 0x004E4942;
aGltfContentFile->write((const char*)&aBinLength, 4);
aGltfContentFile->write((const char*)&aBinType, 4);
- const int64_t aFullLen64 = aContentLen64 + 20 + myBinDataLen64 + 8;
+ int64_t aFullLen64 = aContentLen64 + 20 + myBinDataLen64 + 8;
if (aFullLen64 < std::numeric_limits<uint32_t>::max())
{
{
@@ -1386,12 +1459,47 @@ bool RWGltf_CafWriter::writeJson(
aGltfContentFile->write(aBuffer, aReadLen);
}
}
- OSD_Path aBinFilePath(myBinFileNameFull);
- OSD_File(aBinFilePath).Remove();
- if (OSD_File(aBinFilePath).Exists())
+
+ // Invoke binary append callback if set
+ if (myBinaryAppendCallback)
+ {
+ // Pad to 4-byte alignment before appending
+ while (aGltfContentFile->tellp() % 4 != 0)
+ {
+ aGltfContentFile->write("\0", 1);
+ }
+
+ aAppendedBytes = myBinaryAppendCallback(*aGltfContentFile, (uint32_t)myBinDataLen64);
+
+ // Pad appended data to 4-byte alignment
+ while (aGltfContentFile->tellp() % 4 != 0)
+ {
+ aGltfContentFile->write("\0", 1);
+ aAppendedBytes++;
+ }
+
+ // Update binary length and total length
+ aBinLength = (uint32_t)myBinDataLen64 + aAppendedBytes;
+ aFullLen64 = aContentLen64 + 20 + aBinLength + 8;
+
+ // Seek back and update binary chunk length
+ aGltfContentFile->seekp(aContentLen64 + 20);
+ aGltfContentFile->write((const char*)&aBinLength, 4);
+ aGltfContentFile->seekp(0, std::ios::end);
+ }
+
+ // Remove temp file (skip if using memfd - nothing to remove)
+#ifdef __linux__
+ if (myBinFileFd < 0)
+#endif
{
- Message::SendFail(TCollection_AsciiString("Unable to remove temporary glTF content file '")
- + myBinFileNameFull + "'");
+ OSD_Path aBinFilePath(myBinFileNameFull);
+ OSD_File(aBinFilePath).Remove();
+ if (OSD_File(aBinFilePath).Exists())
+ {
+ Message::SendFail(TCollection_AsciiString("Unable to remove temporary glTF content file '")
+ + myBinFileNameFull + "'");
+ }
}
}
else
@@ -1413,7 +1521,6 @@ bool RWGltf_CafWriter::writeJson(
return false;
}
aGltfContentFile.reset();
- myWriter.reset();
return true;
#else
(void)theDocument;
diff --git a/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.hxx b/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.hxx
index 6f8fea3..5f5b884 100644
--- a/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.hxx
+++ b/src/DataExchange/TKDEGLTF/RWGltf/RWGltf_CafWriter.hxx
@@ -33,7 +33,9 @@
#include <XCAFPrs_DocumentNode.hxx>
#include <XCAFPrs_Style.hxx>
#include <Poly_Triangle.hxx>
+#include <TopoDS_Face.hxx>
+#include <functional>
#include <memory>
class Message_ProgressRange;
@@ -157,6 +159,40 @@ public:
myDracoParameters = theDracoParameters;
}
+ //! Callback type for receiving per-face triangle data during mesh export.
+ //! Called for each TopoDS_Face with its mesh index, face index, triangle start index, triangle count, and the face itself.
+ using FaceDataCallback = std::function<void(Standard_Integer theMeshIndex,
+ Standard_Integer theFaceIndex,
+ Standard_Integer theTriStart,
+ Standard_Integer theTriCount,
+ const TopoDS_Face& theFace)>;
+
+ //! Set callback for receiving per-face triangle mapping data.
+ //! When set, the callback is invoked during binary data export for each face.
+ void SetFaceDataCallback(const FaceDataCallback& theCallback) { myFaceDataCallback = theCallback; }
+
+ //! Callback type for post-processing the JSON header before it's written to GLB.
+ //! Called with the JSON string; callback can modify and return the modified string.
+ //! Only invoked for binary GLB format.
+ //! Note: The callback can modify JSON to reference additional binary data,
+ //! but cannot easily append that binary data (which is written from temp file).
+ //! Best used for JSON-only modifications (metadata, extensions without new binary).
+ using JsonPostProcessCallback = std::function<std::string(const std::string& theJson)>;
+
+ //! Set callback for post-processing the JSON header in binary GLB mode.
+ //! When set, the callback receives the complete JSON string before it's written to the GLB file.
+ void SetJsonPostProcessCallback(const JsonPostProcessCallback& theCallback) { myJsonPostProcessCallback = theCallback; }
+
+ //! Callback type for appending additional binary data to the GLB binary chunk.
+ //! Called with output stream and existing binary length; callback can write additional data.
+ //! Should return the total number of bytes written.
+ using BinaryAppendCallback = std::function<uint32_t(std::ostream& theStream, uint32_t theExistingLength)>;
+
+ //! Set callback for appending binary data after the main binary chunk.
+ //! When set, allows adding custom binary data (e.g., face indices) to the GLB.
+ //! The JSON callback should reference this data with appropriate offsets.
+ void SetBinaryAppendCallback(const BinaryAppendCallback& theCallback) { myBinaryAppendCallback = theCallback; }
+
//! Write glTF file and associated binary file.
//! Triangulation data should be precomputed within shapes!
//! @param[in] theDocument input document
@@ -542,7 +578,13 @@ protected:
NCollection_LinearVector<RWGltf_GltfBufferView> myBuffViewsDraco; //!< vector of buffers view with compression data
bool myToParallel; //!< flag to use multithreading; FALSE by default
// clang-format on
- RWGltf_DracoParameters myDracoParameters; //!< Draco parameters
+ RWGltf_DracoParameters myDracoParameters; //!< Draco parameters
+ FaceDataCallback myFaceDataCallback; //!< optional callback for per-face triangle data
+ Standard_Integer myFaceIndex; //!< current face index for callback
+ Standard_Integer myMeshIndex; //!< current mesh index for callback
+ JsonPostProcessCallback myJsonPostProcessCallback; //!< optional callback for JSON post-processing
+ BinaryAppendCallback myBinaryAppendCallback; //!< optional callback for appending binary data
+ int myBinFileFd; //!< memfd for binary temp file (Linux), -1 otherwise
};
#endif // _RWGltf_CafWriter_HeaderFiler