diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0a71a31011..8fc0fd3f92 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -195,14 +195,13 @@ jobs: - name: Run Clang Format if: matrix.clang_format == 'ON' - run: find source \( -name *.h -o -name *.cpp -o -name *.mm \) ! -path "*/External/*" ! -path "*/NanoGUI/*" | xargs clang-format -i --verbose + run: find source \( -name *.h -o -name *.cpp -o -name *.mm -o -name *.inl \) ! -path "*/External/*" ! -path "*/NanoGUI/*" | xargs clang-format -i --verbose - name: CMake Generate run: cmake -S . -B build -DMATERIALX_BUILD_PYTHON=ON -DMATERIALX_BUILD_VIEWER=ON -DMATERIALX_BUILD_GRAPH_EDITOR=ON -DMATERIALX_TEST_RENDER=OFF -DMATERIALX_WARNINGS_AS_ERRORS=ON ${{matrix.cmake_config}} - name: CMake Build - run: cmake --build . --target install --config Release --parallel 2 - working-directory: build + run: cmake --build build --target install --config Release --parallel 2 - name: CMake Unit Tests run: ctest -VV --output-on-failure --build-config Release @@ -314,8 +313,7 @@ jobs: - name: JavaScript CMake Build if: matrix.build_javascript == 'ON' - run: cmake --build . --target install --config Release --parallel 2 - working-directory: javascript/build + run: cmake --build javascript/build --target install --config Release --parallel 2 - name: JavaScript Unit Tests if: matrix.build_javascript == 'ON' diff --git a/source/MaterialXCore/Definition.cpp b/source/MaterialXCore/Definition.cpp index cf9587ecda..c3150e2a87 100644 --- a/source/MaterialXCore/Definition.cpp +++ b/source/MaterialXCore/Definition.cpp @@ -84,7 +84,7 @@ InterfaceElementPtr NodeDef::getImplementation(const string& target) const } } } - + // Then search for a generic match. for (InterfaceElementPtr interface : interfaces) { diff --git a/source/MaterialXFormat/Util.cpp b/source/MaterialXFormat/Util.cpp index 32feda4d0d..48ded1d6b1 100644 --- a/source/MaterialXFormat/Util.cpp +++ b/source/MaterialXFormat/Util.cpp @@ -234,7 +234,7 @@ FileSearchPath getDefaultDataSearchPath() } currentPath = currentPath.getParentPath(); } - return FileSearchPath(); + return FileSearchPath(); } MATERIALX_NAMESPACE_END diff --git a/source/MaterialXFormat/Util.h b/source/MaterialXFormat/Util.h index 46f55c41ee..c7ef0c6d38 100644 --- a/source/MaterialXFormat/Util.h +++ b/source/MaterialXFormat/Util.h @@ -62,7 +62,7 @@ MX_FORMAT_API FileSearchPath getSourceSearchPath(ConstDocumentPtr doc); /// Return a file search path to the default data library folder. /// The module path and all parent paths are examined to until either there is -/// no parent or the library folder is found. +/// no parent or the library folder is found. MX_FORMAT_API FileSearchPath getDefaultDataSearchPath(); MATERIALX_NAMESPACE_END diff --git a/source/MaterialXGenGlsl/GlslShaderGenerator.cpp b/source/MaterialXGenGlsl/GlslShaderGenerator.cpp index ec5e48d4ec..ea78e1bee3 100644 --- a/source/MaterialXGenGlsl/GlslShaderGenerator.cpp +++ b/source/MaterialXGenGlsl/GlslShaderGenerator.cpp @@ -56,17 +56,17 @@ GlslShaderGenerator::GlslShaderGenerator() : // StringVec elementNames; - + // elementNames = { // - "IM_switch_float_" + GlslShaderGenerator::TARGET, - "IM_switch_color3_" + GlslShaderGenerator::TARGET, - "IM_switch_color4_" + GlslShaderGenerator::TARGET, + "IM_switch_float_" + GlslShaderGenerator::TARGET, + "IM_switch_color3_" + GlslShaderGenerator::TARGET, + "IM_switch_color4_" + GlslShaderGenerator::TARGET, "IM_switch_vector2_" + GlslShaderGenerator::TARGET, "IM_switch_vector3_" + GlslShaderGenerator::TARGET, "IM_switch_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_switch_floatI_" + GlslShaderGenerator::TARGET, "IM_switch_color3I_" + GlslShaderGenerator::TARGET, @@ -85,7 +85,7 @@ GlslShaderGenerator::GlslShaderGenerator() : "IM_swizzle_float_vector2_" + GlslShaderGenerator::TARGET, "IM_swizzle_float_vector3_" + GlslShaderGenerator::TARGET, "IM_swizzle_float_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_swizzle_color3_float_" + GlslShaderGenerator::TARGET, "IM_swizzle_color3_color3_" + GlslShaderGenerator::TARGET, @@ -93,7 +93,7 @@ GlslShaderGenerator::GlslShaderGenerator() : "IM_swizzle_color3_vector2_" + GlslShaderGenerator::TARGET, "IM_swizzle_color3_vector3_" + GlslShaderGenerator::TARGET, "IM_swizzle_color3_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_swizzle_color4_float_" + GlslShaderGenerator::TARGET, "IM_swizzle_color4_color3_" + GlslShaderGenerator::TARGET, @@ -101,7 +101,7 @@ GlslShaderGenerator::GlslShaderGenerator() : "IM_swizzle_color4_vector2_" + GlslShaderGenerator::TARGET, "IM_swizzle_color4_vector3_" + GlslShaderGenerator::TARGET, "IM_swizzle_color4_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_swizzle_vector2_float_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector2_color3_" + GlslShaderGenerator::TARGET, @@ -109,7 +109,7 @@ GlslShaderGenerator::GlslShaderGenerator() : "IM_swizzle_vector2_vector2_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector2_vector3_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector2_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_swizzle_vector3_float_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector3_color3_" + GlslShaderGenerator::TARGET, @@ -117,7 +117,7 @@ GlslShaderGenerator::GlslShaderGenerator() : "IM_swizzle_vector3_vector2_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector3_vector3_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector3_vector4_" + GlslShaderGenerator::TARGET, - + // "IM_swizzle_vector4_float_" + GlslShaderGenerator::TARGET, "IM_swizzle_vector4_color3_" + GlslShaderGenerator::TARGET, diff --git a/source/MaterialXGenMdl/MdlShaderGenerator.cpp b/source/MaterialXGenMdl/MdlShaderGenerator.cpp index e10d586d69..af75a2cef4 100644 --- a/source/MaterialXGenMdl/MdlShaderGenerator.cpp +++ b/source/MaterialXGenMdl/MdlShaderGenerator.cpp @@ -291,9 +291,9 @@ ShaderPtr MdlShaderGenerator::generate(const string& name, ElementPtr element, G { emitLine("float3 displacement__ = " + result + ".geometry.displacement", stage); emitLine("color finalOutput__ = mk_color3(" - "r: math::dot(displacement__, state::texture_tangent_u(0))," - "g: math::dot(displacement__, state::texture_tangent_v(0))," - "b: math::dot(displacement__, state::normal()))", stage); + "r: math::dot(displacement__, state::texture_tangent_u(0))," + "g: math::dot(displacement__, state::texture_tangent_v(0))," + "b: math::dot(displacement__, state::normal()))", stage); } else { diff --git a/source/MaterialXGenMdl/MdlSyntax.cpp b/source/MaterialXGenMdl/MdlSyntax.cpp index 9d5483bcca..7560297ce4 100644 --- a/source/MaterialXGenMdl/MdlSyntax.cpp +++ b/source/MaterialXGenMdl/MdlSyntax.cpp @@ -48,7 +48,7 @@ class MdlFilenameTypeSyntax : public ScalarTypeSyntax // assuming it ends with a slash ... if (outputValue.back() == '/') { - return getDefaultValue(true); + return getDefaultValue(true); } // ... or the last segment does not have an extension suffix size_t idx_s = outputValue.find_last_of('/'); diff --git a/source/MaterialXGenMdl/Nodes/ClosureCompoundNodeMdl.cpp b/source/MaterialXGenMdl/Nodes/ClosureCompoundNodeMdl.cpp index e175696d55..0a2004cd71 100644 --- a/source/MaterialXGenMdl/Nodes/ClosureCompoundNodeMdl.cpp +++ b/source/MaterialXGenMdl/Nodes/ClosureCompoundNodeMdl.cpp @@ -41,7 +41,7 @@ void ClosureCompoundNodeMdl::emitFunctionDefinition(const ShaderNode& node, GenC { if (!outputSocket->getConnection()) continue; - + const ShaderNode* upstream = outputSocket->getConnection()->getNode(); const bool isMaterialExpr = (upstream->hasClassification(ShaderNode::Classification::CLOSURE) || upstream->hasClassification(ShaderNode::Classification::SHADER)); diff --git a/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.cpp b/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.cpp index fd27d5e547..bff1351142 100644 --- a/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.cpp +++ b/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.cpp @@ -368,12 +368,12 @@ const string& MixBsdfNodeMdl::getOperatorName(size_t index) const { switch (index) { - case 0: - return StringConstantsMdl::FG; - case 1: - return StringConstantsMdl::BG; - default: - return StringConstantsMdl::EMPTY; + case 0: + return StringConstantsMdl::FG; + case 1: + return StringConstantsMdl::BG; + default: + return StringConstantsMdl::EMPTY; } } @@ -386,12 +386,12 @@ const string& AddOrMultiplyBsdfNodeMdl::getOperatorName(size_t index) const { switch (index) { - case 0: - return StringConstantsMdl::IN1; - case 1: - return StringConstantsMdl::IN2; - default: - return StringConstantsMdl::EMPTY; + case 0: + return StringConstantsMdl::IN1; + case 1: + return StringConstantsMdl::IN2; + default: + return StringConstantsMdl::EMPTY; } } diff --git a/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.h b/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.h index 75ea46046c..95c51198f8 100644 --- a/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.h +++ b/source/MaterialXGenMdl/Nodes/ClosureLayerNodeMdl.h @@ -21,18 +21,18 @@ class MX_GENMDL_API StringConstantsMdl public: /// String constants - static const string TOP; ///< layer parameter name of the top component + static const string TOP; ///< layer parameter name of the top component static const string BASE; ///< layer parameter name of the base component - static const string FG; ///< parameter of the mix node - static const string BG; ///< parameter of the mix node - static const string IN1; ///< parameter of the add and multiply nodes - static const string IN2; ///< parameter of the add and multiply nodes + static const string FG; ///< parameter of the mix node + static const string BG; ///< parameter of the mix node + static const string IN1; ///< parameter of the add and multiply nodes + static const string IN2; ///< parameter of the add and multiply nodes static const string THICKNESS; ///< thickness parameter name of the thin_film_bsdf - static const string IOR; ///< ior parameter name of the thin_film_bsdf + static const string IOR; ///< ior parameter name of the thin_film_bsdf static const string THIN_FILM_THICKNESS; ///< helper parameter name for transporting thickness - static const string THIN_FILM_IOR; ///< helper parameter name for transporting ior + static const string THIN_FILM_IOR; ///< helper parameter name for transporting ior static const string EMPTY; ///< the empty string "" }; @@ -41,7 +41,7 @@ class MX_GENMDL_API StringConstantsMdl /// thin_film_bsdf through layers and mixers, etc., to the elemental bsdfs that support thin film. /// Because thin-film can not be layered on any BSDF in MDL, we try to push down the parameters to /// the nodes that support thin-film. -template class CarryThinFilmParameters : public TBase +template class CarryThinFilmParameters : public TBase { public: /// Add the thin film inputs for transporting the parameter. diff --git a/source/MaterialXGenMsl/MslShaderGenerator.cpp b/source/MaterialXGenMsl/MslShaderGenerator.cpp index ea3fb7112d..7fe50fef4a 100644 --- a/source/MaterialXGenMsl/MslShaderGenerator.cpp +++ b/source/MaterialXGenMsl/MslShaderGenerator.cpp @@ -1018,7 +1018,7 @@ void MslShaderGenerator::emitPixelStage(const ShaderGraph& graph, GenContext& co emitLightData(context, stage); } } - + bool needsLightBuffer = lighting && context.getOptions().hwMaxActiveLightSources > 0; emitMathMatrixScalarMathOperators(context, stage); diff --git a/source/MaterialXGenOsl/OslShaderGenerator.cpp b/source/MaterialXGenOsl/OslShaderGenerator.cpp index fbb2bb29be..f16770174b 100644 --- a/source/MaterialXGenOsl/OslShaderGenerator.cpp +++ b/source/MaterialXGenOsl/OslShaderGenerator.cpp @@ -536,7 +536,7 @@ void OslShaderGenerator::emitShaderInputs(const VariableBlock& inputs, ShaderSta // which is a struct containing a file string and a colorspace string. // For the published shader interface we here split this into two separate inputs, // which gives a nicer shader interface with widget metadata on each input. - + ValuePtr value = input->getValue(); const string valueStr = value ? value->getValueString() : EMPTY_STRING; diff --git a/source/MaterialXGenShader/HwShaderGenerator.cpp b/source/MaterialXGenShader/HwShaderGenerator.cpp index 568c666478..0db78eda27 100644 --- a/source/MaterialXGenShader/HwShaderGenerator.cpp +++ b/source/MaterialXGenShader/HwShaderGenerator.cpp @@ -260,9 +260,9 @@ ShaderPtr HwShaderGenerator::createShader(const string& name, ElementPtr element if (geomprop) { // A default geomprop was assigned to this graph input. - // For all internal connections to this input, break the connection + // For all internal connections to this input, break the connection // and assign a geomprop node that generates this data. - // Note: If a geomprop node exists already it is reused, + // Note: If a geomprop node exists already it is reused, // so only a single node per geometry type is created. ShaderInputVec connections = socket->getConnections(); for (auto connection : connections) diff --git a/source/MaterialXGenShader/Nodes/HwTransformNode.cpp b/source/MaterialXGenShader/Nodes/HwTransformNode.cpp index 018924855d..76394309af 100644 --- a/source/MaterialXGenShader/Nodes/HwTransformNode.cpp +++ b/source/MaterialXGenShader/Nodes/HwTransformNode.cpp @@ -17,7 +17,7 @@ const string HwTransformNode::WORLD = "world"; void HwTransformNode::createVariables(const ShaderNode& node, GenContext&, Shader& shader) const { - const string toSpace = getToSpace(node); + const string toSpace = getToSpace(node); const string fromSpace = getFromSpace(node); const string& matrix = getMatrix(fromSpace, toSpace); if (!matrix.empty()) diff --git a/source/MaterialXGenShader/ShaderGenerator.cpp b/source/MaterialXGenShader/ShaderGenerator.cpp index 177201a9e3..d5f51aed1c 100644 --- a/source/MaterialXGenShader/ShaderGenerator.cpp +++ b/source/MaterialXGenShader/ShaderGenerator.cpp @@ -270,7 +270,7 @@ void ShaderGenerator::registerImplementation(const string& name, CreatorFunction void ShaderGenerator::registerImplementation(const StringVec& nameVec, CreatorFunction creator) { - for(const string& name : nameVec) + for (const string& name : nameVec) { _implFactory.registerClass(name, creator); } diff --git a/source/MaterialXGenShader/ShaderGenerator.h b/source/MaterialXGenShader/ShaderGenerator.h index 8e7f9855de..fa60a4d63e 100644 --- a/source/MaterialXGenShader/ShaderGenerator.h +++ b/source/MaterialXGenShader/ShaderGenerator.h @@ -151,7 +151,7 @@ class MX_GENSHADER_API ShaderGenerator /// Register a shader node implementation for a given implementation element name void registerImplementation(const string& name, CreatorFunction creator); - + /// Register a shader node implementation for a given set of implementation element names void registerImplementation(const StringVec& nameVec, CreatorFunction creator); diff --git a/source/MaterialXGenShader/ShaderNode.cpp b/source/MaterialXGenShader/ShaderNode.cpp index 3e393178f1..9ef5b0789a 100644 --- a/source/MaterialXGenShader/ShaderNode.cpp +++ b/source/MaterialXGenShader/ShaderNode.cpp @@ -290,7 +290,7 @@ ShaderNodePtr ShaderNode::create(const ShaderGraph* parent, const string& name, else if (nodeDef.getNodeString() == CONSTANT) { newNode->_classification = Classification::TEXTURE | Classification::CONSTANT; - } + } else if (nodeDef.getNodeString() == DOT) { newNode->_classification = Classification::TEXTURE | Classification::DOT; diff --git a/source/MaterialXGenShader/ShaderStage.cpp b/source/MaterialXGenShader/ShaderStage.cpp index b5387bcb94..d304c22dd2 100644 --- a/source/MaterialXGenShader/ShaderStage.cpp +++ b/source/MaterialXGenShader/ShaderStage.cpp @@ -82,8 +82,8 @@ ShaderPort* VariableBlock::add(const TypeDesc* type, const string& name, ValuePt else if (type != it->second->getType()) { throw ExceptionShaderGenError("Trying to add shader port '" + name + "' with type '" + - type->getName() + "', but existing shader port with type '" + - it->second->getType()->getName() + "' was found"); + type->getName() + "', but existing shader port with type '" + + it->second->getType()->getName() + "' was found"); } return it->second.get(); } diff --git a/source/MaterialXGraphEditor/FileDialog.h b/source/MaterialXGraphEditor/FileDialog.h index 49b905f28c..4b6c042ef8 100644 --- a/source/MaterialXGraphEditor/FileDialog.h +++ b/source/MaterialXGraphEditor/FileDialog.h @@ -16,9 +16,9 @@ class FileDialog public: enum Flags { - SelectDirectory = 1 << 0, // select directory instead of regular file - EnterNewFilename = 1 << 1, // allow user to enter new filename when selecting regular file - NoTitleBar = 1 << 2, // hide window title bar + SelectDirectory = 1 << 0, // select directory instead of regular file + EnterNewFilename = 1 << 1, // allow user to enter new filename when selecting regular file + NoTitleBar = 1 << 2, // hide window title bar }; public: diff --git a/source/MaterialXGraphEditor/Graph.cpp b/source/MaterialXGraphEditor/Graph.cpp index bab5df7b58..fc682e8f05 100644 --- a/source/MaterialXGraphEditor/Graph.cpp +++ b/source/MaterialXGraphEditor/Graph.cpp @@ -2620,7 +2620,6 @@ void Graph::addLink(ed::PinId startPinId, ed::PinId endPinId) break; } } - } // Since we accepted new link, lets add one to our list of links. @@ -3668,7 +3667,7 @@ void Graph::addNodePopup(bool cursor) // Filter extra nodes - includes inputs, outputs, groups, and node graphs const std::string NODEGRAPH_ENTRY = "Node Graph"; - // Filter nodedefs and add to menu if matches filter + // Filter nodedefs and add to menu if matches filter for (auto node : _nodesToAdd) { // Filter out list of nodes diff --git a/source/MaterialXGraphEditor/RenderView.cpp b/source/MaterialXGraphEditor/RenderView.cpp index d2967e6b85..3c2e01dff9 100644 --- a/source/MaterialXGraphEditor/RenderView.cpp +++ b/source/MaterialXGraphEditor/RenderView.cpp @@ -299,7 +299,7 @@ void RenderView::loadMesh(const mx::FilePath& filename) _cameraTarget = mx::Vector3(); initCamera(); - + if (_shadowMap) { _imageHandler->releaseRenderResources(_shadowMap); @@ -848,7 +848,7 @@ void RenderView::initCamera() { _viewCamera->setViewportSize(mx::Vector2((float) _viewWidth, (float) _viewHeight)); - if ( _geometryHandler->getMeshes().empty()) + if (_geometryHandler->getMeshes().empty()) { return; } diff --git a/source/MaterialXGraphEditor/UiNode.h b/source/MaterialXGraphEditor/UiNode.h index cf7aa41e28..06d0281676 100644 --- a/source/MaterialXGraphEditor/UiNode.h +++ b/source/MaterialXGraphEditor/UiNode.h @@ -101,7 +101,7 @@ class UiPin { if (_connections[i]->_pinId == pin->_pinId) { - _connections.erase(_connections.begin()+i); + _connections.erase(_connections.begin() + i); } } for (size_t i = 0; i < pin->_connections.size(); i++) diff --git a/source/MaterialXRender/Camera.cpp b/source/MaterialXRender/Camera.cpp index 6464246e3a..7b9579376c 100644 --- a/source/MaterialXRender/Camera.cpp +++ b/source/MaterialXRender/Camera.cpp @@ -23,8 +23,8 @@ Matrix44 Camera::createViewMatrix(const Vector3& eye, } Matrix44 Camera::createPerspectiveMatrixZP(float left, float right, - float bottom, float top, - float nearP, float farP) + float bottom, float top, + float nearP, float farP) { return Matrix44( (2.0f * nearP) / (right - left), 0.0f, (right + left) / (right - left), 0.0f, @@ -34,8 +34,8 @@ Matrix44 Camera::createPerspectiveMatrixZP(float left, float right, } Matrix44 Camera::createOrthographicMatrixZP(float left, float right, - float bottom, float top, - float nearP, float farP) + float bottom, float top, + float nearP, float farP) { return Matrix44( 2.0f / (right - left), 0.0f, 0.0f, 0.0f, diff --git a/source/MaterialXRender/Camera.h b/source/MaterialXRender/Camera.h index a20c0f0e70..3135904b5a 100644 --- a/source/MaterialXRender/Camera.h +++ b/source/MaterialXRender/Camera.h @@ -163,17 +163,17 @@ class MX_RENDER_API Camera static Matrix44 createOrthographicMatrix(float left, float right, float bottom, float top, float nearP, float farP); - + /// Create a perpective projection matrix given a set of clip planes with [0,1] projected Z. static Matrix44 createPerspectiveMatrixZP(float left, float right, - float bottom, float top, - float nearP, float farP); + float bottom, float top, + float nearP, float farP); /// Create an orthographic projection matrix given a set of clip planes with [0,1] projected Z. static Matrix44 createOrthographicMatrixZP(float left, float right, - float bottom, float top, - float nearP, float farP); - + float bottom, float top, + float nearP, float farP); + /// Apply a perspective transform to the given 3D point, performing a /// homogeneous divide on the transformed result. static Vector3 transformPointPerspective(const Matrix44& m, const Vector3& v) @@ -185,7 +185,7 @@ class MX_RENDER_API Camera /// @} protected: - // Transform matrices + // Transform matrices Matrix44 _worldMatrix; Matrix44 _viewMatrix; Matrix44 _projectionMatrix; diff --git a/source/MaterialXRender/CgltfLoader.cpp b/source/MaterialXRender/CgltfLoader.cpp index 1c8ec598a6..a9f5208ec4 100644 --- a/source/MaterialXRender/CgltfLoader.cpp +++ b/source/MaterialXRender/CgltfLoader.cpp @@ -59,7 +59,7 @@ void computeMeshMatrices(GLTFMeshMatrixList& meshMatrices, cgltf_node* cnode) } // Iterate over all children. Note that the existence of a mesh - // does not imply that this is a leaf node so traversal should + // does not imply that this is a leaf node so traversal should // continue even when a mesh is encountered. for (cgltf_size i = 0; i < cnode->children_count; i++) { @@ -76,7 +76,7 @@ using GLTFMeshPathList = std::unordered_map; void computeMeshPaths(GLTFMeshPathList& meshPaths, cgltf_node* cnode, FilePath path, size_t nodeCount, size_t meshCount) { string cnodeName = cnode->name ? string(cnode->name) : DEFAULT_NODE_PREFIX + std::to_string(nodeCount++); - path = path / ( createValidName(cnodeName) + "/" ); + path = path / (createValidName(cnodeName) + "/"); cgltf_mesh* cmesh = cnode->mesh; if (cmesh) @@ -92,7 +92,7 @@ void computeMeshPaths(GLTFMeshPathList& meshPaths, cgltf_node* cnode, FilePath p } // Iterate over all children. Note that the existence of a mesh - // does not imply that this is a leaf node so traversal should + // does not imply that this is a leaf node so traversal should // continue even when a mesh is encountered. for (cgltf_size i = 0; i < cnode->children_count; i++) { @@ -220,11 +220,11 @@ bool CgltfLoader::load(const FilePath& filePath, MeshList& meshList, bool texcoo } // Iterate through all parent transform - for (size_t mtx=0; mtx < positionMatrices.size(); mtx++) + for (size_t mtx = 0; mtx < positionMatrices.size(); mtx++) { const Matrix44& positionMatrix = positionMatrices[mtx]; const Matrix44 normalMatrix = positionMatrix.getInverse().getTranspose(); - + for (cgltf_size primitiveIndex = 0; primitiveIndex < cmesh->primitives_count; ++primitiveIndex) { cgltf_primitive* primitive = &cmesh->primitives[primitiveIndex]; @@ -348,7 +348,7 @@ bool CgltfLoader::load(const FilePath& filePath, MeshList& meshList, bool texcoo { if (_debugLevel > 0) std::cout << "Unknown stream type: " << std::to_string(attribute->type) - << std::endl; + << std::endl; } // Fill in stream diff --git a/source/MaterialXRender/CgltfLoader.h b/source/MaterialXRender/CgltfLoader.h index 4f4a7145ba..fb63cb6102 100644 --- a/source/MaterialXRender/CgltfLoader.h +++ b/source/MaterialXRender/CgltfLoader.h @@ -6,7 +6,7 @@ #ifndef MATERIALX_CGLTFLOADER_H #define MATERIALX_CGLTFLOADER_H -/// @file +/// @file /// GLTF format loader using the Cgltf library #include @@ -32,7 +32,7 @@ class MX_RENDER_API CgltfLoader : public GeometryLoader static CgltfLoaderPtr create() { return std::make_shared(); } /// Load geometry from file path - bool load(const FilePath& filePath, MeshList& meshList, bool texcoordVerticalFlip=false) override; + bool load(const FilePath& filePath, MeshList& meshList, bool texcoordVerticalFlip = false) override; private: unsigned int _debugLevel; diff --git a/source/MaterialXRender/GeometryHandler.cpp b/source/MaterialXRender/GeometryHandler.cpp index e2c974a767..dfea0b2ceb 100644 --- a/source/MaterialXRender/GeometryHandler.cpp +++ b/source/MaterialXRender/GeometryHandler.cpp @@ -89,7 +89,7 @@ bool GeometryHandler::loadGeometry(const FilePath& filePath, bool texcoordVertic bool loaded = false; - std::pair range; + std::pair range; string extension = filePath.getExtension(); range = _geometryLoaders.equal_range(extension); GeometryLoaderMap::iterator first = --range.second; @@ -140,19 +140,17 @@ MeshPtr GeometryHandler::createQuadMesh(const Vector2& uvMin, const Vector2& uvM quadTexCoords->setStride(MeshStream::STRIDE_2D); if (!flipTexCoordsHorizontally) { - quadTexCoords->getData().assign({ - uvMax[0], uvMax[1], - uvMax[0], uvMin[1], - uvMin[0], uvMin[1], - uvMin[0], uvMax[1] }); + quadTexCoords->getData().assign({ uvMax[0], uvMax[1], + uvMax[0], uvMin[1], + uvMin[0], uvMin[1], + uvMin[0], uvMax[1] }); } else { - quadTexCoords->getData().assign({ - uvMax[0], uvMin[1], - uvMax[0], uvMax[1], - uvMin[0], uvMax[1], - uvMin[0], uvMin[1] }); + quadTexCoords->getData().assign({ uvMax[0], uvMin[1], + uvMax[0], uvMax[1], + uvMin[0], uvMax[1], + uvMin[0], uvMin[1] }); } MeshPartitionPtr quadIndices = MeshPartition::create(); quadIndices->getIndices().assign({ 0, 1, 3, 1, 2, 3 }); @@ -161,7 +159,7 @@ MeshPtr GeometryHandler::createQuadMesh(const Vector2& uvMin, const Vector2& uvM quadMesh->addStream(quadPositions); quadMesh->addStream(quadTexCoords); quadMesh->addPartition(quadIndices); - + return quadMesh; } diff --git a/source/MaterialXRender/GeometryHandler.h b/source/MaterialXRender/GeometryHandler.h index 0022487602..5dfc561e0e 100644 --- a/source/MaterialXRender/GeometryHandler.h +++ b/source/MaterialXRender/GeometryHandler.h @@ -121,7 +121,7 @@ class MX_RENDER_API GeometryHandler static MeshPtr createQuadMesh(const Vector2& uvMin = Vector2(0.0f, 0.0f), const Vector2& uvMax = Vector2(1.0f, 1.0f), bool flipTexCoordsHorizontally = false); - + protected: // Recompute bounds for all stored geometry void computeBounds(); diff --git a/source/MaterialXRender/Harmonics.cpp b/source/MaterialXRender/Harmonics.cpp index daf6a59d10..3d5c9d0a1d 100644 --- a/source/MaterialXRender/Harmonics.cpp +++ b/source/MaterialXRender/Harmonics.cpp @@ -9,7 +9,8 @@ MATERIALX_NAMESPACE_BEGIN -namespace { +namespace +{ const double PI = std::acos(-1.0); diff --git a/source/MaterialXRender/Harmonics.h b/source/MaterialXRender/Harmonics.h index 10d5f81e49..f51991361a 100644 --- a/source/MaterialXRender/Harmonics.h +++ b/source/MaterialXRender/Harmonics.h @@ -27,7 +27,8 @@ template class ShCoeffs public: ShCoeffs() = default; - explicit ShCoeffs(const std::array& arr) : _arr(arr) { } + explicit ShCoeffs(const std::array& arr) : + _arr(arr) { } /// @name Comparison Operators /// @{ diff --git a/source/MaterialXRender/ImageHandler.cpp b/source/MaterialXRender/ImageHandler.cpp index d54a18fedd..2d56207f32 100644 --- a/source/MaterialXRender/ImageHandler.cpp +++ b/source/MaterialXRender/ImageHandler.cpp @@ -306,12 +306,11 @@ void ImageSamplingProperties::setProperties(const string& fileNameUniform, bool ImageSamplingProperties::operator==(const ImageSamplingProperties& r) const { - return - (enableMipmaps == r.enableMipmaps && - uaddressMode == r.uaddressMode && - vaddressMode == r.vaddressMode && - filterType == r.filterType && - defaultColor == r.defaultColor) ; + return (enableMipmaps == r.enableMipmaps && + uaddressMode == r.uaddressMode && + vaddressMode == r.vaddressMode && + filterType == r.filterType && + defaultColor == r.defaultColor); } MATERIALX_NAMESPACE_END diff --git a/source/MaterialXRender/ImageHandler.h b/source/MaterialXRender/ImageHandler.h index fafc021857..e8eaf99b2f 100644 --- a/source/MaterialXRender/ImageHandler.h +++ b/source/MaterialXRender/ImageHandler.h @@ -35,7 +35,7 @@ using ImageHandlerPtr = std::shared_ptr; using ImageLoaderPtr = std::shared_ptr; /// Map from strings to vectors of image loaders -using ImageLoaderMap = std::unordered_map< string, std::vector >; +using ImageLoaderMap = std::unordered_map>; /// @class ImageSamplingProperties /// Interface to describe sampling properties for images. @@ -48,16 +48,16 @@ class MX_RENDER_API ImageSamplingProperties /// @param uniformBlock Block containing sampler uniforms void setProperties(const string& fileNameUniform, const VariableBlock& uniformBlock); - + bool operator==(const ImageSamplingProperties& r) const; /// Address mode options. Matches enumerations allowed for image address /// modes, except UNSPECIFIED which indicates no explicit mode was defined. enum class AddressMode : int - { + { UNSPECIFIED = -1, CONSTANT = 0, - CLAMP = 1, + CLAMP = 1, PERIODIC = 2, MIRROR = 3 }; diff --git a/source/MaterialXRender/LightHandler.cpp b/source/MaterialXRender/LightHandler.cpp index cc96d979c7..c7d9311005 100644 --- a/source/MaterialXRender/LightHandler.cpp +++ b/source/MaterialXRender/LightHandler.cpp @@ -51,7 +51,7 @@ void LightHandler::findLights(DocumentPtr doc, vector& lights) void LightHandler::registerLights(DocumentPtr doc, const vector& lights, GenContext& context) { - // Clear context light user data which is set when bindLightShader() + // Clear context light user data which is set when bindLightShader() // is called. This is necessary in case the light types have already been // registered. HwShaderGenerator::unbindLightShaders(context); @@ -71,7 +71,7 @@ void LightHandler::registerLights(DocumentPtr doc, const vector& lights } // Make sure max light count is large enough - const unsigned int lightCount = (unsigned int)lights.size(); + const unsigned int lightCount = (unsigned int) lights.size(); if (lightCount > context.getOptions().hwMaxActiveLightSources) { context.getOptions().hwMaxActiveLightSources = lightCount; diff --git a/source/MaterialXRender/LightHandler.h b/source/MaterialXRender/LightHandler.h index 666edd34a1..852ccfa41d 100644 --- a/source/MaterialXRender/LightHandler.h +++ b/source/MaterialXRender/LightHandler.h @@ -48,7 +48,7 @@ class MX_RENDER_API LightHandler /// @name Global State /// @{ - + /// Set the light transform. void setLightTransform(const Matrix44& mat) { diff --git a/source/MaterialXRender/Mesh.cpp b/source/MaterialXRender/Mesh.cpp index 110829cd21..bfa7dedd13 100644 --- a/source/MaterialXRender/Mesh.cpp +++ b/source/MaterialXRender/Mesh.cpp @@ -18,7 +18,8 @@ const string MeshStream::BITANGENT_ATTRIBUTE("bitangent"); const string MeshStream::COLOR_ATTRIBUTE("color"); const string MeshStream::GEOMETRY_PROPERTY_ATTRIBUTE("geomprop"); -namespace { +namespace +{ const float MAX_FLOAT = std::numeric_limits::max(); const size_t FACE_VERTEX_COUNT = 3; @@ -266,7 +267,7 @@ void Mesh::splitByUdims() // MeshStream methods // -void MeshStream::transform(const Matrix44 &matrix) +void MeshStream::transform(const Matrix44& matrix) { unsigned int stride = getStride(); size_t numElements = _data.size() / getStride(); @@ -274,17 +275,17 @@ void MeshStream::transform(const Matrix44 &matrix) getType() == MeshStream::TEXCOORD_ATTRIBUTE || getType() == MeshStream::GEOMETRY_PROPERTY_ATTRIBUTE) { - for (size_t i=0; i @@ -56,7 +56,7 @@ bool OiioImageLoader::saveImage(const FilePath& filePath, written = imageOutput->write_image( format, static_cast(image->getResourceBuffer()) + (image->getHeight() - 1) * scanlinesize, - OIIO::AutoStride, // default x stride + OIIO::AutoStride, // default x stride static_cast(-scanlinesize), // special y stride OIIO::AutoStride); } @@ -66,10 +66,10 @@ bool OiioImageLoader::saveImage(const FilePath& filePath, } imageOutput->close(); - // Handle deallocation in OpenImageIO 1.x - #if OIIO_VERSION < 10903 +// Handle deallocation in OpenImageIO 1.x +#if OIIO_VERSION < 10903 OIIO::ImageOutput::destroy(imageOutput); - #endif +#endif } } return written; @@ -112,10 +112,10 @@ ImagePtr OiioImageLoader::loadImage(const FilePath& filePath) } imageInput->close(); - // Handle deallocation in OpenImageIO 1.x - #if OIIO_VERSION < 10903 +// Handle deallocation in OpenImageIO 1.x +#if OIIO_VERSION < 10903 OIIO::ImageInput::destroy(imageInput); - #endif +#endif return image; } diff --git a/source/MaterialXRender/OiioImageLoader.h b/source/MaterialXRender/OiioImageLoader.h index 6619c85bb2..38781dad9e 100644 --- a/source/MaterialXRender/OiioImageLoader.h +++ b/source/MaterialXRender/OiioImageLoader.h @@ -7,7 +7,7 @@ #define MATERIALX_OIIOIMAGELOADER_H /// @file -/// Image loader wrapper using OpenImageIO +/// Image loader wrapper using OpenImageIO #include @@ -21,7 +21,7 @@ using OiioImageLoaderPtr = std::shared_ptr; class MX_RENDER_API OiioImageLoader : public ImageLoader { public: - OiioImageLoader() + OiioImageLoader() { // Set all extensions supported by OpenImageIO _extensions.insert(BMP_EXTENSION); @@ -40,7 +40,7 @@ class MX_RENDER_API OiioImageLoader : public ImageLoader _extensions.insert(TXT_EXTENSION); _extensions.insert(TXR_EXTENSION); } - virtual ~OiioImageLoader() { } + virtual ~OiioImageLoader() { } /// Create a new OpenImageIO image loader static OiioImageLoaderPtr create() { return std::make_shared(); } diff --git a/source/MaterialXRender/ShaderMaterial.cpp b/source/MaterialXRender/ShaderMaterial.cpp index d51efa54af..7b898fbe85 100644 --- a/source/MaterialXRender/ShaderMaterial.cpp +++ b/source/MaterialXRender/ShaderMaterial.cpp @@ -8,8 +8,9 @@ MATERIALX_NAMESPACE_BEGIN -ShaderMaterial::ShaderMaterial() : _hasTransparency(false) {} -ShaderMaterial::~ShaderMaterial() {} +ShaderMaterial::ShaderMaterial() : + _hasTransparency(false) { } +ShaderMaterial::~ShaderMaterial() { } void ShaderMaterial::setDocument(DocumentPtr doc) { @@ -62,9 +63,9 @@ bool ShaderMaterial::hasTransparency() const } bool ShaderMaterial::generateEnvironmentShader(GenContext& context, - const FilePath& filename, - DocumentPtr stdLib, - const FilePath& imagePath) + const FilePath& filename, + DocumentPtr stdLib, + const FilePath& imagePath) { // Read in the environment nodegraph. DocumentPtr doc = createDocument(); diff --git a/source/MaterialXRender/ShaderMaterial.h b/source/MaterialXRender/ShaderMaterial.h index cf500463e4..f29b6f763c 100644 --- a/source/MaterialXRender/ShaderMaterial.h +++ b/source/MaterialXRender/ShaderMaterial.h @@ -74,7 +74,7 @@ class MX_RENDER_API ShaderMaterial /// Generate a shader from our currently stored element and /// the given generator context. virtual bool generateShader(GenContext& context) = 0; - + /// Copies shader and API specific generated program from ShaderMaterial to this one. virtual void copyShader(MaterialPtr ShaderMaterial) = 0; @@ -86,7 +86,7 @@ class MX_RENDER_API ShaderMaterial const FilePath& filename, DocumentPtr stdLib, const FilePath& imagePath); - + /// Return the underlying hardware shader. ShaderPtr getShader() const; diff --git a/source/MaterialXRender/ShaderRenderer.h b/source/MaterialXRender/ShaderRenderer.h index c1cfbecfa0..829a0252c1 100644 --- a/source/MaterialXRender/ShaderRenderer.h +++ b/source/MaterialXRender/ShaderRenderer.h @@ -34,7 +34,7 @@ class MX_RENDER_API ShaderRenderer enum class MatrixConvention { OpenGL = 0, - Metal = 1 + Metal = 1 }; /// A map with name and source code for each shader stage. using StageMap = StringMap; @@ -133,7 +133,7 @@ class MX_RENDER_API ShaderRenderer protected: ShaderRenderer(unsigned int width, unsigned int height, Image::BaseType baseType, - MatrixConvention matrixConvention = MatrixConvention::OpenGL); + MatrixConvention matrixConvention = MatrixConvention::OpenGL); protected: unsigned int _width; @@ -167,7 +167,7 @@ class MX_RENDER_API ExceptionRenderError : public Exception { } - ExceptionRenderError& operator=(const ExceptionRenderError& e) + ExceptionRenderError& operator=(const ExceptionRenderError& e) { Exception::operator=(e); _errorLog = e._errorLog; diff --git a/source/MaterialXRender/StbImageLoader.cpp b/source/MaterialXRender/StbImageLoader.cpp index d8747b75ad..b367bf741c 100644 --- a/source/MaterialXRender/StbImageLoader.cpp +++ b/source/MaterialXRender/StbImageLoader.cpp @@ -7,9 +7,9 @@ #if defined(_MSC_VER) #pragma warning(push) - #pragma warning(disable: 4100) - #pragma warning(disable: 4505) - #pragma warning(disable: 4996) + #pragma warning(disable : 4100) + #pragma warning(disable : 4505) + #pragma warning(disable : 4996) #endif #define STB_IMAGE_IMPLEMENTATION @@ -96,7 +96,7 @@ ImagePtr StbImageLoader::loadImage(const FilePath& filePath) int height = 0; int channelCount = 0; Image::BaseType baseType = Image::BaseType::UINT8; - void *buffer = nullptr; + void* buffer = nullptr; // Select standard or float reader based on file extension. string extension = filePath.getExtension(); diff --git a/source/MaterialXRender/StbImageLoader.h b/source/MaterialXRender/StbImageLoader.h index dabbb8ca9e..f9d91fbcc7 100644 --- a/source/MaterialXRender/StbImageLoader.h +++ b/source/MaterialXRender/StbImageLoader.h @@ -34,7 +34,7 @@ class MX_RENDER_API StbImageLoader : public ImageLoader _extensions.insert(PSD_EXTENSION); _extensions.insert(TGA_EXTENSION); } - virtual ~StbImageLoader() { } + virtual ~StbImageLoader() { } /// Create a new stb image loader static StbImageLoaderPtr create() { return std::make_shared(); } diff --git a/source/MaterialXRender/TextureBaker.h b/source/MaterialXRender/TextureBaker.h index 54b1016451..ff6f240481 100644 --- a/source/MaterialXRender/TextureBaker.h +++ b/source/MaterialXRender/TextureBaker.h @@ -27,7 +27,7 @@ using BakedDocumentVec = std::vector>; /// A helper class for baking procedural material content to textures. /// TODO: Add support for graphs containing geometric nodes such as position /// and normal. -template +template class TextureBaker : public Renderer { public: @@ -112,7 +112,7 @@ class TextureBaker : public Renderer /// Set the name of the baked graph element. void setBakedGraphName(const string& name) { - _bakedGraphName= name; + _bakedGraphName = name; } /// Return the name of the baked graph element. @@ -142,8 +142,7 @@ class TextureBaker : public Renderer /// Set the texture filename template. void setTextureFilenameTemplate(const string& filenameTemplate) { - _textureFilenameTemplate = (filenameTemplate.find("$EXTENSION") == string::npos) ? - filenameTemplate + ".$EXTENSION" : filenameTemplate; + _textureFilenameTemplate = (filenameTemplate.find("$EXTENSION") == string::npos) ? filenameTemplate + ".$EXTENSION" : filenameTemplate; } /// Set texFilenameOverrides if template variable exists. @@ -218,13 +217,13 @@ class TextureBaker : public Renderer void optimizeBakedTextures(NodePtr shader); /// Bake material to document in memory and write baked textures to disk. - DocumentPtr bakeMaterialToDoc(DocumentPtr doc, const FileSearchPath& searchPath, const string& materialPath, + DocumentPtr bakeMaterialToDoc(DocumentPtr doc, const FileSearchPath& searchPath, const string& materialPath, const StringVec& udimSet, std::string& documentName); /// Bake materials in the given document and write them to disk. If multiple documents are written, /// then the given output filename will be used as a template. void bakeAllMaterials(DocumentPtr doc, const FileSearchPath& searchPath, const FilePath& outputFileName); - + /// Set whether to write a separate document per material when calling bakeAllMaterials. /// By default separate documents are written. void writeDocumentPerMaterial(bool value) @@ -295,7 +294,7 @@ class TextureBaker : public Renderer StringMap _bakedInputMap; std::unordered_map _worldSpaceNodes; - + bool _flipSavedImage; bool _writeDocumentPerMaterial; diff --git a/source/MaterialXRender/TextureBaker.inl b/source/MaterialXRender/TextureBaker.inl index bcc9401210..65759ed998 100644 --- a/source/MaterialXRender/TextureBaker.inl +++ b/source/MaterialXRender/TextureBaker.inl @@ -13,7 +13,8 @@ MATERIALX_NAMESPACE_BEGIN -namespace { +namespace +{ const string SRGB_TEXTURE = "srgb_texture"; const string LIN_REC709 = "lin_rec709"; @@ -23,7 +24,7 @@ const string DEFAULT_UDIM_PREFIX = "_"; } // anonymous namespace -template +template string TextureBaker::getValueStringFromColor(const Color4& color, const string& type) { if (type == "color4" || type == "vector4") @@ -45,7 +46,7 @@ string TextureBaker::getValueStringFromColor(const Color4& return EMPTY_STRING; } -template +template TextureBaker::TextureBaker(unsigned int width, unsigned int height, Image::BaseType baseType, bool flipSavedImage) : Renderer(width, height, baseType), _distanceUnit("meter"), @@ -97,7 +98,7 @@ TextureBaker::TextureBaker(unsigned int width, unsigned int _frameCaptureImage->createResourceBuffer(); } -template +template size_t TextureBaker::findVarInTemplate(const string& filename, const string& var, size_t start) { size_t i = filename.find(var, start); @@ -112,17 +113,15 @@ size_t TextureBaker::findVarInTemplate(const string& filena return i; } -template +template FilePath TextureBaker::generateTextureFilename(const StringMap& filenameTemplateMap) { string bakedImageName = _textureFilenameTemplate; for (auto& pair : filenameTemplateMap) { - string replacement = (_texTemplateOverrides.count(pair.first)) ? - _texTemplateOverrides[pair.first] : pair.second; - replacement = (filenameTemplateMap.at("$UDIM").empty() && pair.first == "$UDIMPREFIX") ? - EMPTY_STRING : replacement; + string replacement = (_texTemplateOverrides.count(pair.first)) ? _texTemplateOverrides[pair.first] : pair.second; + replacement = (filenameTemplateMap.at("$UDIM").empty() && pair.first == "$UDIMPREFIX") ? EMPTY_STRING : replacement; for (size_t i = 0; (i = findVarInTemplate(bakedImageName, pair.first, i)) != string::npos; i++) { @@ -140,7 +139,7 @@ FilePath TextureBaker::generateTextureFilename(const String return _outputImagePath / bakedImageName; } -template +template StringMap TextureBaker::initializeFileTemplateMap(InputPtr input, NodePtr shader, const string& udim) { FilePath assetPath = FilePath(shader->getActiveSourceUri()); @@ -156,7 +155,7 @@ StringMap TextureBaker::initializeFileTemplateMap(InputPtr return filenameTemplateMap; } -template +template bool TextureBaker::writeBakedImage(const BakedImage& baked, ImagePtr image) { if (!Renderer::_imageHandler->saveImage(baked.filename, image, _flipSavedImage)) @@ -176,11 +175,11 @@ bool TextureBaker::writeBakedImage(const BakedImage& baked, return true; } -template +template void TextureBaker::bakeShaderInputs(NodePtr material, NodePtr shader, GenContext& context, const string& udim) { _material = material; - + if (!shader) { return; @@ -216,16 +215,16 @@ void TextureBaker::bakeShaderInputs(NodePtr material, NodeP Renderer::_imageHandler->clearImageCache(); } -template +template void TextureBaker::bakeGraphOutput(OutputPtr output, GenContext& context, const StringMap& filenameTemplateMap) { if (!output) { return; } - + bool encodeSrgb = _colorSpace == SRGB_TEXTURE && - (output->getType() == "color3" || output->getType() == "color4"); + (output->getType() == "color3" || output->getType() == "color4"); Renderer::getFramebuffer()->setEncodeSrgb(encodeSrgb); ShaderPtr shader = _generator->generate("BakingShader", output, context); @@ -258,7 +257,7 @@ void TextureBaker::bakeGraphOutput(OutputPtr output, GenCon } } -template +template void TextureBaker::optimizeBakedTextures(NodePtr shader) { if (!shader) @@ -320,7 +319,7 @@ void TextureBaker::optimizeBakedTextures(NodePtr shader) } } -template +template DocumentPtr TextureBaker::generateNewDocumentFromShader(NodePtr shader, const StringVec& udimSet) { if (!shader) @@ -359,7 +358,7 @@ DocumentPtr TextureBaker::generateNewDocumentFromShader(Nod // Optionally create a material node, connecting it to the new shader node. if (_material) { - string materialName = (_texTemplateOverrides.count("$MATERIAL"))? _texTemplateOverrides["$MATERIAL"] : _material->getName(); + string materialName = (_texTemplateOverrides.count("$MATERIAL")) ? _texTemplateOverrides["$MATERIAL"] : _material->getName(); NodePtr bakedMaterial = _bakedTextureDoc->addNode(_material->getCategory(), materialName + BAKED_POSTFIX, _material->getType()); for (auto sourceMaterialInput : _material->getInputs()) { @@ -483,9 +482,9 @@ DocumentPtr TextureBaker::generateNewDocumentFromShader(Nod return _bakedTextureDoc; } -template +template DocumentPtr TextureBaker::bakeMaterialToDoc(DocumentPtr doc, const FileSearchPath& searchPath, const string& materialPath, - const StringVec& udimSet, string& documentName) + const StringVec& udimSet, string& documentName) { if (_outputStream) { @@ -551,7 +550,7 @@ DocumentPtr TextureBaker::bakeMaterialToDoc(DocumentPtr doc return generateNewDocumentFromShader(shaderNode, udimSet); } -template +template void TextureBaker::bakeAllMaterials(DocumentPtr doc, const FileSearchPath& searchPath, const FilePath& outputFilename) { if (_outputImagePath.isEmpty()) @@ -593,31 +592,31 @@ void TextureBaker::bakeAllMaterials(DocumentPtr doc, const if (_writeDocumentPerMaterial) { - // Write documents in memory to disk. - size_t bakeCount = bakedDocuments.size(); - for (size_t i = 0; i < bakeCount; i++) - { - if (bakedDocuments[i].second) + // Write documents in memory to disk. + size_t bakeCount = bakedDocuments.size(); + for (size_t i = 0; i < bakeCount; i++) { - FilePath writeFilename = outputFilename; - - // Add additional filename decorations if there are multiple documents. - if (bakedDocuments.size() > 1) + if (bakedDocuments[i].second) { - const string extension = writeFilename.getExtension(); - writeFilename.removeExtension(); - string filenameSeparator = writeFilename.isDirectory()? EMPTY_STRING : "_"; - writeFilename = FilePath(writeFilename.asString() + filenameSeparator + bakedDocuments[i].first + "." + extension); - } + FilePath writeFilename = outputFilename; - writeToXmlFile(bakedDocuments[i].second, writeFilename); - if (_outputStream) - { - *_outputStream << "Wrote baked document: " << writeFilename.asString() << std::endl; + // Add additional filename decorations if there are multiple documents. + if (bakedDocuments.size() > 1) + { + const string extension = writeFilename.getExtension(); + writeFilename.removeExtension(); + string filenameSeparator = writeFilename.isDirectory() ? EMPTY_STRING : "_"; + writeFilename = FilePath(writeFilename.asString() + filenameSeparator + bakedDocuments[i].first + "." + extension); + } + + writeToXmlFile(bakedDocuments[i].second, writeFilename); + if (_outputStream) + { + *_outputStream << "Wrote baked document: " << writeFilename.asString() << std::endl; + } } } } -} else if (_bakedTextureDoc) { writeToXmlFile(_bakedTextureDoc, outputFilename); @@ -628,7 +627,7 @@ void TextureBaker::bakeAllMaterials(DocumentPtr doc, const } } -template +template void TextureBaker::setupUnitSystem(DocumentPtr unitDefinitions) { UnitTypeDefPtr distanceTypeDef = unitDefinitions ? unitDefinitions->getUnitTypeDef("distance") : nullptr; diff --git a/source/MaterialXRender/TinyObjLoader.cpp b/source/MaterialXRender/TinyObjLoader.cpp index 324a1df3e7..b01af1ebf9 100644 --- a/source/MaterialXRender/TinyObjLoader.cpp +++ b/source/MaterialXRender/TinyObjLoader.cpp @@ -23,7 +23,8 @@ MATERIALX_NAMESPACE_BEGIN -namespace { +namespace +{ const float MAX_FLOAT = std::numeric_limits::max(); const size_t FACE_VERTEX_COUNT = 3; @@ -32,9 +33,10 @@ class VertexVector : public VectorN { public: using VectorN::VectorN; - VertexVector(const Vector3& p, const Vector3& n, const Vector2& t) : VectorN(Uninit{}) + VertexVector(const Vector3& p, const Vector3& n, const Vector2& t) : + VectorN(Uninit{}) { - _arr = {p[0], p[1], p[2], n[0], n[1], n[2], t[0], t[1]}; + _arr = { p[0], p[1], p[2], n[0], n[1], n[2], t[0], t[1] }; } }; diff --git a/source/MaterialXRender/TinyObjLoader.h b/source/MaterialXRender/TinyObjLoader.h index 8cfb80762b..e3934f9e41 100644 --- a/source/MaterialXRender/TinyObjLoader.h +++ b/source/MaterialXRender/TinyObjLoader.h @@ -6,7 +6,7 @@ #ifndef MATERIALX_TINYOBJLOADER_H #define MATERIALX_TINYOBJLOADER_H -/// @file +/// @file /// OBJ geometry format loader using the TinyObj library #include diff --git a/source/MaterialXRender/Types.h b/source/MaterialXRender/Types.h index 6af59b9122..4cf936492b 100644 --- a/source/MaterialXRender/Types.h +++ b/source/MaterialXRender/Types.h @@ -63,9 +63,10 @@ class MX_RENDER_API Vector3d : public VectorN public: using VectorN::VectorN; Vector3d() = default; - Vector3d(double x, double y, double z) : VectorN(Uninit{}) + Vector3d(double x, double y, double z) : + VectorN(Uninit{}) { - _arr = {x, y, z}; + _arr = { x, y, z }; } }; @@ -76,9 +77,10 @@ class MX_RENDER_API Vector4d : public VectorN public: using VectorN::VectorN; Vector4d() = default; - Vector4d(double x, double y, double z, double w) : VectorN(Uninit{}) + Vector4d(double x, double y, double z, double w) : + VectorN(Uninit{}) { - _arr = {x, y, z, w}; + _arr = { x, y, z, w }; } }; @@ -89,9 +91,10 @@ class MX_RENDER_API Color3d : public VectorN public: using VectorN::VectorN; Color3d() = default; - Color3d(double r, double g, double b) : VectorN(Uninit{}) + Color3d(double r, double g, double b) : + VectorN(Uninit{}) { - _arr = {r, g, b}; + _arr = { r, g, b }; } }; @@ -101,7 +104,8 @@ class MX_RENDER_API Color3d : public VectorN class MX_RENDER_API Half { public: - explicit Half(float value) : _data(toFloat16(value)) { } + explicit Half(float value) : + _data(toFloat16(value)) { } operator float() const { return toFloat32(_data); } bool operator==(Half rhs) const { return float(*this) == float(rhs); } @@ -134,9 +138,9 @@ class MX_RENDER_API Half static constexpr int const shift = 13; static constexpr int const shiftSign = 16; - static constexpr int32_t const infN = 0x7F800000; // flt32 infinity - static constexpr int32_t const maxN = 0x477FE000; // max flt16 normal as a flt32 - static constexpr int32_t const minN = 0x38800000; // min flt16 normal as a flt32 + static constexpr int32_t const infN = 0x7F800000; // flt32 infinity + static constexpr int32_t const maxN = 0x477FE000; // max flt16 normal as a flt32 + static constexpr int32_t const minN = 0x38800000; // min flt16 normal as a flt32 static constexpr int32_t const signN = (int32_t) 0x80000000; // flt32 sign bit static constexpr int32_t const infC = infN >> shift; diff --git a/source/MaterialXRender/Util.h b/source/MaterialXRender/Util.h index 10799cfd33..922c06e529 100644 --- a/source/MaterialXRender/Util.h +++ b/source/MaterialXRender/Util.h @@ -31,28 +31,28 @@ MX_RENDER_API ShaderPtr createShader(const string& shaderName, GenContext& conte /// Create a shader with a constant color output, using the given standard libraries /// for code generation. MX_RENDER_API ShaderPtr createConstantShader(GenContext& context, - DocumentPtr stdLib, - const string& shaderName, - const Color3& color); + DocumentPtr stdLib, + const string& shaderName, + const Color3& color); /// Create a shader with depth value output, using the given standard libraries /// for code generation. MX_RENDER_API ShaderPtr createDepthShader(GenContext& context, - DocumentPtr stdLib, - const string& shaderName); + DocumentPtr stdLib, + const string& shaderName); /// Create a shader that generates a look-up table for directional albedo, using /// the given standard libraries for code generation. MX_RENDER_API ShaderPtr createAlbedoTableShader(GenContext& context, - DocumentPtr stdLib, - const string& shaderName); + DocumentPtr stdLib, + const string& shaderName); /// Create a blur shader, using the given standard libraries for code generation. MX_RENDER_API ShaderPtr createBlurShader(GenContext& context, - DocumentPtr stdLib, - const string& shaderName, - const string& filterType, - float filterSize); + DocumentPtr stdLib, + const string& shaderName, + const string& filterType, + float filterSize); /// @} /// @name User Interface Utilities diff --git a/source/MaterialXRenderGlsl/GLContext.cpp b/source/MaterialXRenderGlsl/GLContext.cpp index a8fac5b338..e6ebb7674f 100644 --- a/source/MaterialXRenderGlsl/GLContext.cpp +++ b/source/MaterialXRenderGlsl/GLContext.cpp @@ -4,12 +4,12 @@ // #if defined(_WIN32) -#include + #include #elif defined(__linux__) || defined(__FreeBSD__) -#include + #include #elif defined(__APPLE__) -#include -#include + #include + #include #endif #include @@ -130,7 +130,7 @@ GLContext::GLContext(const SimpleWindowPtr window, HardwareContextHandle sharedW _isValid(false) { void* pixelFormat = NSOpenGLChoosePixelFormatWrapper(true, 0, 32, 24, 8, 0, 0, false, - false, false, false, false); + false, false, false, false); if (!pixelFormat) { return; diff --git a/source/MaterialXRenderGlsl/GLContext.h b/source/MaterialXRenderGlsl/GLContext.h index 733778d3c7..f4e4dc1b31 100644 --- a/source/MaterialXRenderGlsl/GLContext.h +++ b/source/MaterialXRenderGlsl/GLContext.h @@ -14,9 +14,9 @@ #include #if defined(__APPLE__) -#include + #include #elif defined(__linux__) || defined(__FreeBSD__) -#include + #include #endif MATERIALX_NAMESPACE_BEGIN diff --git a/source/MaterialXRenderGlsl/GLFramebuffer.cpp b/source/MaterialXRenderGlsl/GLFramebuffer.cpp index bb8e567c58..9516e9ad43 100644 --- a/source/MaterialXRenderGlsl/GLFramebuffer.cpp +++ b/source/MaterialXRenderGlsl/GLFramebuffer.cpp @@ -75,33 +75,33 @@ GLFramebuffer::GLFramebuffer(unsigned int width, unsigned int height, unsigned i string errorMessage; switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; - break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; - break; - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - errorMessage = "GL_FRAMEBUFFER_UNSUPPORTED"; - break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; - break; - case GL_FRAMEBUFFER_UNDEFINED: - errorMessage = "GL_FRAMEBUFFER_UNDEFINED"; - break; - case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: - errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; - break; - default: - errorMessage = std::to_string(status); - break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + errorMessage = "GL_FRAMEBUFFER_UNSUPPORTED"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; + break; + case GL_FRAMEBUFFER_UNDEFINED: + errorMessage = "GL_FRAMEBUFFER_UNDEFINED"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + errorMessage = "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; + break; + default: + errorMessage = std::to_string(status); + break; } throw ExceptionRenderError("Frame buffer object setup failed: " + errorMessage); diff --git a/source/MaterialXRenderGlsl/GLTextureHandler.h b/source/MaterialXRenderGlsl/GLTextureHandler.h index 4485ab98eb..942d6dc446 100644 --- a/source/MaterialXRenderGlsl/GLTextureHandler.h +++ b/source/MaterialXRenderGlsl/GLTextureHandler.h @@ -33,7 +33,7 @@ class MX_RENDERGLSL_API GLTextureHandler : public ImageHandler /// will fail if there are not enough available image units to bind to. bool bindImage(ImagePtr image, const ImageSamplingProperties& samplingProperties) override; - /// Unbind an image. + /// Unbind an image. bool unbindImage(ImagePtr image) override; /// Create rendering resources for the given image. diff --git a/source/MaterialXRenderGlsl/GlslMaterial.cpp b/source/MaterialXRenderGlsl/GlslMaterial.cpp index ce4582d44f..84668d2d0a 100644 --- a/source/MaterialXRenderGlsl/GlslMaterial.cpp +++ b/source/MaterialXRenderGlsl/GlslMaterial.cpp @@ -38,7 +38,7 @@ bool GlslMaterial::loadSource(const FilePath& vertexShaderFile, const FilePath& } // TODO: - // Here we set new source code on the _glProgram without rebuilding + // Here we set new source code on the _glProgram without rebuilding // the _hwShader instance. So the _hwShader is not in sync with the // _glProgram after this operation. _glProgram = GlslProgram::create(); diff --git a/source/MaterialXRenderGlsl/GlslMaterial.h b/source/MaterialXRenderGlsl/GlslMaterial.h index 1e3d0f7f3b..1ae945867a 100644 --- a/source/MaterialXRenderGlsl/GlslMaterial.h +++ b/source/MaterialXRenderGlsl/GlslMaterial.h @@ -24,7 +24,8 @@ using GlslMaterialPtr = std::shared_ptr; class MX_RENDERGLSL_API GlslMaterial : public ShaderMaterial { public: - GlslMaterial() : ShaderMaterial() + GlslMaterial() : + ShaderMaterial() { } ~GlslMaterial() { } @@ -45,7 +46,7 @@ class MX_RENDERGLSL_API GlslMaterial : public ShaderMaterial /// Generate a shader from the given hardware shader. bool generateShader(ShaderPtr hwShader) override; - + /// Copy shader from one material to this one void copyShader(MaterialPtr material) override { diff --git a/source/MaterialXRenderGlsl/GlslProgram.cpp b/source/MaterialXRenderGlsl/GlslProgram.cpp index 900cac0ef1..4497019e91 100644 --- a/source/MaterialXRenderGlsl/GlslProgram.cpp +++ b/source/MaterialXRenderGlsl/GlslProgram.cpp @@ -59,7 +59,7 @@ void GlslProgram::setStages(ShaderPtr shader) // Extract out the shader code per stage _shader = shader; - for (size_t i =0; inumStages(); ++i) + for (size_t i = 0; i < shader->numStages(); ++i) { const ShaderStage& stage = shader->getStage(i); addStage(stage.getName(), stage.getSourceCode()); @@ -101,7 +101,7 @@ void GlslProgram::build() // Compile vertex shader, if any GLuint vertexShaderId = UNDEFINED_OPENGL_RESOURCE_ID; - const string &vertexShaderSource = _stages[Stage::VERTEX]; + const string& vertexShaderSource = _stages[Stage::VERTEX]; if (!vertexShaderSource.empty()) { vertexShaderId = glCreateShader(GL_VERTEX_SHADER); @@ -138,7 +138,7 @@ void GlslProgram::build() fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); // Compile fragment shader - const char *fragmentChar = fragmentShaderSource.c_str(); + const char* fragmentChar = fragmentShaderSource.c_str(); glShaderSource(fragmentShaderId, 1, &fragmentChar, nullptr); glCompileShader(fragmentShaderId); @@ -324,7 +324,7 @@ void GlslProgram::bindPartition(MeshPartitionPtr part) void GlslProgram::bindMesh(MeshPtr mesh) { - _enabledStreamLocations.clear(); + _enabledStreamLocations.clear(); if (_programId == UNDEFINED_OPENGL_RESOURCE_ID) { @@ -547,7 +547,7 @@ void GlslProgram::bindTextures(ImageHandlerPtr imageHandler) // Always bind a texture unless it is a lighting texture. // Lighting textures are handled in the bindLighting() call. - // If no texture can be loaded then the default color defined in + // If no texture can be loaded then the default color defined in // "samplingProperties" will be used to create a fallback texture. if (fileName != HW::ENV_RADIANCE && fileName != HW::ENV_IRRADIANCE) @@ -903,7 +903,7 @@ const GlslProgram::InputMap& GlslProgram::updateUniformsList() // Process constants const VariableBlock& constants = ps.getConstantBlock(); - for (size_t i=0; i< constants.size(); ++i) + for (size_t i = 0; i < constants.size(); ++i) { const ShaderPort* v = constants[i]; // There is no way to match with an unnamed variable @@ -1197,9 +1197,9 @@ void GlslProgram::printUniforms(std::ostream& outputStream) string colorspace = input.second->colorspace; bool isConstant = input.second->isConstant; outputStream << "Program Uniform: \"" << input.first - << "\". Location:" << location - << ". GLtype: " << std::hex << gltype - << ". Size: " << std::dec << size; + << "\". Location:" << location + << ". GLtype: " << std::hex << gltype + << ". Size: " << std::dec << size; if (!type.empty()) outputStream << ". TypeString: \"" << type << "\""; if (!value.empty()) @@ -1217,7 +1217,6 @@ void GlslProgram::printUniforms(std::ostream& outputStream) } } - void GlslProgram::printAttributes(std::ostream& outputStream) { updateAttributesList(); @@ -1229,9 +1228,9 @@ void GlslProgram::printAttributes(std::ostream& outputStream) string type = input.second->typeString; string value = input.second->value ? input.second->value->getValueString() : EMPTY_STRING; outputStream << "Program Attribute: \"" << input.first - << "\". Location:" << location - << ". GLtype: " << std::hex << gltype - << ". Size: " << std::dec << size; + << "\". Location:" << location + << ". GLtype: " << std::hex << gltype + << ". Size: " << std::dec << size; if (!type.empty()) outputStream << ". TypeString: \"" << type << "\""; if (!value.empty()) diff --git a/source/MaterialXRenderGlsl/GlslProgram.h b/source/MaterialXRenderGlsl/GlslProgram.h index 2538c63fcb..08b5dc7cd5 100644 --- a/source/MaterialXRenderGlsl/GlslProgram.h +++ b/source/MaterialXRenderGlsl/GlslProgram.h @@ -109,7 +109,7 @@ class MX_RENDERGLSL_API GlslProgram string path; /// Unit string unit; - /// Colorspace + /// Colorspace string colorspace; /// Program input constructor @@ -119,7 +119,8 @@ class MX_RENDERGLSL_API GlslProgram size(inputSize), isConstant(false), path(inputPath) - { } + { + } }; /// Program input structure shared pointer type using InputPtr = std::shared_ptr; diff --git a/source/MaterialXRenderGlsl/GlslRenderer.h b/source/MaterialXRenderGlsl/GlslRenderer.h index 9ea121aec9..bdf16b44b3 100644 --- a/source/MaterialXRenderGlsl/GlslRenderer.h +++ b/source/MaterialXRenderGlsl/GlslRenderer.h @@ -50,7 +50,7 @@ class MX_RENDERGLSL_API GlslRenderer : public ShaderRenderer { return GLTextureHandler::create(imageLoader); } - + /// Destructor virtual ~GlslRenderer() { } diff --git a/source/MaterialXRenderGlsl/TextureBaker.h b/source/MaterialXRenderGlsl/TextureBaker.h index be1f713cd6..c084b00a1a 100644 --- a/source/MaterialXRenderGlsl/TextureBaker.h +++ b/source/MaterialXRenderGlsl/TextureBaker.h @@ -37,7 +37,7 @@ class MX_RENDERGLSL_API TextureBakerGlsl : public TextureBaker; /// @class SimpleWindow /// A platform-independent window class. -/// +/// /// Plaform-specific resources are encapsulated by a WindowWrapper instance. class MX_RENDERHW_API SimpleWindow { @@ -30,7 +30,7 @@ class MX_RENDERHW_API SimpleWindow virtual ~SimpleWindow(); /// Window initialization - bool initialize(const char* title, unsigned int width, unsigned int height, void *applicationShell); + bool initialize(const char* title, unsigned int width, unsigned int height, void* applicationShell); /// Return our platform-specific resource wrapper WindowWrapperPtr getWindowWrapper() diff --git a/source/MaterialXRenderHw/SimpleWindowLinux.cpp b/source/MaterialXRenderHw/SimpleWindowLinux.cpp index 23779bd92b..75014d4395 100644 --- a/source/MaterialXRenderHw/SimpleWindowLinux.cpp +++ b/source/MaterialXRenderHw/SimpleWindowLinux.cpp @@ -8,8 +8,8 @@ #include #include -#include // for applicationShellWidgetClass -#include // for XEvent definition +#include // for applicationShellWidgetClass +#include // for XEvent definition #include // for XtCallbackProc definition MATERIALX_NAMESPACE_BEGIN @@ -26,7 +26,7 @@ SimpleWindow::SimpleWindow() : bool SimpleWindow::initialize(const char* title, unsigned int width, unsigned int height, - void *applicationShell) + void* applicationShell) { int n = 0; @@ -40,8 +40,8 @@ bool SimpleWindow::initialize(const char* title, if (!initializedXServer) { batchShell = XtOpenApplication(&appContext, "__mx_dummy__app__", - 0, 0, &n, 0, 0, - applicationShellWidgetClass, 0, 0); + 0, 0, &n, 0, 0, + applicationShellWidgetClass, 0, 0); initializedXServer = true; } shell = batchShell; @@ -49,13 +49,13 @@ bool SimpleWindow::initialize(const char* title, else { // Reuse existing application shell; - shell = (Widget)applicationShell; + shell = (Widget) applicationShell; } if (!shell) { _id = 0; - return false;; + return false; } Arg args[6]; diff --git a/source/MaterialXRenderHw/SimpleWindowWindows.cpp b/source/MaterialXRenderHw/SimpleWindowWindows.cpp index de5cf48fc1..56bea01777 100644 --- a/source/MaterialXRenderHw/SimpleWindowWindows.cpp +++ b/source/MaterialXRenderHw/SimpleWindowWindows.cpp @@ -30,19 +30,19 @@ LRESULT CALLBACK NoOpProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { - case WM_CLOSE: - case WM_DESTROY: - break; - default: - return DefWindowProc(hWnd, msg, wParam, lParam); - break; + case WM_CLOSE: + case WM_DESTROY: + break; + default: + return DefWindowProc(hWnd, msg, wParam, lParam); + break; } return 0; } bool SimpleWindow::initialize(const char* title, unsigned int width, unsigned int height, - void * /*applicationShell*/) + void* /*applicationShell*/) { HINSTANCE hInstance = GetModuleHandle(NULL); @@ -50,14 +50,14 @@ bool SimpleWindow::initialize(const char* title, // WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - wc.lpfnWndProc = (WNDPROC)NoOpProc; + wc.lpfnWndProc = (WNDPROC) NoOpProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; // Set the instance to this application wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; // No background required - wc.lpszMenuName = NULL; // No menu required + wc.lpszMenuName = NULL; // No menu required wc.lpszClassName = _windowClassName; if (!RegisterClass(&wc)) @@ -73,10 +73,10 @@ bool SimpleWindow::initialize(const char* title, // Set the rectangle of the client area. RECT WindowRect; - WindowRect.left = (long)0; - WindowRect.top = (long)0; - WindowRect.right = (long)width; - WindowRect.bottom = (long)height; + WindowRect.left = (long) 0; + WindowRect.top = (long) 0; + WindowRect.right = (long) width; + WindowRect.bottom = (long) height; // Calculate the exact window size (including border) so that the // client area has the desired dimensions. @@ -85,14 +85,14 @@ bool SimpleWindow::initialize(const char* title, // Attempt to create the window. HWND hWnd = CreateWindowEx(dwExStyle, _windowClassName, title, - dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, // Window position - WindowRect.right - WindowRect.left, // Window width (including borders) - WindowRect.bottom - WindowRect.top, // Window height (including borders/title bar) - NULL, // No parent window - NULL, // No menu - hInstance, // Instance - NULL); // Don't pass anything To WM_CREATE + dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + 0, 0, // Window position + WindowRect.right - WindowRect.left, // Window width (including borders) + WindowRect.bottom - WindowRect.top, // Window height (including borders/title bar) + NULL, // No parent window + NULL, // No menu + hInstance, // Instance + NULL); // Don't pass anything To WM_CREATE if (!hWnd) { diff --git a/source/MaterialXRenderMsl/MetalFramebuffer.h b/source/MaterialXRenderMsl/MetalFramebuffer.h index ba38365da4..6c8f061a12 100644 --- a/source/MaterialXRenderMsl/MetalFramebuffer.h +++ b/source/MaterialXRenderMsl/MetalFramebuffer.h @@ -48,7 +48,7 @@ class MX_RENDERMSL_API MetalFramebuffer /// to the framebuffer are encoded to the sRGB color space. void setEncodeSrgb(bool encode) { - if(encode != _encodeSrgb) + if (encode != _encodeSrgb) { _encodeSrgb = encode; resize(_width, _height, true); @@ -60,13 +60,13 @@ class MX_RENDERMSL_API MetalFramebuffer { return _encodeSrgb; } - + /// Return the framebuffer width unsigned int getWidth() const { return _width; } /// Return the framebuffer height unsigned int getHeight() const { return _height; } - + /// Bind the framebuffer for rendering. void bind(MTLRenderPassDescriptor* renderpassDesc); @@ -78,18 +78,18 @@ class MX_RENDERMSL_API MetalFramebuffer { return _colorTexture; } - + void setColorTexture(id newColorTexture) { auto sameDim = [](id tex0, id tex1) -> bool { - return [tex0 width] == [tex1 width] && - [tex0 height] == [tex1 height]; + return [tex0 width] == [tex1 width] && + [tex0 height] == [tex1 height]; }; - if((!_colorTextureOwned || sameDim(_colorTexture, newColorTexture)) && - sameDim(newColorTexture, _depthTexture)) + if ((!_colorTextureOwned || sameDim(_colorTexture, newColorTexture)) && + sameDim(newColorTexture, _depthTexture)) { - if(_colorTextureOwned) + if (_colorTextureOwned) [_colorTexture release]; _colorTexture = newColorTexture; } @@ -122,10 +122,10 @@ class MX_RENDERMSL_API MetalFramebuffer Image::BaseType _baseType; bool _encodeSrgb; - id _device = nil; + id _device = nil; id _colorTexture = nil; id _depthTexture = nil; - + bool _colorTextureOwned = false; }; diff --git a/source/MaterialXRenderMsl/MetalFramebuffer.mm b/source/MaterialXRenderMsl/MetalFramebuffer.mm index 432d533fd3..17ee9de9a1 100644 --- a/source/MaterialXRenderMsl/MetalFramebuffer.mm +++ b/source/MaterialXRenderMsl/MetalFramebuffer.mm @@ -71,19 +71,19 @@ if (width != _width || _height != height || forceRecreate) { // Convert texture format to Metal - MTLDataType dataType; - if(pixelFormat == MTLPixelFormatInvalid) + MTLDataType dataType; + if (pixelFormat == MTLPixelFormatInvalid) MetalTextureHandler::mapTextureFormatToMetal(_baseType, _channelCount, _encodeSrgb, dataType, pixelFormat); MTLTextureDescriptor* texDescriptor = [MTLTextureDescriptor - texture2DDescriptorWithPixelFormat:pixelFormat - width:width - height:height - mipmapped:NO]; + texture2DDescriptorWithPixelFormat:pixelFormat + width:width + height:height + mipmapped:NO]; [texDescriptor setStorageMode:MTLStorageModePrivate]; - [texDescriptor setUsage:MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead]; - - if(extColorTexture == nil) + [texDescriptor setUsage:MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead]; + + if (extColorTexture == nil) { _colorTexture = [_device newTextureWithDescriptor:texDescriptor]; _colorTextureOwned = true; @@ -93,7 +93,7 @@ _colorTexture = extColorTexture; _colorTextureOwned = false; } - + texDescriptor.pixelFormat = MTLPixelFormatDepth32Float; [texDescriptor setUsage:MTLTextureUsageRenderTarget]; _depthTexture = [_device newTextureWithDescriptor:texDescriptor]; @@ -108,13 +108,13 @@ [renderpassDesc.colorAttachments[0] setTexture:getColorTexture()]; [renderpassDesc.colorAttachments[0] setLoadAction:MTLLoadActionClear]; [renderpassDesc.colorAttachments[0] setStoreAction:MTLStoreActionStore]; - + [renderpassDesc.depthAttachment setTexture:getDepthTexture()]; [renderpassDesc.depthAttachment setClearDepth:1.0]; [renderpassDesc.depthAttachment setLoadAction:MTLLoadActionClear]; [renderpassDesc.depthAttachment setStoreAction:MTLStoreActionStore]; [renderpassDesc setStencilAttachment:nil]; - + [renderpassDesc setRenderTargetWidth:_width]; [renderpassDesc setRenderTargetHeight:_height]; } @@ -130,45 +130,45 @@ image = Image::create(_width, _height, _channelCount, _baseType); image->createResourceBuffer(); } - - if(cmdQueue == nil) + + if (cmdQueue == nil) { return image; } - - size_t bytesPerRow = _width*_channelCount*MetalTextureHandler::getTextureBaseTypeSize(_baseType); + + size_t bytesPerRow = _width * _channelCount * MetalTextureHandler::getTextureBaseTypeSize(_baseType); size_t bytesPerImage = _height * bytesPerRow; - + id buffer = [_device newBufferWithLength:bytesPerImage options:MTLResourceStorageModeShared]; - + id cmdBuffer = [cmdQueue commandBuffer]; - + id blitCmdEncoder = [cmdBuffer blitCommandEncoder]; [blitCmdEncoder copyFromTexture:_colorTexture sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(_width, _height, 1) - toBuffer:buffer destinationOffset:0 + toBuffer:buffer + destinationOffset:0 destinationBytesPerRow:bytesPerRow destinationBytesPerImage:bytesPerImage options:MTLBlitOptionNone]; - - + [blitCmdEncoder endEncoding]; - + [cmdBuffer commit]; [cmdBuffer waitUntilCompleted]; std::vector imageData(bytesPerImage); memcpy(imageData.data(), [buffer contents], bytesPerImage); - - if([_colorTexture pixelFormat] == MTLPixelFormatBGRA8Unorm) + + if ([_colorTexture pixelFormat] == MTLPixelFormatBGRA8Unorm) { - for(unsigned int j = 0; j < _height; ++j) + for (unsigned int j = 0; j < _height; ++j) { unsigned int rawStart = j * (_width * _channelCount); - for(unsigned int i = 0; i < _width; ++i) + for (unsigned int i = 0; i < _width; ++i) { unsigned int offset = rawStart + _channelCount * i; unsigned char tmp = imageData[offset + 0]; @@ -177,7 +177,7 @@ } } } - + memcpy(image->getResourceBuffer(), imageData.data(), bytesPerImage); [buffer release]; diff --git a/source/MaterialXRenderMsl/MetalState.h b/source/MaterialXRenderMsl/MetalState.h index 15eacc360a..963603a341 100644 --- a/source/MaterialXRenderMsl/MetalState.h +++ b/source/MaterialXRenderMsl/MetalState.h @@ -11,7 +11,7 @@ #include #include -#import +#import #include @@ -25,15 +25,15 @@ struct MetalState { static MetalState* getSingleton() { - if(!singleton) + if (!singleton) { singleton = std::unique_ptr(new MetalState()); } return singleton.get(); } - + MetalState(); - + void initialize(id mtlDevice, id mtlCmdQueue); void initLinearToSRGBKernel(); void triggerProgrammaticCapture(); @@ -42,36 +42,36 @@ struct MetalState void beginEncoder(MTLRenderPassDescriptor* renderpassDesc); void endEncoder(); void endCommandBuffer(); - + void waitForComplition(); - + MaterialX::MetalFramebufferPtr currentFramebuffer(); - + static std::unique_ptr singleton; - - id device = nil; - id cmdQueue = nil; - id cmdBuffer = nil; - id linearToSRGB_pso = nil; - id renderCmdEncoder = nil; + + id device = nil; + id cmdQueue = nil; + id cmdBuffer = nil; + id linearToSRGB_pso = nil; + id renderCmdEncoder = nil; std::stack framebufferStack; - + bool supportsTiledPipeline; - + id opaqueDepthStencilState = nil; id transparentDepthStencilState = nil; id envMapDepthStencilState = nil; - + std::condition_variable inFlightCV; - std::mutex inFlightMutex; - std::atomic inFlightCommandBuffers; + std::mutex inFlightMutex; + std::atomic inFlightCommandBuffers; }; -#define MTL(a) (MetalState::getSingleton()->a) +#define MTL(a) (MetalState::getSingleton()->a) #define MTL_DEPTHSTENCIL_STATE(a) (MetalState::getSingleton()->a##DepthStencilState) -#define MTL_TRIGGER_CAPTURE MetalState::getSingleton()->triggerProgrammaticCapture() -#define MTL_STOP_CAPTURE MetalState::getSingleton()->stopProgrammaticCapture() -#define MTL_PUSH_FRAMEBUFFER(a) MetalState::getSingleton()->framebufferStack.push(a) -#define MTL_POP_FRAMEBUFFER(a) MetalState::getSingleton()->framebufferStack.pop() +#define MTL_TRIGGER_CAPTURE MetalState::getSingleton()->triggerProgrammaticCapture() +#define MTL_STOP_CAPTURE MetalState::getSingleton()->stopProgrammaticCapture() +#define MTL_PUSH_FRAMEBUFFER(a) MetalState::getSingleton()->framebufferStack.push(a) +#define MTL_POP_FRAMEBUFFER(a) MetalState::getSingleton()->framebufferStack.pop() #endif // MATERIALXVIEW_METALSTATE_H diff --git a/source/MaterialXRenderMsl/MetalState.mm b/source/MaterialXRenderMsl/MetalState.mm index 941b00c526..0cba4bb823 100644 --- a/source/MaterialXRenderMsl/MetalState.mm +++ b/source/MaterialXRenderMsl/MetalState.mm @@ -18,7 +18,7 @@ { device = mtlDevice; cmdQueue = mtlCmdQueue; - + #ifdef MAC_OS_VERSION_11_0 if (@available(macOS 11.0, ios 14.0, *)) { @@ -27,20 +27,20 @@ #else supportsTiledPipeline = false; #endif - + MTLDepthStencilDescriptor* depthStencilDesc = [MTLDepthStencilDescriptor new]; - depthStencilDesc.depthWriteEnabled = true; + depthStencilDesc.depthWriteEnabled = true; depthStencilDesc.depthCompareFunction = MTLCompareFunctionLess; opaqueDepthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDesc]; - - depthStencilDesc.depthWriteEnabled = false; + + depthStencilDesc.depthWriteEnabled = false; depthStencilDesc.depthCompareFunction = MTLCompareFunctionLess; transparentDepthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDesc]; - - depthStencilDesc.depthWriteEnabled = true; + + depthStencilDesc.depthWriteEnabled = true; depthStencilDesc.depthCompareFunction = MTLCompareFunctionAlways; envMapDepthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDesc]; - + initLinearToSRGBKernel(); } @@ -55,49 +55,49 @@ #endif options.languageVersion = MTLLanguageVersion2_0; options.fastMathEnabled = true; - + #ifdef MAC_OS_VERSION_11_0 bool useTiledPipeline = supportsTiledPipeline; - if(useTiledPipeline) + if (useTiledPipeline) { - if(@available(macOS 11.0, ios 14.0, *)) + if (@available(macOS 11.0, ios 14.0, *)) { NSString* linearToSRGB_kernel = - @"#include \n" - "#include \n" - " \n" - "using namespace metal; \n" - " \n" - "struct RenderTarget { \n" - " half4 colorTarget [[color(0)]]; \n" - "}; \n" - " \n" - " \n" - " \n" - "half4 linearToSRGB(half4 color_linear) \n" - "{ \n" - " half4 color_srgb; \n" - " for(int i = 0; i < 3; ++i) \n" - " color_srgb[i] = (color_linear[i] < 0.0031308) ? \n" - " (12.92 * color_linear[i]) : \n" - " (1.055 * pow(color_linear[i], 1.0h / 2.2h) - 0.055); \n" - " color_srgb[3] = color_linear[3]; \n" - " return color_srgb; \n" - "} \n" - " \n" - "kernel void LinearToSRGB_kernel( \n" - " imageblock imageBlock, \n" - " ushort2 tid [[ thread_position_in_threadgroup ]]) \n" - "{ \n" - " RenderTarget linearValue = imageBlock.read(tid); \n" - " RenderTarget srgbValue; \n" - " srgbValue.colorTarget = linearToSRGB(linearValue.colorTarget); \n" - " imageBlock.write(srgbValue, tid); \n" - "} \n"; - + @"#include \n" + "#include \n" + " \n" + "using namespace metal; \n" + " \n" + "struct RenderTarget { \n" + " half4 colorTarget [[color(0)]]; \n" + "}; \n" + " \n" + " \n" + " \n" + "half4 linearToSRGB(half4 color_linear) \n" + "{ \n" + " half4 color_srgb; \n" + " for(int i = 0; i < 3; ++i) \n" + " color_srgb[i] = (color_linear[i] < 0.0031308) ? \n" + " (12.92 * color_linear[i]) : \n" + " (1.055 * pow(color_linear[i], 1.0h / 2.2h) - 0.055); \n" + " color_srgb[3] = color_linear[3]; \n" + " return color_srgb; \n" + "} \n" + " \n" + "kernel void LinearToSRGB_kernel( \n" + " imageblock imageBlock, \n" + " ushort2 tid [[ thread_position_in_threadgroup ]]) \n" + "{ \n" + " RenderTarget linearValue = imageBlock.read(tid); \n" + " RenderTarget srgbValue; \n" + " srgbValue.colorTarget = linearToSRGB(linearValue.colorTarget); \n" + " imageBlock.write(srgbValue, tid); \n" + "} \n"; + id library = [device newLibraryWithSource:linearToSRGB_kernel options:options error:&error]; id function = [library newFunctionWithName:@"LinearToSRGB_kernel"]; - + MTLTileRenderPipelineDescriptor* renderPipelineDescriptor = [MTLTileRenderPipelineDescriptor new]; [renderPipelineDescriptor setRasterSampleCount:1]; [[renderPipelineDescriptor colorAttachments][0] setPixelFormat:MTLPixelFormatBGRA8Unorm]; @@ -109,63 +109,63 @@ useTiledPipeline = false; } } - - if(!useTiledPipeline) + + if (!useTiledPipeline) #endif { NSString* linearToSRGB_kernel = - @"#include \n" - "#include \n" - " \n" - "using namespace metal; \n" - " \n" - "struct VSOutput \n" - "{ \n" - " float4 position [[position]]; \n" - "}; \n" - " \n" - "vertex VSOutput VertexMain(uint vertexId [[ vertex_id ]]) \n" - "{ \n" - " VSOutput vsOut; \n" - " \n" - " switch(vertexId) \n" - " { \n" - " case 0: vsOut.position = float4(-1, -1, 0.5, 1); break; \n" - " case 1: vsOut.position = float4(-1, 3, 0.5, 1); break; \n" - " case 2: vsOut.position = float4( 3, -1, 0.5, 1); break; \n" - " }; \n" - " \n" - " return vsOut; \n" - "} \n" - " \n" - "half4 linearToSRGB(half4 color_linear) \n" - "{ \n" - " half4 color_srgb; \n" - " for(int i = 0; i < 3; ++i) \n" - " color_srgb[i] = (color_linear[i] < 0.0031308) ? \n" - " (12.92 * color_linear[i]) : \n" - " (1.055 * pow(color_linear[i], 1.0h / 2.2h) - 0.055);\n" - " color_srgb[3] = color_linear[3]; \n" - " return color_srgb; \n" - "} \n" - " \n" - "fragment half4 FragmentMain( \n" - " texture2d inputTex [[ texture(0) ]], \n" - " float4 fragCoord [[ position ]] \n" - ") \n" - "{ \n" - " constexpr sampler ss( \n" - " coord::pixel, \n" - " address::clamp_to_border, \n" - " filter::linear); \n" - " return linearToSRGB(inputTex.sample(ss, fragCoord.xy)); \n" - "} \n"; + @"#include \n" + "#include \n" + " \n" + "using namespace metal; \n" + " \n" + "struct VSOutput \n" + "{ \n" + " float4 position [[position]]; \n" + "}; \n" + " \n" + "vertex VSOutput VertexMain(uint vertexId [[ vertex_id ]]) \n" + "{ \n" + " VSOutput vsOut; \n" + " \n" + " switch(vertexId) \n" + " { \n" + " case 0: vsOut.position = float4(-1, -1, 0.5, 1); break; \n" + " case 1: vsOut.position = float4(-1, 3, 0.5, 1); break; \n" + " case 2: vsOut.position = float4( 3, -1, 0.5, 1); break; \n" + " }; \n" + " \n" + " return vsOut; \n" + "} \n" + " \n" + "half4 linearToSRGB(half4 color_linear) \n" + "{ \n" + " half4 color_srgb; \n" + " for(int i = 0; i < 3; ++i) \n" + " color_srgb[i] = (color_linear[i] < 0.0031308) ? \n" + " (12.92 * color_linear[i]) : \n" + " (1.055 * pow(color_linear[i], 1.0h / 2.2h) - 0.055);\n" + " color_srgb[3] = color_linear[3]; \n" + " return color_srgb; \n" + "} \n" + " \n" + "fragment half4 FragmentMain( \n" + " texture2d inputTex [[ texture(0) ]], \n" + " float4 fragCoord [[ position ]] \n" + ") \n" + "{ \n" + " constexpr sampler ss( \n" + " coord::pixel, \n" + " address::clamp_to_border, \n" + " filter::linear); \n" + " return linearToSRGB(inputTex.sample(ss, fragCoord.xy)); \n" + "} \n"; id library = [device newLibraryWithSource:linearToSRGB_kernel options:options error:&error]; id vertexfunction = [library newFunctionWithName:@"VertexMain"]; id Fragmentfunction = [library newFunctionWithName:@"FragmentMain"]; - + MTLRenderPipelineDescriptor* renderPipelineDesc = [MTLRenderPipelineDescriptor new]; [renderPipelineDesc setVertexFunction:vertexfunction]; [renderPipelineDesc setFragmentFunction:Fragmentfunction]; @@ -177,13 +177,13 @@ void MetalState::triggerProgrammaticCapture() { - MTLCaptureManager* captureManager = [MTLCaptureManager sharedCaptureManager]; + MTLCaptureManager* captureManager = [MTLCaptureManager sharedCaptureManager]; MTLCaptureDescriptor* captureDescriptor = [MTLCaptureDescriptor new]; - + [captureDescriptor setCaptureObject:device]; - + NSError* error = nil; - if(![captureManager startCaptureWithDescriptor:captureDescriptor error:&error]) + if (![captureManager startCaptureWithDescriptor:captureDescriptor error:&error]) { NSLog(@"Failed to start capture, error %@", error); } @@ -204,7 +204,7 @@ void MetalState::beginEncoder(MTLRenderPassDescriptor* renderpassDesc) { renderCmdEncoder = [cmdBuffer - renderCommandEncoderWithDescriptor:renderpassDesc]; + renderCommandEncoderWithDescriptor:renderpassDesc]; } void MetalState::endEncoder() @@ -216,8 +216,8 @@ { endEncoder(); [cmdBuffer addCompletedHandler:^(id _Nonnull) { - inFlightCommandBuffers--; - inFlightCV.notify_one(); + inFlightCommandBuffers--; + inFlightCV.notify_one(); }]; [cmdBuffer commit]; [cmdBuffer waitUntilCompleted]; @@ -226,8 +226,12 @@ void MetalState::waitForComplition() { std::unique_lock lock(inFlightMutex); - while (inFlightCommandBuffers != 0){ - inFlightCV.wait(lock, [this]{ return inFlightCommandBuffers.load() == 0; }); + while (inFlightCommandBuffers != 0) + { + inFlightCV.wait(lock, [this] + { + return inFlightCommandBuffers.load() == 0; + }); } } diff --git a/source/MaterialXRenderMsl/MetalTextureHandler.h b/source/MaterialXRenderMsl/MetalTextureHandler.h index 4c329f3f6d..cab145663d 100644 --- a/source/MaterialXRenderMsl/MetalTextureHandler.h +++ b/source/MaterialXRenderMsl/MetalTextureHandler.h @@ -28,34 +28,35 @@ using MetalTextureHandlerPtr = std::shared_ptr; class MX_RENDERMSL_API MetalTextureHandler : public ImageHandler { friend class MslProgram; + public: static MetalTextureHandlerPtr create(id device, ImageLoaderPtr imageLoader) { return MetalTextureHandlerPtr(new MetalTextureHandler(device, imageLoader)); } - /// This method binds image and its corresponding sampling properties. /// It also creates the underlying resource if needed. /// Actual binding of texture and sampler to command encoder happens autoamt bool bindImage(ImagePtr image, const ImageSamplingProperties& samplingProperties) override; - -protected: + + protected: /// Bind an image. This method will bind the texture to an active texture /// unit as defined by the corresponding image description. The method /// will fail if there are not enough available image units to bind to. bool bindImage(id renderCmdEncoder, int textureUnit, ImagePtr image); -public: + + public: id getSamplerState(const ImageSamplingProperties& samplingProperties); - + /// Unbind an image. bool unbindImage(ImagePtr image) override; - id getMTLTextureForImage(unsigned int index) const; + id getMTLTextureForImage(unsigned int index) const; id getMTLSamplerStateForImage(unsigned int index); - + /// Create rendering resources for the given image. bool createRenderResources(ImagePtr image, bool generateMipMaps) override; @@ -75,9 +76,9 @@ class MX_RENDERMSL_API MetalTextureHandler : public ImageHandler /// Utility to map generic texture properties to Metal texture formats. static void mapTextureFormatToMetal(Image::BaseType baseType, unsigned int channelCount, bool srgb, MTLDataType& dataType, MTLPixelFormat& pixelFormat); - + static size_t getTextureBaseTypeSize(Image::BaseType baseType); - + id getAssociatedMetalTexture(ImagePtr image); protected: @@ -86,11 +87,11 @@ class MX_RENDERMSL_API MetalTextureHandler : public ImageHandler protected: std::vector _boundTextureLocations; - + std::unordered_map> _metalTextureMap; std::unordered_map> _imageBindingInfo; std::unordered_map, ImageSamplingKeyHasher> _imageSamplerStateMap; - + id _device = nil; }; diff --git a/source/MaterialXRenderMsl/MetalTextureHandler.mm b/source/MaterialXRenderMsl/MetalTextureHandler.mm index 745019ac92..ab62174122 100644 --- a/source/MaterialXRenderMsl/MetalTextureHandler.mm +++ b/source/MaterialXRenderMsl/MetalTextureHandler.mm @@ -35,7 +35,7 @@ id MetalTextureHandler::getSamplerState(const ImageSamplingProperties& samplingProperties) { - if(_imageSamplerStateMap.find(samplingProperties) == _imageSamplerStateMap.end()) + if (_imageSamplerStateMap.find(samplingProperties) == _imageSamplerStateMap.end()) { MTLSamplerDescriptor* samplerDesc = [MTLSamplerDescriptor new]; [samplerDesc setSAddressMode:mapAddressModeToMetal(samplingProperties.uaddressMode)]; @@ -43,17 +43,17 @@ [samplerDesc setTAddressMode:mapAddressModeToMetal(samplingProperties.vaddressMode)]; [samplerDesc setBorderColor:samplingProperties.defaultColor[0] == 0 ? MTLSamplerBorderColorOpaqueBlack : MTLSamplerBorderColorOpaqueWhite]; MTLSamplerMinMagFilter minmagFilter; - MTLSamplerMipFilter mipFilter; + MTLSamplerMipFilter mipFilter; mapFilterTypeToMetal(samplingProperties.filterType, samplingProperties.enableMipmaps, minmagFilter, mipFilter); // Magnification filters are more restrictive than minification [samplerDesc setMagFilter:MTLSamplerMinMagFilterLinear]; [samplerDesc setMinFilter:minmagFilter]; [samplerDesc setMipFilter:mipFilter]; [samplerDesc setMaxAnisotropy:16]; - + _imageSamplerStateMap[samplingProperties] = [_device newSamplerStateWithDescriptor:samplerDesc]; } - + return _imageSamplerStateMap[samplingProperties]; } @@ -70,7 +70,7 @@ } _boundTextureLocations[textureUnit] = image->getResourceId(); - + [renderCmdEncoder setFragmentTexture:_metalTextureMap[image->getResourceId()] atIndex:textureUnit]; [renderCmdEncoder setFragmentSamplerState:getSamplerState(_imageBindingInfo[image->getResourceId()].second) atIndex:textureUnit]; @@ -79,10 +79,10 @@ id MetalTextureHandler::getAssociatedMetalTexture(ImagePtr image) { - if(image) + if (image) { auto tex = _metalTextureMap.find(image->getResourceId()); - if(tex != _metalTextureMap.end()) + if (tex != _metalTextureMap.end()) return (tex->second); } return nil; @@ -91,23 +91,23 @@ id MetalTextureHandler::getMTLTextureForImage(unsigned int index) const { auto imageInfo = _imageBindingInfo.find(index); - if(imageInfo != _imageBindingInfo.end()) + if (imageInfo != _imageBindingInfo.end()) { - if(!imageInfo->second.first) + if (!imageInfo->second.first) return nil; - + auto metalTexture = _metalTextureMap.find(imageInfo->second.first->getResourceId()); - if(metalTexture != _metalTextureMap.end()) + if (metalTexture != _metalTextureMap.end()) return metalTexture->second; } - + return nil; } id MetalTextureHandler::getMTLSamplerStateForImage(unsigned int index) { auto imageInfo = _imageBindingInfo.find(index); - if(imageInfo != _imageBindingInfo.end()) + if (imageInfo != _imageBindingInfo.end()) { return getSamplerState(imageInfo->second.second); } @@ -131,46 +131,46 @@ bool MetalTextureHandler::createRenderResources(ImagePtr image, bool generateMipMaps) { id texture = nil; - + MTLPixelFormat pixelFormat; - MTLDataType dataType; - + MTLDataType dataType; + if (image->getResourceId() == MslProgram::UNDEFINED_METAL_RESOURCE_ID) { static unsigned int resourceId = 0; ++resourceId; - + mapTextureFormatToMetal(image->getBaseType(), image->getChannelCount(), false, dataType, pixelFormat); - + MTLTextureDescriptor* texDesc = [MTLTextureDescriptor new]; [texDesc setTextureType:MTLTextureType2D]; texDesc.width = image->getWidth(); texDesc.height = image->getHeight(); texDesc.mipmapLevelCount = generateMipMaps ? image->getMaxMipCount() : 1; texDesc.usage = MTLTextureUsageShaderRead | - // For now, we set generate mip maps flag off, - // when we want to use the texture as render target - (!generateMipMaps ? MTLTextureUsageRenderTarget : 0); + // For now, we set generate mip maps flag off, + // when we want to use the texture as render target + (!generateMipMaps ? MTLTextureUsageRenderTarget : 0); texDesc.resourceOptions = MTLResourceStorageModePrivate; texDesc.pixelFormat = pixelFormat; - if(generateMipMaps) + if (generateMipMaps) { - if(image->getChannelCount() == 1) + if (image->getChannelCount() == 1) { texDesc.swizzle = MTLTextureSwizzleChannelsMake( - MTLTextureSwizzleRed, - MTLTextureSwizzleRed, - MTLTextureSwizzleRed, - MTLTextureSwizzleRed); + MTLTextureSwizzleRed, + MTLTextureSwizzleRed, + MTLTextureSwizzleRed, + MTLTextureSwizzleRed); } - else if(image->getChannelCount() == 2) + else if (image->getChannelCount() == 2) { texDesc.swizzle = MTLTextureSwizzleChannelsMake( - MTLTextureSwizzleRed, - MTLTextureSwizzleGreen, - MTLTextureSwizzleRed, - MTLTextureSwizzleGreen); + MTLTextureSwizzleRed, + MTLTextureSwizzleGreen, + MTLTextureSwizzleRed, + MTLTextureSwizzleGreen); } } texture = [_device newTextureWithDescriptor:texDesc]; @@ -181,18 +181,17 @@ { mapTextureFormatToMetal(image->getBaseType(), image->getChannelCount(), false, dataType, pixelFormat); - + texture = _metalTextureMap[image->getResourceId()]; } - id cmdQueue = [_device newCommandQueue]; id cmdBuffer = [cmdQueue commandBuffer]; - + id blitCmdEncoder = [cmdBuffer blitCommandEncoder]; - + NSUInteger channelCount = image->getChannelCount(); - + NSUInteger sourceBytesPerRow = image->getWidth() * channelCount * @@ -200,63 +199,64 @@ NSUInteger sourceBytesPerImage = sourceBytesPerRow * image->getHeight(); - - std::vector rearrangedDataF; + + std::vector rearrangedDataF; std::vector rearrangedDataC; void* imageData = image->getResourceBuffer(); - + if ((pixelFormat == MTLPixelFormatRGBA32Float || pixelFormat == MTLPixelFormatRGBA8Unorm) && channelCount == 3) { bool isFloat = pixelFormat == MTLPixelFormatRGBA32Float; - - sourceBytesPerRow = sourceBytesPerRow / 3 * 4; + + sourceBytesPerRow = sourceBytesPerRow / 3 * 4; sourceBytesPerImage = sourceBytesPerImage / 3 * 4; - + size_t srcIdx = 0; - - if(isFloat) + + if (isFloat) { rearrangedDataF.resize(sourceBytesPerImage / sizeof(float)); - for(size_t dstIdx = 0; dstIdx < rearrangedDataF.size(); ++dstIdx) + for (size_t dstIdx = 0; dstIdx < rearrangedDataF.size(); ++dstIdx) { - if((dstIdx & 0x3) == 3) + if ((dstIdx & 0x3) == 3) { rearrangedDataF[dstIdx] = 1.0f; continue; } - - rearrangedDataF[dstIdx] = ((float*)imageData)[srcIdx++]; + + rearrangedDataF[dstIdx] = ((float*) imageData)[srcIdx++]; } - + imageData = rearrangedDataF.data(); } else { rearrangedDataC.resize(sourceBytesPerImage); - for(size_t dstIdx = 0; dstIdx < rearrangedDataC.size(); ++dstIdx) + for (size_t dstIdx = 0; dstIdx < rearrangedDataC.size(); ++dstIdx) { - if((dstIdx & 0x3) == 3) + if ((dstIdx & 0x3) == 3) { rearrangedDataC[dstIdx] = 255; continue; } - - rearrangedDataC[dstIdx] = ((unsigned char*)imageData)[srcIdx++]; + + rearrangedDataC[dstIdx] = ((unsigned char*) imageData)[srcIdx++]; } - + imageData = rearrangedDataC.data(); } - + channelCount = 4; } - + id buffer = nil; - if(imageData) + if (imageData) { buffer = [_device newBufferWithBytes:imageData - length:sourceBytesPerImage - options:MTLStorageModeShared]; - [blitCmdEncoder copyFromBuffer:buffer sourceOffset:0 + length:sourceBytesPerImage + options:MTLStorageModeShared]; + [blitCmdEncoder copyFromBuffer:buffer + sourceOffset:0 sourceBytesPerRow:sourceBytesPerRow sourceBytesPerImage:sourceBytesPerImage sourceSize:MTLSizeMake(image->getWidth(), image->getHeight(), 1) @@ -265,26 +265,26 @@ destinationLevel:0 destinationOrigin:MTLOriginMake(0, 0, 0)]; } - - if(generateMipMaps && image->getMaxMipCount() > 1) + + if (generateMipMaps && image->getMaxMipCount() > 1) [blitCmdEncoder generateMipmapsForTexture:texture]; - + [blitCmdEncoder endEncoding]; - + [cmdBuffer commit]; [cmdBuffer waitUntilCompleted]; - - if(buffer) + + if (buffer) [buffer release]; - + return true; } - + void MetalTextureHandler::releaseRenderResources(ImagePtr image) { - if(!image) + if (!image) return; - + if (image->getResourceId() == MslProgram::UNDEFINED_METAL_RESOURCE_ID) { return; @@ -293,7 +293,7 @@ unbindImage(image); unsigned int resourceId = image->getResourceId(); auto tex = _metalTextureMap.find(resourceId); - if(tex != _metalTextureMap.end()) + if (tex != _metalTextureMap.end()) { [tex->second release]; } @@ -341,11 +341,11 @@ void MetalTextureHandler::mapFilterTypeToMetal(ImageSamplingProperties::FilterType filterTypeEnum, bool enableMipmaps, MTLSamplerMinMagFilter& minMagFilter, MTLSamplerMipFilter& mipFilter) { - if(enableMipmaps) + if (enableMipmaps) { - if(filterTypeEnum == ImageSamplingProperties::FilterType::LINEAR || - filterTypeEnum == ImageSamplingProperties::FilterType::CUBIC || - filterTypeEnum == ImageSamplingProperties::FilterType::UNSPECIFIED) + if (filterTypeEnum == ImageSamplingProperties::FilterType::LINEAR || + filterTypeEnum == ImageSamplingProperties::FilterType::CUBIC || + filterTypeEnum == ImageSamplingProperties::FilterType::UNSPECIFIED) { minMagFilter = MTLSamplerMinMagFilterLinear; mipFilter = MTLSamplerMipFilterLinear; @@ -358,9 +358,9 @@ } else { - if(filterTypeEnum == ImageSamplingProperties::FilterType::LINEAR || - filterTypeEnum == ImageSamplingProperties::FilterType::CUBIC || - filterTypeEnum == ImageSamplingProperties::FilterType::UNSPECIFIED) + if (filterTypeEnum == ImageSamplingProperties::FilterType::LINEAR || + filterTypeEnum == ImageSamplingProperties::FilterType::CUBIC || + filterTypeEnum == ImageSamplingProperties::FilterType::UNSPECIFIED) { minMagFilter = MTLSamplerMinMagFilterLinear; mipFilter = MTLSamplerMipFilterNotMipmapped; @@ -374,51 +374,103 @@ } void MetalTextureHandler::mapTextureFormatToMetal(Image::BaseType baseType, unsigned int channelCount, bool srgb, - MTLDataType& dataType, MTLPixelFormat& pixelFormat) + MTLDataType& dataType, MTLPixelFormat& pixelFormat) { if (baseType == Image::BaseType::UINT8) { dataType = MTLDataTypeChar; switch (channelCount) { - case 4: pixelFormat = srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm; dataType = MTLDataTypeChar4; break; - case 3: pixelFormat = srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm; dataType = MTLDataTypeChar3; break; - case 2: pixelFormat = MTLPixelFormatRG8Unorm; dataType = MTLDataTypeChar2; break; - case 1: pixelFormat = MTLPixelFormatR8Unorm; dataType = MTLDataTypeChar; break; - default: throw Exception("Unsupported channel count in mapTextureFormatToMetal"); + case 4: + pixelFormat = srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm; + dataType = MTLDataTypeChar4; + break; + case 3: + pixelFormat = srgb ? MTLPixelFormatRGBA8Unorm_sRGB : MTLPixelFormatRGBA8Unorm; + dataType = MTLDataTypeChar3; + break; + case 2: + pixelFormat = MTLPixelFormatRG8Unorm; + dataType = MTLDataTypeChar2; + break; + case 1: + pixelFormat = MTLPixelFormatR8Unorm; + dataType = MTLDataTypeChar; + break; + default: + throw Exception("Unsupported channel count in mapTextureFormatToMetal"); } } else if (baseType == Image::BaseType::UINT16) { switch (channelCount) { - case 4: pixelFormat = MTLPixelFormatRGBA16Uint; dataType = MTLDataTypeShort4; break; - case 3: pixelFormat = MTLPixelFormatRGBA16Uint; dataType = MTLDataTypeShort3; break; - case 2: pixelFormat = MTLPixelFormatRG16Uint; dataType = MTLDataTypeShort2; break; - case 1: pixelFormat = MTLPixelFormatR16Uint; dataType = MTLDataTypeShort; break; - default: throw Exception("Unsupported channel count in mapTextureFormatToMetal"); + case 4: + pixelFormat = MTLPixelFormatRGBA16Uint; + dataType = MTLDataTypeShort4; + break; + case 3: + pixelFormat = MTLPixelFormatRGBA16Uint; + dataType = MTLDataTypeShort3; + break; + case 2: + pixelFormat = MTLPixelFormatRG16Uint; + dataType = MTLDataTypeShort2; + break; + case 1: + pixelFormat = MTLPixelFormatR16Uint; + dataType = MTLDataTypeShort; + break; + default: + throw Exception("Unsupported channel count in mapTextureFormatToMetal"); } } else if (baseType == Image::BaseType::HALF) { switch (channelCount) { - case 4: pixelFormat = MTLPixelFormatRGBA16Float; dataType = MTLDataTypeHalf4; break; - case 3: pixelFormat = MTLPixelFormatRGBA16Float; dataType = MTLDataTypeHalf3; break; - case 2: pixelFormat = MTLPixelFormatRG16Float; dataType = MTLDataTypeHalf2; break; - case 1: pixelFormat = MTLPixelFormatR16Float; dataType = MTLDataTypeHalf ; break; - default: throw Exception("Unsupported channel count in mapTextureFormatToMetal"); + case 4: + pixelFormat = MTLPixelFormatRGBA16Float; + dataType = MTLDataTypeHalf4; + break; + case 3: + pixelFormat = MTLPixelFormatRGBA16Float; + dataType = MTLDataTypeHalf3; + break; + case 2: + pixelFormat = MTLPixelFormatRG16Float; + dataType = MTLDataTypeHalf2; + break; + case 1: + pixelFormat = MTLPixelFormatR16Float; + dataType = MTLDataTypeHalf; + break; + default: + throw Exception("Unsupported channel count in mapTextureFormatToMetal"); } } else if (baseType == Image::BaseType::FLOAT) { switch (channelCount) { - case 4: pixelFormat = MTLPixelFormatRGBA32Float; dataType = MTLDataTypeFloat4; break; - case 3: pixelFormat = MTLPixelFormatRGBA32Float; dataType = MTLDataTypeFloat3; break; - case 2: pixelFormat = MTLPixelFormatRG32Float; dataType = MTLDataTypeFloat2; break; - case 1: pixelFormat = MTLPixelFormatR32Float; dataType = MTLDataTypeFloat; break; - default: throw Exception("Unsupported channel count in mapTextureFormatToMetal"); + case 4: + pixelFormat = MTLPixelFormatRGBA32Float; + dataType = MTLDataTypeFloat4; + break; + case 3: + pixelFormat = MTLPixelFormatRGBA32Float; + dataType = MTLDataTypeFloat3; + break; + case 2: + pixelFormat = MTLPixelFormatRG32Float; + dataType = MTLDataTypeFloat2; + break; + case 1: + pixelFormat = MTLPixelFormatR32Float; + dataType = MTLDataTypeFloat; + break; + default: + throw Exception("Unsupported channel count in mapTextureFormatToMetal"); } } else @@ -447,5 +499,4 @@ } } - MATERIALX_NAMESPACE_END diff --git a/source/MaterialXRenderMsl/MslMaterial.h b/source/MaterialXRenderMsl/MslMaterial.h index cc80af1e18..0f6e45a9ce 100644 --- a/source/MaterialXRenderMsl/MslMaterial.h +++ b/source/MaterialXRenderMsl/MslMaterial.h @@ -26,7 +26,8 @@ using MslMaterialPtr = std::shared_ptr; class MX_RENDERMSL_API MslMaterial : public ShaderMaterial { public: - MslMaterial() : ShaderMaterial() + MslMaterial() : + ShaderMaterial() { } ~MslMaterial() { } @@ -47,7 +48,7 @@ class MX_RENDERMSL_API MslMaterial : public ShaderMaterial /// Generate a shader from the given hardware shader. bool generateShader(ShaderPtr hwShader) override; - + /// Copy shader from one material to this one void copyShader(MaterialPtr material) override { @@ -113,9 +114,10 @@ class MX_RENDERMSL_API MslMaterial : public ShaderMaterial GeometryHandlerPtr geometryHandler, ImageHandlerPtr imageHandler, LightHandlerPtr lightHandler); + protected: void clearShader() override; - + protected: MslProgramPtr _glProgram; }; diff --git a/source/MaterialXRenderMsl/MslMaterial.mm b/source/MaterialXRenderMsl/MslMaterial.mm index 66fc0462f2..da466c7a8e 100644 --- a/source/MaterialXRenderMsl/MslMaterial.mm +++ b/source/MaterialXRenderMsl/MslMaterial.mm @@ -38,7 +38,7 @@ } // TODO: - // Here we set new source code on the _glProgram without rebuilding + // Here we set new source code on the _glProgram without rebuilding // the _hwShader instance. So the _hwShader is not in sync with the // _glProgram after this operation. _glProgram = MslProgram::create(); @@ -105,19 +105,19 @@ } void MslMaterial::prepareUsedResources(CameraPtr cam, - GeometryHandlerPtr geometryHandler, - ImageHandlerPtr imageHandler, - LightHandlerPtr lightHandler) + GeometryHandlerPtr geometryHandler, + ImageHandlerPtr imageHandler, + LightHandlerPtr lightHandler) { if (!_glProgram) { return; } - + _glProgram->prepareUsedResources(MTL(renderCmdEncoder), - cam, geometryHandler, - imageHandler, - lightHandler); + cam, geometryHandler, + imageHandler, + lightHandler); } void MslMaterial::bindMesh(MeshPtr mesh) @@ -176,14 +176,14 @@ _boundImages.clear(); _glProgram->setEnableMipMaps(enableMipmaps); - + // Texture and Samplers being bound to the right texture and sampler in MslPipelineStateObject automatically. } ImagePtr MslMaterial::bindImage(const FilePath& filePath, - const std::string& uniformName, - ImageHandlerPtr imageHandler, - const ImageSamplingProperties& samplingProperties) + const std::string& uniformName, + ImageHandlerPtr imageHandler, + const ImageSamplingProperties& samplingProperties) { if (!_glProgram) { @@ -203,8 +203,8 @@ } void MslMaterial::bindLighting(LightHandlerPtr lightHandler, - ImageHandlerPtr imageHandler, - const ShadowState& shadowState) + ImageHandlerPtr imageHandler, + const ShadowState& shadowState) { if (!_glProgram) { @@ -239,7 +239,7 @@ _glProgram->bindTexture(imageHandler, TEXTURE_NAME(HW::AMB_OCC_MAP), shadowState.ambientOcclusionMap, samplingProperties); - + _glProgram->bindUniform(HW::AMB_OCC_GAIN, Value::createValue(shadowState.ambientOcclusionGain)); } } @@ -253,10 +253,10 @@ MeshIndexBuffer& indexData = part->getIndices(); [MTL(renderCmdEncoder) drawIndexedPrimitives:MTLPrimitiveTypeTriangle - indexCount:indexData.size() - indexType:MTLIndexTypeUInt32 - indexBuffer:_glProgram->getIndexBuffer(part) - indexBufferOffset:0]; + indexCount:indexData.size() + indexType:MTLIndexTypeUInt32 + indexBuffer:_glProgram->getIndexBuffer(part) + indexBufferOffset:0]; } void MslMaterial::unbindGeometry() @@ -291,13 +291,13 @@ port = publicUniforms->find( [path](ShaderPort* port) { - return (port && stringEndsWith(port->getPath(), path)); - }); + return (port && stringEndsWith(port->getPath(), path)); + }); // Check if the uniform exists in the shader program if (port && !_glProgram->getUniformsList().count( - publicUniforms->getInstance() + "." + - port->getVariable())) + publicUniforms->getInstance() + "." + + port->getVariable())) { port = nullptr; } @@ -335,4 +335,3 @@ } MATERIALX_NAMESPACE_END - diff --git a/source/MaterialXRenderMsl/MslPipelineStateObject.h b/source/MaterialXRenderMsl/MslPipelineStateObject.h index acc603407d..496b2d8e60 100644 --- a/source/MaterialXRenderMsl/MslPipelineStateObject.h +++ b/source/MaterialXRenderMsl/MslPipelineStateObject.h @@ -106,7 +106,7 @@ class MX_RENDERMSL_API MslProgram string path; /// Unit string unit; - /// Colorspace + /// Colorspace string colorspace; /// Program input constructor @@ -116,7 +116,8 @@ class MX_RENDERMSL_API MslProgram size(inputSize), isConstant(false), path(inputPath) - { } + { + } }; /// Program input structure shared pointer type using InputPtr = std::shared_ptr; @@ -153,7 +154,7 @@ class MX_RENDERMSL_API MslProgram /// @param renderCmdEncoder encoder that binds the pipeline state object. /// @return False if failed bool bind(id renderCmdEncoder); - + /// Bind inputs /// @param renderCmdEncoder encoder that inputs will be bound to. /// @param cam Camera object use to view the object @@ -162,10 +163,10 @@ class MX_RENDERMSL_API MslProgram /// @param lightHandler /// @return void - No return value void prepareUsedResources(id renderCmdEncoder, - CameraPtr cam, - GeometryHandlerPtr geometryHandler, - ImageHandlerPtr imageHandler, - LightHandlerPtr lightHandler); + CameraPtr cam, + GeometryHandlerPtr geometryHandler, + ImageHandlerPtr imageHandler, + LightHandlerPtr lightHandler); /// Return true if a uniform with the given name is present. bool hasUniform(const string& name); @@ -188,15 +189,15 @@ class MX_RENDERMSL_API MslProgram /// Bind input geometry streams void bindMesh(id renderCmdEncoder, MeshPtr mesh); - + /// Queries the index buffer assinged to a mesh partition - id getIndexBuffer(MeshPartitionPtr mesh) { - if(_indexBufferIds.find(mesh) != _indexBufferIds.end()) + id getIndexBuffer(MeshPartitionPtr mesh) + { + if (_indexBufferIds.find(mesh) != _indexBufferIds.end()) return _indexBufferIds[mesh]; return nil; } - /// Unbind any bound geometry void unbindGeometry(); @@ -204,7 +205,7 @@ class MX_RENDERMSL_API MslProgram void bindTextures(id renderCmdEncoder, LightHandlerPtr lightHandler, ImageHandlerPtr imageHandler); - + void bindTexture(ImageHandlerPtr imageHandler, string shaderTextureName, ImagePtr imagePtr, @@ -215,17 +216,17 @@ class MX_RENDERMSL_API MslProgram /// Bind view information void bindViewInformation(CameraPtr camera); - + /// Bind time and frame void bindTimeAndFrame(float time = 1.0f, float frame = 1.0f); /// @} /// @name Utilities /// @{ - + /// Returns if alpha blending is enabled. bool isTransparent() const { return _alphaBlendingEnabled; } - + /// Specify textures bound to this program shouldn't be mip mapped. void setEnableMipMaps(bool enableMipMapping) { _enableMipMapping = enableMipMapping; } @@ -263,13 +264,13 @@ class MX_RENDERMSL_API MslProgram const FilePath& filePath, ImageSamplingProperties samplingProperties, ImageHandlerPtr imageHandler); - + // Bind an individual texture to a program uniform location ImagePtr bindTexture(id renderCmdEncoder, unsigned int uniformLocation, ImagePtr imagePtr, ImageHandlerPtr imageHandler); - + void bindUniformBuffers(id renderCmdEncoder, LightHandlerPtr lightHandler, CameraPtr camera); @@ -294,7 +295,7 @@ class MX_RENDERMSL_API MslProgram std::unordered_map _globalUniformNameList; // List of program input attributes InputMap _attributeList; - + std::unordered_map _explicitBoundImages; // Hardware shader (if any) used for program creation @@ -309,18 +310,18 @@ class MX_RENDERMSL_API MslProgram // Program texture map std::unordered_map _programTextures; - + // Metal Device Object id _device = nil; - + // Currently bound mesh MeshPtr _boundMesh = nullptr; bool _alphaBlendingEnabled = false; - + float _time = 0.0f; float _frame = 0.0f; - + bool _enableMipMapping = true; }; diff --git a/source/MaterialXRenderMsl/MslRenderer.h b/source/MaterialXRenderMsl/MslRenderer.h index ca87d9dd3e..f18afd683f 100644 --- a/source/MaterialXRenderMsl/MslRenderer.h +++ b/source/MaterialXRenderMsl/MslRenderer.h @@ -45,13 +45,13 @@ class MX_RENDERMSL_API MslRenderer : public ShaderRenderer public: /// Create a MSL renderer instance static MslRendererPtr create(unsigned int width = 512, unsigned int height = 512, Image::BaseType baseType = Image::BaseType::UINT8); - + /// Create a texture handler for Metal textures ImageHandlerPtr createImageHandler(ImageLoaderPtr imageLoader) { return MetalTextureHandler::create(_device, imageLoader); } - + /// Returns Metal Device used for rendering id getMetalDevice() const; @@ -84,13 +84,13 @@ class MX_RENDERMSL_API MslRenderer : public ShaderRenderer /// Update the program with value of the uniform. void updateUniform(const string& name, ConstValuePtr value) override; - + /// Set the size of the rendered image void setSize(unsigned int width, unsigned int height) override; /// Render the current program to an offscreen buffer. void render() override; - + /// Render the current program in texture space to an off-screen buffer. void renderTextureSpace(const Vector2& uvMin, const Vector2& uvMax); @@ -126,23 +126,23 @@ class MX_RENDERMSL_API MslRenderer : public ShaderRenderer } /// @} - + protected: MslRenderer(unsigned int width, unsigned int height, Image::BaseType baseType); - + void triggerProgrammaticCapture(); void stopProgrammaticCapture(); - + void createFrameBuffer(bool encodeSrgb); - + private: - MslProgramPtr _program; + MslProgramPtr _program; - id _device = nil; - id _cmdQueue = nil; + id _device = nil; + id _cmdQueue = nil; id _cmdBuffer = nil; - - MetalFramebufferPtr _framebuffer; + + MetalFramebufferPtr _framebuffer; bool _initialized; diff --git a/source/MaterialXRenderMsl/MslRenderer.mm b/source/MaterialXRenderMsl/MslRenderer.mm index f5e794c2b3..1a01b8bebf 100644 --- a/source/MaterialXRenderMsl/MslRenderer.mm +++ b/source/MaterialXRenderMsl/MslRenderer.mm @@ -54,7 +54,7 @@ _device = MTLCreateSystemDefaultDevice(); _cmdQueue = [_device newCommandQueue]; createFrameBuffer(true); - + _initialized = true; } } @@ -78,22 +78,22 @@ void MslRenderer::renderTextureSpace(const Vector2& uvMin, const Vector2& uvMax) { bool captureRenderTextureSpace = false; - if(captureRenderTextureSpace) + if (captureRenderTextureSpace) triggerProgrammaticCapture(); - + MTLRenderPassDescriptor* desc = [MTLRenderPassDescriptor new]; _framebuffer->bind(desc); - + _cmdBuffer = [_cmdQueue commandBuffer]; - + id rendercmdEncoder = [_cmdBuffer renderCommandEncoderWithDescriptor:desc]; _program->bind(rendercmdEncoder); _program->prepareUsedResources(rendercmdEncoder, - _camera, - _geometryHandler, - _imageHandler, - _lightHandler); - + _camera, + _geometryHandler, + _imageHandler, + _lightHandler); + MeshPtr mesh = _geometryHandler->createQuadMesh(uvMin, uvMax, true); _program->bindMesh(rendercmdEncoder, mesh); MeshPartitionPtr part = mesh->getPartition(0); @@ -104,16 +104,16 @@ indexType:MTLIndexTypeUInt32 indexBuffer:_program->getIndexBuffer(part) indexBufferOffset:0]; - + _framebuffer->unbind(); [rendercmdEncoder endEncoding]; - + [_cmdBuffer commit]; [_cmdBuffer waitUntilCompleted]; - + [desc release]; - - if(captureRenderTextureSpace) + + if (captureRenderTextureSpace) stopProgrammaticCapture(); } @@ -149,17 +149,16 @@ _height = height; createFrameBuffer(true); } - } void MslRenderer::triggerProgrammaticCapture() { - MTLCaptureManager* captureManager = [MTLCaptureManager sharedCaptureManager]; + MTLCaptureManager* captureManager = [MTLCaptureManager sharedCaptureManager]; MTLCaptureDescriptor* captureDescriptor = [MTLCaptureDescriptor new]; captureDescriptor.captureObject = _device; - + NSError* error = nil; - if(![captureManager startCaptureWithDescriptor:captureDescriptor error:&error]) + if (![captureManager startCaptureWithDescriptor:captureDescriptor error:&error]) { NSLog(@"Failed to start capture, error %@", error); } @@ -174,26 +173,25 @@ void MslRenderer::render() { bool captureFrame = false; - if(captureFrame) + if (captureFrame) triggerProgrammaticCapture(); - + _cmdBuffer = [_cmdQueue commandBuffer]; MTLRenderPassDescriptor* renderpassDesc = [MTLRenderPassDescriptor new]; - + _framebuffer->bind(renderpassDesc); [renderpassDesc.colorAttachments[0] setClearColor: - MTLClearColorMake(_screenColor[0], _screenColor[1], _screenColor[2], 1.0f)]; - + MTLClearColorMake(_screenColor[0], _screenColor[1], _screenColor[2], 1.0f)]; + id renderCmdEncoder = [_cmdBuffer renderCommandEncoderWithDescriptor:renderpassDesc]; MTLDepthStencilDescriptor* depthStencilDesc = [MTLDepthStencilDescriptor new]; - depthStencilDesc.depthWriteEnabled = !(_program->isTransparent()); + depthStencilDesc.depthWriteEnabled = !(_program->isTransparent()); depthStencilDesc.depthCompareFunction = MTLCompareFunctionLess; - + id depthStencilState = [_device newDepthStencilStateWithDescriptor:depthStencilDesc]; [renderCmdEncoder setDepthStencilState:depthStencilState]; - [renderCmdEncoder setCullMode:MTLCullModeBack]; try @@ -215,15 +213,15 @@ auto part = mesh->getPartition(i); _program->bindPartition(part); MeshIndexBuffer& indexData = part->getIndices(); - - if(_program->isTransparent()) + + if (_program->isTransparent()) { [renderCmdEncoder setCullMode:MTLCullModeFront]; - [renderCmdEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:(int)indexData.size() indexType:MTLIndexTypeUInt32 indexBuffer:_program->getIndexBuffer(part) indexBufferOffset:0]; + [renderCmdEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:(int) indexData.size() indexType:MTLIndexTypeUInt32 indexBuffer:_program->getIndexBuffer(part) indexBufferOffset:0]; [renderCmdEncoder setCullMode:MTLCullModeBack]; } - - [renderCmdEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:(int)indexData.size() indexType:MTLIndexTypeUInt32 indexBuffer:_program->getIndexBuffer(part) indexBufferOffset:0]; + + [renderCmdEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:(int) indexData.size() indexType:MTLIndexTypeUInt32 indexBuffer:_program->getIndexBuffer(part) indexBufferOffset:0]; } } } @@ -233,18 +231,18 @@ _framebuffer->unbind(); throw e; } - + [renderCmdEncoder endEncoding]; - + _framebuffer->unbind(); - + [_cmdBuffer commit]; [_cmdBuffer waitUntilCompleted]; - + [_cmdBuffer release]; _cmdBuffer = nil; - - if(captureFrame) + + if (captureFrame) stopProgrammaticCapture(); } diff --git a/source/MaterialXView/Editor.cpp b/source/MaterialXView/Editor.cpp index ff91f0f129..5026f825f6 100644 --- a/source/MaterialXView/Editor.cpp +++ b/source/MaterialXView/Editor.cpp @@ -18,14 +18,14 @@ namespace class EditorColorPicker : public ng::ColorPicker { public: - EditorColorPicker(ng::Widget *parent, const ng::Color& color) : + EditorColorPicker(ng::Widget* parent, const ng::Color& color) : ng::ColorPicker(parent, color) { - ng::Popup *popup = this->popup(); - ng::Widget *floatGroup = new ng::Widget(popup); + ng::Popup* popup = this->popup(); + ng::Widget* floatGroup = new ng::Widget(popup); auto layout = new ng::GridLayout(ng::Orientation::Horizontal, 2, - ng::Alignment::Middle, 2, 2); + ng::Alignment::Middle, 2, 2); layout->set_col_alignment({ ng::Alignment::Fill, ng::Alignment::Fill }); layout->set_spacing(1, 1); floatGroup->set_layout(layout); @@ -51,7 +51,8 @@ class EditorColorPicker : public ng::ColorPicker // The color wheel does not handle alpha properly, so only // overwrite RGB in the callback. - m_callback = [this](const ng::Color &value) { + m_callback = [this](const ng::Color& value) + { _colorWidgets[0]->set_value(value[0]); _colorWidgets[1]->set_value(value[1]); _colorWidgets[2]->set_value(value[2]); @@ -110,7 +111,7 @@ void PropertyEditor::create(Viewer& parent) _window->set_position(previousPosition); _window->set_visible(_visible); - ng::VScrollPanel *scroll_panel = new ng::VScrollPanel(_window); + ng::VScrollPanel* scroll_panel = new ng::VScrollPanel(_window); scroll_panel->set_fixed_height(300); _container = new ng::Widget(scroll_panel); _container->set_layout(new ng::GroupLayout(1, 1, 1, 1)); @@ -122,7 +123,7 @@ void PropertyEditor::create(Viewer& parent) // 3 cell layout for label plus widget value pair. _gridLayout3 = new ng::GridLayout(ng::Orientation::Horizontal, 3, - ng::Alignment::Minimum, 2, 2); + ng::Alignment::Minimum, 2, 2); _gridLayout3->set_col_alignment({ ng::Alignment::Minimum, ng::Alignment::Maximum, ng::Alignment::Maximum }); } @@ -150,7 +151,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st { ng::Widget* twoColumns = new ng::Widget(container); twoColumns->set_layout(_gridLayout2); - ng::Label* groupLabel = new ng::Label(twoColumns, group); + ng::Label* groupLabel = new ng::Label(twoColumns, group); groupLabel->set_font_size(20); groupLabel->set_font("sans-bold"); new ng::Label(twoColumns, ""); @@ -163,7 +164,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st auto indexInEnumeration = [&value, &enumValues, &enumeration]() { size_t index = 0; - for (auto& enumValue: enumValues) + for (auto& enumValue : enumValues) { if (value->getValueString() == enumValue->getValueString()) { @@ -172,7 +173,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st index++; } index = 0; - for (auto& enumName: enumeration) + for (auto& enumName : enumeration) { if (value->getValueString() == enumName) { @@ -191,7 +192,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st twoColumns->set_layout(_gridLayout2); new ng::Label(twoColumns, label); - ng::ComboBox* comboBox = new ng::ComboBox(twoColumns, {""}); + ng::ComboBox* comboBox = new ng::ComboBox(twoColumns, { "" }); comboBox->set_enabled(editable); comboBox->set_items(enumeration); comboBox->set_selected_index(static_cast(valueIndex)); @@ -259,7 +260,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st mx::MaterialPtr material = viewer->getSelectedMaterial(); if (material) { - material->modifyUniform(path, mx::Value::createValue(value)); + material->modifyUniform(path, mx::Value::createValue(value)); } }); floatBox->set_fixed_size(ng::Vector2i(100, 20)); @@ -333,12 +334,12 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st { mx::Color3 v = value->asA(); ng::Color c(v[0], v[1], v[2], 1.0); - + new ng::Label(twoColumns, label); auto colorVar = new EditorColorPicker(twoColumns, c); colorVar->set_fixed_size({ 100, 20 }); colorVar->set_font_size(15); - colorVar->set_final_callback([path, viewer](const ng::Color &c) + colorVar->set_final_callback([path, viewer](const ng::Color& c) { mx::MaterialPtr material = viewer->getSelectedMaterial(); if (material) @@ -362,7 +363,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st auto colorVar = new EditorColorPicker(twoColumns, c); colorVar->set_fixed_size({ 100, 20 }); colorVar->set_font_size(15); - colorVar->set_final_callback([path, viewer](const ng::Color &c) + colorVar->set_final_callback([path, viewer](const ng::Color& c) { mx::MaterialPtr material = viewer->getSelectedMaterial(); if (material) @@ -583,10 +584,10 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st else { new ng::Label(twoColumns, label); - ng::TextBox* stringVar = new ng::TextBox(twoColumns, v); + ng::TextBox* stringVar = new ng::TextBox(twoColumns, v); stringVar->set_fixed_size({ 100, 20 }); stringVar->set_font_size(15); - stringVar->set_callback([path, viewer](const std::string &v) + stringVar->set_callback([path, viewer](const std::string& v) { mx::MaterialPtr material = viewer->getSelectedMaterial(); mx::ShaderPort* uniform = material ? material->findUniform(path) : nullptr; @@ -646,7 +647,7 @@ void PropertyEditor::updateContents(Viewer* viewer) mx::UIPropertyGroup groups; mx::UIPropertyGroup unnamedGroups; const std::string pathSeparator(":"); - mx::createUIPropertyGroups(elem->getDocument(), *publicUniforms, groups, unnamedGroups, pathSeparator); + mx::createUIPropertyGroups(elem->getDocument(), *publicUniforms, groups, unnamedGroups, pathSeparator); // First add items with named groups. std::string previousFolder; @@ -691,7 +692,7 @@ ng::FloatBox* createFloatWidget(ng::Widget* parent, const std::string& la { new ng::Label(parent, label); - ng::Slider *slider = new ng::Slider(parent); + ng::Slider* slider = new ng::Slider(parent); slider->set_value(value); ng::FloatBox* box = new ng::FloatBox(parent, value); @@ -732,7 +733,7 @@ ng::FloatBox* createFloatWidget(ng::Widget* parent, const std::string& la } } - slider->set_callback([box, callback](float value) + slider->set_callback([box, callback](float value) { box->set_value(value); callback(value); @@ -747,12 +748,12 @@ ng::FloatBox* createFloatWidget(ng::Widget* parent, const std::string& la } ng::IntBox* createIntWidget(ng::Widget* parent, const std::string& label, int value, - const mx::UIProperties* ui, std::function callback) + const mx::UIProperties* ui, std::function callback) { new ng::Label(parent, label); - ng::Slider *slider = new ng::Slider(parent); - slider->set_value((float)value); + ng::Slider* slider = new ng::Slider(parent); + slider->set_value((float) value); ng::IntBox* box = new ng::IntBox(parent, value); box->set_fixed_width(60); @@ -781,7 +782,7 @@ ng::IntBox* createIntWidget(ng::Widget* parent, const std::string& label, i } if (range.first != range.second) { - std::pair float_range((float)range.first, (float)range.second); + std::pair float_range((float) range.first, (float) range.second); slider->set_range(float_range); } if (ui->uiStep) @@ -794,12 +795,12 @@ ng::IntBox* createIntWidget(ng::Widget* parent, const std::string& label, i slider->set_callback([box, callback](float value) { - box->set_value((int)value); - callback((int)value); + box->set_value((int) value); + callback((int) value); }); box->set_callback([slider, callback](int value) { - slider->set_value((float)value); + slider->set_value((float) value); callback(value); }); diff --git a/source/MaterialXView/Editor.h b/source/MaterialXView/Editor.h index 8e74ca987d..b1fb4a3ade 100644 --- a/source/MaterialXView/Editor.h +++ b/source/MaterialXView/Editor.h @@ -19,7 +19,7 @@ namespace ng = nanogui; class Viewer; -class PropertyEditor +class PropertyEditor { public: PropertyEditor(); @@ -58,7 +58,7 @@ class PropertyEditor }; ng::FloatBox* createFloatWidget(ng::Widget* parent, const std::string& label, float value, - const mx::UIProperties*ui, std::function callback = nullptr); + const mx::UIProperties* ui, std::function callback = nullptr); ng::IntBox* createIntWidget(ng::Widget* parent, const std::string& label, int value, const mx::UIProperties* ui, std::function callback); diff --git a/source/MaterialXView/Main.cpp b/source/MaterialXView/Main.cpp index 99104f7fa2..c703e48883 100644 --- a/source/MaterialXView/Main.cpp +++ b/source/MaterialXView/Main.cpp @@ -13,40 +13,40 @@ NANOGUI_FORCE_DISCRETE_GPU(); -const std::string options = -" Options: \n" -" --material [FILENAME] Specify the filename of the MTLX document to be displayed in the viewer\n" -" --mesh [FILENAME] Specify the filename of the OBJ mesh to be displayed in the viewer\n" -" --meshRotation [VECTOR3] Specify the rotation of the displayed mesh as three comma-separated floats, representing rotations in degrees about the X, Y, and Z axes (defaults to 0,0,0)\n" -" --meshScale [FLOAT] Specify the uniform scale of the displayed mesh\n" -" --enableTurntable[BOOLEAN] Specify whether to enable turntable rendering of the scene\n" -" --turntableSteps [INTEGER] Specify the number of steps for a complete turntable rotation. Defaults to 360\n" -" --cameraPosition [VECTOR3] Specify the position of the camera as three comma-separated floats (defaults to 0,0,5)\n" -" --cameraTarget [VECTOR3] Specify the position of the camera target as three comma-separated floats (defaults to 0,0,0)\n" -" --cameraViewAngle [FLOAT] Specify the view angle of the camera, or zero for an orthographic projection (defaults to 45)\n" -" --cameraZoom [FLOAT] Specify the zoom factor for the camera, implemented as a mesh scale multiplier (defaults to 1)\n" -" --envRad [FILENAME] Specify the filename of the environment light to display, stored as HDR environment radiance in the latitude-longitude format\n" -" --envMethod [INTEGER] Specify the environment lighting method (0 = filtered importance sampling, 1 = prefiltered environment maps, defaults to 0)\n" -" --envSampleCount [INTEGER] Specify the environment sample count (defaults to 16)\n" -" --lightRotation [FLOAT] Specify the rotation in degrees of the lighting environment about the Y axis (defaults to 0)\n" -" --shadowMap [BOOLEAN] Specify whether shadow mapping is enabled (defaults to true)\n" -" --path [FILEPATH] Specify an additional data search path location (e.g. '/projects/MaterialX'). This absolute path will be queried when locating data libraries, XInclude references, and referenced images.\n" -" --library [FILEPATH] Specify an additional data library folder (e.g. 'vendorlib', 'studiolib'). This relative path will be appended to each location in the data search path when loading data libraries.\n" -" --screenWidth [INTEGER] Specify the width of the screen image in pixels (defaults to 1280)\n" -" --screenHeight [INTEGER] Specify the height of the screen image in pixels (defaults to 960)\n" -" --screenColor [VECTOR3] Specify the background color of the viewer as three comma-separated floats (defaults to 0.3,0.3,0.32)\n" -" --drawEnvironment [BOOLEAN] Specify whether to render the environment as the background (defaults to false)\n" -" --captureFilename [FILENAME] Specify the filename to which the first rendered frame should be written\n" -" --bakeWidth [INTEGER] Specify the target width for texture baking (defaults to maximum image width of the source document)\n" -" --bakeHeight [INTEGER] Specify the target height for texture baking (defaults to maximum image height of the source document)\n" -" --bakeFilename [STRING] Specify the output document filename for texture baking\n" -" --refresh [FLOAT] Specify the refresh period for the viewer in milliseconds (defaults to 50, set to -1 to disable)\n" -" --remap [TOKEN1:TOKEN2] Specify the remapping from one token to another when MaterialX document is loaded\n" -" --skip [NAME] Specify to skip elements matching the given name attribute\n" -" --terminator [STRING] Specify to enforce the given terminator string for file prefixes\n" -" --help Display the complete list of command-line options\n"; +const std::string options = + " Options: \n" + " --material [FILENAME] Specify the filename of the MTLX document to be displayed in the viewer\n" + " --mesh [FILENAME] Specify the filename of the OBJ mesh to be displayed in the viewer\n" + " --meshRotation [VECTOR3] Specify the rotation of the displayed mesh as three comma-separated floats, representing rotations in degrees about the X, Y, and Z axes (defaults to 0,0,0)\n" + " --meshScale [FLOAT] Specify the uniform scale of the displayed mesh\n" + " --enableTurntable[BOOLEAN] Specify whether to enable turntable rendering of the scene\n" + " --turntableSteps [INTEGER] Specify the number of steps for a complete turntable rotation. Defaults to 360\n" + " --cameraPosition [VECTOR3] Specify the position of the camera as three comma-separated floats (defaults to 0,0,5)\n" + " --cameraTarget [VECTOR3] Specify the position of the camera target as three comma-separated floats (defaults to 0,0,0)\n" + " --cameraViewAngle [FLOAT] Specify the view angle of the camera, or zero for an orthographic projection (defaults to 45)\n" + " --cameraZoom [FLOAT] Specify the zoom factor for the camera, implemented as a mesh scale multiplier (defaults to 1)\n" + " --envRad [FILENAME] Specify the filename of the environment light to display, stored as HDR environment radiance in the latitude-longitude format\n" + " --envMethod [INTEGER] Specify the environment lighting method (0 = filtered importance sampling, 1 = prefiltered environment maps, defaults to 0)\n" + " --envSampleCount [INTEGER] Specify the environment sample count (defaults to 16)\n" + " --lightRotation [FLOAT] Specify the rotation in degrees of the lighting environment about the Y axis (defaults to 0)\n" + " --shadowMap [BOOLEAN] Specify whether shadow mapping is enabled (defaults to true)\n" + " --path [FILEPATH] Specify an additional data search path location (e.g. '/projects/MaterialX'). This absolute path will be queried when locating data libraries, XInclude references, and referenced images.\n" + " --library [FILEPATH] Specify an additional data library folder (e.g. 'vendorlib', 'studiolib'). This relative path will be appended to each location in the data search path when loading data libraries.\n" + " --screenWidth [INTEGER] Specify the width of the screen image in pixels (defaults to 1280)\n" + " --screenHeight [INTEGER] Specify the height of the screen image in pixels (defaults to 960)\n" + " --screenColor [VECTOR3] Specify the background color of the viewer as three comma-separated floats (defaults to 0.3,0.3,0.32)\n" + " --drawEnvironment [BOOLEAN] Specify whether to render the environment as the background (defaults to false)\n" + " --captureFilename [FILENAME] Specify the filename to which the first rendered frame should be written\n" + " --bakeWidth [INTEGER] Specify the target width for texture baking (defaults to maximum image width of the source document)\n" + " --bakeHeight [INTEGER] Specify the target height for texture baking (defaults to maximum image height of the source document)\n" + " --bakeFilename [STRING] Specify the output document filename for texture baking\n" + " --refresh [FLOAT] Specify the refresh period for the viewer in milliseconds (defaults to 50, set to -1 to disable)\n" + " --remap [TOKEN1:TOKEN2] Specify the remapping from one token to another when MaterialX document is loaded\n" + " --skip [NAME] Specify to skip elements matching the given name attribute\n" + " --terminator [STRING] Specify to enforce the given terminator string for file prefixes\n" + " --help Display the complete list of command-line options\n"; -template void parseToken(std::string token, std::string type, T& res) +template void parseToken(std::string token, std::string type, T& res) { if (token.empty()) { @@ -64,7 +64,7 @@ template void parseToken(std::string token, std::string type, T& res) } int main(int argc, char* const argv[]) -{ +{ std::vector tokens; for (int i = 1; i < argc; i++) { @@ -131,7 +131,7 @@ int main(int argc, char* const argv[]) else if (token == "--turntableSteps") { parseToken(nextToken, "integer", turntableSteps); - turntableSteps = std::clamp(turntableSteps, 2, 360);; + turntableSteps = std::clamp(turntableSteps, 2, 360); } else if (token == "--cameraPosition") { @@ -159,7 +159,7 @@ int main(int argc, char* const argv[]) else if (token == "--envSampleCount") { parseToken(nextToken, "integer", envSampleCount); - } + } else if (token == "--lightRotation") { parseToken(nextToken, "float", lightRotation); diff --git a/source/MaterialXView/RenderPipeline.h b/source/MaterialXView/RenderPipeline.h index 82f5990513..87baac3fa4 100644 --- a/source/MaterialXView/RenderPipeline.h +++ b/source/MaterialXView/RenderPipeline.h @@ -44,16 +44,16 @@ class RenderPipeline virtual ~RenderPipeline() { } virtual void initialize(void* device, void* command_queue) = 0; - + virtual mx::ImageHandlerPtr createImageHandler() = 0; - virtual mx::MaterialPtr createMaterial() = 0; + virtual mx::MaterialPtr createMaterial() = 0; virtual void bakeTextures() = 0; - + virtual void updateAlbedoTable(int tableSize) = 0; virtual std::shared_ptr createTextureBaker(unsigned int width, unsigned int height, mx::Image::BaseType baseType) = 0; - + virtual void renderFrame(void* color_texture, int shadowMapSize, const char* dirLightNodeCat) = 0; virtual void initFramebuffer(int width, int height, @@ -62,9 +62,9 @@ class RenderPipeline void* color_texture) = 0; virtual mx::ImagePtr getShadowMap(int shadowMapSize) = 0; - + virtual mx::ImagePtr getFrameImage() = 0; - + public: Viewer* _viewer; };