Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HYDRA-833 - Maya MaterialX material bindings on Maya geometry #72

Merged
merged 1 commit into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions lib/mayaHydra/hydraExtensions/adapters/materialAdapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,31 @@
#include <pxr/imaging/hd/material.h>
#include <pxr/pxr.h>
#include <pxr/usd/sdf/types.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdMtlx/reader.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usdImaging/usdImaging/materialParamUtils.h>
#include <pxr/usdImaging/usdImaging/tokens.h>

#include <maya/MNodeMessage.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>

#include <MaterialXCore/Document.h>
#include <MaterialXFormat/XmlIo.h>

PXR_NAMESPACE_OPEN_SCOPE

namespace {

TF_DEFINE_PRIVATE_TOKENS(
_tokens,
(mtlx)
((mtlxSurface, "mtlx:surface"))
(surface)
);

const VtValue _emptyValue;
const TfToken _emptyToken;
const TfTokenVector _stSamplerCoords = { TfToken("st") };
Expand Down Expand Up @@ -231,10 +246,81 @@ class MayaHydraShadingEngineAdapter : public MayaHydraMaterialAdapter
}
}

bool PopulateMaterialXNetworkMap(HdMaterialNetworkMap& networkMap)
{
// Get the dependency node
MStatus status;
MFnDependencyNode node(_surfaceShader, &status);
if (!status) {
return false;
}

// Fetch the "renderDocument" attribute from the node
static const MString renderDocumentStr("renderDocument");
auto mtlxDocPlug = node.findPlug(renderDocumentStr, true, &status);
if (!status) {
return false;
}

// Construct a MaterialX document
auto mtlxDocStr = mtlxDocPlug.asString();
auto mtlxDoc = MaterialX::createDocument();
MaterialX::readFromXmlString(mtlxDoc, mtlxDocStr.asChar());

// Create a Usd Stage from the MaterialX document
auto stage = UsdStage::CreateInMemory("tmp.usda", TfNullPtr);
UsdMtlxRead(mtlxDoc, stage);

// Search for material group in the Usd Stage
static const SdfPath basePath("/MaterialX/Materials");
auto mtlxRange = stage->GetPrimAtPath(basePath).GetChildren();
if (mtlxRange.empty()) {
return false;
}

// There should be only one material. Fetch it.
UsdShadeMaterial mtlxMaterial(*mtlxRange.begin());
if (!mtlxMaterial) {
return false;
}

// Get MaterialX output
UsdShadeOutput mtlxOutput = mtlxMaterial.GetOutput(_tokens->mtlxSurface);
if (!mtlxOutput) {
return false;
}

// Get MaterialX shader outputs
UsdShadeAttributeVector mtlxShaderOutputs =
UsdShadeUtils::GetValueProducingAttributes(mtlxOutput, /*shaderOutputsOnly*/true);
if (mtlxShaderOutputs.empty()) {
return false;
}

// Finally get MaterialX shader
UsdShadeShader mtlxShader(mtlxShaderOutputs[0].GetPrim());
if (!mtlxShader) {
return false;
}

// Convert the MaterialX shader to HdMaterialNetwork
UsdImagingBuildHdMaterialNetworkFromTerminal(
mtlxShader.GetPrim(), _tokens->surface, {_tokens->mtlx},
{_tokens->mtlx}, &networkMap, UsdTimeCode());

return true;
}

VtValue GetMaterialResource() override
{
TF_DEBUG(MAYAHYDRALIB_ADAPTER_MATERIALS)
.Msg("MayaHydraShadingEngineAdapter::GetMaterialResource(): %s\n", GetID().GetText());

HdMaterialNetworkMap materialXNetworkMap;
if (PopulateMaterialXNetworkMap(materialXNetworkMap)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there any reason not to do the translation inside MayaHydraMaterialNetworkConverter? I feel it's better to move the code into MayaHydraMaterialNetworkConverter as MatX is also one kind of Material.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The interface of MayaHydraMaterialNetworkConverter seems to be developped specifically for UsdPreviewSurface network. I think we would have hard times adapting and rewriting it for the needs of MaterialX. For example method HdMaterialNode* GetMaterial would need to change its output type as well as all other public methods have no meaning for MaterialX (like GetPreviewShaderParams). I don't see any reason for readapting MayaHydraMaterialNetworkConverter for MaterialX

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, sounds like having a base materialConverter and diferent sub materialConverters would make the architecture looks better, as the actual conversion is the responsibility of materialConverter, not materialAdapter.

I'm fine with the current code, just trying to make it easier to maintain, we could also refactor it later when we need more materialConverters in the future.

return VtValue(materialXNetworkMap);
}

MayaHydraMaterialNetworkConverter::MayaHydraMaterialNetworkConverterInit initStruct(
GetID(), _enableXRayShadingMode, &_materialPathToMobj);

Expand Down
1 change: 1 addition & 0 deletions test/lib/mayaUsd/render/mayaToHydra/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ set(INTERACTIVE_TEST_SCRIPT_FILES
testSceneBrowser.py
testStageAddPrim.py
testTransforms.py
testMaterialXOnNative.py
testNewSceneWithStage.py
testMayaLights.py
testUSDLights.py
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 41 additions & 0 deletions test/lib/mayaUsd/render/mayaToHydra/testMaterialXOnNative.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright 2024 Autodesk
#
# 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.
#
import maya.cmds as cmds
import mayaUtils
import fixturesUtils
import mtohUtils
import unittest

class TestMaterialXOnNative(mtohUtils.MtohTestCase):
_file = __file__

IMAGEDIFF_FAIL_THRESHOLD = 0.01
IMAGEDIFF_FAIL_PERCENT = 0.1

def verifySnapshot(self, imageName):
cmds.refresh()
self.assertSnapshotClose(imageName,
self.IMAGEDIFF_FAIL_THRESHOLD,
self.IMAGEDIFF_FAIL_PERCENT)

@unittest.skipUnless(mtohUtils.checkForPlugin('LookdevXMaya'), "Requires LookDevX Plugin.")
def test_MaterialX(self):
mayaUtils.openTestScene("testMaterialX", "RedMtlxSphere.ma")
self.setBasicCam(2)
self.setHdStormRenderer()
self.verifySnapshot("RedMtlxSphere.png")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we missing to pass IMAGEDIFF_FAIL_THRESHOLD and IMAGEDIFF_FAIL_PERCENT here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, they are passed from inside verifySnapshot method

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, sorry, I missed that. :)


if __name__ == '__main__':
fixturesUtils.runTests(globals())
Loading
Loading