5This module contains the core definitions and utilities for reading and wring MaterialX
19JSON_MIMETYPE_KEY =
'mimetype'
20JSON_MIMETYPE: str =
'application/mtlx+json'
22JSON_CATEGORY_NAME_SEPARATOR: str =
':'
24MATERIALX_DOCUMENT_ROOT: str =
'materialx'
27INPUTS_STRING =
'inputs'
28OUTPUTS_STRING =
'outputs'
29CHILDREN_STRING =
'children'
33 Class for holding options for writing MaterialX to JSON.
36 - elementPredicate: MaterialX function predicate for filtering elements to write
37 - indent: The number of spaces to indent the JSON hierarchy
38 - separators: JSON separators. Default is: (',', ': ')
39 - addInputOutputCategories: Add input and output categories to JSON elements. Default is False
52 Class for holding options for reading MaterialX from JSON
55 - upgradeVersion: Upgrade the MaterialX document to the latest version
65 Class for handling read and write of MaterialX from and to JSON
67 def elementToJSON(self, elem: mx.Element, jsonParent: dict, writeOptions: JsonWriteOptions =
None) -> dict:
69 @brief Convert an MaterialX XML element to JSON.
70 Will recursively traverse the parent/child Element hierarchy.
71 @param elem The MaterialX element to convert
72 @param jsonParent The JSON element append to
73 @param writeOptions The write options to use. Default is None
75 if (writeOptions
and writeOptions.elementPredicate
and not writeOptions.elementPredicate(elem)):
78 if (elem.getSourceUri() !=
""):
83 jsonElem[
'name'] = elem.getName()
84 category = elem.getCategory()
87 if (writeOptions
and writeOptions.addInputOutputCategories)
or (category
not in [
'input',
'output']):
88 jsonElem[
'category'] = category
91 for attrName
in elem.getAttributeNames():
92 jsonElem[attrName] = elem.getAttribute(attrName)
97 non_input_outputs = []
98 for child
in elem.getChildren():
99 category = child.getCategory()
100 if category ==
'input':
102 elif category ==
'output':
109 jsonElem[INPUTS_STRING] = inputs
110 if len(non_input_outputs) > 0:
111 jsonElem[CHILDREN_STRING] = non_input_outputs
113 jsonElem[OUTPUTS_STRING] = outputs
116 jsonParent.append(jsonElem)
120 def documentToJSON(self, doc: mx.Document, writeOptions: JsonWriteOptions =
None) -> dict:
122 Convert an MaterialX XML document to JSON
123 @param doc The MaterialX document to convert
124 @param writeOptions The write options to use. Default is None
125 @return The JSON document
129 root[JSON_MIMETYPE_KEY] = JSON_MIMETYPE
135 for attrName
in doc.getAttributeNames():
136 documentRoot[attrName] = doc.getAttribute(attrName)
140 for elem
in doc.getChildren():
142 documentRoot[
'children'] = children
145 root[MATERIALX_DOCUMENT_ROOT] = documentRoot
151 Convert an MaterialX XML document to JSON string
152 @param doc The MaterialX document to convert
153 @param writeOptions The write options to use. Default is None
154 @return The JSON string
162 indentation = writeOptions.indent
163 sep = writeOptions.separators
164 json_string = json.dumps(result, indent=indentation, separators=sep)
168 def elementFromJSON(self, node: dict, elem: mx.Element, readOptions: JsonReadOptions =
None) ->
None:
170 @brief Convert an JSON element to MaterialX
171 @param node The JSON element to read
172 @param elem The MaterialX element to write to
173 @param readOptions The read options to use. Default is None
179 if isinstance(value, str):
180 if key
not in [
'name',
'category']:
181 elem.setAttribute(key, str(value))
184 elif key == INPUTS_STRING:
188 childElem = elem.addChildOfCategory(category, name)
191 elif key == CHILDREN_STRING:
193 category = child[
'category']
195 childElem = elem.addChildOfCategory(category, name)
198 elif key == OUTPUTS_STRING:
202 childElem = elem.addChildOfCategory(category, name)
205 def documentFromJSON(self, jsonDoc: dict, doc: mx.Document, readOptions: JsonReadOptions =
None) -> bool:
207 @brief Convert a JSON document to MaterialX
208 @param jsonDoc The JSON document to read
209 @param doc The MaterialX document to write to
210 @param readOptions The read options to use. Default is None
214 if JSON_MIMETYPE_KEY
in jsonDoc
and jsonDoc[JSON_MIMETYPE_KEY] == JSON_MIMETYPE:
215 if MATERIALX_DOCUMENT_ROOT
in jsonDoc:
219 print(
'JSON document is missing a MaterialX root element')
221 print(
'JSON document is not a MaterialX document')
225 if readOptions
and readOptions.upgradeVersion:
232 @brief Convert a JSON document to MaterialX
233 @param jsonString The JSON string to read
234 @param doc The MaterialX document to write to
235 @param readOptions The read options to use. Default is None
236 @return True if successful, false otherwise
238 jsonDoc = json.loads(jsonString)
246 Utility class for MaterialX JSON
251 @brief Read a JSON file
252 @param fileName The file name to read
253 @return The JSON document
255 jsonFile = open(fileName,
'r')
259 jsonObject = json.load(jsonFile)
268 @brief Convert a JSON string to a JSON document
269 @param jsonString The JSON string to convert
270 @return The JSON document
272 return json.loads(jsonString)
277 @brief Convert a JSON document to a JSON string
278 @param jsonObject The JSON document to convert
279 @return The JSON string
281 return json.dumps(jsonObject, indent=indentation)
286 @brief Convert a MaterialX document to XML string
287 @param doc The MaterialX document to convert
288 @return The XML string
290 return mx.writeToXmlString(doc)
295 @brief Convert an XML string to a MaterialX document
296 @param doc The MaterialX document to write to
297 @param xmlString The XML string to convert
299 mx.readFromXmlString(doc, xmlString)
302 def writeJson(jsonObject: dict, fileName: str, indentation = 2) ->
None:
304 @brief Write a JSON document to file
305 @param jsonObject The JSON document to write
306 @param fileName The file name to write to
308 with open(fileName,
'w')
as outfile:
309 json.dump(jsonObject, outfile, indent=indentation)
312 def getFiles(rootPath: str, extension: str) -> list:
314 @brief Get all files with the given extension from the given root path
315 @param rootPath The root path to search from
316 @param extension The extension to search for
317 @return A list of file paths
320 exts = (extension, extension.upper() )
321 for subdir, dirs, files
in os.walk(rootPath):
323 if file.lower().endswith(exts):
324 filelist.append(os.path.join(subdir, file))
328 def loadLibraries(searchPath: mx.FileSearchPath, libraryFolders: list) -> tuple:
330 @brief Load all libraries from the given search path and library folders
331 @param searchPath The search path to use
332 @param libraryFolders The library folders to use
333 @return A tuple containing the library document and a status string
336 lib = mx.createDocument()
338 libFiles = mx.loadLibraries(libraryFolders, searchPath, lib)
339 status =
'- Loaded %d library definitions from %d files' % (len(lib.getNodeDefs()), len(libFiles))
340 except mx.Exception
as err:
341 status =
'- Failed to load library definitions: "%s"' % err
346 def jsonFileToXml(fileName: str, readOptions: JsonReadOptions =
None) -> mx.Document:
348 @brief Convert a JSON file to an XML file
349 @param fileName The file name to read from
350 @param readOptions The read options to use. Default is None
351 @return The MaterialX document if successful, None otherwise
355 jsonFile = open(fileName,
'r')
358 jsonObject = json.load(jsonFile)
362 newDoc = mx.createDocument()
363 readDoc = mtlxjson.documentFromJSON(jsonObject, newDoc, readOptions)
370 def jsonFileToXmlFile(fileName: str, outputFilename: str, readOptions: JsonReadOptions =
None) -> bool:
372 @brief Convert a JSON file to an XML file
373 @param fileName The file name to read from
374 @param outputFilename The file name to write to
375 @param readOptions The read options to use. Default is None
376 @return True if successful, false otherwise
378 jsonFile = open(fileName,
'r')
381 jsonObject = json.load(jsonFile)
387 newDoc = mx.createDocument()
388 created = mtlxjson.documentFromJSON(jsonObject, newDoc, readOptions)
390 if newDoc.getChildren():
391 mx.writeToXmlFile(newDoc, outputFilename)
397 def xmlFileToJsonFile(xmlFileName: str, jsonFileName: str, writeOptions: JsonWriteOptions =
None) ->
None:
399 Convert an MaterialX XML file to a JSON file
400 @param xmlFileName The XML file to read from
401 @param jsonFileName The JSON file to write to
402 @param writeOptions The write options to use. Default is None
406 doc = mx.createDocument()
407 mx.readFromXmlFile(doc, xmlFileName)
410 doc_result = mtlxjson.documentToJSON(doc, writeOptions)
413 with open(jsonFileName,
'w')
as outfile:
417 indentation = writeOptions.indent
418 sep = writeOptions.separators
419 json.dump(doc_result, outfile, indent=indentation, separators=sep)
Class for holding options for reading MaterialX from JSON.
__init__(self)
Constructor.
Class for holding options for writing MaterialX to JSON.
mx.ElementPredicate elementPredicate
bool addInputOutputCategories
__init__(self)
Constructor.
Class for handling read and write of MaterialX from and to JSON.
None elementFromJSON(self, dict node, mx.Element elem, JsonReadOptions readOptions=None)
Convert an JSON element to MaterialX.
dict elementToJSON(self, mx.Element elem, dict jsonParent, JsonWriteOptions writeOptions=None)
Convert an MaterialX XML element to JSON.
bool documentFromJSON(self, dict jsonDoc, mx.Document doc, JsonReadOptions readOptions=None)
Convert a JSON document to MaterialX.
dict documentToJSON(self, mx.Document doc, JsonWriteOptions writeOptions=None)
Convert an MaterialX XML document to JSON.
str documentToJSONString(self, mx.Document doc, JsonWriteOptions writeOptions=None)
Convert an MaterialX XML document to JSON string.
bool documentFromJSONString(self, str jsonString, mx.Document doc, JsonReadOptions readOptions=None)
Convert a JSON document to MaterialX.
Utility class for MaterialX JSON.
None xmlFileToJsonFile(str xmlFileName, str jsonFileName, JsonWriteOptions writeOptions=None)
Convert an MaterialX XML file to a JSON file.
mx.Document jsonFileToXml(str fileName, JsonReadOptions readOptions=None)
Convert a JSON file to an XML file.
dict jsonStringToJson(str jsonString)
Convert a JSON string to a JSON document.
str documentToXMLString(mx.Document doc)
Convert a MaterialX document to XML string.
list getFiles(str rootPath, str extension)
Get all files with the given extension from the given root path.
bool jsonFileToXmlFile(str fileName, str outputFilename, JsonReadOptions readOptions=None)
Convert a JSON file to an XML file.
None writeJson(dict jsonObject, str fileName, indentation=2)
Write a JSON document to file.
dict readJson(str fileName)
Read a JSON file.
tuple loadLibraries(mx.FileSearchPath searchPath, list libraryFolders)
Load all libraries from the given search path and library folders.
str jsonToJSONString(dict jsonObject, indentation=2)
Convert a JSON document to a JSON string.
None xmlStringToDocument(mx.Document doc, str xmlString)
Convert an XML string to a MaterialX document.