예제 #1
0
static bool isCompound(const MPlug& plgInShape)
{
	MPlugArray plgaConnectedTo;
	plgInShape.connectedTo(plgaConnectedTo, true, true);
	int numSelectedShapes = plgaConnectedTo.length();

	if(numSelectedShapes > 0) {

		MObject node = plgaConnectedTo[0].node();

		MDagPath dagPath;
		MDagPath::getAPathTo(node, dagPath);
		int numChildren = dagPath.childCount();

		if (node.hasFn(MFn::kTransform))
		{
			MFnTransform trNode(dagPath);
			const char* name = trNode.name().asChar();
			printf("name = %s\n", name);

			for (int i=0;i<numChildren;i++)
			{
				MObject child = dagPath.child(i);
				if(child.hasFn(MFn::kMesh))
				{
					return false;
				}

				if(child.hasFn(MFn::kTransform))
				{
					MDagPath dagPath;
					MDagPath::getAPathTo(child, dagPath);
					MFnTransform trNode(dagPath);
					const char* name = trNode.name().asChar();
					printf("name = %s\n", name);

					int numGrandChildren = dagPath.childCount();
					{
						for (int i=0;i<numGrandChildren;i++)
						{
							MObject grandchild = dagPath.child(i);
							if(grandchild.hasFn(MFn::kMesh))
							{
								return true;
							}
						}
					}
				}
			}
		}
	}
	return false;
}
예제 #2
0
파일: util.cpp 프로젝트: BigRoy/Maya-devkit
bool getDagPathByChildName(MDagPath & ioDagPath, const std::string & iChildName)
{
    unsigned int numChildren = ioDagPath.childCount();
    std::string strippedName = stripPathAndNamespace(iChildName);
    MObject closeMatch;

    for (unsigned int i = 0; i < numChildren; ++i)
    {
        MObject child = ioDagPath.child(i);
        MFnDagNode dagChild(child);
        std::string name = dagChild.partialPathName().asChar();
        if (name == iChildName)
        {
            ioDagPath.push(child);
            return true;
        }

        if (closeMatch.isNull())
        {
            if (strippedName == stripPathAndNamespace(name))
            {
                closeMatch = child;
            }
        }
    }

    if (!closeMatch.isNull())
    {
        ioDagPath.push(closeMatch);
        return true;
    }

    return false;
}
예제 #3
0
void LiveScene::getChildDags( const MDagPath& dagPath, MDagPathArray& paths ) const
{
	for( unsigned i=0; i < dagPath.childCount(); ++i )
	{
		MDagPath childPath = dagPath;
		childPath.push( dagPath.child( i ) );
		
		if( dagPath.length() == 0 )
		{
			// bizarrely, this iterates through things like the translate manipulator and
			// the view cube too, so lets skip them so they don't show up:
			if( childPath.node().hasFn( MFn::kManipulator3D ) )
			{
				continue;
			}

			// looks like it also gives us the ground plane, so again, lets skip that:
			if( childPath.fullPathName() == "|groundPlane_transform" )
			{
				continue;
			}
		}
		
		paths.append( childPath );
	}
}
    // ------------------------------------------------------------
    void SceneGraph::findForcedNodes()
    {
        MStatus status;

        if ( mExportSelectedOnly )
        {
            MSelectionList selectedItems;
            MGlobal::getActiveSelectionList ( selectedItems );
            uint selectedCount = selectedItems.length();
            MDagPathArray queue;

            for ( uint i = 0; i < selectedCount; ++i )
            {
                MDagPath selectedPath;
                status = selectedItems.getDagPath ( i, selectedPath );
                if ( status == MStatus::kSuccess ) queue.append ( selectedPath );
            }

            while ( queue.length() > 0 )
            {
                MDagPath selectedPath = queue[queue.length() - 1];
                queue.remove ( queue.length() - 1 );

                // Queue up the children.
                uint childCount = selectedPath.childCount();
                for ( uint i = 0; i < childCount; ++i )
                {
                    MObject node = selectedPath.child ( i );
                    MDagPath childPath = selectedPath;
                    childPath.push ( node );
                    queue.append ( childPath );
                }

                // Look for a mesh
                if ( selectedPath.node().hasFn ( MFn::kMesh ) )
                {
                    // export forced nodes in path
                    addForcedNodes ( selectedPath );
                }
            }
        }
        else
        {
            for ( MItDag dagIt ( MItDag::kBreadthFirst ); !dagIt.isDone(); dagIt.next() )
            {
                MDagPath currentPath;
                status = dagIt.getPath ( currentPath );
                if ( status == MStatus::kSuccess )
                {
                    MFnDagNode node ( currentPath );
                    String nodeName = node.name().asChar();
                    if ( currentPath.node().hasFn ( MFn::kMesh ) )
                    {
                        // export forced nodes in path
                        addForcedNodes ( currentPath );
                    }
                }
            }
        }
    }
