Esempio n. 1
0
MStatus sgBDataCmd_key::startExport( MString pathFolder )
{
	MStatus status;

	m_filePaths.clear();
	for( unsigned int i=0; i< m_pathArrExport.length(); i++ )
	{
		MFnDagNode fnNode( m_pathArrExport[i], &status );
		if( !status ) continue;
		MString targetName = fnNode.partialPathName();
		targetName.substitute( ":", "_" );
		targetName.substitute( "|", "_" );
		m_filePaths.append( pathFolder + "\\" + targetName + ".sgKeyData" );
	}

	m_objectKeyDatasExport.setLength( m_pathArrExport.length() );

	for( unsigned int i=0; i< m_pathArrExport.length(); i++ )
	{
		setObjectKeyDataDefault( m_objectKeyDatasExport[i], m_pathArrExport[i], m_exportByMatrix );

		unsigned int unit = MTime().unit();
		MString  nameTarget = MFnDagNode( m_pathArrExport[i] ).fullPathName();

		std::ofstream outFile( m_filePaths[i].asChar(), ios::binary );

		writeString( nameTarget, outFile );
		writeUnsignedInt( unit, outFile );
		writeStringArray( m_objectKeyDatasExport[i].namesAttribute, outFile );

		outFile.close();
	}
	return MS::kSuccess;
}
//-----------------------------------------------------------------------------
// Returns the vsSkinner node if the passed node is connected to a vsSkinner node
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::ConnectedToSkinnerNode(
	const MDagPath &iDagPath,
	MDagPath &oDagPath )
{
	MPlugArray pA;
	MPlugArray pA1;

	if ( MFnDagNode( iDagPath ).getConnections( pA ) && pA.length() )
	{
		MObject mObj;

		const uint np( pA.length() );
		for ( uint i( 0U ); i != np; ++i )
		{
			if ( pA[ i ].connectedTo( pA1, true, true ) && pA1.length() )
			{
				const uint np1( pA1.length() );
				for ( uint j( 0U ); j != np1; ++j )
				{
					mObj = pA1[ j ].node();

					if ( IsSkinnerNode( mObj ) )
					{
						MDagPath::getAPathTo( mObj, oDagPath );
						return MS::kSuccess;
					}
				}
			}
		}
	}

	return MS::kFailure;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::IsSkinnerNode(
	const MDagPath &iDagPath )
{
	if ( iDagPath.hasFn( MFn::kPluginShape ) && MFnDagNode( iDagPath ).typeName() == "vsSkinner" )
		return MS::kSuccess;

	return MS::kFailure;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::DoDetachMesh(
	const MDagPath &mDagPath )
{
	if ( !IsSkinnerNode( mDagPath ) )
		return MS::kFailure;

	CVsSkinnerNode *pSkinnerNode( reinterpret_cast< CVsSkinnerNode * >( MFnDagNode( mDagPath ).userNode() ) );
	return pSkinnerNode->DetachMesh( m_undo.DagModifier() );
}
void Exporter::createSceneGraph(MFnDagNode& path, int parentIndex)
{
	Node output;
	std::vector<std::string> pathparts;
	output.name = path.fullPathName().asChar();
	splitStringToVector(output.name, pathparts, "|");
	output.name = pathparts[pathparts.size() - 1];
	if (!strcmp(output.name.c_str(), "persp"))
		return;
	else if (!strcmp(output.name.c_str(), "top"))
		return;
	else if (!strcmp(output.name.c_str(), "side"))
		return;
	else if (!strcmp(output.name.c_str(), "front"))
		return;
	output.parent = parentIndex;
	output.transform = path.transformationMatrix().matrix;



	scene_.sceneGraph.push_back(output);
	int children = path.childCount();
	int parent = scene_.sceneGraph.size() - 1;
	for (int i = 0; i < children; i++)
	{
		cout << path.child(i).apiTypeStr() << endl;
		if (!strcmp(path.child(i).apiTypeStr(), "kMesh")){
			scene_.sceneGraph[parent].type = 1;
			MFnMesh mesh(path.child(i));
			MDagPath dag_path;
			MItDag dag_iter(MItDag::kBreadthFirst, MFn::kMesh);
			int y = 0;
			while (!dag_iter.isDone())
			{
				if (dag_iter.getPath(dag_path))
				{
					MFnDagNode dag_node = dag_path.node();
					if (!dag_node.isIntermediateObject())
					{
						if (!strcmp(mesh.partialPathName().asChar(), dag_node.partialPathName().asChar()))
							scene_.sceneGraph[parent].mesh = y;
						y++;
					}
				}
				dag_iter.next();
			}
		}
//		else if (!strcmp(path.child(i).apiTypeStr(), "kCamera")); kan l�gga till fler typer h�r
		else
		createSceneGraph(MFnDagNode(path.child(i)), parent);
	}


}
Esempio n. 6
0
	MStatus FillStrandGaps::doIt(const MArgList & args) {
		std::list<MObject> targets;
		MStatus status = ArgList_GetModelObjects(args, syntax(), "-t", targets);
		if (status != MStatus::kNotFound && status != MStatus::kSuccess) {
			HMEVALUATE_RETURN_DESCRIPTION("ArgList_GetModelObjects", status);
		}

		if (targets.empty()) {
			MSelectionList activeSelectionList;
			HMEVALUATE_RETURN(status = MGlobal::getActiveSelectionList(activeSelectionList), status);

			if (activeSelectionList.length() > 0) {
				for (unsigned int i = 0; i < activeSelectionList.length(); ++i) {
					MObject object;

					HMEVALUATE_RETURN(status = activeSelectionList.getDependNode(i, object), status);

					MFnDagNode dagNode(object);
					MTypeId typeId;
					HMEVALUATE_RETURN(typeId = dagNode.typeId(&status), status);

					if (typeId == HelixBase::id || typeId == Helix::id)
						targets.push_back(object);
					else
						MGlobal::displayWarning(MString("Ignoring unknown object \"") + dagNode.fullPathName() + "\"");
				}
			}
			else {
				/*
				 * Extract all helices
				 */

				MItDag itDag(MItDag::kDepthFirst, MFn::kPluginTransformNode, &status);
				HMEVALUATE_RETURN_DESCRIPTION("MItDag::#ctor", status);

				for (; !itDag.isDone(); itDag.next()) {
					MObject object;
					HMEVALUATE_RETURN(object = itDag.currentItem(&status), status);

					bool is_helix;
					HMEVALUATE_RETURN(is_helix = MFnDagNode(object).typeId(&status) == Helix::id, status);
					if (is_helix)
						targets.push_back(object);
				}
			}
		}

		return m_operation.fill(targets);
	}
		MStatus CreateCurves::undo() {
			MStatus status;
			
			for(unsigned int i = 0; i < m_curves.length(); ++i) {
				std::cerr << "DeleteNode: " << MFnDagNode(m_curves[i]).fullPathName().asChar() << std::endl;

				if (!(status = MGlobal::removeFromModel(m_curves[i]))) {
					status.perror("MGlobal::removeFromModel");
					return status;
				}
			}

			m_curves.clear();

			return MStatus::kSuccess;
		}
Esempio n. 8
0
bool HesperisIO::FindNamedChild(MObject & dst, const std::string & name, MObject & oparent)
{
    if(oparent == MObject::kNullObj) {
        MItDag itdag(MItDag::kBreadthFirst);
        oparent = itdag.currentItem();
        MGlobal::displayInfo(MFnDagNode(oparent).name() + " as default parent");
    }
    
    MFnDagNode ppf(oparent);
    for(unsigned i = 0; i <ppf.childCount(); i++) {
        MFnDagNode pf(ppf.child(i));
        std::string curname = pf.name().asChar();
        if(SHelper::isMatched(curname, name)) {
            dst = ppf.child(i);
            return true;
        }
    }
    return false;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MObject CVsSkinnerCmd::DoNewVolume(
	const MDagPath &skinnerPath,
	const MDagPath &pDagPath )
{
	if ( !IsSkinnerNode( skinnerPath ) )
		return MObject::kNullObj;

	CVsSkinnerNode *pSkinnerNode( reinterpret_cast< CVsSkinnerNode * >( MFnDagNode( skinnerPath ).userNode() ) );

	double strength( 1.0 );
	if ( m_undo.ArgDatabase().isFlagSet( kOptStrength ) )
	{
		m_undo.ArgDatabase().getFlagArgument( kOptStrength, 0, strength );
	}

	double falloff( 0.25 );
	if ( m_undo.ArgDatabase().isFlagSet( kOptFalloff ) )
	{
		m_undo.ArgDatabase().getFlagArgument( kOptFalloff, 0, falloff );
	}

	return pSkinnerNode->NewVolume( strength, falloff, pDagPath, m_undo );
}
Esempio n. 10
0
		void BaseShapeUI::draw( const MDrawRequest & request, M3dView & view ) const {
			if (s_drawData.failure)
				return;

			MStatus status;

			view.beginGL();

			if (!s_drawData.initialized)
				initializeDraw();

			BaseShape *shape = (BaseShape *) surfaceShape();

			Model::Base base(MFnDagNode(shape->thisMObject()).parent(0, &status));

			if (!status) {
				status.perror("MFnDagNode::parent");
				return;
			}

			//MDagPath path = request.multiPath();
			MMaterial material = request.material();
			MColor color, borderColor;

			if (!(status = material.getDiffuse(color))) {
				status.perror("MMaterial::getDiffuse");
				return;
			}

			bool wireframe = (M3dView::DisplayStyle) request.token() == M3dView::kWireFrame;

			if (wireframe) {
				glPushAttrib(GL_POLYGON_BIT);

				glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
			}

			glUseProgram(s_drawData.program);
			
			switch (request.displayStatus())
            {
            case M3dView::kLead :
				borderColor = view.colorAtIndex( LEAD_COLOR);
				//glUniform1f(s_drawData.border_uniform, 1.0f);
				s_drawData.updateBorderUniform(1.0f);
				//glUniform3f(s_drawData.borderColor_uniform, borderColor.r, borderColor.g, borderColor.b);
				s_drawData.updateBorderColorUniform(borderColor.r, borderColor.g, borderColor.b);
				break;
            case M3dView::kActive :
                borderColor = view.colorAtIndex( ACTIVE_COLOR);
				//glUniform1f(s_drawData.border_uniform, 1.0f);
				s_drawData.updateBorderUniform(1.0f);
				//glUniform3f(s_drawData.borderColor_uniform, borderColor.r, borderColor.g, borderColor.b);
				s_drawData.updateBorderColorUniform(borderColor.r, borderColor.g, borderColor.b);
                break;
            case M3dView::kActiveAffected :
                borderColor = view.colorAtIndex( ACTIVE_AFFECTED_COLOR);
				//glUniform1f(s_drawData.border_uniform, 0.0f);
				s_drawData.updateBorderUniform(0.0f);
                break;
            case M3dView::kDormant :
				borderColor = view.colorAtIndex( DORMANT_COLOR, M3dView::kDormantColors);
				//glUniform1f(s_drawData.border_uniform, 0.0f);
				s_drawData.updateBorderUniform(0.0f);
                break;
            case M3dView::kHilite :
                borderColor = view.colorAtIndex( HILITE_COLOR);
				//glUniform1f(s_drawData.border_uniform, 1.0f);
				s_drawData.updateBorderUniform(1.0f);
				//glUniform3f(s_drawData.borderColor_uniform, borderColor.r, borderColor.g, borderColor.b);
				s_drawData.updateBorderColorUniform(borderColor.r, borderColor.g, borderColor.b);
                break;
            }

			//glUniform3f(s_drawData.color_uniform, color.r, color.g, color.b);
			s_drawData.updateColorUniform(color.r, color.g, color.b);

			glCallList(s_drawData.display_list);

			if (wireframe)
				glPopAttrib();

			view.endGL();
		}
Esempio n. 11
0
bool usdWriteJob::beginJob(const std::string &iFileName,
                         bool append,
                         double startTime,
                         double endTime)
{
    // Check for DAG nodes that are a child of an already specified DAG node to export
    // if that's the case, report the issue and skip the export
    PxrUsdMayaUtil::ShapeSet::const_iterator m, n;
    PxrUsdMayaUtil::ShapeSet::const_iterator endPath = mArgs.dagPaths.end();
    for (m = mArgs.dagPaths.begin(); m != endPath; ) {
        MDagPath path1 = *m; m++;
        for (n = m; n != endPath; n++) {
            MDagPath path2 = *n;
            if (PxrUsdMayaUtil::isAncestorDescendentRelationship(path1,path2)) {
                MString errorMsg = path1.fullPathName();
                errorMsg += " and ";
                errorMsg += path2.fullPathName();
                errorMsg += " have an ancestor relationship. Skipping USD Export.";
                MGlobal::displayError(errorMsg);
                return false;
            }
        }  // for n
    }  // for m

    // Make sure the file name is a valid one with a proper USD extension.
    const std::string iFileExtension = TfStringGetSuffix(iFileName, '.');
    if (iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionDefault   || 
            iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionASCII || 
            iFileExtension == PxrUsdMayaTranslatorTokens->UsdFileExtensionCrate) {
        mFileName = iFileName;
    } else {
        mFileName = TfStringPrintf("%s.%s",
                                   iFileName.c_str(),
                                   PxrUsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText());
    }

    MGlobal::displayInfo("usdWriteJob::beginJob: Create stage file "+MString(mFileName.c_str()));

    ArResolverContext resolverCtx = ArGetResolver().GetCurrentContext();
    if (append) {
        mStage = UsdStage::Open(SdfLayer::FindOrOpen(mFileName), resolverCtx);
        if (!mStage) {
            MGlobal::displayError("Failed to open stage file "+MString(mFileName.c_str()));
            return false;
            }
    } else {
        mStage = UsdStage::CreateNew(mFileName, resolverCtx);
        if (!mStage) {
            MGlobal::displayError("Failed to create stage file "+MString(mFileName.c_str()));
            return false;
        }
    }

    // Set time range for the USD file
    mStage->SetStartTimeCode(startTime);
    mStage->SetEndTimeCode(endTime);
    
    mModelKindWriter.Reset();

    // Setup the requested render layer mode:
    //     defaultLayer    - Switch to the default render layer before exporting,
    //                       then switch back afterwards (no layer switching if
    //                       the current layer IS the default layer).
    //     currentLayer    - No layer switching before or after exporting. Just
    //                       use whatever is the current render layer for export.
    //     modelingVariant - Switch to the default render layer before exporting,
    //                       and export each render layer in the scene as a
    //                       modeling variant, then switch back afterwards (no
    //                       layer switching if the current layer IS the default
    //                       layer). The default layer will be made the default
    //                       modeling variant.
    MFnRenderLayer currentLayer(MFnRenderLayer::currentLayer());
    mCurrentRenderLayerName = currentLayer.name();

    if (mArgs.renderLayerMode == PxUsdExportJobArgsTokens->modelingVariant) {
        // Handle usdModelRootOverridePath for USD Variants
        MFnRenderLayer::listAllRenderLayers(mRenderLayerObjs);
        if (mRenderLayerObjs.length() > 1) {
            mArgs.usdModelRootOverridePath = SdfPath("/_BaseModel_");
        }
    }

    // Switch to the default render layer unless the renderLayerMode is
    // 'currentLayer', or the default layer is already the current layer.
    if (mArgs.renderLayerMode != PxUsdExportJobArgsTokens->currentLayer &&
            MFnRenderLayer::currentLayer() != MFnRenderLayer::defaultRenderLayer()) {
        // Set the RenderLayer to the default render layer
        MFnRenderLayer defaultLayer(MFnRenderLayer::defaultRenderLayer());
        MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+
                                        defaultLayer.name(), false, false);
    }

    // Pre-process the argument dagPath path names into two sets. One set
    // contains just the arg dagPaths, and the other contains all parents of
    // arg dagPaths all the way up to the world root. Partial path names are
    // enough because Maya guarantees them to still be unique, and they require
    // less work to hash and compare than full path names.
    TfHashSet<std::string, TfHash> argDagPaths;
    TfHashSet<std::string, TfHash> argDagPathParents;
    PxrUsdMayaUtil::ShapeSet::const_iterator end = mArgs.dagPaths.end();
    for (PxrUsdMayaUtil::ShapeSet::const_iterator it = mArgs.dagPaths.begin();
            it != end; ++it) {
        MDagPath curDagPath = *it;
        std::string curDagPathStr(curDagPath.partialPathName().asChar());
        argDagPaths.insert(curDagPathStr);

        while (curDagPath.pop() && curDagPath.length() >= 0) {
            curDagPathStr = curDagPath.partialPathName().asChar();
            if (argDagPathParents.find(curDagPathStr) != argDagPathParents.end()) {
                // We've already traversed up from this path.
                break;
            }
            argDagPathParents.insert(curDagPathStr);
        }
    }

    // Now do a depth-first traversal of the Maya DAG from the world root.
    // We keep a reference to arg dagPaths as we encounter them.
    MDagPath curLeafDagPath;
    for (MItDag itDag(MItDag::kDepthFirst, MFn::kInvalid); !itDag.isDone(); itDag.next()) {
        MDagPath curDagPath;
        itDag.getPath(curDagPath);
        std::string curDagPathStr(curDagPath.partialPathName().asChar());

        if (argDagPathParents.find(curDagPathStr) != argDagPathParents.end()) {
            // This dagPath is a parent of one of the arg dagPaths. It should
            // be included in the export, but not necessarily all of its
            // children should be, so we continue to traverse down.
        } else if (argDagPaths.find(curDagPathStr) != argDagPaths.end()) {
            // This dagPath IS one of the arg dagPaths. It AND all of its
            // children should be included in the export.
            curLeafDagPath = curDagPath;
        } else if (!MFnDagNode(curDagPath).hasParent(curLeafDagPath.node())) {
            // This dagPath is not a child of one of the arg dagPaths, so prune
            // it and everything below it from the traversal.
            itDag.prune();
            continue;
        }

        MayaPrimWriterPtr primWriter = nullptr;
        if (!createPrimWriter(curDagPath, &primWriter) &&
                curDagPath.length() > 0) {
            // This dagPath and all of its children should be pruned.
            itDag.prune();
            continue;
        }

        if (primWriter) {
            mMayaPrimWriterList.push_back(primWriter);

            // Write out data (non-animated/default values).
            if (UsdPrim usdPrim = primWriter->write(UsdTimeCode::Default())) {
                MDagPath dag = primWriter->getDagPath();
                mDagPathToUsdPathMap[dag] = usdPrim.GetPath();

                // If we are merging transforms and the object derives from
                // MayaTransformWriter but isn't actually a transform node, we
                // need to add its parent.
                if (mArgs.mergeTransformAndShape) {
                    MayaTransformWriterPtr xformWriter =
                            boost::dynamic_pointer_cast<MayaTransformWriter>(
                                    primWriter);
                    if (xformWriter) {
                        MDagPath xformDag = xformWriter->getTransformDagPath();
                        mDagPathToUsdPathMap[xformDag] = usdPrim.GetPath();
                    }
                }

                mModelKindWriter.OnWritePrim(usdPrim, primWriter);

                if (primWriter->shouldPruneChildren()) {
                    itDag.prune();
                }
            }
        }
    }

    // Writing Materials/Shading
    PxrUsdMayaTranslatorMaterial::ExportShadingEngines(
                mStage, 
                mArgs.dagPaths,
                mArgs.shadingMode,
                mArgs.mergeTransformAndShape,
                mArgs.usdModelRootOverridePath);

    if (!mModelKindWriter.MakeModelHierarchy(mStage)) {
        return false;
    }

    // now we populate the chasers and run export default
    mChasers.clear();
    PxrUsdMayaChaserRegistry::FactoryContext ctx(mStage, mDagPathToUsdPathMap, mArgs);
    for (const std::string& chaserName : mArgs.chaserNames) {
        if (PxrUsdMayaChaserRefPtr fn = 
                PxrUsdMayaChaserRegistry::GetInstance().Create(chaserName, ctx)) {
            mChasers.push_back(fn);
        }
        else {
            std::string error = TfStringPrintf("Failed to create chaser: %s",
                                               chaserName.c_str());
            MGlobal::displayError(MString(error.c_str()));
        }
    }

    for (const PxrUsdMayaChaserRefPtr& chaser : mChasers) {
        if (!chaser->ExportDefault()) {
            return false;
        }
    }

    return true;
}
Esempio n. 12
0
MString getFullNameFromRef(const MObject & in_Ref)
{
   return MFnDagNode(in_Ref).fullPathName();
}
// identifierar alla mesharna i scenen och extraherar data fr�n dem
bool Exporter::IdentifyAndExtractMeshes()
{
	UINT index = 0;
	scene_.meshes.clear();

	//itererar �ver DG:n och lagrar rgba-v�rden och texturnamn i ett tempor�rt material
	material tempmaterial;
	MItDependencyNodes matIt(MFn::kLambert);
	MString aC("ambientColor"), dC("color"), sC("specularColor"), gC("incandescence"), tC("transparency");
	while (!matIt.isDone()){
		if (matIt.item().hasFn(MFn::kPhong))
		{
			MFnPhongShader tempphong(matIt.item());
			tempmaterial.type = PHONG;
			extractColor(tempmaterial.ambient, tempphong, aC);
			extractColor(tempmaterial.diffuse, tempphong, dC);
			extractColor(tempmaterial.specular, tempphong, sC);
			extractColor(tempmaterial.glow, tempphong, gC);
			extractColor(tempmaterial.transparency, tempphong, tC);
		}
		else if (matIt.thisNode().hasFn(MFn::kBlinn))
		{
			MFnBlinnShader tempblinn(matIt.item());
			tempmaterial.type = BLINN;
			extractColor(tempmaterial.ambient, tempblinn, aC);
			extractColor(tempmaterial.diffuse, tempblinn, dC);
			extractColor(tempmaterial.specular, tempblinn, sC);
			extractColor(tempmaterial.glow, tempblinn, gC);
			extractColor(tempmaterial.transparency, tempblinn, tC);
		}
		else if (matIt.item().hasFn(MFn::kLambert))
		{
			MFnLambertShader templamb(matIt.item());
			tempmaterial.type = LAMBERT;
			extractColor(tempmaterial.ambient, templamb, aC);
			extractColor(tempmaterial.diffuse, templamb, dC);
			extractColor(tempmaterial.specular, templamb, sC);
			extractColor(tempmaterial.glow, templamb, gC);
			extractColor(tempmaterial.transparency, templamb, tC);
		}
		else
			printf("No material found\n");
		scene_.materials.push_back(tempmaterial);
		matIt.next();
	}

	//Turn off or on Blendshapes
	matIt.reset(MFn::kBlendShape);
	while (!matIt.isDone())
	{
		MFnBlendShapeDeformer bs(matIt.item());

		//Get the envelope attribute plug
		MPlug pl = bs.findPlug("en");

		//Set the 0 to disable FFD effect, enable by setting it to 1:
		pl.setValue(1.0f);

		matIt.next();
	}

	//Get Actual Blendshapes
	matIt.reset(MFn::kBlendShape);
	while (!matIt.isDone())
	{
		MFnBlendShapeDeformer bs(matIt.item());

		MObjectArray base_objects;

		//print blend shape name
		cout << "Blendshape " << bs.name().asChar() << endl;

		//Get a list of objects that this blend shape deforms
		bs.getBaseObjects(base_objects);

		cout << "NumBaseOBjects " << base_objects.length() << endl;

		//loop through each blendshaped object
		for (int i = 0; i < base_objects.length(); ++i)
		{
			//Get the base shape
			MObject Base = base_objects[i];

			//Output all of the target shapes and weights
			OutputBlendShapes(bs, Base);
		}
		//Get next blend shapes
		matIt.next();
	}

	MDagPath dag_path;
	MItDag dag_iter(MItDag::kBreadthFirst, MFn::kMesh);

	while (!dag_iter.isDone())
	{
		if (dag_iter.getPath(dag_path))
		{
			MFnDagNode dag_node = dag_path.node();

			// vill endast ha "icke-history"-f�rem�l
			if (!dag_node.isIntermediateObject())
			{
				// triangulera meshen innan man h�mtar punkterna
				MFnMesh mesh(dag_path);
				ExtractMeshData(mesh, index);
				index++;
			}
		}

		dag_iter.next();
	}

	MItDependencyNodes it(MFn::kSkinClusterFilter);
	for (; !it.isDone(); it.next()) {


		MObject object = it.item();


		OutputSkinCluster(object);

	}

	//Hitta kamera data
	dag_iter.reset(dag_iter.root(), MItDag::kBreadthFirst, MFn::kCamera);
	while (!dag_iter.isDone())
	{

		extractCamera(dag_iter.item());
		dag_iter.next();
	}

	//itererar dag och s�ker data f�r tillg�ngliga ljus
	//om ej ljus finns i scenen ignoreras denna iteration f�r sagda scen.
	dag_iter.reset(dag_iter.root(), MItDag::kBreadthFirst, MFn::kLight);
	while (!dag_iter.isDone())
	{
		//funktion till v�r iterator
		MFnLight func(dag_iter.item());

		//namn:
		export_stream_ << "Light: " << func.name().asChar() << std::endl;

		//kalla p�EextractLight function
		extractLight(dag_iter.item());

		//vidare till n�sta ljus i dag'en
		dag_iter.next();


		/*
		if (dag_iter.getPath(dag_path))
		{
		auto test = dag_path.fullPathName();
		export_stream_ << "light: " << test << std::endl;
		}
		dag_iter.next();
		*/
	}

	dag_iter.reset(dag_iter.root(), MItDag::kBreadthFirst, MFn::kJoint);
	while (!dag_iter.isDone())
	{
		if (dag_iter.getPath(dag_path))
		{
			MFnDagNode dag_node = dag_path.node();

			if (!dag_node.isIntermediateObject())
			{
				extractJointData(dag_path);
			}
		}
		dag_iter.next();
	}
	int breadth=0;
	dag_iter.reset(dag_iter.root(), MItDag::kBreadthFirst, MFn::kTransform);
	while (!dag_iter.isDone())
	{
		int depth = dag_iter.depth();
		if (depth > 1)
			break;
		if (dag_iter.getPath(dag_path))
		{
			createSceneGraph(MFnDagNode(dag_path),-1);
		}
		breadth++;
		dag_iter.next();
	}
	/*
	//general purpose iterator, sista argument �r filtret
		dag_iter.reset(dag_iter.root(), MItDag::kBreadthFirst, MFn::kLight);
		while (!dag_iter.isDone())
		{
		if (dag_iter.getPath(dag_path))
		{

		}
		dag_iter.next();
		}
		*/


	return true;
}
Esempio n. 14
0
//-----------------------------------------------------------------------------
//
// Purpose: Create a Maya Dag node named properly
//
//-----------------------------------------------------------------------------
MStatus ValveMaya::CreateDagNode(
	const char *const i_nodeType,
	const char *const i_transformName,
	const MObject &i_parentObj,
	MObject *o_pTransformObj,
	MObject *o_pShapeObj,
	MDagModifier *i_mDagModifier)
{
	MStatus retVal;

	// If the user didn't supply an MDagModifier make a temporary one
	MDagModifier tmpDagModifier;
	MDagModifier &mDagModifier( i_mDagModifier ? *i_mDagModifier : tmpDagModifier );

	// Try and create the node
	const MObject tObj( mDagModifier.createNode( i_nodeType, i_parentObj, &retVal ) );
	if ( !retVal )
		return retVal;

	mDagModifier.doIt();

	// Failed... undo the Dag modifier and return failure
	if ( tObj.isNull() )
	{
		mDagModifier.undoIt();
        return MS::kFailure;
	}

	// If the caller wants a copy of the created Transform MObject save it
	if ( o_pTransformObj )
		*o_pTransformObj = tObj;

	// The name the shape will be called
	MString sName;

	// Set the name of the transform, it's either the name of the node type or the called specified name
	if ( i_transformName )
	{
		retVal = mDagModifier.renameNode( tObj, i_transformName );
		sName = i_transformName;
    }
	else
	{
		retVal = mDagModifier.renameNode( tObj, i_nodeType );
		sName = i_nodeType;
	}

	// If the rename failed, undo the dag modifier and quit
	if ( !retVal )
	{
		mDagModifier.undoIt();
		return retVal;
	}

	mDagModifier.doIt();

	// Search for the shape node that was created, normally there will be only 1 shape but there are pathological
	// cases, some might not quite be handled here but most will be
	MDagPath tDagPath( MDagPath::getAPathTo( tObj ) );
	unsigned sEnd( 0 );
	tDagPath.numberOfShapesDirectlyBelow( sEnd );

	for ( unsigned si( 0 ); si != sEnd; ++si )
	{
		MDagPath sDagPath( tDagPath );
		sDagPath.extendToShapeDirectlyBelow( si );

		if ( MFnDagNode( sDagPath ).typeName() == i_nodeType )
		{
			// Add the %d suffix so sscanf can be used to check if Maya added a numeric suffix to the transform name
			const MString tScanfName( sName + "%d" );

			// Add the 'Shape' Suffix to the shape name
			sName += "Shape";

			// Get the actual name Maya assigned the node so it can be scanned for a Maya added numeric suffix
			const MString tName( MFnDependencyNode( tObj ).name() );
			int numericSuffix( 0 );

			switch ( sscanf( tName.asChar(), tScanfName.asChar(), &numericSuffix ) )
			{
			case 0:
			default:
				// There was no numeric suffix added by Maya, so nothing extra to add
				break;
			case 1:
				// Maya added a numeric suffix, add it to the shape name
				sName += numericSuffix;
				break;
			}

			// Rename the shape node so it now matches the transform, this operation can't really fail
			const MObject sObj( sDagPath.node() );

			// If the caller wants a copy of the created Transform MObject save it
			if ( o_pShapeObj )
				*o_pShapeObj = sObj;

			mDagModifier.renameNode( sObj, sName );
			mDagModifier.doIt();

			// Just do the first shape of the appropriate type found
			break;
		}
	}
			
	return retVal;
}
Esempio n. 15
0
MStatus slopeShaderBehavior::connectNodeToNode( MObject &sourceNode, MObject &destinationNode, bool force )
//
//	Description:
//		Overloaded function from MPxDragAndDropBehavior
//	this method will handle the connection between the slopeShader and the shader it is
//	assigned to as well as any meshes that it is assigned to. 
//
{
	MStatus result = MS::kFailure;
	MFnDependencyNode src(sourceNode);

	//if we are dragging from a lambert
	//we want to check what we are dragging
	//onto.
	if(sourceNode.hasFn(MFn::kLambert))
	{
		MObject shaderNode;
		MPlugArray connections;
		MObjectArray shaderNodes;
		shaderNodes.clear();

		//if the source node was a lambert
		//than we will check the downstream connections to see 
		//if a slope shader is assigned to it.
		//
		src.getConnections(connections);
		unsigned i;
		for(i = 0; i < connections.length(); i++)
		{
			//check the incoming connections to this plug
			//
			MPlugArray connectedPlugs;
			connections[i].connectedTo(connectedPlugs, true, false);
			for(unsigned j = 0; j < connectedPlugs.length(); j++)
			{
				//if the incoming node is a slope shader than 
				//append the node to the shaderNodes array
				//
				MObject currentnode = connectedPlugs[j].node();
				if(MFnDependencyNode(currentnode).typeName() == "slopeShader")
				{
					shaderNodes.append(currentnode);
				}
			}
		}

		//if we found a shading node
		//than check the destination node 
		//type to see if it is a mesh
		//
		if(shaderNodes.length() > 0)
		{
			MFnDependencyNode dest(destinationNode);
			if(destinationNode.hasFn(MFn::kMesh))
			{
				//if the node is a mesh than for each slopeShader
				//connect the worldMesh attribute to the dirtyShaderPlug
				//attribute to force an evaluation of the node when the mesh
				//changes
				//
				for(i = 0; i < shaderNodes.length(); i++)
				{
					MPlug srcPlug = dest.findPlug("worldMesh");
					MPlug destPlug = MFnDependencyNode(shaderNodes[i]).findPlug("dirtyShaderPlug");

					if(!srcPlug.isNull() && !destPlug.isNull())
					{
						MString cmd = "connectAttr -na ";
						cmd += srcPlug.name() + " ";
						cmd += destPlug.name();
						MGlobal::executeCommand(cmd);
					}
				}

				//get the shading engine so we can assign the shader
				//to the mesh after doing the connection
				//
				MObject shadingEngine = findShadingEngine(sourceNode);

				//if there is a valid shading engine than make
				//the connection
				//
				if(!shadingEngine.isNull())
				{
					MString cmd = "sets -edit -forceElement ";
					cmd += MFnDependencyNode(shadingEngine).name() + " ";
					cmd += MFnDagNode(destinationNode).partialPathName();
					result = MGlobal::executeCommand(cmd);
				}
			}
		}
	}
	else if(src.typeName() == "slopeShader")
	//if we are dragging from a slope shader
	//than we want to see what we are dragging onto
	//
	{
		if(destinationNode.hasFn(MFn::kMesh))
		{
			//if the user is dragging onto a mesh
			//than make the connection from the worldMesh
			//to the dirtyShader plug on the slopeShader
			//
			MFnDependencyNode dest(destinationNode);
			MPlug srcPlug = dest.findPlug("worldMesh");
			MPlug destPlug = src.findPlug("dirtyShaderPlug");
			if(!srcPlug.isNull() && !destPlug.isNull())
			{
				MString cmd = "connectAttr -na ";
				cmd += srcPlug.name() + " ";
				cmd += destPlug.name();
				result = MGlobal::executeCommand(cmd);
			}
		}
	}

	return result;
}
Esempio n. 16
0
void liqWriteArchive::writeObjectToRib(const MDagPath &objDagPath, bool writeTransform)
{
  if (!isObjectVisible(objDagPath)) {
    return;
  }

  if (debug) { cout << "liquidWriteArchive: writing object: " << objDagPath.fullPathName().asChar() << endl; }
  if (objDagPath.node().hasFn(MFn::kShape) || MFnDagNode( objDagPath ).typeName() == "liquidCoorSys") {
    // we're looking at a shape node, so write out the geometry to the RIB
    outputObjectName(objDagPath);

    liqRibNode ribNode;
    ribNode.set(objDagPath, 0, MRT_Unknown);

    // don't write out clipping planes
    if ( ribNode.object(0)->type == MRT_ClipPlane ) return;

    if ( ribNode.rib.box != "" && ribNode.rib.box != "-" ) {
      RiArchiveRecord( RI_COMMENT, "Additional RIB:\n%s", ribNode.rib.box.asChar() );
    }
    if ( ribNode.rib.readArchive != "" && ribNode.rib.readArchive != "-" ) {
      // the following test prevents a really nasty infinite loop !!
      if ( ribNode.rib.readArchive != outputFilename )
        RiArchiveRecord( RI_COMMENT, "Read Archive Data: \nReadArchive \"%s\"", ribNode.rib.readArchive.asChar() );
    }
    if ( ribNode.rib.delayedReadArchive != "" && ribNode.rib.delayedReadArchive != "-" ) {
      // the following test prevents a really nasty infinite loop !!
      if ( ribNode.rib.delayedReadArchive != outputFilename )
        RiArchiveRecord( RI_COMMENT, "Delayed Read Archive Data: \nProcedural \"DelayedReadArchive\" [ \"%s\" ] [ %f %f %f %f %f %f ]", ribNode.rib.delayedReadArchive.asChar(), ribNode.bound[0], ribNode.bound[3], ribNode.bound[1], ribNode.bound[4], ribNode.bound[2], ribNode.bound[5]);
    }

    // If it's a curve we should write the basis function
    if ( ribNode.object(0)->type == MRT_NuCurve ) {
      RiBasis( RiBSplineBasis, 1, RiBSplineBasis, 1 );
    }

    if ( !ribNode.object(0)->ignore ) {
      ribNode.object(0)->writeObject();
    }
  } else {
    // we're looking at a transform node
    bool wroteTransform = false;
    if (writeTransform && (objDagPath.apiType() == MFn::kTransform)) {
      if (debug) { cout << "liquidWriteArchive: writing transform: " << objDagPath.fullPathName().asChar() << endl; }
      // push the transform onto the RIB stack
      outputObjectName(objDagPath);
      MFnDagNode mfnDag(objDagPath);
      MMatrix tm = mfnDag.transformationMatrix();
      if (true) { // (!tm.isEquivalent(MMatrix::identity)) {
        RtMatrix riTM;
        tm.get(riTM);
        wroteTransform = true;
        outputIndentation();
        RiAttributeBegin();
        indentLevel++;
        outputIndentation();
        RiConcatTransform(riTM);
      }
    }
    // go through all the children of this node and deal with each of them
    int nChildren = objDagPath.childCount();
    if (debug) { cout << "liquidWriteArchive: object " << objDagPath.fullPathName().asChar() << "has " << nChildren << " children" << endl; }
    for(int i=0; i<nChildren; ++i) {
      if (debug) { cout << "liquidWriteArchive: writing child number " << i << endl; }
      MDagPath childDagNode;
      MStatus stat = MDagPath::getAPathTo(objDagPath.child(i), childDagNode);
      if (stat) {
        writeObjectToRib(childDagNode, outputChildTransforms);
      } else {
        MGlobal::displayWarning("error getting a dag path to child node of object " + objDagPath.fullPathName());
      }
    }
    if (wroteTransform) {
      indentLevel--;
      outputIndentation();
      RiAttributeEnd();
    }
  }
  if (debug) { cout << "liquidWriteArchive: finished writing object: " << objDagPath.fullPathName().asChar() << endl; }
}