예제 #5
0
파일: common.cpp 프로젝트: chadmv/cvwrap
MStatus GetShapeNode(MDagPath& path, bool intermediate) {
  MStatus status;

  if (IsShapeNode(path)) {
    // Start at the transform so we can honor the intermediate flag.
    path.pop();
  }

  if (path.hasFn(MFn::kTransform)) {
    unsigned int shapeCount = path.childCount();

    for (unsigned int i = 0; i < shapeCount; ++i) {
      status = path.push(path.child(i));
      CHECK_MSTATUS_AND_RETURN_IT(status);
      if (!IsShapeNode(path)) {
        path.pop();
        continue;
      }

      MFnDagNode fnNode(path, &status);
      CHECK_MSTATUS_AND_RETURN_IT(status);
      if ((!fnNode.isIntermediateObject() && !intermediate) ||
          (fnNode.isIntermediateObject() && intermediate)) {
        return MS::kSuccess;
      }
      // Go to the next shape
      path.pop();
    }
  }

  // No valid shape node found.
  return MS::kFailure;
}
예제 #6
0
파일: group.cpp 프로젝트: rpavlik/maya2osg
osg::ref_ptr<osg::Node> Group::exporta(MDagPath &dp)
{
	osg::ref_ptr<osg::Group> osggroup;

	// Get the node of this path
	MObject node = dp.node();

	// 1. Create the adequate type of node
	if( node.hasFn(MFn::kEmitter) ) {
		// Emitters are subclasses of Transform
		// We build the transform and then add the emitter as a child
		osggroup = Transform::exporta(node);
		osggroup->addChild( PointEmitter::exporta(node).get() );
	}
	else if( node.hasFn(MFn::kTransform) ){
		osggroup = Transform::exporta(node);
	}
	else {
		// Generic group (kWorld)
		osggroup = new osg::Group();
	}

	// 2. Process and add children
	for(int i=0; i<dp.childCount(); i++){
		// Add child to the path and recursively call the exportation function
		MDagPath dpc(dp);
		dpc.push(dp.child(i));
		osg::ref_ptr<osg::Node> child = DAGNode::exporta(dpc);
		if(child.valid()){
			// ** Check ** If any children is a LightSource, deactivate culling 
			// for this group in order to apply the light even though it is not
			// directly visible
			if( dynamic_cast<osg::LightSource *>(child.get()) != NULL )
				osggroup->setCullingActive(false);
			osggroup->addChild(child.get());
		}
	}

	// 3. If there are no children, the node is ignored
	if( osggroup->getNumChildren() == 0 ){
		// Buuuuuuut, if there is an animation, it is saved to disk
		// because it can be a useful camera animation
		osg::AnimationPathCallback *cb = dynamic_cast< osg::AnimationPathCallback * >(osggroup->getUpdateCallback());
		if(cb){
			MFnDependencyNode dn(node);
			std::cout << "EXPORTING CAMERA ANIMATION: " << dn.name().asChar() << std::endl;
            CameraAnimation::save(cb->getAnimationPath(), Config::instance()->getSceneFilePath().getDirectory() + "/" + Config::instance()->getSceneFilePath().getFileBaseName() + "_" + std::string(dn.name().asChar()) + ".path" );
		}
		return NULL;
	}

    // Name the node (mesh)
	MFnDependencyNode dnodefn(node);
	osggroup->setName( dnodefn.name().asChar() );

	return (osg::Node *)osggroup.get();
}
예제 #7
0
bool ik2Bsolver::findFirstJointChild(const MDagPath & root, MDagPath & result)
{
    const unsigned count = root.childCount();
    unsigned i;
    for(i=0; i<count; i++) {
        MObject c = root.child(i);
        if(c.hasFn(MFn::kJoint)) {
            MDagPath::getAPathTo(c, result);
            return 1;
        }
    }
    return 0;
}
/*
	Draw traversal utility to prune out everything but shapes.
*/
bool MSurfaceDrawTraversal::filterNode( const MDagPath &traversalItem )
{
	bool prune = false;
	if ( traversalItem.childCount() == 0)
	{
		if ( !traversalItem.hasFn( MFn::kMesh) &&
			!traversalItem.hasFn( MFn::kNurbsSurface) &&
			!traversalItem.hasFn( MFn::kSubdiv)
			)
		{
			prune = true;
		}
	}
	return prune;
}
예제 #9
0
// todo: extend with own light extensions.
bool isLightTransform(MDagPath& dagPath)
{
    uint numChilds = dagPath.childCount();
    for (uint chId = 0; chId < numChilds; chId++)
    {
        MDagPath childPath = dagPath;
        MStatus stat = childPath.push(dagPath.child(chId));
        if (!stat)
        {
            continue;
        }
        if (childPath.node().hasFn(MFn::kLight))
            return true;
    }
    return false;
}
예제 #10
0
MStatus unShowAvailableSystems::findAvailableSystems(std::string& str,MDagPath& dagPath)
{
	MStatus stat = MS::kSuccess;

	if(dagPath.hasFn(MFn::kJoint))
	{
		MFnIkJoint jointFn(dagPath);
		std::string name = dagPath.partialPathName().asChar();
		MPlug plug = jointFn.findPlug("unRibbonEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			char s[256];
			sprintf(s,"%s RibbonSystem %s\n",name.c_str(),enabled ? "True" : "False");
			str += s;
		}
		plug = jointFn.findPlug("unParticleEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			char s[256];
			sprintf(s,"%s ParticleSystem %s\n",name.c_str(),enabled ? "True" : "False");
			str += s;
		}
	}

	for (unsigned int i = 0; i < dagPath.childCount(); i++)
	{
		MObject child = dagPath.child(i);
		MDagPath childPath;
		stat = MDagPath::getAPathTo(child,childPath);
		if (MS::kSuccess != stat)
		{
			return MS::kFailure;
		}
		stat = findAvailableSystems(str,childPath);
		if (MS::kSuccess != stat)
			return MS::kFailure;
	}
	return MS::kSuccess;
}
예제 #11
0
bool findCamera(MDagPath& dagPath)
{
    if (dagPath.node().hasFn(MFn::kCamera))
        return true;
    uint numChilds = dagPath.childCount();
    for (uint chId = 0; chId < numChilds; chId++)
    {
        MDagPath childPath = dagPath;
        MStatus stat = childPath.push(dagPath.child(chId));
        if (!stat)
        {
            continue;
        }
        MString childName = childPath.fullPathName();
        return findCamera(childPath);
    }

    return false;
}
예제 #12
0
void DMPDSExporter::traverseSubSkeleton( DMPParameters* param, const MDagPath& dagPath )
{
	MStatus stat; 
	fillSubSkeleton(param, dagPath); 
	// look for meshes and cameras within the node's children
	for (unsigned int i=0; i<dagPath.childCount(); i++)
	{
		MObject child = dagPath.child(i);
		MDagPath childPath = dagPath;
		stat = childPath.push(child);
		if (MStatus::kSuccess != stat)
		{
			std::cout << "Error retrieving path to child " << i << " of: " << dagPath.fullPathName().asChar();
			std::cout.flush();
			return;
		}
		fillSubSkeleton(param, childPath);
		if (MStatus::kSuccess != stat)
		{
			return;
		}
	}
}
예제 #13
0
MStatus AlembicExportCommand::doIt(const MArgList &args)
{
  ESS_PROFILE_SCOPE("AlembicExportCommand::doIt");

  MStatus status = MS::kFailure;

  MTime currentAnimStartTime = MAnimControl::animationStartTime(),
        currentAnimEndTime = MAnimControl::animationEndTime(),
        oldCurTime = MAnimControl::currentTime(),
        curMinTime = MAnimControl::minTime(),
        curMaxTime = MAnimControl::maxTime();
  MArgParser argData(syntax(), args, &status);

  if (argData.isFlagSet("help")) {
    // TODO: implement help for this command
    // MGlobal::displayInfo(util::getHelpText());
    return MS::kSuccess;
  }

  unsigned int jobCount = argData.numberOfFlagUses("jobArg");
  MStringArray jobStrings;
  if (jobCount == 0) {
    // TODO: display dialog
    MGlobal::displayError("[ExocortexAlembic] No jobs specified.");
    MPxCommand::setResult(
        "Error caught in AlembicExportCommand::doIt: no job specified");
    return status;
  }
  else {
    // get all of the jobstrings
    for (unsigned int i = 0; i < jobCount; i++) {
      MArgList jobArgList;
      argData.getFlagArgumentList("jobArg", i, jobArgList);
      jobStrings.append(jobArgList.asString(0));
    }
  }

  // create a vector to store the jobs
  std::vector<AlembicWriteJob *> jobPtrs;
  double minFrame = 1000000.0;
  double maxFrame = -1000000.0;
  double maxSteps = 1;
  double maxSubsteps = 1;

  // init the curve accumulators
  AlembicCurveAccumulator::Initialize();

  try {
    // for each job, check the arguments
    bool failure = false;
    for (unsigned int i = 0; i < jobStrings.length(); ++i) {
      double frameIn = 1.0;
      double frameOut = 1.0;
      double frameSteps = 1.0;
      double frameSubSteps = 1.0;
      MString filename;
      bool purepointcache = false;
      bool normals = true;
      bool uvs = true;
      bool facesets = true;
      bool bindpose = true;
      bool dynamictopology = false;
      bool globalspace = false;
      bool withouthierarchy = false;
      bool transformcache = false;
      bool useInitShadGrp = false;
      bool useOgawa = false;  // Later, will need to be changed!

      MStringArray objectStrings;
      std::vector<std::string> prefixFilters;
      std::set<std::string> attributes;
      std::vector<std::string> userPrefixFilters;
      std::set<std::string> userAttributes;
      MObjectArray objects;
      std::string search_str, replace_str;

      // process all tokens of the job
      MStringArray tokens;
      jobStrings[i].split(';', tokens);
      for (unsigned int j = 0; j < tokens.length(); j++) {
        MStringArray valuePair;
        tokens[j].split('=', valuePair);
        if (valuePair.length() != 2) {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }

        const MString &lowerValue = valuePair[0].toLowerCase();
        if (lowerValue == "in") {
          frameIn = valuePair[1].asDouble();
        }
        else if (lowerValue == "out") {
          frameOut = valuePair[1].asDouble();
        }
        else if (lowerValue == "step") {
          frameSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "substep") {
          frameSubSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "normals") {
          normals = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "uvs") {
          uvs = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "facesets") {
          facesets = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "bindpose") {
          bindpose = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "purepointcache") {
          purepointcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "dynamictopology") {
          dynamictopology = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "globalspace") {
          globalspace = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "withouthierarchy") {
          withouthierarchy = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "transformcache") {
          transformcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "filename") {
          filename = valuePair[1];
        }
        else if (lowerValue == "objects") {
          // try to find each object
          valuePair[1].split(',', objectStrings);
        }
        else if (lowerValue == "useinitshadgrp") {
          useInitShadGrp = valuePair[1].asInt() != 0;
        }

        // search/replace
        else if (lowerValue == "search") {
          search_str = valuePair[1].asChar();
        }
        else if (lowerValue == "replace") {
          replace_str = valuePair[1].asChar();
        }
        else if (lowerValue == "ogawa") {
          useOgawa = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "attrprefixes") {
          splitListArg(valuePair[1], prefixFilters);
        }
        else if (lowerValue == "attrs") {
          splitListArg(valuePair[1], attributes);
        }
        else if (lowerValue == "userattrprefixes") {
          splitListArg(valuePair[1], userPrefixFilters);
        }
        else if (lowerValue == "userattrs") {
          splitListArg(valuePair[1], userAttributes);
        }
        else {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }
      }

      // now check the object strings
      for (unsigned int k = 0; k < objectStrings.length(); k++) {
        MSelectionList sl;
        MString objectString = objectStrings[k];
        sl.add(objectString);
        MDagPath dag;
        for (unsigned int l = 0; l < sl.length(); l++) {
          sl.getDagPath(l, dag);
          MObject objRef = dag.node();
          if (objRef.isNull()) {
            MGlobal::displayWarning("[ExocortexAlembic] Skipping object '" +
                                    objectStrings[k] + "', not found.");
            break;
          }

          // get all parents
          MObjectArray parents;

          // check if this is a camera
          bool isCamera = false;
          for (unsigned int m = 0; m < dag.childCount(); ++m) {
            MFnDagNode child(dag.child(m));
            MFn::Type ctype = child.object().apiType();
            if (ctype == MFn::kCamera) {
              isCamera = true;
              break;
            }
          }

          if (dag.node().apiType() == MFn::kTransform && !isCamera &&
              !globalspace && !withouthierarchy) {
            MDagPath ppath = dag;
            while (!ppath.node().isNull() && ppath.length() > 0 &&
                   ppath.isValid()) {
              parents.append(ppath.node());
              if (ppath.pop() != MStatus::kSuccess) {
                break;
              }
            }
          }
          else {
            parents.append(dag.node());
          }

          // push all parents in
          while (parents.length() > 0) {
            bool found = false;
            for (unsigned int m = 0; m < objects.length(); m++) {
              if (objects[m] == parents[parents.length() - 1]) {
                found = true;
                break;
              }
            }
            if (!found) {
              objects.append(parents[parents.length() - 1]);
            }
            parents.remove(parents.length() - 1);
          }

          // check all of the shapes below
          if (!transformcache) {
            sl.getDagPath(l, dag);
            for (unsigned int m = 0; m < dag.childCount(); m++) {
              MFnDagNode child(dag.child(m));
              if (child.isIntermediateObject()) {
                continue;
              }
              objects.append(child.object());
            }
          }
        }
      }

      // check if we have incompatible subframes
      if (maxSubsteps > 1.0 && frameSubSteps > 1.0) {
        const double part = (frameSubSteps > maxSubsteps)
                                ? (frameSubSteps / maxSubsteps)
                                : (maxSubsteps / frameSubSteps);
        if (abs(part - floor(part)) > 0.001) {
          MString frameSubStepsStr, maxSubstepsStr;
          frameSubStepsStr.set(frameSubSteps);
          maxSubstepsStr.set(maxSubsteps);
          MGlobal::displayError(
              "[ExocortexAlembic] You cannot combine substeps " +
              frameSubStepsStr + " and " + maxSubstepsStr +
              " in one export. Aborting.");
          return MStatus::kInvalidParameter;
        }
      }

      // remember the min and max values for the frames
      if (frameIn < minFrame) {
        minFrame = frameIn;
      }
      if (frameOut > maxFrame) {
        maxFrame = frameOut;
      }
      if (frameSteps > maxSteps) {
        maxSteps = frameSteps;
      }
      if (frameSteps > 1.0) {
        frameSubSteps = 1.0;
      }
      if (frameSubSteps > maxSubsteps) {
        maxSubsteps = frameSubSteps;
      }

      // check if we have a filename
      if (filename.length() == 0) {
        MGlobal::displayError("[ExocortexAlembic] No filename specified.");
        for (size_t k = 0; k < jobPtrs.size(); k++) {
          delete (jobPtrs[k]);
        }
        MPxCommand::setResult(
            "Error caught in AlembicExportCommand::doIt: no filename "
            "specified");
        return MStatus::kFailure;
      }

      // construct the frames
      MDoubleArray frames;
      {
        const double frameIncr = frameSteps / frameSubSteps;
        for (double frame = frameIn; frame <= frameOut; frame += frameIncr) {
          frames.append(frame);
        }
      }

      AlembicWriteJob *job =
          new AlembicWriteJob(filename, objects, frames, useOgawa,
              prefixFilters, attributes, userPrefixFilters, userAttributes);
      job->SetOption("exportNormals", normals ? "1" : "0");
      job->SetOption("exportUVs", uvs ? "1" : "0");
      job->SetOption("exportFaceSets", facesets ? "1" : "0");
      job->SetOption("exportInitShadGrp", useInitShadGrp ? "1" : "0");
      job->SetOption("exportBindPose", bindpose ? "1" : "0");
      job->SetOption("exportPurePointCache", purepointcache ? "1" : "0");
      job->SetOption("exportDynamicTopology", dynamictopology ? "1" : "0");
      job->SetOption("indexedNormals", "1");
      job->SetOption("indexedUVs", "1");
      job->SetOption("exportInGlobalSpace", globalspace ? "1" : "0");
      job->SetOption("flattenHierarchy", withouthierarchy ? "1" : "0");
      job->SetOption("transformCache", transformcache ? "1" : "0");

      // check if the search/replace strings are valid!
      if (search_str.length() ? !replace_str.length()
                              : replace_str.length())  // either search or
                                                       // replace string is
                                                       // missing or empty!
      {
        ESS_LOG_WARNING(
            "Missing search or replace parameter. No strings will be "
            "replaced.");
        job->replacer = SearchReplace::createReplacer();
      }
      else {
        job->replacer = SearchReplace::createReplacer(search_str, replace_str);
      }

      // check if the job is satifsied
      if (job->PreProcess() != MStatus::kSuccess) {
        MGlobal::displayError("[ExocortexAlembic] Job skipped. Not satisfied.");
        delete (job);
        failure = true;
        break;
      }

      // push the job to our registry
      MGlobal::displayInfo("[ExocortexAlembic] Using WriteJob:" +
                           jobStrings[i]);
      jobPtrs.push_back(job);
    }

    if (failure) {
      for (size_t k = 0; k < jobPtrs.size(); k++) {
        delete (jobPtrs[k]);
      }
      return MS::kFailure;
    }

    // compute the job count
    unsigned int jobFrameCount = 0;
    for (size_t i = 0; i < jobPtrs.size(); i++)
      jobFrameCount += (unsigned int)jobPtrs[i]->GetNbObjects() *
                       (unsigned int)jobPtrs[i]->GetFrames().size();

    // now, let's run through all frames, and process the jobs
    const double frameRate = MTime(1.0, MTime::kSeconds).as(MTime::uiUnit());
    const double incrSteps = maxSteps / maxSubsteps;
    double nextFrame = minFrame + incrSteps;

    for (double frame = minFrame; frame <= maxFrame;
         frame += incrSteps, nextFrame += incrSteps) {
      MAnimControl::setCurrentTime(MTime(frame / frameRate, MTime::kSeconds));
      MAnimControl::setAnimationEndTime(
          MTime(nextFrame / frameRate, MTime::kSeconds));
      MAnimControl::playForward();  // this way, it forces Maya to play exactly
      // one frame! and particles are updated!

      AlembicCurveAccumulator::StartRecordingFrame();
      for (size_t i = 0; i < jobPtrs.size(); i++) {
        MStatus status = jobPtrs[i]->Process(frame);
        if (status != MStatus::kSuccess) {
          MGlobal::displayError("[ExocortexAlembic] Job aborted :" +
                                jobPtrs[i]->GetFileName());
          for (size_t k = 0; k < jobPtrs.size(); k++) {
            delete (jobPtrs[k]);
          }
          restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                         curMinTime, curMaxTime);
          return status;
        }
      }
      AlembicCurveAccumulator::StopRecordingFrame();
    }
  }
  catch (...) {
    MGlobal::displayError(
        "[ExocortexAlembic] Jobs aborted, force closing all archives!");
    for (std::vector<AlembicWriteJob *>::iterator beg = jobPtrs.begin();
         beg != jobPtrs.end(); ++beg) {
      (*beg)->forceCloseArchive();
    }
    restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                   curMinTime, curMaxTime);
    MPxCommand::setResult("Error caught in AlembicExportCommand::doIt");
    status = MS::kFailure;
  }
  MAnimControl::stop();
  AlembicCurveAccumulator::Destroy();

  // restore the animation start/end time and the current time!
  restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                 curMinTime, curMaxTime);

  // delete all jobs
  for (size_t k = 0; k < jobPtrs.size(); k++) {
    delete (jobPtrs[k]);
  }

  // remove all known archives
  deleteAllArchives();
  return status;
}
void OutputMaterials(MSelectionList selected){
	
	//::output << "BRUS";//header Brush
	//StartChunck();
MString temp;
MString affich;
	

	
int MatExists=0;

	for(int i=0;i<selected.length();i++){
Affich("element selectioné");

	MDagPath path;
	MObject obj;
	
	int index;
	selected.getDagPath(i,path);
	index = path.childCount();
	affich ="childs ";affich+=index;
	Affich(affich);

	selected.getDependNode(index,obj);


	
	
	//obj=path.child(0);//.child(0);

	

	//MFnMesh fn(path);
	//obj=fn.parent(0);
	//path.getPath(path);
	MFnMesh fna(path.child(1));
	
	
	unsigned int instancenumbers;
	MObjectArray shaders;
	MIntArray indices;
	
	fna.getConnectedShaders(instancenumbers,shaders,indices);

	affich = "shaders lenght "; 
	affich += shaders.length();
Affich(affich);

switch(shaders.length()) {

		// if no shader applied to the mesh instance
		case 0:
			{
				//***************Affich("pas de matériaux");
			}
			break;

		// if all faces use the same material
	
		// if more than one material is used, write out the face indices the materials
		// are applied to.
		default:
			{
				//************************Affich("trouvé plusieurs matériaux");

				
				//write_int(shaders.length());

				// now write each material and the face indices that use them
				
				for(int j=0;j < shaders.length();++j)
				{						
					for(int matest=0;matest<Matid.length();matest++){
						//**************************Affich(Matid[matest].asChar());
						//*****************************Affich(GetShaderName( shaders[j] ).asChar());
						if(Matid[matest]== GetShaderName( shaders[j] )){
						MatExists = 1;
						
						}//fin if matid
						
						}// fin for matest
					if(MatExists != 1){
					//*****************************Affich("matériau absent de la liste, enregistrement");
					Matid.append(GetShaderName( shaders[j] ).asChar());
					::output << "BRUS";//header Brush
						StartChunck();
							//write_int(Matid.length());//id Brush
						//écrire le nb de textures
						int a=nb_Tex_by_Brush[Matid.length()-1];
						if (a==0) a=1;
						info="nb de textures pour ce brush ";
						info+=nb_Tex_by_Brush[Matid.length()-1];
						Affich(info);

							write_int(a);//nb textures in brush
	
						::output << GetShaderName( shaders[j] ).asChar();
						::output << char(0x00);
						
						
					OutputColors(shaders[j],"color");


						//red
						//write_float(0);
						//green
						//write_float(1);
						//blue
						//write_float(0);
						//alpha
						//write_float(1);
						//shininess
						write_float(0);
						// Brush Blend
						//brush - brush handle
						//blend -
						//1: alpha
						//2: multiply (default)
						//3: add
						write_int(0);
						//blend FX
						//brush - brush handle
						//fx -
						//1: full-bright
						//2: use vertex colors instead of brush color +shininess
						//3:just vertex color no shininess
						//4: flatshaded
						//8: disable fog  
						int flag=0;
						if (Flags.use_vertex_colors==1 && Flags.vertex_colors==1) flag=3; // par défaut 0
						write_int(flag);// écriture uniquement des vertex
						
						//écrire les id textures
						
						
						if (nb_Tex_by_Brush[Matid.length()-1]==0){
							a=-1;
						}else{
						a=Texids_by_brush[Matid.length()-1];
						}
						info="texid ";
						info+=a;
						Affich(info);
						write_int(a);//int texture_id   -1  no texture for this brush
						
						EndChunck();
					//Affich(temp);
					}else {
					//*************************************	Affich("matériau existe dans la liste");
					}// fin if matexists
					
					MatExists = 0;
						

				}//fin for j shaders
			}// fin case default
			break;
		}//fin switches

	}//fin for selected
		


}// fin output materials
예제 #15
0
파일: skeleton.cpp 프로젝트: cpzhang/zen
// Load a joint
void skeleton::loadJoint(MDagPath& jointDag,joint* parent)
{
	int i;
	joint newJoint;
	joint* parentJoint = parent;
	if (jointDag.hasFn(MFn::kJoint))
	{
		MFnIkJoint jointFn(jointDag);

		// Get parent index
		int idx=-1;
		if (parent)
		{
			idx = parent->id;
		}
		// Get joint matrix
		MMatrix worldMatrix = jointDag.inclusiveMatrix();
		/*float translation1[3];
		float rotation1[4];
		float scale1[3];
		extractTranMatrix(worldMatrix,translation1,rotation1,scale1);
		Quaternion q(rotation1[0],rotation1[1],rotation1[2],rotation1[3]);
		float angle;
		Vector3 axis;
		q.ToAngleAxis(angle,axis);
		Vector3 x,y,z;
		q.ToAxes(x,y,z);*/
		//printMatrix(worldMatrix);
	
		// Calculate scaling factor inherited by parent
		// Calculate Local Matrix
		MMatrix localMatrix = worldMatrix;
		if (parent)
			localMatrix = worldMatrix * parent->worldMatrix.inverse();
		float translation2[3];
		float rotation2[4];
		float scale2[3];
		extractTranMatrix(worldMatrix,translation2,rotation2,scale2);
		//printMatrix(localMatrix);
	
		// Set joint info
		newJoint.name = jointFn.partialPathName();
		newJoint.id = m_joints.size();
		newJoint.parentIndex = idx;
		newJoint.jointDag = jointDag;
		newJoint.worldMatrix = worldMatrix;
		newJoint.localMatrix = localMatrix;

		for (int iRow = 0; iRow < 4; iRow++)
			for (int iCol = 0; iCol < 3; iCol++)
				newJoint.tran.m_mat[iRow][iCol] = (FLOAT)worldMatrix[iRow][iCol];

		//printMatrix(worldMatrix);

		/*MQuaternion q;
		q = worldMatrix;
		newJoint.tran.q[0] = (float)q.x;
		newJoint.tran.q[1] = (float)q.y;
		newJoint.tran.q[2] = (float)q.z;
		newJoint.tran.q[3] = (float)q.w;
		newJoint.tran.t[0] = (float)worldMatrix[3][0];
		newJoint.tran.t[1] = (float)worldMatrix[3][1];
		newJoint.tran.t[2] = (float)worldMatrix[3][2];*/

		MPlug plug = jointFn.findPlug("unRibbonEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			if(enabled)
			{
				plug = jointFn.findPlug("unRibbonVisible");
				bool visible;
				plug.getValue(visible);
				plug = jointFn.findPlug("unRibbonAbove");
				float above;
				plug.getValue(above);
				plug = jointFn.findPlug("unRibbonBelow");
				float below;
				plug.getValue(below);
				plug = jointFn.findPlug("unRibbonEdgesPerSecond");
				short edgePerSecond;
				plug.getValue(edgePerSecond);
				plug = jointFn.findPlug("unRibbonEdgeLife");
				float edgeLife;
				plug.getValue(edgeLife);
				plug = jointFn.findPlug("unRibbonGravity");
				float gravity;
				plug.getValue(gravity);
				plug = jointFn.findPlug("unRibbonTextureRows");
				short rows;
				plug.getValue(rows);
				plug = jointFn.findPlug("unRibbonTextureCols");
				short cols;
				plug.getValue(cols);
				plug = jointFn.findPlug("unRibbonTextureSlot");
				short slot;
				plug.getValue(slot);
				plug = jointFn.findPlug("unRibbonVertexColor");
				MObject object;
				plug.getValue(object);
				MFnNumericData data(object);
				float r,g,b;
				data.getData(r,g,b);
				plug = jointFn.findPlug("unRibbonVertexAlpha");
				float alpha;
				plug.getValue(alpha);
				plug = jointFn.findPlug("unRibbonBlendMode");
				short blendMode;
				plug.getValue(blendMode);
				plug = jointFn.findPlug("unRibbonTextureFilename");

				MItDependencyGraph dgIt(plug, MFn::kFileTexture,
					MItDependencyGraph::kUpstream, 
					MItDependencyGraph::kBreadthFirst,
					MItDependencyGraph::kNodeLevel);

				dgIt.disablePruningOnFilter();

				MString textureName;
				if (!dgIt.isDone())
				{
					MObject textureNode = dgIt.thisNode();
					MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
					filenamePlug.getValue(textureName);
				}
				else
				{
					char str[256];
					sprintf(str,"%s ribbon system must has file-texture",newJoint.name.asChar());
					MessageBox(0,str,0,0);
				}

				newJoint.hasRibbonSystem = true;
				newJoint.ribbon.visible = visible;
				newJoint.ribbon.above = above;
				newJoint.ribbon.below = below;
				newJoint.ribbon.gravity = gravity;
				newJoint.ribbon.edgePerSecond = edgePerSecond;
				newJoint.ribbon.edgeLife = edgeLife;
				newJoint.ribbon.rows = rows;
				newJoint.ribbon.cols = cols;
				newJoint.ribbon.slot = slot;
				newJoint.ribbon.color[0] = r;
				newJoint.ribbon.color[1] = g;
				newJoint.ribbon.color[2] = b;
				newJoint.ribbon.alpha = alpha;
				newJoint.ribbon.blendMode = blendMode;
				newJoint.ribbon.textureFilename = textureName.asChar();
			}
		}
		plug = jointFn.findPlug("unParticleEnabled");
		if(!plug.isNull())
		{
			bool enabled;
			plug.getValue(enabled);
			if(enabled)
			{
				newJoint.hasParticleSystem = true;

				plug = jointFn.findPlug("unParticleVisible");
				bool visible;
				plug.getValue(visible);
				plug = jointFn.findPlug("unParticleSpeed");
				float speed;
				plug.getValue(speed);
				plug = jointFn.findPlug("unParticleVariationPercent");
				float variation;
				plug.getValue(variation);
				plug = jointFn.findPlug("unParticleConeAngle");
				float coneAngle;
				plug.getValue(coneAngle);
				plug = jointFn.findPlug("unParticleGravity");
				float gravity;
				plug.getValue(gravity);
				plug = jointFn.findPlug("unParticleExplosiveForce");
				float explosiveForce = 0.0f;
				if(!plug.isNull())
				{
					plug.getValue(explosiveForce);
				}
				plug = jointFn.findPlug("unParticleLife");
				float life;
				plug.getValue(life);
				plug = jointFn.findPlug("unParticleLifeVariation");
				float lifeVar;
				if(plug.isNull())
				{
					lifeVar = 0.0f;
				}
				else
				{
					plug.getValue(lifeVar);
				}
				plug = jointFn.findPlug("unParticleEmissionRate");
				float emissionRate;
				plug.getValue(emissionRate);
				plug = jointFn.findPlug("unParticleLimitNum");
				short limitNum;
				plug.getValue(limitNum);
				plug = jointFn.findPlug("unParticleInitialNum");
				short initialNum = 0;
				if(!plug.isNull())plug.getValue(initialNum);
				plug = jointFn.findPlug("unParticleAttachToEmitter");
				bool attachToEmitter;
				plug.getValue(attachToEmitter);
				plug = jointFn.findPlug("unParticleMoveWithEmitter");
				bool moveWithEmitter = false;
				if(!plug.isNull())plug.getValue(moveWithEmitter);
				//23
				plug = jointFn.findPlug("unParticleForTheSword");
				bool forTheSword = false;
				if(!plug.isNull())plug.getValue(forTheSword);
				//24
				plug = jointFn.findPlug("unParticleForTheSwordInitialAngle");
				float forTheSwordInitialAngle = 0;
				if(!plug.isNull())plug.getValue(forTheSwordInitialAngle);
				//25
				plug = jointFn.findPlug("unParticleWander");
				bool wander = false;
				if(!plug.isNull())plug.getValue(wander);
				//25
				plug = jointFn.findPlug("unParticleWanderRadius");
				float wanderRadius = 0.0f;
				if(!plug.isNull())plug.getValue(wanderRadius);
				//25
				plug = jointFn.findPlug("unParticleWanderSpeed");
				float wanderSpeed = 0.0f;
				if(!plug.isNull())plug.getValue(wanderSpeed);
				plug = jointFn.findPlug("unParticleAspectRatio");
				float aspectRatio;
				if(plug.isNull())
				{
					aspectRatio = 1.0f;
				}
				else
				{
					plug.getValue(aspectRatio);
				}
				plug = jointFn.findPlug("unParticleInitialAngleBegin");
				float angleBegin;
				if(plug.isNull())
				{
					angleBegin = 0.0f;
				}
				else
				{
					plug.getValue(angleBegin);
				}
				plug = jointFn.findPlug("unParticleInitialAngleEnd");
				float angleEnd;
				if(plug.isNull())
				{
					angleEnd = 0.0f;
				}
				else
				{
					plug.getValue(angleEnd);
				}
				plug = jointFn.findPlug("unParticleRotationSpeed");
				float rotationSpeed;
				if(plug.isNull())
				{
					rotationSpeed = 0;
				}
				else
				{
					plug.getValue(rotationSpeed);
				}
				plug = jointFn.findPlug("unParticleRotationSpeedVar");
				float rotationSpeedVar;
				if(plug.isNull())
				{
					rotationSpeedVar = 0;
				}
				else
				{
					plug.getValue(rotationSpeedVar);
				}
				plug = jointFn.findPlug("unParticleEmitterWidth");
				float width;
				plug.getValue(width);
				plug = jointFn.findPlug("unParticleEmitterLength");
				float length;
				plug.getValue(length);
				plug = jointFn.findPlug("unParticleEmitterHeight");
				float height = 0.0f;
				if(!plug.isNull())
				{
					plug.getValue(height);
				}
				plug = jointFn.findPlug("unParticleBlendMode");
				short blendMode;
				plug.getValue(blendMode);
				plug = jointFn.findPlug("unParticleTextureFilename");

				MItDependencyGraph dgIt(plug, MFn::kFileTexture,
					MItDependencyGraph::kUpstream, 
					MItDependencyGraph::kBreadthFirst,
					MItDependencyGraph::kNodeLevel);

				dgIt.disablePruningOnFilter();

				MString textureName;
				if (!dgIt.isDone())
				{
					MObject textureNode = dgIt.thisNode();
					MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
					filenamePlug.getValue(textureName);
				}
				else
				{
					char str[256];
					sprintf(str,"%s particle system must has file-texture",newJoint.name.asChar());
					MessageBox(0,str,0,0);
				}
				plug = jointFn.findPlug("unParticleTextureRows");
				short rows;
				plug.getValue(rows);
				plug = jointFn.findPlug("unParticleTextureCols");
				short cols;
				plug.getValue(cols);
				plug = jointFn.findPlug("unParticleTextureChangeStyle");
				short changeStyle;
				if(plug.isNull())
				{
					//0 - 顺序
					//1 - 随机
					changeStyle = 0;
				}
				else
				{
					plug.getValue(changeStyle);
				}
				plug = jointFn.findPlug("unParticleTextureChangeInterval");
				short changeInterval;
				if(plug.isNull())
				{
					//默认30ms换一个
					changeInterval = 30;
				}
				else
				{
					plug.getValue(changeInterval);
				}
				plug = jointFn.findPlug("unParticleTailLength");
				float tailLength;
				plug.getValue(tailLength);
				plug = jointFn.findPlug("unParticleTimeMiddle");
				float timeMiddle;
				plug.getValue(timeMiddle);
				plug = jointFn.findPlug("unParticleColorStart");
				MObject object;
				plug.getValue(object);
				MFnNumericData dataS(object);
				float colorStart[3];
				dataS.getData(colorStart[0],colorStart[1],colorStart[2]);
				plug = jointFn.findPlug("unParticleColorMiddle");
				plug.getValue(object);
				MFnNumericData dataM(object);
				float colorMiddle[3];
				dataM.getData(colorMiddle[0],colorMiddle[1],colorMiddle[2]);
				plug = jointFn.findPlug("unParticleColorEnd");
				plug.getValue(object);
				MFnNumericData dataE(object);
				float colorEnd[3];
				dataE.getData(colorEnd[0],colorEnd[1],colorEnd[2]);
				plug = jointFn.findPlug("unParticleAlpha");
				plug.getValue(object);
				MFnNumericData dataAlpha(object);
				float alpha[3];
				dataAlpha.getData(alpha[0],alpha[1],alpha[2]);
				//Scale
				plug = jointFn.findPlug("unParticleScale");
				plug.getValue(object);
				MFnNumericData dataScale(object);
				float scale[3];
				dataScale.getData(scale[0],scale[1],scale[2]);
				//ScaleVar
				plug = jointFn.findPlug("unParticleScaleVar");
				float scaleVar[3] = {0.0f,0.0f,0.0f};
				if(!plug.isNull())
				{
					plug.getValue(object);
					MFnNumericData dataScaleVar(object);
					dataScaleVar.getData(scaleVar[0],scaleVar[1],scaleVar[2]);
				}
				//FixedSize
				plug = jointFn.findPlug("unParticleFixedSize");
				bool fixedSize = false;
				if(!plug.isNull())
				{
					plug.getValue(fixedSize);
				}
				//HeadLifeSpan
				plug = jointFn.findPlug("unParticleHeadLifeSpan");
				plug.getValue(object);
				MFnNumericData dataHeadLifeSpan(object);
				short headLifeSpan[3];
				dataHeadLifeSpan.getData(headLifeSpan[0],headLifeSpan[1],headLifeSpan[2]);
				plug = jointFn.findPlug("unParticleHeadDecay");
				plug.getValue(object);
				MFnNumericData dataHeadDecay(object);
				short headDecay[3];
				dataHeadDecay.getData(headDecay[0],headDecay[1],headDecay[2]);
				plug = jointFn.findPlug("unParticleTailLifeSpan");
				plug.getValue(object);
				MFnNumericData dataTailLifeSpan(object);
				short tailLifeSpan[3];
				dataTailLifeSpan.getData(tailLifeSpan[0],tailLifeSpan[1],tailLifeSpan[2]);
				plug = jointFn.findPlug("unParticleTailDecay");
				plug.getValue(object);
				MFnNumericData dataTailDecay(object);
				short tailDecay[3];
				dataTailDecay.getData(tailDecay[0],tailDecay[1],tailDecay[2]);
				plug = jointFn.findPlug("unParticleHead");
				bool head;
				plug.getValue(head);
				plug = jointFn.findPlug("unParticleTail");
				bool tail;
				plug.getValue(tail);
				plug = jointFn.findPlug("unParticleUnShaded");
				bool unshaded;
				plug.getValue(unshaded);
				plug = jointFn.findPlug("unParticleUnFogged");
				bool unfogged;
				plug.getValue(unfogged);
				plug = jointFn.findPlug("unParticleBlockByY0");
				bool blockByY0 = false;
				if(!plug.isNull())
					plug.getValue(blockByY0);

				newJoint.particle.visible = visible;
				newJoint.particle.speed = speed;
				newJoint.particle.variation = variation / 100.0f;
				newJoint.particle.coneAngle = coneAngle;
				newJoint.particle.gravity = gravity;
				newJoint.particle.explosiveForce = explosiveForce;
				newJoint.particle.life = life;
				newJoint.particle.lifeVar = lifeVar;
				newJoint.particle.emissionRate = emissionRate;
				newJoint.particle.initialNum = initialNum;
				newJoint.particle.limitNum = limitNum;
				newJoint.particle.attachToEmitter = attachToEmitter;
				newJoint.particle.moveWithEmitter = moveWithEmitter;
				newJoint.particle.forTheSword = forTheSword;
				newJoint.particle.forTheSwordInitialAngle = forTheSwordInitialAngle;
				newJoint.particle.wander = wander;
				newJoint.particle.wanderRadius = wanderRadius;
				newJoint.particle.wanderSpeed = wanderSpeed;
				newJoint.particle.aspectRatio = aspectRatio;
				newJoint.particle.initialAngleBegin = angleBegin;
				newJoint.particle.initialAngleEnd = angleEnd;
				newJoint.particle.rotationSpeed = rotationSpeed;
				newJoint.particle.rotationSpeedVar = rotationSpeedVar;
				newJoint.particle.width = width;
				newJoint.particle.length = length;
				newJoint.particle.height = height;
				newJoint.particle.blendMode = blendMode;
				newJoint.particle.textureFilename = textureName.asChar();
				newJoint.particle.textureRows = rows;
				newJoint.particle.textureCols = cols;
				newJoint.particle.changeStyle = changeStyle;
				newJoint.particle.changeInterval = changeInterval;
				newJoint.particle.tailLength = tailLength;
				newJoint.particle.timeMiddle = timeMiddle;
				newJoint.particle.colorStart[0] = colorStart[0];
				newJoint.particle.colorStart[1] = colorStart[1];
				newJoint.particle.colorStart[2] = colorStart[2];
				newJoint.particle.colorMiddle[0] = colorMiddle[0];
				newJoint.particle.colorMiddle[1] = colorMiddle[1];
				newJoint.particle.colorMiddle[2] = colorMiddle[2];
				newJoint.particle.colorEnd[0] = colorEnd[0];
				newJoint.particle.colorEnd[1] = colorEnd[1];
				newJoint.particle.colorEnd[2] = colorEnd[2];
				newJoint.particle.alpha[0] = alpha[0];
				newJoint.particle.alpha[1] = alpha[1];
				newJoint.particle.alpha[2] = alpha[2];
				newJoint.particle.scale[0] = scale[0];
				newJoint.particle.scale[1] = scale[1];
				newJoint.particle.scale[2] = scale[2];
				newJoint.particle.scaleVar[0] = scaleVar[0];
				newJoint.particle.scaleVar[1] = scaleVar[1];
				newJoint.particle.scaleVar[2] = scaleVar[2];
				newJoint.particle.fixedSize = fixedSize;
				newJoint.particle.headLifeSpan[0] = headLifeSpan[0];
				newJoint.particle.headLifeSpan[1] = headLifeSpan[1];
				newJoint.particle.headLifeSpan[2] = headLifeSpan[2];
				newJoint.particle.headDecay[0] = headDecay[0];
				newJoint.particle.headDecay[1] = headDecay[1];
				newJoint.particle.headDecay[2] = headDecay[2];
				newJoint.particle.tailLifeSpan[0] = tailLifeSpan[0];
				newJoint.particle.tailLifeSpan[1] = tailLifeSpan[1];
				newJoint.particle.tailLifeSpan[2] = tailLifeSpan[2];
				newJoint.particle.tailDecay[0] = tailDecay[0];
				newJoint.particle.tailDecay[1] = tailDecay[1];
				newJoint.particle.tailDecay[2] = tailDecay[2];
				newJoint.particle.head = head;
				newJoint.particle.tail = tail;
				newJoint.particle.unshaded = unshaded;
				newJoint.particle.unfogged = unfogged;
				newJoint.particle.blockByY0 = blockByY0;
			}
		}

		m_joints.push_back(newJoint);
		// Get pointer to newly created joint
		parentJoint = &newJoint;
	}
	// Load children joints
	for (i=0; i<jointDag.childCount();i++)
	{
		MObject child;
		child = jointDag.child(i);
		MDagPath childDag = jointDag;
		childDag.push(child);
		loadJoint(childDag,parentJoint);
	}

}
예제 #16
0
	// Method for iterating over nodes in a dependency graph from top to bottom
	MStatus OgreExporter::translateNode(MDagPath& dagPath)
	{
		if (m_params.exportAnimCurves)
		{
			MObject dagPathNode = dagPath.node();
			MItDependencyGraph animIter( dagPathNode,
				MFn::kAnimCurve,
				MItDependencyGraph::kUpstream,
				MItDependencyGraph::kDepthFirst,
				MItDependencyGraph::kNodeLevel,
				&stat );

			if (stat)
			{
				for (; !animIter.isDone(); animIter.next())
				{
					MObject anim = animIter.thisNode(&stat);
					MFnAnimCurve animFn(anim,&stat);
					std::cout << "Found animation curve: " << animFn.name().asChar() << "\n";
					std::cout << "Translating animation curve: " << animFn.name().asChar() << "...\n";
					std::cout.flush();
					stat = writeAnim(animFn);
					if (MS::kSuccess == stat)
					{
						std::cout << "OK\n";
						std::cout.flush();
					}
					else
					{
						std::cout << "Error, Aborting operation\n";
						std::cout.flush();
						return MS::kFailure;
					}
				}
			}
		}
		if (dagPath.hasFn(MFn::kMesh)&&(m_params.exportMesh||m_params.exportMaterial||m_params.exportSkeleton)
			&& (dagPath.childCount() == 0))
		{	// we have found a mesh shape node, it can't have any children, and it contains
			// all the mesh geometry data
			MDagPath meshDag = dagPath;
			MFnMesh meshFn(meshDag);
			if (!meshFn.isIntermediateObject())
			{
				std::cout << "Found mesh node: " << meshDag.fullPathName().asChar() << "\n";
				std::cout << "Loading mesh node " << meshDag.fullPathName().asChar() << "...\n";
				std::cout.flush();
				stat = m_pMesh->load(meshDag,m_params);
				if (MS::kSuccess == stat)
				{
					std::cout << "OK\n";
					std::cout.flush();
				}
				else
				{
					std::cout << "Error, mesh skipped\n";
					std::cout.flush();
				}
			}
		}
		else if (dagPath.hasFn(MFn::kCamera)&&(m_params.exportCameras) && (!dagPath.hasFn(MFn::kShape)))
		{	// we have found a camera shape node, it can't have any children, and it contains
			// all information about the camera
			MFnCamera cameraFn(dagPath);
			if (!cameraFn.isIntermediateObject())
			{
				std::cout <<  "Found camera node: "<< dagPath.fullPathName().asChar() << "\n";
				std::cout <<  "Translating camera node: "<< dagPath.fullPathName().asChar() << "...\n";
				std::cout.flush();
				stat = writeCamera(cameraFn);
				if (MS::kSuccess == stat)
				{
					std::cout << "OK\n";
					std::cout.flush();
				}
				else
				{
					std::cout << "Error, Aborting operation\n";
					std::cout.flush();
					return MS::kFailure;
				}
			}
		}
		else if ( ( dagPath.apiType() == MFn::kParticle ) && m_params.exportParticles )
		{	// we have found a set of particles
			MFnDagNode fnNode(dagPath);
			if (!fnNode.isIntermediateObject())
			{
				std::cout <<  "Found particles node: "<< dagPath.fullPathName().asChar() << "\n";
				std::cout <<  "Translating particles node: "<< dagPath.fullPathName().asChar() << "...\n";
				std::cout.flush();
				Particles particles;
				particles.load(dagPath,m_params);
				stat = particles.writeToXML(m_params);
				if (MS::kSuccess == stat)
				{
					std::cout << "OK\n";
					std::cout.flush();
				}
				else
				{
					std::cout << "Error, Aborting operation\n";
					std::cout.flush();
					return MS::kFailure;
				}
			}
		}
		// look for meshes and cameras within the node's children
		for (uint i=0; i<dagPath.childCount(); i++)
		{
			MObject child = dagPath.child(i);
			 MDagPath childPath = dagPath;
			stat = childPath.push(child);
			if (MS::kSuccess != stat)
			{
				std::cout << "Error retrieving path to child " << i << " of: " << dagPath.fullPathName().asChar();
				std::cout.flush();
				return MS::kFailure;
			}
			stat = translateNode(childPath);
			if (MS::kSuccess != stat)
				return MS::kFailure;
		}
		return MS::kSuccess;
	}
예제 #17
0
MStatus atomExport::exportSelected(	ofstream &animFile, 
									MString &copyFlags,
									std::set<std::string> &attrStrings,
									bool includeChildren, 
									bool useSpecifiedTimes, 
									MTime &startTime,
									MTime &endTime,
									bool statics,
									bool cached,
									bool sdk,
									bool constraint,
									bool layers,
									const MString& exportEditsFile,
									atomTemplateReader &templateReader)
{
	MStatus status = MS::kFailure;

	//	If the selection list is empty, then there are no anim curves
	//	to export.
	//
	MSelectionList sList;
	std::vector<unsigned int> depths;


	SelectionGetter::getSelectedObjects(includeChildren,sList,depths);
	if (sList.isEmpty()) {
		MString msg = MStringResource::getString(kNothingSelected, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}
	//	Copy any anim curves to the API clipboard.
	//
	MString command(copyFlags);
	


	// Always write out header
	if (!fWriter.writeHeader(animFile,useSpecifiedTimes,
							 startTime,endTime)) {
		return (MS::kFailure);
	}


	atomAnimLayers animLayers;
	std::vector<atomNodeWithAnimLayers *> nodesWithAnimLayers;
	if(layers)
	{
		bool hasAnimLayers =  animLayers.getOrderedAnimLayers(); //any layers in the scene?
		hasAnimLayers = setUpAnimLayers(sList,animLayers, nodesWithAnimLayers,attrStrings,templateReader);
		//any layers on our selection?
		if(hasAnimLayers)
		{
			//add the layers to the sList...
			unsigned int oldLength = sList.length();
			animLayers.addLayersToStartOfSelectionList(sList);
			unsigned int diffLength = sList.length() - oldLength;
			atomNodeWithAnimLayers * nullPad = NULL;
			for(unsigned int k =0 ;k < diffLength;++k) //need to pad the beginning of the nodesWithAnimlayers with any layer that was added
			{
				nodesWithAnimLayers.insert(nodesWithAnimLayers.begin(),nullPad);
				depths.insert(depths.begin(),0);
			}
		}
	}
	
	//if caching is on, we pre iterate through the objects, find 
	//each plug that's cached and then cache the data all at once
	std::vector<atomCachedPlugs *> cachedPlugs;
	if(cached)
	{
		bool passed = setUpCache(sList,cachedPlugs,animLayers,sdk, constraint, layers, attrStrings,templateReader,startTime, endTime,
			fWriter.getAngularUnit(), fWriter.getLinearUnit()); //this sets it up and runs the cache;
		if(passed == false) //failed for some reason, one reason is that the user canceled the computation
		{
			//first delete everything though
			//delete any cachedPlugs objects that we created.
			for(unsigned int z = 0; z< cachedPlugs.size(); ++z)
			{
				if(cachedPlugs[z])
					delete cachedPlugs[z];
			}
			//and delete any any layers too
			for(unsigned int zz = 0; zz< nodesWithAnimLayers.size(); ++zz)
			{
				if(nodesWithAnimLayers[zz])
					delete nodesWithAnimLayers[zz];
			}
			MString msg = MStringResource::getString(kCachingCanceled, status);
			MGlobal::displayError(msg);
			return (MS::kFailure);
		}
	}

	unsigned int numObjects = sList.length();

	bool computationFinished = true;
	//not sure if in a headless mode we may want to not show the progress, should
	//still run if that's the case
	bool hasActiveProgress = false;
	if (MProgressWindow::reserve()) {
		hasActiveProgress = true;
		MProgressWindow::setInterruptable(true);
   		MProgressWindow::startProgress();
    	MProgressWindow::setProgressRange(0, numObjects);
		MProgressWindow::setProgress(0);
		MStatus stringStat;
		MString msg = MStringResource::getString(kExportProgress, stringStat);
		if(stringStat == MS::kSuccess)
			MProgressWindow::setTitle(msg);
	}

	if (exportEditsFile.length() > 0) {
		fWriter.writeExportEditsFilePresent(animFile);
	}

	if(layers)
	{
		animLayers.writeAnimLayers(animFile,fWriter);
	}

	bool haveAnyAnimatableStuff = false; //will remain false if no curves or statics
	for (unsigned int i = 0; i < numObjects; i++) 
	{
		if(hasActiveProgress)
			MProgressWindow::setProgress(i);
		MString localCommand;
		bool haveAnimatedCurves = false; //local flag, if true this node has animated curves
		bool haveAnimatableChannels = false; //local flag, if true node has some animatable statics

		MDagPath path;
		MObject node;
		if (sList.getDagPath (i, path) == MS::kSuccess) 
		{
			MString name = path.partialPathName();
			//if the name is in the template, only then write it out...
			if(templateReader.findNode(name)== false)
				continue;

			//we use this to both write out the cached plugs for this node but for also to not write out
			//the plugs which are cached when writing anim curves.
			atomCachedPlugs * cachedPlug = NULL;
			if(cached && i < cachedPlugs.size())
				cachedPlug = cachedPlugs[i];

			atomNodeWithAnimLayers  *layerPlug = NULL;
			if(layers && i < nodesWithAnimLayers.size())
				layerPlug = nodesWithAnimLayers[i];

			unsigned int depth = depths[i];
			unsigned int childCount = path.childCount();
			MObject object = path.node();
			atomNodeNameReplacer::NodeType nodeType = (object.hasFn(MFn::kShape)) ? atomNodeNameReplacer::eShape : atomNodeNameReplacer::eDag;
			fWriter.writeNodeStart(animFile,nodeType,name,depth,childCount);
			
			
			MPlugArray animatablePlugs;
			MSelectionList localList;
			localList.add(object);
			MAnimUtil::findAnimatablePlugs(localList,animatablePlugs);
			
			if(writeAnimCurves(animFile,name,cachedPlug, layerPlug, command, haveAnimatedCurves,templateReader) != MS::kSuccess )
			{
				return (MS::kFailure);
			}
			else if(haveAnimatedCurves)
			{
				haveAnyAnimatableStuff = true;
			}
			if(statics||cached)
			{
				writeStaticAndCached (animatablePlugs,cachedPlug,statics,cached,animFile,attrStrings,name,depth,childCount, haveAnimatableChannels,templateReader);
			}
			fWriter.writeNodeEnd(animFile);

		}
		else if (sList.getDependNode (i, node) == MS::kSuccess) {
			
			if (!node.hasFn (MFn::kDependencyNode)) {
				return (MS::kFailure);
			}
			MPlugArray animatablePlugs;
			MFnDependencyNode fnNode (node, &status);
			MString name = fnNode.name();
			atomNodeNameReplacer::NodeType nodeType = atomNodeNameReplacer::eDepend;
			atomNodeWithAnimLayers  *layerPlug = NULL;
			//if a layer we get our own attrs
			if(i< animLayers.length())
			{
				MPlugArray plugs;
				animLayers.getPlugs(i,animatablePlugs);
				nodeType = atomNodeNameReplacer::eAnimLayer;
			}
			else
			{
				if(templateReader.findNode(name)== false)
				{
					continue;
				}
				MSelectionList localList;
				localList.add(node);
				MAnimUtil::findAnimatablePlugs(localList,animatablePlugs);
				if(layers && i < nodesWithAnimLayers.size())
					layerPlug = nodesWithAnimLayers[i];
			}
			//we use this to both write out the cached plugs for this node but for also to not write out
			//the plugs which are cached when writing anim curves.
			atomCachedPlugs * cachedPlug = NULL;
			if(cached && i < cachedPlugs.size())
				cachedPlug = cachedPlugs[i];

			fWriter.writeNodeStart(animFile,nodeType,name);

			if(writeAnimCurves(animFile,name, cachedPlug,layerPlug,command, haveAnimatedCurves,templateReader) != MS::kSuccess )
			{
				return (MS::kFailure);
			}
			else if(haveAnimatedCurves)
			{
				haveAnyAnimatableStuff = true;
			}


			if(statics||cached)
			{
				writeStaticAndCached (animatablePlugs,cachedPlug,statics,cached,animFile,attrStrings,name,0,0,haveAnimatableChannels,templateReader);
			}
			fWriter.writeNodeEnd(animFile);
		}
		if(haveAnimatableChannels==true)
			haveAnyAnimatableStuff = true;

		if  (hasActiveProgress && MProgressWindow::isCancelled())
		{
			computationFinished = false;
			break;
		}
		
	}
	
	if (exportEditsFile.length() > 0) {
		fWriter.writeExportEditsFile(animFile,exportEditsFile);
	}
	
	//delete any cachedPlugs objects that we created.
	for(unsigned int z = 0; z< cachedPlugs.size(); ++z)
	{
		if(cachedPlugs[z])
			delete cachedPlugs[z];
	}
	//and delete any any layers too
	for(unsigned int zz = 0; zz< nodesWithAnimLayers.size(); ++zz)
	{
		if(nodesWithAnimLayers[zz])
			delete nodesWithAnimLayers[zz];
	}
	if(computationFinished == false) //failed for some reason, one reason is that the user canceled the computation
	{
		MString msg = MStringResource::getString(kSavingCanceled, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}

	if(hasActiveProgress)
		MProgressWindow::endProgress();

	if(haveAnyAnimatableStuff == false)
	{
		MString msg = MStringResource::getString(kAnimCurveNotFound, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}
	else return (MS::kSuccess);
}	
예제 #18
0
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MSelectionList CVsSkinnerCmd::DoNewVolumes(
	const MDagPath &skinnerPath,
	const MSelectionList &skeletonList )
{
	MSelectionList retList;

	const bool optSelected( m_undo.ArgDatabase().isFlagSet( kOptSelected ) );

	MSelectionList optSelection;
	m_undo.ArgDatabase().getObjects( optSelection );

	// TODO: Maybe some fancier logic to only create volumes on joints that make sense?
	//		 Perhaps the ol' has children but no shapes gag?  Watch out for vstHelperBones!

	MDagPath mDagPath;
	for ( MItSelectionList sIt( optSelection ); !sIt.isDone(); sIt.next() )
	{
		if ( sIt.itemType() == MItSelectionList::kDagSelectionItem && sIt.getDagPath( mDagPath ) && mDagPath.hasFn( MFn::kTransform ) )
		{
			if ( optSelected )
			{
				MObject cObj( DoNewVolume( skinnerPath, mDagPath ) );
				if ( cObj.isNull() )
				{
					mwarn << "Couldn't create new volume on " << skinnerPath.partialPathName()
						<< " using " << mDagPath.partialPathName() << " as a parent" << std::endl;
				}
				else
				{
					retList.add( skinnerPath, cObj, true );
				}
			}
			else
			{
				MItDag dIt;
				for ( dIt.reset( mDagPath ); !dIt.isDone(); dIt.next() )
				{
					dIt.getPath( mDagPath );

					if ( mDagPath.childCount() )
					{
						uint nShapes( 0 );
						mDagPath.numberOfShapesDirectlyBelow( nShapes );

						if ( nShapes == 0U || mDagPath.hasFn( MFn::kJoint ) )
						{
							MObject cObj( DoNewVolume( skinnerPath, mDagPath ) );
							if ( cObj.isNull() )
							{
								mwarn << "Couldn't create new volume on " << skinnerPath.partialPathName()
									<< " using " << mDagPath.partialPathName() << " as a parent" << std::endl;
							}
							else
							{
								retList.add( skinnerPath, cObj, true );
							}
						}
					}
				}
			}
		}
	}

	return retList;
}
예제 #19
0
void DMPDSExporter::fillBones( DMPSkeletonData::SubSkeletonStruct* subSkel, string parent, DMPParameters* param, MDagPath& jointDag )
{
	MStatus status;
	if (jointDag.apiType() != MFn::kJoint)
	{
		return; // early out.
	}
	DMPSkeletonData::BoneStruct newBone;
	newBone.boneHandle = (unsigned int)subSkel->bones.size();
	newBone.name = jointDag.partialPathName().asUTF8();
	newBone.parentName = parent;

	MFnIkJoint fnJoint(jointDag, &status);
	//	matrix = [S] * [RO] * [R] * [JO] * [IS] * [T]
	/*
		These matrices are defined as follows:
		•[S] : scale
		•[RO] : rotateOrient (attribute name is rotateAxis)
		•[R] : rotate
		•[JO] : jointOrient
		•[IS] : parentScaleInverse
		•[T] : translate

		The methods to get the value of these matrices are:
		•[S] : getScale
		•[RO] : getScaleOrientation
		•[R] : getRotation
		•[JO] : getOrientation
		•[IS] : (the inverse of the getScale on the parent transformation matrix)
		•[T] : translation

	*/
	MVector trans = fnJoint.getTranslation(MSpace::kTransform);
	double scale[3];
	fnJoint.getScale(scale);
	MQuaternion R, RO, JO;
	fnJoint.getScaleOrientation(RO);
	fnJoint.getRotation(R);
	fnJoint.getOrientation(JO);
	MQuaternion rot = RO * R * JO; 
	
	newBone.translate[0] = trans.x * param->lum;
	newBone.translate[1] = trans.y * param->lum;
	newBone.translate[2] = trans.z * param->lum;

	newBone.orientation[0] = rot.w;
	newBone.orientation[1] = rot.x;
	newBone.orientation[2] = rot.y;
	newBone.orientation[3] = rot.z;

	newBone.scale[0] = scale[0];
	newBone.scale[1] = scale[1];
	newBone.scale[2] = scale[2];

	subSkel->bones.push_back(newBone);
	// Load child joints
	for (unsigned int i=0; i<jointDag.childCount();i++)
	{
		MObject child;
		child = jointDag.child(i);
		MDagPath childDag = jointDag;
		childDag.push(child);
		fillBones(subSkel, newBone.name, param, childDag);
	}
	// now go for animations
	if (param->bExportSkelAnimation)
	{
		for (unsigned int i = 0; i < subSkel->animations.size(); ++i)
		{
			DMPSkeletonData::TransformAnimation& anim = subSkel->animations[i];
			DMPSkeletonData::TransformTrack subTrack;
			subTrack.targetBone = newBone.name;

			MPlug		plugT;	// translate
 			MPlug		plugR;	// R
 			MPlug		plugRO;	// RO
 			MPlug		plugJO;	// JO
			MPlug		plugS;	// scale
			double		dataT[3];
			double		dataR[3];
			double		dataRO[3];
			double		dataJO[3];
			double		dataS[3];
			MFnDependencyNode	fnDependNode( jointDag.node(), &status );
			
			plugT = fnDependNode.findPlug("translate", false, &status);
 			plugR = fnDependNode.findPlug("rotate", false, &status);
 			plugRO = fnDependNode.findPlug("rotateAxis", false, &status);
 			plugJO = fnDependNode.findPlug("jointOrient", false, &status);
			plugS = fnDependNode.findPlug("scale", false, &status);

			float timeStep = param->samplerRate;
			if (param->animSampleType == DMPParameters::AST_Frame)
			{
				timeStep /= param->fps;
			}
			for (float curTime = anim.startTime; curTime <= anim.endTime; curTime += timeStep)
			{
				MTime		mayaTime;
				DMPSkeletonData::TransformKeyFrame keyframe;
				keyframe.time = curTime - anim.startTime;
				mayaTime.setUnit(MTime::kSeconds);
				mayaTime.setValue(curTime);

				// Get its value at the specified Time.
				plugT.child(0).getValue(dataT[0], MDGContext(mayaTime));
				plugT.child(1).getValue(dataT[1], MDGContext(mayaTime));
				plugT.child(2).getValue(dataT[2], MDGContext(mayaTime));

				plugR.child(0).getValue(dataR[0], MDGContext(mayaTime));
				plugR.child(1).getValue(dataR[1], MDGContext(mayaTime));
				plugR.child(2).getValue(dataR[2], MDGContext(mayaTime));

				plugRO.child(0).getValue(dataRO[0], MDGContext(mayaTime));
				plugRO.child(1).getValue(dataRO[1], MDGContext(mayaTime));
				plugRO.child(2).getValue(dataRO[2], MDGContext(mayaTime));

				plugJO.child(0).getValue(dataJO[0], MDGContext(mayaTime));
				plugJO.child(1).getValue(dataJO[1], MDGContext(mayaTime));
				plugJO.child(2).getValue(dataJO[2], MDGContext(mayaTime));

				plugS.child(0).getValue(dataS[0], MDGContext(mayaTime));
				plugS.child(1).getValue(dataS[1], MDGContext(mayaTime));
				plugS.child(2).getValue(dataS[2], MDGContext(mayaTime));

				// fill the frame.
				keyframe.translate[0] = dataT[0] * param->lum;
				keyframe.translate[1] = dataT[1] * param->lum;
				keyframe.translate[2] = dataT[2] * param->lum;
				// calculate quaternion.
				MEulerRotation	rotR(dataR[0], dataR[1], dataR[2]);
				MEulerRotation	rotRO(dataRO[0], dataRO[1], dataRO[2]);
				MEulerRotation	rotJO(dataJO[0], dataJO[1], dataJO[2]);

				MQuaternion finalRot = rotRO.asQuaternion()*rotR.asQuaternion()*rotJO.asQuaternion();
				
				keyframe.orientation[0] = finalRot.w;
				keyframe.orientation[1] = finalRot.x;
				keyframe.orientation[2] = finalRot.y;
				keyframe.orientation[3] = finalRot.z;

				keyframe.scale[0] = dataS[0];
				keyframe.scale[1] = dataS[1];
				keyframe.scale[2] = dataS[2];

				subTrack.frames.push_back(keyframe);
			}
			anim.tracks.push_back(subTrack);
		}
	}
}
예제 #20
0
collision_shape_t::pointer collisionShapeNode::createCompositeShape(const MPlug& plgInShape)
{

	std::vector<collision_shape_t::pointer> childCollisionShapes;
	std::vector< vec3f> childPositions;
	std::vector< quatf> childOrientations;

	MPlugArray plgaConnectedTo;
	plgInShape.connectedTo(plgaConnectedTo, true, true);
	int numSelectedShapes = plgaConnectedTo.length();

	if(numSelectedShapes > 0) {

		MObject node = plgaConnectedTo[0].node();

		MDagPath dagPath;
		MDagPath::getAPathTo(node, dagPath);
		int numChildren = dagPath.childCount();

		if (node.hasFn(MFn::kTransform))
		{
			MFnTransform trNode(dagPath);
			MVector mtranslation = trNode.getTranslation(MSpace::kTransform);
			MObject thisObject(thisMObject());

			MFnDagNode fnDagNode(thisObject);
			MStatus status;

			MFnTransform fnParentTransform(fnDagNode.parent(0, &status));

			mtranslation = trNode.getTranslation(MSpace::kPostTransform);
			mtranslation = fnParentTransform.getTranslation(MSpace::kTransform);

			const char* name = trNode.name().asChar();
			printf("name = %s\n", name);

			for (int i=0;i<numChildren;i++)
			{
				MObject child = dagPath.child(i);
				if(child.hasFn(MFn::kMesh))
				{
					return false;
				}

				if(child.hasFn(MFn::kTransform))
				{
					MDagPath dagPath;
					MDagPath::getAPathTo(child, dagPath);
					MFnTransform trNode(dagPath);

					MVector mtranslation = trNode.getTranslation(MSpace::kTransform);
					mtranslation = trNode.getTranslation(MSpace::kPostTransform);

					MQuaternion mrotation;
					trNode.getRotation(mrotation, MSpace::kTransform);
					double mscale[3];
					trNode.getScale(mscale);

					vec3f childPos((float)mtranslation.x, (float)mtranslation.y, (float)mtranslation.z);
					quatf childOrn((float)mrotation.w, (float)mrotation.x, (float)mrotation.y, (float)mrotation.z);

					const char* name = trNode.name().asChar();
					printf("name = %s\n", name);

					int numGrandChildren = dagPath.childCount();
					{
						for (int i=0;i<numGrandChildren;i++)
						{
							MObject grandchild = dagPath.child(i);
							if(grandchild.hasFn(MFn::kMesh))
							{

								collision_shape_t::pointer childShape = createCollisionShape(grandchild);
								if (childShape)
								{
									childCollisionShapes.push_back(childShape);
									childPositions.push_back(childPos);
									childOrientations.push_back(childOrn);
								}
							}
						}
					}
				}
			}
		}
	}

	if (childCollisionShapes.size()>0)
	{

		composite_shape_t::pointer composite = solver_t::create_composite_shape(
			&childCollisionShapes[0],
			&childPositions[0],
			&childOrientations[0],
			childCollisionShapes.size()
			);
		return composite;
	}
	return 0;
}
    // --------------------------------------
    void ReferenceManager::processReference ( const MObject& referenceNode )
    {
        MStatus status;
        MFnDependencyNode referenceNodeFn ( referenceNode, &status );
        if (status != MStatus::kSuccess) return;

#if MAYA_API_VERSION >= 600
        MString referenceNodeName = MFnDependencyNode( referenceNode ).name();

        Reference* reference = new Reference();
        reference->referenceNode = referenceNode;
        mReferences.push_back ( reference );

        // Get the paths of the root transforms included in this reference
        MObjectArray subReferences;
        getRootObjects ( referenceNode, reference->paths, subReferences );
        uint pathCount = reference->paths.length();

        // Process the sub-references first
        uint subReferenceCount = subReferences.length();
        for (uint i = 0; i < subReferenceCount; ++i)
        {
            MObject& subReference = subReferences[i];
            if ( subReference != MObject::kNullObj ) processReference ( subReference );
        }

        // Retrieve the reference node's filename
        MString command = MString("reference -rfn \"") + referenceNodeFn.name() + MString("\" -q -filename;");
        MString filename;
        status = MGlobal::executeCommand ( command, filename );
        if (status != MStatus::kSuccess || filename.length() == 0) return;

        // Strip the filename of the multiple file token
        int stripIndex = filename.index('{');
        if (stripIndex != -1) filename = filename.substring(0, stripIndex - 1);

        // Avoid transform look-ups on COLLADA references.
        int extLocation = filename.rindex('.');
        if (extLocation > 0)
        {
            MString ext = filename.substring(extLocation + 1, filename.length() - 1).toLowerCase();
            if (ext == "dae" || ext == "xml") return;
        }

        // Check for already existing file information
        // Otherwise create a new file information sheet with current node names
        for ( ReferenceFileList::iterator it = mFiles.begin(); it != mFiles.end(); ++it )
        {
            if ((*it)->filename == filename) 
            { 
                reference->file = (*it); 
                break; 
            }
        }

        if ( reference->file == NULL ) reference->file = processReferenceFile(filename);

        // Get the list of the root transform's first child's unreferenced parents.
        // This is a list of the imported nodes!
        for (uint j = 0; j < pathCount; ++j)
        {
            MDagPath path = reference->paths[j];
            if (path.childCount() > 0)
            {
                path.push ( path.child(0) );
                MFnDagNode childNode ( path );
                if (!childNode.object().hasFn(MFn::kTransform)) continue;

                uint parentCount = childNode.parentCount();
                for (uint k = 0; k < parentCount; ++k)
                {
                    MFnDagNode parentNode(childNode.parent(k));
                    if (parentNode.object() == MObject::kNullObj || parentNode.isFromReferencedFile()) continue;

                    MDagPath parentPath = MDagPath::getAPathTo(parentNode.object());
                    if (parentPath.length() > 0)
                    {
                        ReferenceRootList::iterator it = 
                            reference->reroots.insert( reference->reroots.end(), ReferenceRoot() );
                        (*it).index = j;
                        (*it).reroot = parentPath;
                    }
                }
            }
        }
#endif
    }
예제 #22
0
// List logic. This is a pretty simple example that
// builds a list of mesh shapes to return.
//
MStatus viewObjectFilter::getList(MSelectionList &list)
{
	bool debugFilterUsage = false;
	if (debugFilterUsage)
	{
		unsigned int viewCount = M3dView::numberOf3dViews();
		if (viewCount)
		{
			for (unsigned int i=0; i<viewCount; i++)
			{
				M3dView view;
				if (MStatus::kSuccess == M3dView::get3dView( i, view ))
				{
					if (view.objectListFilterName() == name())
					{
						printf("*** Update filter list %s. Exclusion=%d, Inverted=%d\n",
							name().asChar(), MObjectListFilter::kExclusionList == filterType(),
							mInvertedList);
					}
				}
			}
		}
	}
	// Clear out old list
	list.clear();

	if (mInvertedList)
	{
		MStatus status;
		MItDag::TraversalType traversalType = MItDag::kDepthFirst;
		MItDag dagIterator( traversalType, MFn::kInvalid, &status);

		for ( ; !dagIterator.isDone(); dagIterator.next() )
		{
			MDagPath dagPath;
			status = dagIterator.getPath(dagPath);
			if ( status != MStatus::kSuccess )
			{
				status.perror("MItDag::getPath");
				continue;
			}
			if (dagPath.hasFn( MFn::kMesh ))
			{
				dagIterator.prune();
				continue;
			}
			if (dagPath.childCount() <= 1)
			{
				status = list.add( dagPath );
			}
		}
	}
	else
	{
		// Get a list of all the meshes in the scene
		MItDag::TraversalType traversalType = MItDag::kDepthFirst;
		MFn::Type filter = MFn::kMesh;
		MStatus status;

		MItDag dagIterator( traversalType, filter, &status);
		for ( ; !dagIterator.isDone(); dagIterator.next() )
		{
			MDagPath dagPath;
			status = dagIterator.getPath(dagPath);
			if ( status != MStatus::kSuccess )
			{
				status.perror("MItDag::getPath");
				continue;
			}

			status = list.add( dagPath );
			if ( status != MStatus::kSuccess )
			{
				status.perror("MSelectionList add");
			}
		}
	}

	if (list.length())
	{
		return MStatus::kSuccess;
	}
	return MStatus::kFailure;
}
예제 #23
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; }
}